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 std::any_of(FD->param_begin(), FD->param_end(), [](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(
988         PrintingPolicy, OS,
989         TemplateParameterList::shouldIncludeTypeForArgument(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 =
1388         std::count_if(RD->field_begin(), RD->field_end(),
1389                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1390     assert(Bindings.size() != NumFields);
1391     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1392         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1393         << (NumFields < Bindings.size());
1394     return true;
1395   };
1396 
1397   //   all of E's non-static data members shall be [...] well-formed
1398   //   when named as e.name in the context of the structured binding,
1399   //   E shall not have an anonymous union member, ...
1400   unsigned I = 0;
1401   for (auto *FD : RD->fields()) {
1402     if (FD->isUnnamedBitfield())
1403       continue;
1404 
1405     // All the non-static data members are required to be nameable, so they
1406     // must all have names.
1407     if (!FD->getDeclName()) {
1408       if (RD->isLambda()) {
1409         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1410         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1411         return true;
1412       }
1413 
1414       if (FD->isAnonymousStructOrUnion()) {
1415         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1416           << DecompType << FD->getType()->isUnionType();
1417         S.Diag(FD->getLocation(), diag::note_declared_at);
1418         return true;
1419       }
1420 
1421       // FIXME: Are there any other ways we could have an anonymous member?
1422     }
1423 
1424     // We have a real field to bind.
1425     if (I >= Bindings.size())
1426       return DiagnoseBadNumberOfBindings();
1427     auto *B = Bindings[I++];
1428     SourceLocation Loc = B->getLocation();
1429 
1430     // The field must be accessible in the context of the structured binding.
1431     // We already checked that the base class is accessible.
1432     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1433     // const_cast here.
1434     S.CheckStructuredBindingMemberAccess(
1435         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1436         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1437                                      BasePair.getAccess(), FD->getAccess())));
1438 
1439     // Initialize the binding to Src.FD.
1440     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1441     if (E.isInvalid())
1442       return true;
1443     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1444                             VK_LValue, &BasePath);
1445     if (E.isInvalid())
1446       return true;
1447     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1448                                   CXXScopeSpec(), FD,
1449                                   DeclAccessPair::make(FD, FD->getAccess()),
1450                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1451     if (E.isInvalid())
1452       return true;
1453 
1454     // If the type of the member is T, the referenced type is cv T, where cv is
1455     // the cv-qualification of the decomposition expression.
1456     //
1457     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1458     // 'const' to the type of the field.
1459     Qualifiers Q = DecompType.getQualifiers();
1460     if (FD->isMutable())
1461       Q.removeConst();
1462     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1463   }
1464 
1465   if (I != Bindings.size())
1466     return DiagnoseBadNumberOfBindings();
1467 
1468   return false;
1469 }
1470 
1471 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1472   QualType DecompType = DD->getType();
1473 
1474   // If the type of the decomposition is dependent, then so is the type of
1475   // each binding.
1476   if (DecompType->isDependentType()) {
1477     for (auto *B : DD->bindings())
1478       B->setType(Context.DependentTy);
1479     return;
1480   }
1481 
1482   DecompType = DecompType.getNonReferenceType();
1483   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1484 
1485   // C++1z [dcl.decomp]/2:
1486   //   If E is an array type [...]
1487   // As an extension, we also support decomposition of built-in complex and
1488   // vector types.
1489   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1490     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1491       DD->setInvalidDecl();
1492     return;
1493   }
1494   if (auto *VT = DecompType->getAs<VectorType>()) {
1495     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1496       DD->setInvalidDecl();
1497     return;
1498   }
1499   if (auto *CT = DecompType->getAs<ComplexType>()) {
1500     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1501       DD->setInvalidDecl();
1502     return;
1503   }
1504 
1505   // C++1z [dcl.decomp]/3:
1506   //   if the expression std::tuple_size<E>::value is a well-formed integral
1507   //   constant expression, [...]
1508   llvm::APSInt TupleSize(32);
1509   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1510   case IsTupleLike::Error:
1511     DD->setInvalidDecl();
1512     return;
1513 
1514   case IsTupleLike::TupleLike:
1515     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1516       DD->setInvalidDecl();
1517     return;
1518 
1519   case IsTupleLike::NotTupleLike:
1520     break;
1521   }
1522 
1523   // C++1z [dcl.dcl]/8:
1524   //   [E shall be of array or non-union class type]
1525   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1526   if (!RD || RD->isUnion()) {
1527     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1528         << DD << !RD << DecompType;
1529     DD->setInvalidDecl();
1530     return;
1531   }
1532 
1533   // C++1z [dcl.decomp]/4:
1534   //   all of E's non-static data members shall be [...] direct members of
1535   //   E or of the same unambiguous public base class of E, ...
1536   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1537     DD->setInvalidDecl();
1538 }
1539 
1540 /// Merge the exception specifications of two variable declarations.
1541 ///
1542 /// This is called when there's a redeclaration of a VarDecl. The function
1543 /// checks if the redeclaration might have an exception specification and
1544 /// validates compatibility and merges the specs if necessary.
1545 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1546   // Shortcut if exceptions are disabled.
1547   if (!getLangOpts().CXXExceptions)
1548     return;
1549 
1550   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1551          "Should only be called if types are otherwise the same.");
1552 
1553   QualType NewType = New->getType();
1554   QualType OldType = Old->getType();
1555 
1556   // We're only interested in pointers and references to functions, as well
1557   // as pointers to member functions.
1558   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1559     NewType = R->getPointeeType();
1560     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1561   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1562     NewType = P->getPointeeType();
1563     OldType = OldType->castAs<PointerType>()->getPointeeType();
1564   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1565     NewType = M->getPointeeType();
1566     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1567   }
1568 
1569   if (!NewType->isFunctionProtoType())
1570     return;
1571 
1572   // There's lots of special cases for functions. For function pointers, system
1573   // libraries are hopefully not as broken so that we don't need these
1574   // workarounds.
1575   if (CheckEquivalentExceptionSpec(
1576         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1577         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1578     New->setInvalidDecl();
1579   }
1580 }
1581 
1582 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1583 /// function declaration are well-formed according to C++
1584 /// [dcl.fct.default].
1585 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1586   unsigned NumParams = FD->getNumParams();
1587   unsigned ParamIdx = 0;
1588 
1589   // This checking doesn't make sense for explicit specializations; their
1590   // default arguments are determined by the declaration we're specializing,
1591   // not by FD.
1592   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1593     return;
1594   if (auto *FTD = FD->getDescribedFunctionTemplate())
1595     if (FTD->isMemberSpecialization())
1596       return;
1597 
1598   // Find first parameter with a default argument
1599   for (; ParamIdx < NumParams; ++ParamIdx) {
1600     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1601     if (Param->hasDefaultArg())
1602       break;
1603   }
1604 
1605   // C++20 [dcl.fct.default]p4:
1606   //   In a given function declaration, each parameter subsequent to a parameter
1607   //   with a default argument shall have a default argument supplied in this or
1608   //   a previous declaration, unless the parameter was expanded from a
1609   //   parameter pack, or shall be a function parameter pack.
1610   for (; ParamIdx < NumParams; ++ParamIdx) {
1611     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1612     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1613         !(CurrentInstantiationScope &&
1614           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1615       if (Param->isInvalidDecl())
1616         /* We already complained about this parameter. */;
1617       else if (Param->getIdentifier())
1618         Diag(Param->getLocation(),
1619              diag::err_param_default_argument_missing_name)
1620           << Param->getIdentifier();
1621       else
1622         Diag(Param->getLocation(),
1623              diag::err_param_default_argument_missing);
1624     }
1625   }
1626 }
1627 
1628 /// Check that the given type is a literal type. Issue a diagnostic if not,
1629 /// if Kind is Diagnose.
1630 /// \return \c true if a problem has been found (and optionally diagnosed).
1631 template <typename... Ts>
1632 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1633                              SourceLocation Loc, QualType T, unsigned DiagID,
1634                              Ts &&...DiagArgs) {
1635   if (T->isDependentType())
1636     return false;
1637 
1638   switch (Kind) {
1639   case Sema::CheckConstexprKind::Diagnose:
1640     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1641                                       std::forward<Ts>(DiagArgs)...);
1642 
1643   case Sema::CheckConstexprKind::CheckValid:
1644     return !T->isLiteralType(SemaRef.Context);
1645   }
1646 
1647   llvm_unreachable("unknown CheckConstexprKind");
1648 }
1649 
1650 /// Determine whether a destructor cannot be constexpr due to
1651 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1652                                                const CXXDestructorDecl *DD,
1653                                                Sema::CheckConstexprKind Kind) {
1654   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1655     const CXXRecordDecl *RD =
1656         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1657     if (!RD || RD->hasConstexprDestructor())
1658       return true;
1659 
1660     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1661       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1662           << static_cast<int>(DD->getConstexprKind()) << !FD
1663           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1664       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1665           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1666     }
1667     return false;
1668   };
1669 
1670   const CXXRecordDecl *RD = DD->getParent();
1671   for (const CXXBaseSpecifier &B : RD->bases())
1672     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1673       return false;
1674   for (const FieldDecl *FD : RD->fields())
1675     if (!Check(FD->getLocation(), FD->getType(), FD))
1676       return false;
1677   return true;
1678 }
1679 
1680 /// Check whether a function's parameter types are all literal types. If so,
1681 /// return true. If not, produce a suitable diagnostic and return false.
1682 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1683                                          const FunctionDecl *FD,
1684                                          Sema::CheckConstexprKind Kind) {
1685   unsigned ArgIndex = 0;
1686   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1687   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1688                                               e = FT->param_type_end();
1689        i != e; ++i, ++ArgIndex) {
1690     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1691     SourceLocation ParamLoc = PD->getLocation();
1692     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1693                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1694                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1695                          FD->isConsteval()))
1696       return false;
1697   }
1698   return true;
1699 }
1700 
1701 /// Check whether a function's return type is a literal type. If so, return
1702 /// true. If not, produce a suitable diagnostic and return false.
1703 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1704                                      Sema::CheckConstexprKind Kind) {
1705   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1706                        diag::err_constexpr_non_literal_return,
1707                        FD->isConsteval()))
1708     return false;
1709   return true;
1710 }
1711 
1712 /// Get diagnostic %select index for tag kind for
1713 /// record diagnostic message.
1714 /// WARNING: Indexes apply to particular diagnostics only!
1715 ///
1716 /// \returns diagnostic %select index.
1717 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1718   switch (Tag) {
1719   case TTK_Struct: return 0;
1720   case TTK_Interface: return 1;
1721   case TTK_Class:  return 2;
1722   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1723   }
1724 }
1725 
1726 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1727                                        Stmt *Body,
1728                                        Sema::CheckConstexprKind Kind);
1729 
1730 // Check whether a function declaration satisfies the requirements of a
1731 // constexpr function definition or a constexpr constructor definition. If so,
1732 // return true. If not, produce appropriate diagnostics (unless asked not to by
1733 // Kind) and return false.
1734 //
1735 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1736 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1737                                             CheckConstexprKind Kind) {
1738   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1739   if (MD && MD->isInstance()) {
1740     // C++11 [dcl.constexpr]p4:
1741     //  The definition of a constexpr constructor shall satisfy the following
1742     //  constraints:
1743     //  - the class shall not have any virtual base classes;
1744     //
1745     // FIXME: This only applies to constructors and destructors, not arbitrary
1746     // member functions.
1747     const CXXRecordDecl *RD = MD->getParent();
1748     if (RD->getNumVBases()) {
1749       if (Kind == CheckConstexprKind::CheckValid)
1750         return false;
1751 
1752       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1753         << isa<CXXConstructorDecl>(NewFD)
1754         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1755       for (const auto &I : RD->vbases())
1756         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1757             << I.getSourceRange();
1758       return false;
1759     }
1760   }
1761 
1762   if (!isa<CXXConstructorDecl>(NewFD)) {
1763     // C++11 [dcl.constexpr]p3:
1764     //  The definition of a constexpr function shall satisfy the following
1765     //  constraints:
1766     // - it shall not be virtual; (removed in C++20)
1767     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1768     if (Method && Method->isVirtual()) {
1769       if (getLangOpts().CPlusPlus20) {
1770         if (Kind == CheckConstexprKind::Diagnose)
1771           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1772       } else {
1773         if (Kind == CheckConstexprKind::CheckValid)
1774           return false;
1775 
1776         Method = Method->getCanonicalDecl();
1777         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1778 
1779         // If it's not obvious why this function is virtual, find an overridden
1780         // function which uses the 'virtual' keyword.
1781         const CXXMethodDecl *WrittenVirtual = Method;
1782         while (!WrittenVirtual->isVirtualAsWritten())
1783           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1784         if (WrittenVirtual != Method)
1785           Diag(WrittenVirtual->getLocation(),
1786                diag::note_overridden_virtual_function);
1787         return false;
1788       }
1789     }
1790 
1791     // - its return type shall be a literal type;
1792     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1793       return false;
1794   }
1795 
1796   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1797     // A destructor can be constexpr only if the defaulted destructor could be;
1798     // we don't need to check the members and bases if we already know they all
1799     // have constexpr destructors.
1800     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1801       if (Kind == CheckConstexprKind::CheckValid)
1802         return false;
1803       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1804         return false;
1805     }
1806   }
1807 
1808   // - each of its parameter types shall be a literal type;
1809   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1810     return false;
1811 
1812   Stmt *Body = NewFD->getBody();
1813   assert(Body &&
1814          "CheckConstexprFunctionDefinition called on function with no body");
1815   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1816 }
1817 
1818 /// Check the given declaration statement is legal within a constexpr function
1819 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1820 ///
1821 /// \return true if the body is OK (maybe only as an extension), false if we
1822 ///         have diagnosed a problem.
1823 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1824                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1825                                    Sema::CheckConstexprKind Kind) {
1826   // C++11 [dcl.constexpr]p3 and p4:
1827   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1828   //  contain only
1829   for (const auto *DclIt : DS->decls()) {
1830     switch (DclIt->getKind()) {
1831     case Decl::StaticAssert:
1832     case Decl::Using:
1833     case Decl::UsingShadow:
1834     case Decl::UsingDirective:
1835     case Decl::UnresolvedUsingTypename:
1836     case Decl::UnresolvedUsingValue:
1837     case Decl::UsingEnum:
1838       //   - static_assert-declarations
1839       //   - using-declarations,
1840       //   - using-directives,
1841       //   - using-enum-declaration
1842       continue;
1843 
1844     case Decl::Typedef:
1845     case Decl::TypeAlias: {
1846       //   - typedef declarations and alias-declarations that do not define
1847       //     classes or enumerations,
1848       const auto *TN = cast<TypedefNameDecl>(DclIt);
1849       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1850         // Don't allow variably-modified types in constexpr functions.
1851         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1853           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1854             << TL.getSourceRange() << TL.getType()
1855             << isa<CXXConstructorDecl>(Dcl);
1856         }
1857         return false;
1858       }
1859       continue;
1860     }
1861 
1862     case Decl::Enum:
1863     case Decl::CXXRecord:
1864       // C++1y allows types to be defined, not just declared.
1865       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1866         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1867           SemaRef.Diag(DS->getBeginLoc(),
1868                        SemaRef.getLangOpts().CPlusPlus14
1869                            ? diag::warn_cxx11_compat_constexpr_type_definition
1870                            : diag::ext_constexpr_type_definition)
1871               << isa<CXXConstructorDecl>(Dcl);
1872         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1873           return false;
1874         }
1875       }
1876       continue;
1877 
1878     case Decl::EnumConstant:
1879     case Decl::IndirectField:
1880     case Decl::ParmVar:
1881       // These can only appear with other declarations which are banned in
1882       // C++11 and permitted in C++1y, so ignore them.
1883       continue;
1884 
1885     case Decl::Var:
1886     case Decl::Decomposition: {
1887       // C++1y [dcl.constexpr]p3 allows anything except:
1888       //   a definition of a variable of non-literal type or of static or
1889       //   thread storage duration or [before C++2a] for which no
1890       //   initialization is performed.
1891       const auto *VD = cast<VarDecl>(DclIt);
1892       if (VD->isThisDeclarationADefinition()) {
1893         if (VD->isStaticLocal()) {
1894           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1895             SemaRef.Diag(VD->getLocation(),
1896                          diag::err_constexpr_local_var_static)
1897               << isa<CXXConstructorDecl>(Dcl)
1898               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1899           }
1900           return false;
1901         }
1902         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1903                              diag::err_constexpr_local_var_non_literal_type,
1904                              isa<CXXConstructorDecl>(Dcl)))
1905           return false;
1906         if (!VD->getType()->isDependentType() &&
1907             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1908           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1909             SemaRef.Diag(
1910                 VD->getLocation(),
1911                 SemaRef.getLangOpts().CPlusPlus20
1912                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1913                     : diag::ext_constexpr_local_var_no_init)
1914                 << isa<CXXConstructorDecl>(Dcl);
1915           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1916             return false;
1917           }
1918           continue;
1919         }
1920       }
1921       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1922         SemaRef.Diag(VD->getLocation(),
1923                      SemaRef.getLangOpts().CPlusPlus14
1924                       ? diag::warn_cxx11_compat_constexpr_local_var
1925                       : diag::ext_constexpr_local_var)
1926           << isa<CXXConstructorDecl>(Dcl);
1927       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1928         return false;
1929       }
1930       continue;
1931     }
1932 
1933     case Decl::NamespaceAlias:
1934     case Decl::Function:
1935       // These are disallowed in C++11 and permitted in C++1y. Allow them
1936       // everywhere as an extension.
1937       if (!Cxx1yLoc.isValid())
1938         Cxx1yLoc = DS->getBeginLoc();
1939       continue;
1940 
1941     default:
1942       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1943         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1944             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1945       }
1946       return false;
1947     }
1948   }
1949 
1950   return true;
1951 }
1952 
1953 /// Check that the given field is initialized within a constexpr constructor.
1954 ///
1955 /// \param Dcl The constexpr constructor being checked.
1956 /// \param Field The field being checked. This may be a member of an anonymous
1957 ///        struct or union nested within the class being checked.
1958 /// \param Inits All declarations, including anonymous struct/union members and
1959 ///        indirect members, for which any initialization was provided.
1960 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1961 ///        multiple notes for different members to the same error.
1962 /// \param Kind Whether we're diagnosing a constructor as written or determining
1963 ///        whether the formal requirements are satisfied.
1964 /// \return \c false if we're checking for validity and the constructor does
1965 ///         not satisfy the requirements on a constexpr constructor.
1966 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1967                                           const FunctionDecl *Dcl,
1968                                           FieldDecl *Field,
1969                                           llvm::SmallSet<Decl*, 16> &Inits,
1970                                           bool &Diagnosed,
1971                                           Sema::CheckConstexprKind Kind) {
1972   // In C++20 onwards, there's nothing to check for validity.
1973   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1974       SemaRef.getLangOpts().CPlusPlus20)
1975     return true;
1976 
1977   if (Field->isInvalidDecl())
1978     return true;
1979 
1980   if (Field->isUnnamedBitfield())
1981     return true;
1982 
1983   // Anonymous unions with no variant members and empty anonymous structs do not
1984   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1985   // indirect fields don't need initializing.
1986   if (Field->isAnonymousStructOrUnion() &&
1987       (Field->getType()->isUnionType()
1988            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1989            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1990     return true;
1991 
1992   if (!Inits.count(Field)) {
1993     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1994       if (!Diagnosed) {
1995         SemaRef.Diag(Dcl->getLocation(),
1996                      SemaRef.getLangOpts().CPlusPlus20
1997                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1998                          : diag::ext_constexpr_ctor_missing_init);
1999         Diagnosed = true;
2000       }
2001       SemaRef.Diag(Field->getLocation(),
2002                    diag::note_constexpr_ctor_missing_init);
2003     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2004       return false;
2005     }
2006   } else if (Field->isAnonymousStructOrUnion()) {
2007     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2008     for (auto *I : RD->fields())
2009       // If an anonymous union contains an anonymous struct of which any member
2010       // is initialized, all members must be initialized.
2011       if (!RD->isUnion() || Inits.count(I))
2012         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2013                                            Kind))
2014           return false;
2015   }
2016   return true;
2017 }
2018 
2019 /// Check the provided statement is allowed in a constexpr function
2020 /// definition.
2021 static bool
2022 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2023                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2024                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2025                            Sema::CheckConstexprKind Kind) {
2026   // - its function-body shall be [...] a compound-statement that contains only
2027   switch (S->getStmtClass()) {
2028   case Stmt::NullStmtClass:
2029     //   - null statements,
2030     return true;
2031 
2032   case Stmt::DeclStmtClass:
2033     //   - static_assert-declarations
2034     //   - using-declarations,
2035     //   - using-directives,
2036     //   - typedef declarations and alias-declarations that do not define
2037     //     classes or enumerations,
2038     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2039       return false;
2040     return true;
2041 
2042   case Stmt::ReturnStmtClass:
2043     //   - and exactly one return statement;
2044     if (isa<CXXConstructorDecl>(Dcl)) {
2045       // C++1y allows return statements in constexpr constructors.
2046       if (!Cxx1yLoc.isValid())
2047         Cxx1yLoc = S->getBeginLoc();
2048       return true;
2049     }
2050 
2051     ReturnStmts.push_back(S->getBeginLoc());
2052     return true;
2053 
2054   case Stmt::AttributedStmtClass:
2055     // Attributes on a statement don't affect its formal kind and hence don't
2056     // affect its validity in a constexpr function.
2057     return CheckConstexprFunctionStmt(SemaRef, Dcl,
2058                                       cast<AttributedStmt>(S)->getSubStmt(),
2059                                       ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind);
2060 
2061   case Stmt::CompoundStmtClass: {
2062     // C++1y allows compound-statements.
2063     if (!Cxx1yLoc.isValid())
2064       Cxx1yLoc = S->getBeginLoc();
2065 
2066     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2067     for (auto *BodyIt : CompStmt->body()) {
2068       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2069                                       Cxx1yLoc, Cxx2aLoc, Kind))
2070         return false;
2071     }
2072     return true;
2073   }
2074 
2075   case Stmt::IfStmtClass: {
2076     // C++1y allows if-statements.
2077     if (!Cxx1yLoc.isValid())
2078       Cxx1yLoc = S->getBeginLoc();
2079 
2080     IfStmt *If = cast<IfStmt>(S);
2081     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2082                                     Cxx1yLoc, Cxx2aLoc, Kind))
2083       return false;
2084     if (If->getElse() &&
2085         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2086                                     Cxx1yLoc, Cxx2aLoc, Kind))
2087       return false;
2088     return true;
2089   }
2090 
2091   case Stmt::WhileStmtClass:
2092   case Stmt::DoStmtClass:
2093   case Stmt::ForStmtClass:
2094   case Stmt::CXXForRangeStmtClass:
2095   case Stmt::ContinueStmtClass:
2096     // C++1y allows all of these. We don't allow them as extensions in C++11,
2097     // because they don't make sense without variable mutation.
2098     if (!SemaRef.getLangOpts().CPlusPlus14)
2099       break;
2100     if (!Cxx1yLoc.isValid())
2101       Cxx1yLoc = S->getBeginLoc();
2102     for (Stmt *SubStmt : S->children())
2103       if (SubStmt &&
2104           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2105                                       Cxx1yLoc, Cxx2aLoc, Kind))
2106         return false;
2107     return true;
2108 
2109   case Stmt::SwitchStmtClass:
2110   case Stmt::CaseStmtClass:
2111   case Stmt::DefaultStmtClass:
2112   case Stmt::BreakStmtClass:
2113     // C++1y allows switch-statements, and since they don't need variable
2114     // mutation, we can reasonably allow them in C++11 as an extension.
2115     if (!Cxx1yLoc.isValid())
2116       Cxx1yLoc = S->getBeginLoc();
2117     for (Stmt *SubStmt : S->children())
2118       if (SubStmt &&
2119           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2120                                       Cxx1yLoc, Cxx2aLoc, Kind))
2121         return false;
2122     return true;
2123 
2124   case Stmt::GCCAsmStmtClass:
2125   case Stmt::MSAsmStmtClass:
2126     // C++2a allows inline assembly statements.
2127   case Stmt::CXXTryStmtClass:
2128     if (Cxx2aLoc.isInvalid())
2129       Cxx2aLoc = S->getBeginLoc();
2130     for (Stmt *SubStmt : S->children()) {
2131       if (SubStmt &&
2132           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2133                                       Cxx1yLoc, Cxx2aLoc, Kind))
2134         return false;
2135     }
2136     return true;
2137 
2138   case Stmt::CXXCatchStmtClass:
2139     // Do not bother checking the language mode (already covered by the
2140     // try block check).
2141     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2142                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2143                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2144       return false;
2145     return true;
2146 
2147   default:
2148     if (!isa<Expr>(S))
2149       break;
2150 
2151     // C++1y allows expression-statements.
2152     if (!Cxx1yLoc.isValid())
2153       Cxx1yLoc = S->getBeginLoc();
2154     return true;
2155   }
2156 
2157   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2158     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2159         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2160   }
2161   return false;
2162 }
2163 
2164 /// Check the body for the given constexpr function declaration only contains
2165 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2166 ///
2167 /// \return true if the body is OK, false if we have found or diagnosed a
2168 /// problem.
2169 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2170                                        Stmt *Body,
2171                                        Sema::CheckConstexprKind Kind) {
2172   SmallVector<SourceLocation, 4> ReturnStmts;
2173 
2174   if (isa<CXXTryStmt>(Body)) {
2175     // C++11 [dcl.constexpr]p3:
2176     //  The definition of a constexpr function shall satisfy the following
2177     //  constraints: [...]
2178     // - its function-body shall be = delete, = default, or a
2179     //   compound-statement
2180     //
2181     // C++11 [dcl.constexpr]p4:
2182     //  In the definition of a constexpr constructor, [...]
2183     // - its function-body shall not be a function-try-block;
2184     //
2185     // This restriction is lifted in C++2a, as long as inner statements also
2186     // apply the general constexpr rules.
2187     switch (Kind) {
2188     case Sema::CheckConstexprKind::CheckValid:
2189       if (!SemaRef.getLangOpts().CPlusPlus20)
2190         return false;
2191       break;
2192 
2193     case Sema::CheckConstexprKind::Diagnose:
2194       SemaRef.Diag(Body->getBeginLoc(),
2195            !SemaRef.getLangOpts().CPlusPlus20
2196                ? diag::ext_constexpr_function_try_block_cxx20
2197                : diag::warn_cxx17_compat_constexpr_function_try_block)
2198           << isa<CXXConstructorDecl>(Dcl);
2199       break;
2200     }
2201   }
2202 
2203   // - its function-body shall be [...] a compound-statement that contains only
2204   //   [... list of cases ...]
2205   //
2206   // Note that walking the children here is enough to properly check for
2207   // CompoundStmt and CXXTryStmt body.
2208   SourceLocation Cxx1yLoc, Cxx2aLoc;
2209   for (Stmt *SubStmt : Body->children()) {
2210     if (SubStmt &&
2211         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2212                                     Cxx1yLoc, Cxx2aLoc, Kind))
2213       return false;
2214   }
2215 
2216   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2217     // If this is only valid as an extension, report that we don't satisfy the
2218     // constraints of the current language.
2219     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2220         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2221       return false;
2222   } else if (Cxx2aLoc.isValid()) {
2223     SemaRef.Diag(Cxx2aLoc,
2224          SemaRef.getLangOpts().CPlusPlus20
2225            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2226            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2227       << isa<CXXConstructorDecl>(Dcl);
2228   } else if (Cxx1yLoc.isValid()) {
2229     SemaRef.Diag(Cxx1yLoc,
2230          SemaRef.getLangOpts().CPlusPlus14
2231            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2232            : diag::ext_constexpr_body_invalid_stmt)
2233       << isa<CXXConstructorDecl>(Dcl);
2234   }
2235 
2236   if (const CXXConstructorDecl *Constructor
2237         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2238     const CXXRecordDecl *RD = Constructor->getParent();
2239     // DR1359:
2240     // - every non-variant non-static data member and base class sub-object
2241     //   shall be initialized;
2242     // DR1460:
2243     // - if the class is a union having variant members, exactly one of them
2244     //   shall be initialized;
2245     if (RD->isUnion()) {
2246       if (Constructor->getNumCtorInitializers() == 0 &&
2247           RD->hasVariantMembers()) {
2248         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2249           SemaRef.Diag(
2250               Dcl->getLocation(),
2251               SemaRef.getLangOpts().CPlusPlus20
2252                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2253                   : diag::ext_constexpr_union_ctor_no_init);
2254         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2255           return false;
2256         }
2257       }
2258     } else if (!Constructor->isDependentContext() &&
2259                !Constructor->isDelegatingConstructor()) {
2260       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2261 
2262       // Skip detailed checking if we have enough initializers, and we would
2263       // allow at most one initializer per member.
2264       bool AnyAnonStructUnionMembers = false;
2265       unsigned Fields = 0;
2266       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2267            E = RD->field_end(); I != E; ++I, ++Fields) {
2268         if (I->isAnonymousStructOrUnion()) {
2269           AnyAnonStructUnionMembers = true;
2270           break;
2271         }
2272       }
2273       // DR1460:
2274       // - if the class is a union-like class, but is not a union, for each of
2275       //   its anonymous union members having variant members, exactly one of
2276       //   them shall be initialized;
2277       if (AnyAnonStructUnionMembers ||
2278           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2279         // Check initialization of non-static data members. Base classes are
2280         // always initialized so do not need to be checked. Dependent bases
2281         // might not have initializers in the member initializer list.
2282         llvm::SmallSet<Decl*, 16> Inits;
2283         for (const auto *I: Constructor->inits()) {
2284           if (FieldDecl *FD = I->getMember())
2285             Inits.insert(FD);
2286           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2287             Inits.insert(ID->chain_begin(), ID->chain_end());
2288         }
2289 
2290         bool Diagnosed = false;
2291         for (auto *I : RD->fields())
2292           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2293                                              Kind))
2294             return false;
2295       }
2296     }
2297   } else {
2298     if (ReturnStmts.empty()) {
2299       // C++1y doesn't require constexpr functions to contain a 'return'
2300       // statement. We still do, unless the return type might be void, because
2301       // otherwise if there's no return statement, the function cannot
2302       // be used in a core constant expression.
2303       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2304                 (Dcl->getReturnType()->isVoidType() ||
2305                  Dcl->getReturnType()->isDependentType());
2306       switch (Kind) {
2307       case Sema::CheckConstexprKind::Diagnose:
2308         SemaRef.Diag(Dcl->getLocation(),
2309                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2310                         : diag::err_constexpr_body_no_return)
2311             << Dcl->isConsteval();
2312         if (!OK)
2313           return false;
2314         break;
2315 
2316       case Sema::CheckConstexprKind::CheckValid:
2317         // The formal requirements don't include this rule in C++14, even
2318         // though the "must be able to produce a constant expression" rules
2319         // still imply it in some cases.
2320         if (!SemaRef.getLangOpts().CPlusPlus14)
2321           return false;
2322         break;
2323       }
2324     } else if (ReturnStmts.size() > 1) {
2325       switch (Kind) {
2326       case Sema::CheckConstexprKind::Diagnose:
2327         SemaRef.Diag(
2328             ReturnStmts.back(),
2329             SemaRef.getLangOpts().CPlusPlus14
2330                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2331                 : diag::ext_constexpr_body_multiple_return);
2332         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2333           SemaRef.Diag(ReturnStmts[I],
2334                        diag::note_constexpr_body_previous_return);
2335         break;
2336 
2337       case Sema::CheckConstexprKind::CheckValid:
2338         if (!SemaRef.getLangOpts().CPlusPlus14)
2339           return false;
2340         break;
2341       }
2342     }
2343   }
2344 
2345   // C++11 [dcl.constexpr]p5:
2346   //   if no function argument values exist such that the function invocation
2347   //   substitution would produce a constant expression, the program is
2348   //   ill-formed; no diagnostic required.
2349   // C++11 [dcl.constexpr]p3:
2350   //   - every constructor call and implicit conversion used in initializing the
2351   //     return value shall be one of those allowed in a constant expression.
2352   // C++11 [dcl.constexpr]p4:
2353   //   - every constructor involved in initializing non-static data members and
2354   //     base class sub-objects shall be a constexpr constructor.
2355   //
2356   // Note that this rule is distinct from the "requirements for a constexpr
2357   // function", so is not checked in CheckValid mode.
2358   SmallVector<PartialDiagnosticAt, 8> Diags;
2359   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2360       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2361     SemaRef.Diag(Dcl->getLocation(),
2362                  diag::ext_constexpr_function_never_constant_expr)
2363         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2364     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2365       SemaRef.Diag(Diags[I].first, Diags[I].second);
2366     // Don't return false here: we allow this for compatibility in
2367     // system headers.
2368   }
2369 
2370   return true;
2371 }
2372 
2373 /// Get the class that is directly named by the current context. This is the
2374 /// class for which an unqualified-id in this scope could name a constructor
2375 /// or destructor.
2376 ///
2377 /// If the scope specifier denotes a class, this will be that class.
2378 /// If the scope specifier is empty, this will be the class whose
2379 /// member-specification we are currently within. Otherwise, there
2380 /// is no such class.
2381 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2382   assert(getLangOpts().CPlusPlus && "No class names in C!");
2383 
2384   if (SS && SS->isInvalid())
2385     return nullptr;
2386 
2387   if (SS && SS->isNotEmpty()) {
2388     DeclContext *DC = computeDeclContext(*SS, true);
2389     return dyn_cast_or_null<CXXRecordDecl>(DC);
2390   }
2391 
2392   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2393 }
2394 
2395 /// isCurrentClassName - Determine whether the identifier II is the
2396 /// name of the class type currently being defined. In the case of
2397 /// nested classes, this will only return true if II is the name of
2398 /// the innermost class.
2399 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2400                               const CXXScopeSpec *SS) {
2401   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2402   return CurDecl && &II == CurDecl->getIdentifier();
2403 }
2404 
2405 /// Determine whether the identifier II is a typo for the name of
2406 /// the class type currently being defined. If so, update it to the identifier
2407 /// that should have been used.
2408 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2409   assert(getLangOpts().CPlusPlus && "No class names in C!");
2410 
2411   if (!getLangOpts().SpellChecking)
2412     return false;
2413 
2414   CXXRecordDecl *CurDecl;
2415   if (SS && SS->isSet() && !SS->isInvalid()) {
2416     DeclContext *DC = computeDeclContext(*SS, true);
2417     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2418   } else
2419     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2420 
2421   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2422       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2423           < II->getLength()) {
2424     II = CurDecl->getIdentifier();
2425     return true;
2426   }
2427 
2428   return false;
2429 }
2430 
2431 /// Determine whether the given class is a base class of the given
2432 /// class, including looking at dependent bases.
2433 static bool findCircularInheritance(const CXXRecordDecl *Class,
2434                                     const CXXRecordDecl *Current) {
2435   SmallVector<const CXXRecordDecl*, 8> Queue;
2436 
2437   Class = Class->getCanonicalDecl();
2438   while (true) {
2439     for (const auto &I : Current->bases()) {
2440       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2441       if (!Base)
2442         continue;
2443 
2444       Base = Base->getDefinition();
2445       if (!Base)
2446         continue;
2447 
2448       if (Base->getCanonicalDecl() == Class)
2449         return true;
2450 
2451       Queue.push_back(Base);
2452     }
2453 
2454     if (Queue.empty())
2455       return false;
2456 
2457     Current = Queue.pop_back_val();
2458   }
2459 
2460   return false;
2461 }
2462 
2463 /// Check the validity of a C++ base class specifier.
2464 ///
2465 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2466 /// and returns NULL otherwise.
2467 CXXBaseSpecifier *
2468 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2469                          SourceRange SpecifierRange,
2470                          bool Virtual, AccessSpecifier Access,
2471                          TypeSourceInfo *TInfo,
2472                          SourceLocation EllipsisLoc) {
2473   QualType BaseType = TInfo->getType();
2474   if (BaseType->containsErrors()) {
2475     // Already emitted a diagnostic when parsing the error type.
2476     return nullptr;
2477   }
2478   // C++ [class.union]p1:
2479   //   A union shall not have base classes.
2480   if (Class->isUnion()) {
2481     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2482       << SpecifierRange;
2483     return nullptr;
2484   }
2485 
2486   if (EllipsisLoc.isValid() &&
2487       !TInfo->getType()->containsUnexpandedParameterPack()) {
2488     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2489       << TInfo->getTypeLoc().getSourceRange();
2490     EllipsisLoc = SourceLocation();
2491   }
2492 
2493   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2494 
2495   if (BaseType->isDependentType()) {
2496     // Make sure that we don't have circular inheritance among our dependent
2497     // bases. For non-dependent bases, the check for completeness below handles
2498     // this.
2499     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2500       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2501           ((BaseDecl = BaseDecl->getDefinition()) &&
2502            findCircularInheritance(Class, BaseDecl))) {
2503         Diag(BaseLoc, diag::err_circular_inheritance)
2504           << BaseType << Context.getTypeDeclType(Class);
2505 
2506         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2507           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2508             << BaseType;
2509 
2510         return nullptr;
2511       }
2512     }
2513 
2514     // Make sure that we don't make an ill-formed AST where the type of the
2515     // Class is non-dependent and its attached base class specifier is an
2516     // dependent type, which violates invariants in many clang code paths (e.g.
2517     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2518     // explicitly mark the Class decl invalid. The diagnostic was already
2519     // emitted.
2520     if (!Class->getTypeForDecl()->isDependentType())
2521       Class->setInvalidDecl();
2522     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2523                                           Class->getTagKind() == TTK_Class,
2524                                           Access, TInfo, EllipsisLoc);
2525   }
2526 
2527   // Base specifiers must be record types.
2528   if (!BaseType->isRecordType()) {
2529     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2530     return nullptr;
2531   }
2532 
2533   // C++ [class.union]p1:
2534   //   A union shall not be used as a base class.
2535   if (BaseType->isUnionType()) {
2536     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2537     return nullptr;
2538   }
2539 
2540   // For the MS ABI, propagate DLL attributes to base class templates.
2541   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2542     if (Attr *ClassAttr = getDLLAttr(Class)) {
2543       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2544               BaseType->getAsCXXRecordDecl())) {
2545         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2546                                             BaseLoc);
2547       }
2548     }
2549   }
2550 
2551   // C++ [class.derived]p2:
2552   //   The class-name in a base-specifier shall not be an incompletely
2553   //   defined class.
2554   if (RequireCompleteType(BaseLoc, BaseType,
2555                           diag::err_incomplete_base_class, SpecifierRange)) {
2556     Class->setInvalidDecl();
2557     return nullptr;
2558   }
2559 
2560   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2561   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2562   assert(BaseDecl && "Record type has no declaration");
2563   BaseDecl = BaseDecl->getDefinition();
2564   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2565   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2566   assert(CXXBaseDecl && "Base type is not a C++ type");
2567 
2568   // Microsoft docs say:
2569   // "If a base-class has a code_seg attribute, derived classes must have the
2570   // same attribute."
2571   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2572   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2573   if ((DerivedCSA || BaseCSA) &&
2574       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2575     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2576     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2577       << CXXBaseDecl;
2578     return nullptr;
2579   }
2580 
2581   // A class which contains a flexible array member is not suitable for use as a
2582   // base class:
2583   //   - If the layout determines that a base comes before another base,
2584   //     the flexible array member would index into the subsequent base.
2585   //   - If the layout determines that base comes before the derived class,
2586   //     the flexible array member would index into the derived class.
2587   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2588     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2589       << CXXBaseDecl->getDeclName();
2590     return nullptr;
2591   }
2592 
2593   // C++ [class]p3:
2594   //   If a class is marked final and it appears as a base-type-specifier in
2595   //   base-clause, the program is ill-formed.
2596   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2597     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2598       << CXXBaseDecl->getDeclName()
2599       << FA->isSpelledAsSealed();
2600     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2601         << CXXBaseDecl->getDeclName() << FA->getRange();
2602     return nullptr;
2603   }
2604 
2605   if (BaseDecl->isInvalidDecl())
2606     Class->setInvalidDecl();
2607 
2608   // Create the base specifier.
2609   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2610                                         Class->getTagKind() == TTK_Class,
2611                                         Access, TInfo, EllipsisLoc);
2612 }
2613 
2614 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2615 /// one entry in the base class list of a class specifier, for
2616 /// example:
2617 ///    class foo : public bar, virtual private baz {
2618 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2619 BaseResult
2620 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2621                          ParsedAttributes &Attributes,
2622                          bool Virtual, AccessSpecifier Access,
2623                          ParsedType basetype, SourceLocation BaseLoc,
2624                          SourceLocation EllipsisLoc) {
2625   if (!classdecl)
2626     return true;
2627 
2628   AdjustDeclIfTemplate(classdecl);
2629   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2630   if (!Class)
2631     return true;
2632 
2633   // We haven't yet attached the base specifiers.
2634   Class->setIsParsingBaseSpecifiers();
2635 
2636   // We do not support any C++11 attributes on base-specifiers yet.
2637   // Diagnose any attributes we see.
2638   for (const ParsedAttr &AL : Attributes) {
2639     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2640       continue;
2641     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2642                           ? (unsigned)diag::warn_unknown_attribute_ignored
2643                           : (unsigned)diag::err_base_specifier_attribute)
2644         << AL << AL.getRange();
2645   }
2646 
2647   TypeSourceInfo *TInfo = nullptr;
2648   GetTypeFromParser(basetype, &TInfo);
2649 
2650   if (EllipsisLoc.isInvalid() &&
2651       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2652                                       UPPC_BaseType))
2653     return true;
2654 
2655   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2656                                                       Virtual, Access, TInfo,
2657                                                       EllipsisLoc))
2658     return BaseSpec;
2659   else
2660     Class->setInvalidDecl();
2661 
2662   return true;
2663 }
2664 
2665 /// Use small set to collect indirect bases.  As this is only used
2666 /// locally, there's no need to abstract the small size parameter.
2667 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2668 
2669 /// Recursively add the bases of Type.  Don't add Type itself.
2670 static void
2671 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2672                   const QualType &Type)
2673 {
2674   // Even though the incoming type is a base, it might not be
2675   // a class -- it could be a template parm, for instance.
2676   if (auto Rec = Type->getAs<RecordType>()) {
2677     auto Decl = Rec->getAsCXXRecordDecl();
2678 
2679     // Iterate over its bases.
2680     for (const auto &BaseSpec : Decl->bases()) {
2681       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2682         .getUnqualifiedType();
2683       if (Set.insert(Base).second)
2684         // If we've not already seen it, recurse.
2685         NoteIndirectBases(Context, Set, Base);
2686     }
2687   }
2688 }
2689 
2690 /// Performs the actual work of attaching the given base class
2691 /// specifiers to a C++ class.
2692 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2693                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2694  if (Bases.empty())
2695     return false;
2696 
2697   // Used to keep track of which base types we have already seen, so
2698   // that we can properly diagnose redundant direct base types. Note
2699   // that the key is always the unqualified canonical type of the base
2700   // class.
2701   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2702 
2703   // Used to track indirect bases so we can see if a direct base is
2704   // ambiguous.
2705   IndirectBaseSet IndirectBaseTypes;
2706 
2707   // Copy non-redundant base specifiers into permanent storage.
2708   unsigned NumGoodBases = 0;
2709   bool Invalid = false;
2710   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2711     QualType NewBaseType
2712       = Context.getCanonicalType(Bases[idx]->getType());
2713     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2714 
2715     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2716     if (KnownBase) {
2717       // C++ [class.mi]p3:
2718       //   A class shall not be specified as a direct base class of a
2719       //   derived class more than once.
2720       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2721           << KnownBase->getType() << Bases[idx]->getSourceRange();
2722 
2723       // Delete the duplicate base class specifier; we're going to
2724       // overwrite its pointer later.
2725       Context.Deallocate(Bases[idx]);
2726 
2727       Invalid = true;
2728     } else {
2729       // Okay, add this new base class.
2730       KnownBase = Bases[idx];
2731       Bases[NumGoodBases++] = Bases[idx];
2732 
2733       // Note this base's direct & indirect bases, if there could be ambiguity.
2734       if (Bases.size() > 1)
2735         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2736 
2737       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2738         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2739         if (Class->isInterface() &&
2740               (!RD->isInterfaceLike() ||
2741                KnownBase->getAccessSpecifier() != AS_public)) {
2742           // The Microsoft extension __interface does not permit bases that
2743           // are not themselves public interfaces.
2744           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2745               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2746               << RD->getSourceRange();
2747           Invalid = true;
2748         }
2749         if (RD->hasAttr<WeakAttr>())
2750           Class->addAttr(WeakAttr::CreateImplicit(Context));
2751       }
2752     }
2753   }
2754 
2755   // Attach the remaining base class specifiers to the derived class.
2756   Class->setBases(Bases.data(), NumGoodBases);
2757 
2758   // Check that the only base classes that are duplicate are virtual.
2759   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2760     // Check whether this direct base is inaccessible due to ambiguity.
2761     QualType BaseType = Bases[idx]->getType();
2762 
2763     // Skip all dependent types in templates being used as base specifiers.
2764     // Checks below assume that the base specifier is a CXXRecord.
2765     if (BaseType->isDependentType())
2766       continue;
2767 
2768     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2769       .getUnqualifiedType();
2770 
2771     if (IndirectBaseTypes.count(CanonicalBase)) {
2772       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2773                          /*DetectVirtual=*/true);
2774       bool found
2775         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2776       assert(found);
2777       (void)found;
2778 
2779       if (Paths.isAmbiguous(CanonicalBase))
2780         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2781             << BaseType << getAmbiguousPathsDisplayString(Paths)
2782             << Bases[idx]->getSourceRange();
2783       else
2784         assert(Bases[idx]->isVirtual());
2785     }
2786 
2787     // Delete the base class specifier, since its data has been copied
2788     // into the CXXRecordDecl.
2789     Context.Deallocate(Bases[idx]);
2790   }
2791 
2792   return Invalid;
2793 }
2794 
2795 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2796 /// class, after checking whether there are any duplicate base
2797 /// classes.
2798 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2799                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2800   if (!ClassDecl || Bases.empty())
2801     return;
2802 
2803   AdjustDeclIfTemplate(ClassDecl);
2804   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2805 }
2806 
2807 /// Determine whether the type \p Derived is a C++ class that is
2808 /// derived from the type \p Base.
2809 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2810   if (!getLangOpts().CPlusPlus)
2811     return false;
2812 
2813   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2814   if (!DerivedRD)
2815     return false;
2816 
2817   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2818   if (!BaseRD)
2819     return false;
2820 
2821   // If either the base or the derived type is invalid, don't try to
2822   // check whether one is derived from the other.
2823   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2824     return false;
2825 
2826   // FIXME: In a modules build, do we need the entire path to be visible for us
2827   // to be able to use the inheritance relationship?
2828   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2829     return false;
2830 
2831   return DerivedRD->isDerivedFrom(BaseRD);
2832 }
2833 
2834 /// Determine whether the type \p Derived is a C++ class that is
2835 /// derived from the type \p Base.
2836 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2837                          CXXBasePaths &Paths) {
2838   if (!getLangOpts().CPlusPlus)
2839     return false;
2840 
2841   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2842   if (!DerivedRD)
2843     return false;
2844 
2845   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2846   if (!BaseRD)
2847     return false;
2848 
2849   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2850     return false;
2851 
2852   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2853 }
2854 
2855 static void BuildBasePathArray(const CXXBasePath &Path,
2856                                CXXCastPath &BasePathArray) {
2857   // We first go backward and check if we have a virtual base.
2858   // FIXME: It would be better if CXXBasePath had the base specifier for
2859   // the nearest virtual base.
2860   unsigned Start = 0;
2861   for (unsigned I = Path.size(); I != 0; --I) {
2862     if (Path[I - 1].Base->isVirtual()) {
2863       Start = I - 1;
2864       break;
2865     }
2866   }
2867 
2868   // Now add all bases.
2869   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2870     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2871 }
2872 
2873 
2874 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2875                               CXXCastPath &BasePathArray) {
2876   assert(BasePathArray.empty() && "Base path array must be empty!");
2877   assert(Paths.isRecordingPaths() && "Must record paths!");
2878   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2879 }
2880 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2881 /// conversion (where Derived and Base are class types) is
2882 /// well-formed, meaning that the conversion is unambiguous (and
2883 /// that all of the base classes are accessible). Returns true
2884 /// and emits a diagnostic if the code is ill-formed, returns false
2885 /// otherwise. Loc is the location where this routine should point to
2886 /// if there is an error, and Range is the source range to highlight
2887 /// if there is an error.
2888 ///
2889 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2890 /// diagnostic for the respective type of error will be suppressed, but the
2891 /// check for ill-formed code will still be performed.
2892 bool
2893 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2894                                    unsigned InaccessibleBaseID,
2895                                    unsigned AmbiguousBaseConvID,
2896                                    SourceLocation Loc, SourceRange Range,
2897                                    DeclarationName Name,
2898                                    CXXCastPath *BasePath,
2899                                    bool IgnoreAccess) {
2900   // First, determine whether the path from Derived to Base is
2901   // ambiguous. This is slightly more expensive than checking whether
2902   // the Derived to Base conversion exists, because here we need to
2903   // explore multiple paths to determine if there is an ambiguity.
2904   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2905                      /*DetectVirtual=*/false);
2906   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2907   if (!DerivationOkay)
2908     return true;
2909 
2910   const CXXBasePath *Path = nullptr;
2911   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2912     Path = &Paths.front();
2913 
2914   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2915   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2916   // user to access such bases.
2917   if (!Path && getLangOpts().MSVCCompat) {
2918     for (const CXXBasePath &PossiblePath : Paths) {
2919       if (PossiblePath.size() == 1) {
2920         Path = &PossiblePath;
2921         if (AmbiguousBaseConvID)
2922           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2923               << Base << Derived << Range;
2924         break;
2925       }
2926     }
2927   }
2928 
2929   if (Path) {
2930     if (!IgnoreAccess) {
2931       // Check that the base class can be accessed.
2932       switch (
2933           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2934       case AR_inaccessible:
2935         return true;
2936       case AR_accessible:
2937       case AR_dependent:
2938       case AR_delayed:
2939         break;
2940       }
2941     }
2942 
2943     // Build a base path if necessary.
2944     if (BasePath)
2945       ::BuildBasePathArray(*Path, *BasePath);
2946     return false;
2947   }
2948 
2949   if (AmbiguousBaseConvID) {
2950     // We know that the derived-to-base conversion is ambiguous, and
2951     // we're going to produce a diagnostic. Perform the derived-to-base
2952     // search just one more time to compute all of the possible paths so
2953     // that we can print them out. This is more expensive than any of
2954     // the previous derived-to-base checks we've done, but at this point
2955     // performance isn't as much of an issue.
2956     Paths.clear();
2957     Paths.setRecordingPaths(true);
2958     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2959     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2960     (void)StillOkay;
2961 
2962     // Build up a textual representation of the ambiguous paths, e.g.,
2963     // D -> B -> A, that will be used to illustrate the ambiguous
2964     // conversions in the diagnostic. We only print one of the paths
2965     // to each base class subobject.
2966     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2967 
2968     Diag(Loc, AmbiguousBaseConvID)
2969     << Derived << Base << PathDisplayStr << Range << Name;
2970   }
2971   return true;
2972 }
2973 
2974 bool
2975 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2976                                    SourceLocation Loc, SourceRange Range,
2977                                    CXXCastPath *BasePath,
2978                                    bool IgnoreAccess) {
2979   return CheckDerivedToBaseConversion(
2980       Derived, Base, diag::err_upcast_to_inaccessible_base,
2981       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2982       BasePath, IgnoreAccess);
2983 }
2984 
2985 
2986 /// Builds a string representing ambiguous paths from a
2987 /// specific derived class to different subobjects of the same base
2988 /// class.
2989 ///
2990 /// This function builds a string that can be used in error messages
2991 /// to show the different paths that one can take through the
2992 /// inheritance hierarchy to go from the derived class to different
2993 /// subobjects of a base class. The result looks something like this:
2994 /// @code
2995 /// struct D -> struct B -> struct A
2996 /// struct D -> struct C -> struct A
2997 /// @endcode
2998 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2999   std::string PathDisplayStr;
3000   std::set<unsigned> DisplayedPaths;
3001   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3002        Path != Paths.end(); ++Path) {
3003     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3004       // We haven't displayed a path to this particular base
3005       // class subobject yet.
3006       PathDisplayStr += "\n    ";
3007       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3008       for (CXXBasePath::const_iterator Element = Path->begin();
3009            Element != Path->end(); ++Element)
3010         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3011     }
3012   }
3013 
3014   return PathDisplayStr;
3015 }
3016 
3017 //===----------------------------------------------------------------------===//
3018 // C++ class member Handling
3019 //===----------------------------------------------------------------------===//
3020 
3021 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3022 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3023                                 SourceLocation ColonLoc,
3024                                 const ParsedAttributesView &Attrs) {
3025   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3026   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3027                                                   ASLoc, ColonLoc);
3028   CurContext->addHiddenDecl(ASDecl);
3029   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3030 }
3031 
3032 /// CheckOverrideControl - Check C++11 override control semantics.
3033 void Sema::CheckOverrideControl(NamedDecl *D) {
3034   if (D->isInvalidDecl())
3035     return;
3036 
3037   // We only care about "override" and "final" declarations.
3038   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3039     return;
3040 
3041   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3042 
3043   // We can't check dependent instance methods.
3044   if (MD && MD->isInstance() &&
3045       (MD->getParent()->hasAnyDependentBases() ||
3046        MD->getType()->isDependentType()))
3047     return;
3048 
3049   if (MD && !MD->isVirtual()) {
3050     // If we have a non-virtual method, check if if hides a virtual method.
3051     // (In that case, it's most likely the method has the wrong type.)
3052     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3053     FindHiddenVirtualMethods(MD, OverloadedMethods);
3054 
3055     if (!OverloadedMethods.empty()) {
3056       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3057         Diag(OA->getLocation(),
3058              diag::override_keyword_hides_virtual_member_function)
3059           << "override" << (OverloadedMethods.size() > 1);
3060       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3061         Diag(FA->getLocation(),
3062              diag::override_keyword_hides_virtual_member_function)
3063           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3064           << (OverloadedMethods.size() > 1);
3065       }
3066       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3067       MD->setInvalidDecl();
3068       return;
3069     }
3070     // Fall through into the general case diagnostic.
3071     // FIXME: We might want to attempt typo correction here.
3072   }
3073 
3074   if (!MD || !MD->isVirtual()) {
3075     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3076       Diag(OA->getLocation(),
3077            diag::override_keyword_only_allowed_on_virtual_member_functions)
3078         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3079       D->dropAttr<OverrideAttr>();
3080     }
3081     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3082       Diag(FA->getLocation(),
3083            diag::override_keyword_only_allowed_on_virtual_member_functions)
3084         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3085         << FixItHint::CreateRemoval(FA->getLocation());
3086       D->dropAttr<FinalAttr>();
3087     }
3088     return;
3089   }
3090 
3091   // C++11 [class.virtual]p5:
3092   //   If a function is marked with the virt-specifier override and
3093   //   does not override a member function of a base class, the program is
3094   //   ill-formed.
3095   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3096   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3097     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3098       << MD->getDeclName();
3099 }
3100 
3101 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3102   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3103     return;
3104   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3105   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3106     return;
3107 
3108   SourceLocation Loc = MD->getLocation();
3109   SourceLocation SpellingLoc = Loc;
3110   if (getSourceManager().isMacroArgExpansion(Loc))
3111     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3112   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3113   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3114       return;
3115 
3116   if (MD->size_overridden_methods() > 0) {
3117     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3118       unsigned DiagID =
3119           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3120               ? DiagInconsistent
3121               : DiagSuggest;
3122       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3123       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3124       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3125     };
3126     if (isa<CXXDestructorDecl>(MD))
3127       EmitDiag(
3128           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3129           diag::warn_suggest_destructor_marked_not_override_overriding);
3130     else
3131       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3132                diag::warn_suggest_function_marked_not_override_overriding);
3133   }
3134 }
3135 
3136 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3137 /// function overrides a virtual member function marked 'final', according to
3138 /// C++11 [class.virtual]p4.
3139 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3140                                                   const CXXMethodDecl *Old) {
3141   FinalAttr *FA = Old->getAttr<FinalAttr>();
3142   if (!FA)
3143     return false;
3144 
3145   Diag(New->getLocation(), diag::err_final_function_overridden)
3146     << New->getDeclName()
3147     << FA->isSpelledAsSealed();
3148   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3149   return true;
3150 }
3151 
3152 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3153   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3154   // FIXME: Destruction of ObjC lifetime types has side-effects.
3155   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3156     return !RD->isCompleteDefinition() ||
3157            !RD->hasTrivialDefaultConstructor() ||
3158            !RD->hasTrivialDestructor();
3159   return false;
3160 }
3161 
3162 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3163   ParsedAttributesView::const_iterator Itr =
3164       llvm::find_if(list, [](const ParsedAttr &AL) {
3165         return AL.isDeclspecPropertyAttribute();
3166       });
3167   if (Itr != list.end())
3168     return &*Itr;
3169   return nullptr;
3170 }
3171 
3172 // Check if there is a field shadowing.
3173 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3174                                       DeclarationName FieldName,
3175                                       const CXXRecordDecl *RD,
3176                                       bool DeclIsField) {
3177   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3178     return;
3179 
3180   // To record a shadowed field in a base
3181   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3182   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3183                            CXXBasePath &Path) {
3184     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3185     // Record an ambiguous path directly
3186     if (Bases.find(Base) != Bases.end())
3187       return true;
3188     for (const auto Field : Base->lookup(FieldName)) {
3189       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3190           Field->getAccess() != AS_private) {
3191         assert(Field->getAccess() != AS_none);
3192         assert(Bases.find(Base) == Bases.end());
3193         Bases[Base] = Field;
3194         return true;
3195       }
3196     }
3197     return false;
3198   };
3199 
3200   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3201                      /*DetectVirtual=*/true);
3202   if (!RD->lookupInBases(FieldShadowed, Paths))
3203     return;
3204 
3205   for (const auto &P : Paths) {
3206     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3207     auto It = Bases.find(Base);
3208     // Skip duplicated bases
3209     if (It == Bases.end())
3210       continue;
3211     auto BaseField = It->second;
3212     assert(BaseField->getAccess() != AS_private);
3213     if (AS_none !=
3214         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3215       Diag(Loc, diag::warn_shadow_field)
3216         << FieldName << RD << Base << DeclIsField;
3217       Diag(BaseField->getLocation(), diag::note_shadow_field);
3218       Bases.erase(It);
3219     }
3220   }
3221 }
3222 
3223 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3224 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3225 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3226 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3227 /// present (but parsing it has been deferred).
3228 NamedDecl *
3229 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3230                                MultiTemplateParamsArg TemplateParameterLists,
3231                                Expr *BW, const VirtSpecifiers &VS,
3232                                InClassInitStyle InitStyle) {
3233   const DeclSpec &DS = D.getDeclSpec();
3234   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3235   DeclarationName Name = NameInfo.getName();
3236   SourceLocation Loc = NameInfo.getLoc();
3237 
3238   // For anonymous bitfields, the location should point to the type.
3239   if (Loc.isInvalid())
3240     Loc = D.getBeginLoc();
3241 
3242   Expr *BitWidth = static_cast<Expr*>(BW);
3243 
3244   assert(isa<CXXRecordDecl>(CurContext));
3245   assert(!DS.isFriendSpecified());
3246 
3247   bool isFunc = D.isDeclarationOfFunction();
3248   const ParsedAttr *MSPropertyAttr =
3249       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3250 
3251   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3252     // The Microsoft extension __interface only permits public member functions
3253     // and prohibits constructors, destructors, operators, non-public member
3254     // functions, static methods and data members.
3255     unsigned InvalidDecl;
3256     bool ShowDeclName = true;
3257     if (!isFunc &&
3258         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3259       InvalidDecl = 0;
3260     else if (!isFunc)
3261       InvalidDecl = 1;
3262     else if (AS != AS_public)
3263       InvalidDecl = 2;
3264     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3265       InvalidDecl = 3;
3266     else switch (Name.getNameKind()) {
3267       case DeclarationName::CXXConstructorName:
3268         InvalidDecl = 4;
3269         ShowDeclName = false;
3270         break;
3271 
3272       case DeclarationName::CXXDestructorName:
3273         InvalidDecl = 5;
3274         ShowDeclName = false;
3275         break;
3276 
3277       case DeclarationName::CXXOperatorName:
3278       case DeclarationName::CXXConversionFunctionName:
3279         InvalidDecl = 6;
3280         break;
3281 
3282       default:
3283         InvalidDecl = 0;
3284         break;
3285     }
3286 
3287     if (InvalidDecl) {
3288       if (ShowDeclName)
3289         Diag(Loc, diag::err_invalid_member_in_interface)
3290           << (InvalidDecl-1) << Name;
3291       else
3292         Diag(Loc, diag::err_invalid_member_in_interface)
3293           << (InvalidDecl-1) << "";
3294       return nullptr;
3295     }
3296   }
3297 
3298   // C++ 9.2p6: A member shall not be declared to have automatic storage
3299   // duration (auto, register) or with the extern storage-class-specifier.
3300   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3301   // data members and cannot be applied to names declared const or static,
3302   // and cannot be applied to reference members.
3303   switch (DS.getStorageClassSpec()) {
3304   case DeclSpec::SCS_unspecified:
3305   case DeclSpec::SCS_typedef:
3306   case DeclSpec::SCS_static:
3307     break;
3308   case DeclSpec::SCS_mutable:
3309     if (isFunc) {
3310       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3311 
3312       // FIXME: It would be nicer if the keyword was ignored only for this
3313       // declarator. Otherwise we could get follow-up errors.
3314       D.getMutableDeclSpec().ClearStorageClassSpecs();
3315     }
3316     break;
3317   default:
3318     Diag(DS.getStorageClassSpecLoc(),
3319          diag::err_storageclass_invalid_for_member);
3320     D.getMutableDeclSpec().ClearStorageClassSpecs();
3321     break;
3322   }
3323 
3324   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3325                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3326                       !isFunc);
3327 
3328   if (DS.hasConstexprSpecifier() && isInstField) {
3329     SemaDiagnosticBuilder B =
3330         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3331     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3332     if (InitStyle == ICIS_NoInit) {
3333       B << 0 << 0;
3334       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3335         B << FixItHint::CreateRemoval(ConstexprLoc);
3336       else {
3337         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3338         D.getMutableDeclSpec().ClearConstexprSpec();
3339         const char *PrevSpec;
3340         unsigned DiagID;
3341         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3342             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3343         (void)Failed;
3344         assert(!Failed && "Making a constexpr member const shouldn't fail");
3345       }
3346     } else {
3347       B << 1;
3348       const char *PrevSpec;
3349       unsigned DiagID;
3350       if (D.getMutableDeclSpec().SetStorageClassSpec(
3351           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3352           Context.getPrintingPolicy())) {
3353         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3354                "This is the only DeclSpec that should fail to be applied");
3355         B << 1;
3356       } else {
3357         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3358         isInstField = false;
3359       }
3360     }
3361   }
3362 
3363   NamedDecl *Member;
3364   if (isInstField) {
3365     CXXScopeSpec &SS = D.getCXXScopeSpec();
3366 
3367     // Data members must have identifiers for names.
3368     if (!Name.isIdentifier()) {
3369       Diag(Loc, diag::err_bad_variable_name)
3370         << Name;
3371       return nullptr;
3372     }
3373 
3374     IdentifierInfo *II = Name.getAsIdentifierInfo();
3375 
3376     // Member field could not be with "template" keyword.
3377     // So TemplateParameterLists should be empty in this case.
3378     if (TemplateParameterLists.size()) {
3379       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3380       if (TemplateParams->size()) {
3381         // There is no such thing as a member field template.
3382         Diag(D.getIdentifierLoc(), diag::err_template_member)
3383             << II
3384             << SourceRange(TemplateParams->getTemplateLoc(),
3385                 TemplateParams->getRAngleLoc());
3386       } else {
3387         // There is an extraneous 'template<>' for this member.
3388         Diag(TemplateParams->getTemplateLoc(),
3389             diag::err_template_member_noparams)
3390             << II
3391             << SourceRange(TemplateParams->getTemplateLoc(),
3392                 TemplateParams->getRAngleLoc());
3393       }
3394       return nullptr;
3395     }
3396 
3397     if (SS.isSet() && !SS.isInvalid()) {
3398       // The user provided a superfluous scope specifier inside a class
3399       // definition:
3400       //
3401       // class X {
3402       //   int X::member;
3403       // };
3404       if (DeclContext *DC = computeDeclContext(SS, false))
3405         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3406                                      D.getName().getKind() ==
3407                                          UnqualifiedIdKind::IK_TemplateId);
3408       else
3409         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3410           << Name << SS.getRange();
3411 
3412       SS.clear();
3413     }
3414 
3415     if (MSPropertyAttr) {
3416       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3417                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3418       if (!Member)
3419         return nullptr;
3420       isInstField = false;
3421     } else {
3422       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3423                                 BitWidth, InitStyle, AS);
3424       if (!Member)
3425         return nullptr;
3426     }
3427 
3428     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3429   } else {
3430     Member = HandleDeclarator(S, D, TemplateParameterLists);
3431     if (!Member)
3432       return nullptr;
3433 
3434     // Non-instance-fields can't have a bitfield.
3435     if (BitWidth) {
3436       if (Member->isInvalidDecl()) {
3437         // don't emit another diagnostic.
3438       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3439         // C++ 9.6p3: A bit-field shall not be a static member.
3440         // "static member 'A' cannot be a bit-field"
3441         Diag(Loc, diag::err_static_not_bitfield)
3442           << Name << BitWidth->getSourceRange();
3443       } else if (isa<TypedefDecl>(Member)) {
3444         // "typedef member 'x' cannot be a bit-field"
3445         Diag(Loc, diag::err_typedef_not_bitfield)
3446           << Name << BitWidth->getSourceRange();
3447       } else {
3448         // A function typedef ("typedef int f(); f a;").
3449         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3450         Diag(Loc, diag::err_not_integral_type_bitfield)
3451           << Name << cast<ValueDecl>(Member)->getType()
3452           << BitWidth->getSourceRange();
3453       }
3454 
3455       BitWidth = nullptr;
3456       Member->setInvalidDecl();
3457     }
3458 
3459     NamedDecl *NonTemplateMember = Member;
3460     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3461       NonTemplateMember = FunTmpl->getTemplatedDecl();
3462     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3463       NonTemplateMember = VarTmpl->getTemplatedDecl();
3464 
3465     Member->setAccess(AS);
3466 
3467     // If we have declared a member function template or static data member
3468     // template, set the access of the templated declaration as well.
3469     if (NonTemplateMember != Member)
3470       NonTemplateMember->setAccess(AS);
3471 
3472     // C++ [temp.deduct.guide]p3:
3473     //   A deduction guide [...] for a member class template [shall be
3474     //   declared] with the same access [as the template].
3475     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3476       auto *TD = DG->getDeducedTemplate();
3477       // Access specifiers are only meaningful if both the template and the
3478       // deduction guide are from the same scope.
3479       if (AS != TD->getAccess() &&
3480           TD->getDeclContext()->getRedeclContext()->Equals(
3481               DG->getDeclContext()->getRedeclContext())) {
3482         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3483         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3484             << TD->getAccess();
3485         const AccessSpecDecl *LastAccessSpec = nullptr;
3486         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3487           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3488             LastAccessSpec = AccessSpec;
3489         }
3490         assert(LastAccessSpec && "differing access with no access specifier");
3491         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3492             << AS;
3493       }
3494     }
3495   }
3496 
3497   if (VS.isOverrideSpecified())
3498     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3499                                          AttributeCommonInfo::AS_Keyword));
3500   if (VS.isFinalSpecified())
3501     Member->addAttr(FinalAttr::Create(
3502         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3503         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3504 
3505   if (VS.getLastLocation().isValid()) {
3506     // Update the end location of a method that has a virt-specifiers.
3507     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3508       MD->setRangeEnd(VS.getLastLocation());
3509   }
3510 
3511   CheckOverrideControl(Member);
3512 
3513   assert((Name || isInstField) && "No identifier for non-field ?");
3514 
3515   if (isInstField) {
3516     FieldDecl *FD = cast<FieldDecl>(Member);
3517     FieldCollector->Add(FD);
3518 
3519     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3520       // Remember all explicit private FieldDecls that have a name, no side
3521       // effects and are not part of a dependent type declaration.
3522       if (!FD->isImplicit() && FD->getDeclName() &&
3523           FD->getAccess() == AS_private &&
3524           !FD->hasAttr<UnusedAttr>() &&
3525           !FD->getParent()->isDependentContext() &&
3526           !InitializationHasSideEffects(*FD))
3527         UnusedPrivateFields.insert(FD);
3528     }
3529   }
3530 
3531   return Member;
3532 }
3533 
3534 namespace {
3535   class UninitializedFieldVisitor
3536       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3537     Sema &S;
3538     // List of Decls to generate a warning on.  Also remove Decls that become
3539     // initialized.
3540     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3541     // List of base classes of the record.  Classes are removed after their
3542     // initializers.
3543     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3544     // Vector of decls to be removed from the Decl set prior to visiting the
3545     // nodes.  These Decls may have been initialized in the prior initializer.
3546     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3547     // If non-null, add a note to the warning pointing back to the constructor.
3548     const CXXConstructorDecl *Constructor;
3549     // Variables to hold state when processing an initializer list.  When
3550     // InitList is true, special case initialization of FieldDecls matching
3551     // InitListFieldDecl.
3552     bool InitList;
3553     FieldDecl *InitListFieldDecl;
3554     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3555 
3556   public:
3557     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3558     UninitializedFieldVisitor(Sema &S,
3559                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3560                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3561       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3562         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3563 
3564     // Returns true if the use of ME is not an uninitialized use.
3565     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3566                                          bool CheckReferenceOnly) {
3567       llvm::SmallVector<FieldDecl*, 4> Fields;
3568       bool ReferenceField = false;
3569       while (ME) {
3570         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3571         if (!FD)
3572           return false;
3573         Fields.push_back(FD);
3574         if (FD->getType()->isReferenceType())
3575           ReferenceField = true;
3576         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3577       }
3578 
3579       // Binding a reference to an uninitialized field is not an
3580       // uninitialized use.
3581       if (CheckReferenceOnly && !ReferenceField)
3582         return true;
3583 
3584       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3585       // Discard the first field since it is the field decl that is being
3586       // initialized.
3587       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3588         UsedFieldIndex.push_back((*I)->getFieldIndex());
3589       }
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(), DS.getTypeSpecTypeLoc());
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   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8439   assert(RD && "defaulted comparison is not defaulted in a class");
8440 
8441   // Perform any unqualified lookups we're going to need to default this
8442   // function.
8443   if (S) {
8444     UnresolvedSet<32> Operators;
8445     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8446                                           FD->getOverloadedOperator());
8447     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8448         Context, Operators.pairs()));
8449   }
8450 
8451   // C++2a [class.compare.default]p1:
8452   //   A defaulted comparison operator function for some class C shall be a
8453   //   non-template function declared in the member-specification of C that is
8454   //    -- a non-static const member of C having one parameter of type
8455   //       const C&, or
8456   //    -- a friend of C having two parameters of type const C& or two
8457   //       parameters of type C.
8458   QualType ExpectedParmType1 = Context.getRecordType(RD);
8459   QualType ExpectedParmType2 =
8460       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8461   if (isa<CXXMethodDecl>(FD))
8462     ExpectedParmType1 = ExpectedParmType2;
8463   for (const ParmVarDecl *Param : FD->parameters()) {
8464     if (!Param->getType()->isDependentType() &&
8465         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8466         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8467       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8468       // corresponding defaulted 'operator<=>' already.
8469       if (!FD->isImplicit()) {
8470         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8471             << (int)DCK << Param->getType() << ExpectedParmType1
8472             << !isa<CXXMethodDecl>(FD)
8473             << ExpectedParmType2 << Param->getSourceRange();
8474       }
8475       return true;
8476     }
8477   }
8478   if (FD->getNumParams() == 2 &&
8479       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8480                            FD->getParamDecl(1)->getType())) {
8481     if (!FD->isImplicit()) {
8482       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8483           << (int)DCK
8484           << FD->getParamDecl(0)->getType()
8485           << FD->getParamDecl(0)->getSourceRange()
8486           << FD->getParamDecl(1)->getType()
8487           << FD->getParamDecl(1)->getSourceRange();
8488     }
8489     return true;
8490   }
8491 
8492   // ... non-static const member ...
8493   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8494     assert(!MD->isStatic() && "comparison function cannot be a static member");
8495     if (!MD->isConst()) {
8496       SourceLocation InsertLoc;
8497       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8498         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8499       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8500       // corresponding defaulted 'operator<=>' already.
8501       if (!MD->isImplicit()) {
8502         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8503           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8504       }
8505 
8506       // Add the 'const' to the type to recover.
8507       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8508       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8509       EPI.TypeQuals.addConst();
8510       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8511                                           FPT->getParamTypes(), EPI));
8512     }
8513   } else {
8514     // A non-member function declared in a class must be a friend.
8515     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8516   }
8517 
8518   // C++2a [class.eq]p1, [class.rel]p1:
8519   //   A [defaulted comparison other than <=>] shall have a declared return
8520   //   type bool.
8521   if (DCK != DefaultedComparisonKind::ThreeWay &&
8522       !FD->getDeclaredReturnType()->isDependentType() &&
8523       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8524     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8525         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8526         << FD->getReturnTypeSourceRange();
8527     return true;
8528   }
8529   // C++2a [class.spaceship]p2 [P2002R0]:
8530   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8531   //   R shall not contain a placeholder type.
8532   if (DCK == DefaultedComparisonKind::ThreeWay &&
8533       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8534       !Context.hasSameType(FD->getDeclaredReturnType(),
8535                            Context.getAutoDeductType())) {
8536     Diag(FD->getLocation(),
8537          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8538         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8539         << FD->getReturnTypeSourceRange();
8540     return true;
8541   }
8542 
8543   // For a defaulted function in a dependent class, defer all remaining checks
8544   // until instantiation.
8545   if (RD->isDependentType())
8546     return false;
8547 
8548   // Determine whether the function should be defined as deleted.
8549   DefaultedComparisonInfo Info =
8550       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8551 
8552   bool First = FD == FD->getCanonicalDecl();
8553 
8554   // If we want to delete the function, then do so; there's nothing else to
8555   // check in that case.
8556   if (Info.Deleted) {
8557     if (!First) {
8558       // C++11 [dcl.fct.def.default]p4:
8559       //   [For a] user-provided explicitly-defaulted function [...] if such a
8560       //   function is implicitly defined as deleted, the program is ill-formed.
8561       //
8562       // This is really just a consequence of the general rule that you can
8563       // only delete a function on its first declaration.
8564       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8565           << FD->isImplicit() << (int)DCK;
8566       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8567                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8568           .visit();
8569       return true;
8570     }
8571 
8572     SetDeclDeleted(FD, FD->getLocation());
8573     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8574       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8575           << (int)DCK;
8576       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8577                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8578           .visit();
8579     }
8580     return false;
8581   }
8582 
8583   // C++2a [class.spaceship]p2:
8584   //   The return type is deduced as the common comparison type of R0, R1, ...
8585   if (DCK == DefaultedComparisonKind::ThreeWay &&
8586       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8587     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8588     if (RetLoc.isInvalid())
8589       RetLoc = FD->getBeginLoc();
8590     // FIXME: Should we really care whether we have the complete type and the
8591     // 'enumerator' constants here? A forward declaration seems sufficient.
8592     QualType Cat = CheckComparisonCategoryType(
8593         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8594     if (Cat.isNull())
8595       return true;
8596     Context.adjustDeducedFunctionResultType(
8597         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8598   }
8599 
8600   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8601   //   An explicitly-defaulted function that is not defined as deleted may be
8602   //   declared constexpr or consteval only if it is constexpr-compatible.
8603   // C++2a [class.compare.default]p3 [P2002R0]:
8604   //   A defaulted comparison function is constexpr-compatible if it satisfies
8605   //   the requirements for a constexpr function [...]
8606   // The only relevant requirements are that the parameter and return types are
8607   // literal types. The remaining conditions are checked by the analyzer.
8608   if (FD->isConstexpr()) {
8609     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8610         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8611         !Info.Constexpr) {
8612       Diag(FD->getBeginLoc(),
8613            diag::err_incorrect_defaulted_comparison_constexpr)
8614           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8615       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8616                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8617           .visit();
8618     }
8619   }
8620 
8621   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8622   //   If a constexpr-compatible function is explicitly defaulted on its first
8623   //   declaration, it is implicitly considered to be constexpr.
8624   // FIXME: Only applying this to the first declaration seems problematic, as
8625   // simple reorderings can affect the meaning of the program.
8626   if (First && !FD->isConstexpr() && Info.Constexpr)
8627     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8628 
8629   // C++2a [except.spec]p3:
8630   //   If a declaration of a function does not have a noexcept-specifier
8631   //   [and] is defaulted on its first declaration, [...] the exception
8632   //   specification is as specified below
8633   if (FD->getExceptionSpecType() == EST_None) {
8634     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8635     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8636     EPI.ExceptionSpec.Type = EST_Unevaluated;
8637     EPI.ExceptionSpec.SourceDecl = FD;
8638     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8639                                         FPT->getParamTypes(), EPI));
8640   }
8641 
8642   return false;
8643 }
8644 
8645 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8646                                              FunctionDecl *Spaceship) {
8647   Sema::CodeSynthesisContext Ctx;
8648   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8649   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8650   Ctx.Entity = Spaceship;
8651   pushCodeSynthesisContext(Ctx);
8652 
8653   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8654     EqualEqual->setImplicit();
8655 
8656   popCodeSynthesisContext();
8657 }
8658 
8659 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8660                                      DefaultedComparisonKind DCK) {
8661   assert(FD->isDefaulted() && !FD->isDeleted() &&
8662          !FD->doesThisDeclarationHaveABody());
8663   if (FD->willHaveBody() || FD->isInvalidDecl())
8664     return;
8665 
8666   SynthesizedFunctionScope Scope(*this, FD);
8667 
8668   // Add a context note for diagnostics produced after this point.
8669   Scope.addContextNote(UseLoc);
8670 
8671   {
8672     // Build and set up the function body.
8673     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8674     SourceLocation BodyLoc =
8675         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8676     StmtResult Body =
8677         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8678     if (Body.isInvalid()) {
8679       FD->setInvalidDecl();
8680       return;
8681     }
8682     FD->setBody(Body.get());
8683     FD->markUsed(Context);
8684   }
8685 
8686   // The exception specification is needed because we are defining the
8687   // function. Note that this will reuse the body we just built.
8688   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8689 
8690   if (ASTMutationListener *L = getASTMutationListener())
8691     L->CompletedImplicitDefinition(FD);
8692 }
8693 
8694 static Sema::ImplicitExceptionSpecification
8695 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8696                                         FunctionDecl *FD,
8697                                         Sema::DefaultedComparisonKind DCK) {
8698   ComputingExceptionSpec CES(S, FD, Loc);
8699   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8700 
8701   if (FD->isInvalidDecl())
8702     return ExceptSpec;
8703 
8704   // The common case is that we just defined the comparison function. In that
8705   // case, just look at whether the body can throw.
8706   if (FD->hasBody()) {
8707     ExceptSpec.CalledStmt(FD->getBody());
8708   } else {
8709     // Otherwise, build a body so we can check it. This should ideally only
8710     // happen when we're not actually marking the function referenced. (This is
8711     // only really important for efficiency: we don't want to build and throw
8712     // away bodies for comparison functions more than we strictly need to.)
8713 
8714     // Pretend to synthesize the function body in an unevaluated context.
8715     // Note that we can't actually just go ahead and define the function here:
8716     // we are not permitted to mark its callees as referenced.
8717     Sema::SynthesizedFunctionScope Scope(S, FD);
8718     EnterExpressionEvaluationContext Context(
8719         S, Sema::ExpressionEvaluationContext::Unevaluated);
8720 
8721     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8722     SourceLocation BodyLoc =
8723         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8724     StmtResult Body =
8725         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8726     if (!Body.isInvalid())
8727       ExceptSpec.CalledStmt(Body.get());
8728 
8729     // FIXME: Can we hold onto this body and just transform it to potentially
8730     // evaluated when we're asked to define the function rather than rebuilding
8731     // it? Either that, or we should only build the bits of the body that we
8732     // need (the expressions, not the statements).
8733   }
8734 
8735   return ExceptSpec;
8736 }
8737 
8738 void Sema::CheckDelayedMemberExceptionSpecs() {
8739   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8740   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8741 
8742   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8743   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8744 
8745   // Perform any deferred checking of exception specifications for virtual
8746   // destructors.
8747   for (auto &Check : Overriding)
8748     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8749 
8750   // Perform any deferred checking of exception specifications for befriended
8751   // special members.
8752   for (auto &Check : Equivalent)
8753     CheckEquivalentExceptionSpec(Check.second, Check.first);
8754 }
8755 
8756 namespace {
8757 /// CRTP base class for visiting operations performed by a special member
8758 /// function (or inherited constructor).
8759 template<typename Derived>
8760 struct SpecialMemberVisitor {
8761   Sema &S;
8762   CXXMethodDecl *MD;
8763   Sema::CXXSpecialMember CSM;
8764   Sema::InheritedConstructorInfo *ICI;
8765 
8766   // Properties of the special member, computed for convenience.
8767   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8768 
8769   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8770                        Sema::InheritedConstructorInfo *ICI)
8771       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8772     switch (CSM) {
8773     case Sema::CXXDefaultConstructor:
8774     case Sema::CXXCopyConstructor:
8775     case Sema::CXXMoveConstructor:
8776       IsConstructor = true;
8777       break;
8778     case Sema::CXXCopyAssignment:
8779     case Sema::CXXMoveAssignment:
8780       IsAssignment = true;
8781       break;
8782     case Sema::CXXDestructor:
8783       break;
8784     case Sema::CXXInvalid:
8785       llvm_unreachable("invalid special member kind");
8786     }
8787 
8788     if (MD->getNumParams()) {
8789       if (const ReferenceType *RT =
8790               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8791         ConstArg = RT->getPointeeType().isConstQualified();
8792     }
8793   }
8794 
8795   Derived &getDerived() { return static_cast<Derived&>(*this); }
8796 
8797   /// Is this a "move" special member?
8798   bool isMove() const {
8799     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8800   }
8801 
8802   /// Look up the corresponding special member in the given class.
8803   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8804                                              unsigned Quals, bool IsMutable) {
8805     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8806                                        ConstArg && !IsMutable);
8807   }
8808 
8809   /// Look up the constructor for the specified base class to see if it's
8810   /// overridden due to this being an inherited constructor.
8811   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8812     if (!ICI)
8813       return {};
8814     assert(CSM == Sema::CXXDefaultConstructor);
8815     auto *BaseCtor =
8816       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8817     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8818       return MD;
8819     return {};
8820   }
8821 
8822   /// A base or member subobject.
8823   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8824 
8825   /// Get the location to use for a subobject in diagnostics.
8826   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8827     // FIXME: For an indirect virtual base, the direct base leading to
8828     // the indirect virtual base would be a more useful choice.
8829     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8830       return B->getBaseTypeLoc();
8831     else
8832       return Subobj.get<FieldDecl*>()->getLocation();
8833   }
8834 
8835   enum BasesToVisit {
8836     /// Visit all non-virtual (direct) bases.
8837     VisitNonVirtualBases,
8838     /// Visit all direct bases, virtual or not.
8839     VisitDirectBases,
8840     /// Visit all non-virtual bases, and all virtual bases if the class
8841     /// is not abstract.
8842     VisitPotentiallyConstructedBases,
8843     /// Visit all direct or virtual bases.
8844     VisitAllBases
8845   };
8846 
8847   // Visit the bases and members of the class.
8848   bool visit(BasesToVisit Bases) {
8849     CXXRecordDecl *RD = MD->getParent();
8850 
8851     if (Bases == VisitPotentiallyConstructedBases)
8852       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8853 
8854     for (auto &B : RD->bases())
8855       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8856           getDerived().visitBase(&B))
8857         return true;
8858 
8859     if (Bases == VisitAllBases)
8860       for (auto &B : RD->vbases())
8861         if (getDerived().visitBase(&B))
8862           return true;
8863 
8864     for (auto *F : RD->fields())
8865       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8866           getDerived().visitField(F))
8867         return true;
8868 
8869     return false;
8870   }
8871 };
8872 }
8873 
8874 namespace {
8875 struct SpecialMemberDeletionInfo
8876     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8877   bool Diagnose;
8878 
8879   SourceLocation Loc;
8880 
8881   bool AllFieldsAreConst;
8882 
8883   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8884                             Sema::CXXSpecialMember CSM,
8885                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8886       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8887         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8888 
8889   bool inUnion() const { return MD->getParent()->isUnion(); }
8890 
8891   Sema::CXXSpecialMember getEffectiveCSM() {
8892     return ICI ? Sema::CXXInvalid : CSM;
8893   }
8894 
8895   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8896 
8897   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8898   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8899 
8900   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8901   bool shouldDeleteForField(FieldDecl *FD);
8902   bool shouldDeleteForAllConstMembers();
8903 
8904   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8905                                      unsigned Quals);
8906   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8907                                     Sema::SpecialMemberOverloadResult SMOR,
8908                                     bool IsDtorCallInCtor);
8909 
8910   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8911 };
8912 }
8913 
8914 /// Is the given special member inaccessible when used on the given
8915 /// sub-object.
8916 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8917                                              CXXMethodDecl *target) {
8918   /// If we're operating on a base class, the object type is the
8919   /// type of this special member.
8920   QualType objectTy;
8921   AccessSpecifier access = target->getAccess();
8922   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8923     objectTy = S.Context.getTypeDeclType(MD->getParent());
8924     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8925 
8926   // If we're operating on a field, the object type is the type of the field.
8927   } else {
8928     objectTy = S.Context.getTypeDeclType(target->getParent());
8929   }
8930 
8931   return S.isMemberAccessibleForDeletion(
8932       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8933 }
8934 
8935 /// Check whether we should delete a special member due to the implicit
8936 /// definition containing a call to a special member of a subobject.
8937 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8938     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8939     bool IsDtorCallInCtor) {
8940   CXXMethodDecl *Decl = SMOR.getMethod();
8941   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8942 
8943   int DiagKind = -1;
8944 
8945   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8946     DiagKind = !Decl ? 0 : 1;
8947   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8948     DiagKind = 2;
8949   else if (!isAccessible(Subobj, Decl))
8950     DiagKind = 3;
8951   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8952            !Decl->isTrivial()) {
8953     // A member of a union must have a trivial corresponding special member.
8954     // As a weird special case, a destructor call from a union's constructor
8955     // must be accessible and non-deleted, but need not be trivial. Such a
8956     // destructor is never actually called, but is semantically checked as
8957     // if it were.
8958     DiagKind = 4;
8959   }
8960 
8961   if (DiagKind == -1)
8962     return false;
8963 
8964   if (Diagnose) {
8965     if (Field) {
8966       S.Diag(Field->getLocation(),
8967              diag::note_deleted_special_member_class_subobject)
8968         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8969         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8970     } else {
8971       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8972       S.Diag(Base->getBeginLoc(),
8973              diag::note_deleted_special_member_class_subobject)
8974           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8975           << Base->getType() << DiagKind << IsDtorCallInCtor
8976           << /*IsObjCPtr*/false;
8977     }
8978 
8979     if (DiagKind == 1)
8980       S.NoteDeletedFunction(Decl);
8981     // FIXME: Explain inaccessibility if DiagKind == 3.
8982   }
8983 
8984   return true;
8985 }
8986 
8987 /// Check whether we should delete a special member function due to having a
8988 /// direct or virtual base class or non-static data member of class type M.
8989 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8990     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8991   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8992   bool IsMutable = Field && Field->isMutable();
8993 
8994   // C++11 [class.ctor]p5:
8995   // -- any direct or virtual base class, or non-static data member with no
8996   //    brace-or-equal-initializer, has class type M (or array thereof) and
8997   //    either M has no default constructor or overload resolution as applied
8998   //    to M's default constructor results in an ambiguity or in a function
8999   //    that is deleted or inaccessible
9000   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9001   // -- a direct or virtual base class B that cannot be copied/moved because
9002   //    overload resolution, as applied to B's corresponding special member,
9003   //    results in an ambiguity or a function that is deleted or inaccessible
9004   //    from the defaulted special member
9005   // C++11 [class.dtor]p5:
9006   // -- any direct or virtual base class [...] has a type with a destructor
9007   //    that is deleted or inaccessible
9008   if (!(CSM == Sema::CXXDefaultConstructor &&
9009         Field && Field->hasInClassInitializer()) &&
9010       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9011                                    false))
9012     return true;
9013 
9014   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9015   // -- any direct or virtual base class or non-static data member has a
9016   //    type with a destructor that is deleted or inaccessible
9017   if (IsConstructor) {
9018     Sema::SpecialMemberOverloadResult SMOR =
9019         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9020                               false, false, false, false, false);
9021     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9022       return true;
9023   }
9024 
9025   return false;
9026 }
9027 
9028 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9029     FieldDecl *FD, QualType FieldType) {
9030   // The defaulted special functions are defined as deleted if this is a variant
9031   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9032   // type under ARC.
9033   if (!FieldType.hasNonTrivialObjCLifetime())
9034     return false;
9035 
9036   // Don't make the defaulted default constructor defined as deleted if the
9037   // member has an in-class initializer.
9038   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9039     return false;
9040 
9041   if (Diagnose) {
9042     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9043     S.Diag(FD->getLocation(),
9044            diag::note_deleted_special_member_class_subobject)
9045         << getEffectiveCSM() << ParentClass << /*IsField*/true
9046         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9047   }
9048 
9049   return true;
9050 }
9051 
9052 /// Check whether we should delete a special member function due to the class
9053 /// having a particular direct or virtual base class.
9054 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9055   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9056   // If program is correct, BaseClass cannot be null, but if it is, the error
9057   // must be reported elsewhere.
9058   if (!BaseClass)
9059     return false;
9060   // If we have an inheriting constructor, check whether we're calling an
9061   // inherited constructor instead of a default constructor.
9062   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9063   if (auto *BaseCtor = SMOR.getMethod()) {
9064     // Note that we do not check access along this path; other than that,
9065     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9066     // FIXME: Check that the base has a usable destructor! Sink this into
9067     // shouldDeleteForClassSubobject.
9068     if (BaseCtor->isDeleted() && Diagnose) {
9069       S.Diag(Base->getBeginLoc(),
9070              diag::note_deleted_special_member_class_subobject)
9071           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9072           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9073           << /*IsObjCPtr*/false;
9074       S.NoteDeletedFunction(BaseCtor);
9075     }
9076     return BaseCtor->isDeleted();
9077   }
9078   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9079 }
9080 
9081 /// Check whether we should delete a special member function due to the class
9082 /// having a particular non-static data member.
9083 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9084   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9085   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9086 
9087   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9088     return true;
9089 
9090   if (CSM == Sema::CXXDefaultConstructor) {
9091     // For a default constructor, all references must be initialized in-class
9092     // and, if a union, it must have a non-const member.
9093     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9094       if (Diagnose)
9095         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9096           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9097       return true;
9098     }
9099     // C++11 [class.ctor]p5: any non-variant non-static data member of
9100     // const-qualified type (or array thereof) with no
9101     // brace-or-equal-initializer does not have a user-provided default
9102     // constructor.
9103     if (!inUnion() && FieldType.isConstQualified() &&
9104         !FD->hasInClassInitializer() &&
9105         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9106       if (Diagnose)
9107         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9108           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9109       return true;
9110     }
9111 
9112     if (inUnion() && !FieldType.isConstQualified())
9113       AllFieldsAreConst = false;
9114   } else if (CSM == Sema::CXXCopyConstructor) {
9115     // For a copy constructor, data members must not be of rvalue reference
9116     // type.
9117     if (FieldType->isRValueReferenceType()) {
9118       if (Diagnose)
9119         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9120           << MD->getParent() << FD << FieldType;
9121       return true;
9122     }
9123   } else if (IsAssignment) {
9124     // For an assignment operator, data members must not be of reference type.
9125     if (FieldType->isReferenceType()) {
9126       if (Diagnose)
9127         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9128           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9129       return true;
9130     }
9131     if (!FieldRecord && FieldType.isConstQualified()) {
9132       // C++11 [class.copy]p23:
9133       // -- a non-static data member of const non-class type (or array thereof)
9134       if (Diagnose)
9135         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9136           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9137       return true;
9138     }
9139   }
9140 
9141   if (FieldRecord) {
9142     // Some additional restrictions exist on the variant members.
9143     if (!inUnion() && FieldRecord->isUnion() &&
9144         FieldRecord->isAnonymousStructOrUnion()) {
9145       bool AllVariantFieldsAreConst = true;
9146 
9147       // FIXME: Handle anonymous unions declared within anonymous unions.
9148       for (auto *UI : FieldRecord->fields()) {
9149         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9150 
9151         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9152           return true;
9153 
9154         if (!UnionFieldType.isConstQualified())
9155           AllVariantFieldsAreConst = false;
9156 
9157         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9158         if (UnionFieldRecord &&
9159             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9160                                           UnionFieldType.getCVRQualifiers()))
9161           return true;
9162       }
9163 
9164       // At least one member in each anonymous union must be non-const
9165       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9166           !FieldRecord->field_empty()) {
9167         if (Diagnose)
9168           S.Diag(FieldRecord->getLocation(),
9169                  diag::note_deleted_default_ctor_all_const)
9170             << !!ICI << MD->getParent() << /*anonymous union*/1;
9171         return true;
9172       }
9173 
9174       // Don't check the implicit member of the anonymous union type.
9175       // This is technically non-conformant, but sanity demands it.
9176       return false;
9177     }
9178 
9179     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9180                                       FieldType.getCVRQualifiers()))
9181       return true;
9182   }
9183 
9184   return false;
9185 }
9186 
9187 /// C++11 [class.ctor] p5:
9188 ///   A defaulted default constructor for a class X is defined as deleted if
9189 /// X is a union and all of its variant members are of const-qualified type.
9190 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9191   // This is a silly definition, because it gives an empty union a deleted
9192   // default constructor. Don't do that.
9193   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9194     bool AnyFields = false;
9195     for (auto *F : MD->getParent()->fields())
9196       if ((AnyFields = !F->isUnnamedBitfield()))
9197         break;
9198     if (!AnyFields)
9199       return false;
9200     if (Diagnose)
9201       S.Diag(MD->getParent()->getLocation(),
9202              diag::note_deleted_default_ctor_all_const)
9203         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9204     return true;
9205   }
9206   return false;
9207 }
9208 
9209 /// Determine whether a defaulted special member function should be defined as
9210 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9211 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9212 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9213                                      InheritedConstructorInfo *ICI,
9214                                      bool Diagnose) {
9215   if (MD->isInvalidDecl())
9216     return false;
9217   CXXRecordDecl *RD = MD->getParent();
9218   assert(!RD->isDependentType() && "do deletion after instantiation");
9219   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9220     return false;
9221 
9222   // C++11 [expr.lambda.prim]p19:
9223   //   The closure type associated with a lambda-expression has a
9224   //   deleted (8.4.3) default constructor and a deleted copy
9225   //   assignment operator.
9226   // C++2a adds back these operators if the lambda has no lambda-capture.
9227   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9228       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9229     if (Diagnose)
9230       Diag(RD->getLocation(), diag::note_lambda_decl);
9231     return true;
9232   }
9233 
9234   // For an anonymous struct or union, the copy and assignment special members
9235   // will never be used, so skip the check. For an anonymous union declared at
9236   // namespace scope, the constructor and destructor are used.
9237   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9238       RD->isAnonymousStructOrUnion())
9239     return false;
9240 
9241   // C++11 [class.copy]p7, p18:
9242   //   If the class definition declares a move constructor or move assignment
9243   //   operator, an implicitly declared copy constructor or copy assignment
9244   //   operator is defined as deleted.
9245   if (MD->isImplicit() &&
9246       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9247     CXXMethodDecl *UserDeclaredMove = nullptr;
9248 
9249     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9250     // deletion of the corresponding copy operation, not both copy operations.
9251     // MSVC 2015 has adopted the standards conforming behavior.
9252     bool DeletesOnlyMatchingCopy =
9253         getLangOpts().MSVCCompat &&
9254         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9255 
9256     if (RD->hasUserDeclaredMoveConstructor() &&
9257         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9258       if (!Diagnose) return true;
9259 
9260       // Find any user-declared move constructor.
9261       for (auto *I : RD->ctors()) {
9262         if (I->isMoveConstructor()) {
9263           UserDeclaredMove = I;
9264           break;
9265         }
9266       }
9267       assert(UserDeclaredMove);
9268     } else if (RD->hasUserDeclaredMoveAssignment() &&
9269                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9270       if (!Diagnose) return true;
9271 
9272       // Find any user-declared move assignment operator.
9273       for (auto *I : RD->methods()) {
9274         if (I->isMoveAssignmentOperator()) {
9275           UserDeclaredMove = I;
9276           break;
9277         }
9278       }
9279       assert(UserDeclaredMove);
9280     }
9281 
9282     if (UserDeclaredMove) {
9283       Diag(UserDeclaredMove->getLocation(),
9284            diag::note_deleted_copy_user_declared_move)
9285         << (CSM == CXXCopyAssignment) << RD
9286         << UserDeclaredMove->isMoveAssignmentOperator();
9287       return true;
9288     }
9289   }
9290 
9291   // Do access control from the special member function
9292   ContextRAII MethodContext(*this, MD);
9293 
9294   // C++11 [class.dtor]p5:
9295   // -- for a virtual destructor, lookup of the non-array deallocation function
9296   //    results in an ambiguity or in a function that is deleted or inaccessible
9297   if (CSM == CXXDestructor && MD->isVirtual()) {
9298     FunctionDecl *OperatorDelete = nullptr;
9299     DeclarationName Name =
9300       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9301     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9302                                  OperatorDelete, /*Diagnose*/false)) {
9303       if (Diagnose)
9304         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9305       return true;
9306     }
9307   }
9308 
9309   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9310 
9311   // Per DR1611, do not consider virtual bases of constructors of abstract
9312   // classes, since we are not going to construct them.
9313   // Per DR1658, do not consider virtual bases of destructors of abstract
9314   // classes either.
9315   // Per DR2180, for assignment operators we only assign (and thus only
9316   // consider) direct bases.
9317   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9318                                  : SMI.VisitPotentiallyConstructedBases))
9319     return true;
9320 
9321   if (SMI.shouldDeleteForAllConstMembers())
9322     return true;
9323 
9324   if (getLangOpts().CUDA) {
9325     // We should delete the special member in CUDA mode if target inference
9326     // failed.
9327     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9328     // is treated as certain special member, which may not reflect what special
9329     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9330     // expects CSM to match MD, therefore recalculate CSM.
9331     assert(ICI || CSM == getSpecialMember(MD));
9332     auto RealCSM = CSM;
9333     if (ICI)
9334       RealCSM = getSpecialMember(MD);
9335 
9336     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9337                                                    SMI.ConstArg, Diagnose);
9338   }
9339 
9340   return false;
9341 }
9342 
9343 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9344   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9345   assert(DFK && "not a defaultable function");
9346   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9347 
9348   if (DFK.isSpecialMember()) {
9349     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9350                               nullptr, /*Diagnose=*/true);
9351   } else {
9352     DefaultedComparisonAnalyzer(
9353         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9354         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9355         .visit();
9356   }
9357 }
9358 
9359 /// Perform lookup for a special member of the specified kind, and determine
9360 /// whether it is trivial. If the triviality can be determined without the
9361 /// lookup, skip it. This is intended for use when determining whether a
9362 /// special member of a containing object is trivial, and thus does not ever
9363 /// perform overload resolution for default constructors.
9364 ///
9365 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9366 /// member that was most likely to be intended to be trivial, if any.
9367 ///
9368 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9369 /// determine whether the special member is trivial.
9370 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9371                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9372                                      bool ConstRHS,
9373                                      Sema::TrivialABIHandling TAH,
9374                                      CXXMethodDecl **Selected) {
9375   if (Selected)
9376     *Selected = nullptr;
9377 
9378   switch (CSM) {
9379   case Sema::CXXInvalid:
9380     llvm_unreachable("not a special member");
9381 
9382   case Sema::CXXDefaultConstructor:
9383     // C++11 [class.ctor]p5:
9384     //   A default constructor is trivial if:
9385     //    - all the [direct subobjects] have trivial default constructors
9386     //
9387     // Note, no overload resolution is performed in this case.
9388     if (RD->hasTrivialDefaultConstructor())
9389       return true;
9390 
9391     if (Selected) {
9392       // If there's a default constructor which could have been trivial, dig it
9393       // out. Otherwise, if there's any user-provided default constructor, point
9394       // to that as an example of why there's not a trivial one.
9395       CXXConstructorDecl *DefCtor = nullptr;
9396       if (RD->needsImplicitDefaultConstructor())
9397         S.DeclareImplicitDefaultConstructor(RD);
9398       for (auto *CI : RD->ctors()) {
9399         if (!CI->isDefaultConstructor())
9400           continue;
9401         DefCtor = CI;
9402         if (!DefCtor->isUserProvided())
9403           break;
9404       }
9405 
9406       *Selected = DefCtor;
9407     }
9408 
9409     return false;
9410 
9411   case Sema::CXXDestructor:
9412     // C++11 [class.dtor]p5:
9413     //   A destructor is trivial if:
9414     //    - all the direct [subobjects] have trivial destructors
9415     if (RD->hasTrivialDestructor() ||
9416         (TAH == Sema::TAH_ConsiderTrivialABI &&
9417          RD->hasTrivialDestructorForCall()))
9418       return true;
9419 
9420     if (Selected) {
9421       if (RD->needsImplicitDestructor())
9422         S.DeclareImplicitDestructor(RD);
9423       *Selected = RD->getDestructor();
9424     }
9425 
9426     return false;
9427 
9428   case Sema::CXXCopyConstructor:
9429     // C++11 [class.copy]p12:
9430     //   A copy constructor is trivial if:
9431     //    - the constructor selected to copy each direct [subobject] is trivial
9432     if (RD->hasTrivialCopyConstructor() ||
9433         (TAH == Sema::TAH_ConsiderTrivialABI &&
9434          RD->hasTrivialCopyConstructorForCall())) {
9435       if (Quals == Qualifiers::Const)
9436         // We must either select the trivial copy constructor or reach an
9437         // ambiguity; no need to actually perform overload resolution.
9438         return true;
9439     } else if (!Selected) {
9440       return false;
9441     }
9442     // In C++98, we are not supposed to perform overload resolution here, but we
9443     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9444     // cases like B as having a non-trivial copy constructor:
9445     //   struct A { template<typename T> A(T&); };
9446     //   struct B { mutable A a; };
9447     goto NeedOverloadResolution;
9448 
9449   case Sema::CXXCopyAssignment:
9450     // C++11 [class.copy]p25:
9451     //   A copy assignment operator is trivial if:
9452     //    - the assignment operator selected to copy each direct [subobject] is
9453     //      trivial
9454     if (RD->hasTrivialCopyAssignment()) {
9455       if (Quals == Qualifiers::Const)
9456         return true;
9457     } else if (!Selected) {
9458       return false;
9459     }
9460     // In C++98, we are not supposed to perform overload resolution here, but we
9461     // treat that as a language defect.
9462     goto NeedOverloadResolution;
9463 
9464   case Sema::CXXMoveConstructor:
9465   case Sema::CXXMoveAssignment:
9466   NeedOverloadResolution:
9467     Sema::SpecialMemberOverloadResult SMOR =
9468         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9469 
9470     // The standard doesn't describe how to behave if the lookup is ambiguous.
9471     // We treat it as not making the member non-trivial, just like the standard
9472     // mandates for the default constructor. This should rarely matter, because
9473     // the member will also be deleted.
9474     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9475       return true;
9476 
9477     if (!SMOR.getMethod()) {
9478       assert(SMOR.getKind() ==
9479              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9480       return false;
9481     }
9482 
9483     // We deliberately don't check if we found a deleted special member. We're
9484     // not supposed to!
9485     if (Selected)
9486       *Selected = SMOR.getMethod();
9487 
9488     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9489         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9490       return SMOR.getMethod()->isTrivialForCall();
9491     return SMOR.getMethod()->isTrivial();
9492   }
9493 
9494   llvm_unreachable("unknown special method kind");
9495 }
9496 
9497 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9498   for (auto *CI : RD->ctors())
9499     if (!CI->isImplicit())
9500       return CI;
9501 
9502   // Look for constructor templates.
9503   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9504   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9505     if (CXXConstructorDecl *CD =
9506           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9507       return CD;
9508   }
9509 
9510   return nullptr;
9511 }
9512 
9513 /// The kind of subobject we are checking for triviality. The values of this
9514 /// enumeration are used in diagnostics.
9515 enum TrivialSubobjectKind {
9516   /// The subobject is a base class.
9517   TSK_BaseClass,
9518   /// The subobject is a non-static data member.
9519   TSK_Field,
9520   /// The object is actually the complete object.
9521   TSK_CompleteObject
9522 };
9523 
9524 /// Check whether the special member selected for a given type would be trivial.
9525 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9526                                       QualType SubType, bool ConstRHS,
9527                                       Sema::CXXSpecialMember CSM,
9528                                       TrivialSubobjectKind Kind,
9529                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9530   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9531   if (!SubRD)
9532     return true;
9533 
9534   CXXMethodDecl *Selected;
9535   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9536                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9537     return true;
9538 
9539   if (Diagnose) {
9540     if (ConstRHS)
9541       SubType.addConst();
9542 
9543     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9544       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9545         << Kind << SubType.getUnqualifiedType();
9546       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9547         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9548     } else if (!Selected)
9549       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9550         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9551     else if (Selected->isUserProvided()) {
9552       if (Kind == TSK_CompleteObject)
9553         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9554           << Kind << SubType.getUnqualifiedType() << CSM;
9555       else {
9556         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9557           << Kind << SubType.getUnqualifiedType() << CSM;
9558         S.Diag(Selected->getLocation(), diag::note_declared_at);
9559       }
9560     } else {
9561       if (Kind != TSK_CompleteObject)
9562         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9563           << Kind << SubType.getUnqualifiedType() << CSM;
9564 
9565       // Explain why the defaulted or deleted special member isn't trivial.
9566       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9567                                Diagnose);
9568     }
9569   }
9570 
9571   return false;
9572 }
9573 
9574 /// Check whether the members of a class type allow a special member to be
9575 /// trivial.
9576 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9577                                      Sema::CXXSpecialMember CSM,
9578                                      bool ConstArg,
9579                                      Sema::TrivialABIHandling TAH,
9580                                      bool Diagnose) {
9581   for (const auto *FI : RD->fields()) {
9582     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9583       continue;
9584 
9585     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9586 
9587     // Pretend anonymous struct or union members are members of this class.
9588     if (FI->isAnonymousStructOrUnion()) {
9589       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9590                                     CSM, ConstArg, TAH, Diagnose))
9591         return false;
9592       continue;
9593     }
9594 
9595     // C++11 [class.ctor]p5:
9596     //   A default constructor is trivial if [...]
9597     //    -- no non-static data member of its class has a
9598     //       brace-or-equal-initializer
9599     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9600       if (Diagnose)
9601         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9602             << FI;
9603       return false;
9604     }
9605 
9606     // Objective C ARC 4.3.5:
9607     //   [...] nontrivally ownership-qualified types are [...] not trivially
9608     //   default constructible, copy constructible, move constructible, copy
9609     //   assignable, move assignable, or destructible [...]
9610     if (FieldType.hasNonTrivialObjCLifetime()) {
9611       if (Diagnose)
9612         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9613           << RD << FieldType.getObjCLifetime();
9614       return false;
9615     }
9616 
9617     bool ConstRHS = ConstArg && !FI->isMutable();
9618     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9619                                    CSM, TSK_Field, TAH, Diagnose))
9620       return false;
9621   }
9622 
9623   return true;
9624 }
9625 
9626 /// Diagnose why the specified class does not have a trivial special member of
9627 /// the given kind.
9628 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9629   QualType Ty = Context.getRecordType(RD);
9630 
9631   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9632   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9633                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9634                             /*Diagnose*/true);
9635 }
9636 
9637 /// Determine whether a defaulted or deleted special member function is trivial,
9638 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9639 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9640 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9641                                   TrivialABIHandling TAH, bool Diagnose) {
9642   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9643 
9644   CXXRecordDecl *RD = MD->getParent();
9645 
9646   bool ConstArg = false;
9647 
9648   // C++11 [class.copy]p12, p25: [DR1593]
9649   //   A [special member] is trivial if [...] its parameter-type-list is
9650   //   equivalent to the parameter-type-list of an implicit declaration [...]
9651   switch (CSM) {
9652   case CXXDefaultConstructor:
9653   case CXXDestructor:
9654     // Trivial default constructors and destructors cannot have parameters.
9655     break;
9656 
9657   case CXXCopyConstructor:
9658   case CXXCopyAssignment: {
9659     // Trivial copy operations always have const, non-volatile parameter types.
9660     ConstArg = true;
9661     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9662     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9663     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9664       if (Diagnose)
9665         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9666           << Param0->getSourceRange() << Param0->getType()
9667           << Context.getLValueReferenceType(
9668                Context.getRecordType(RD).withConst());
9669       return false;
9670     }
9671     break;
9672   }
9673 
9674   case CXXMoveConstructor:
9675   case CXXMoveAssignment: {
9676     // Trivial move operations always have non-cv-qualified parameters.
9677     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9678     const RValueReferenceType *RT =
9679       Param0->getType()->getAs<RValueReferenceType>();
9680     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9681       if (Diagnose)
9682         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9683           << Param0->getSourceRange() << Param0->getType()
9684           << Context.getRValueReferenceType(Context.getRecordType(RD));
9685       return false;
9686     }
9687     break;
9688   }
9689 
9690   case CXXInvalid:
9691     llvm_unreachable("not a special member");
9692   }
9693 
9694   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9695     if (Diagnose)
9696       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9697            diag::note_nontrivial_default_arg)
9698         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9699     return false;
9700   }
9701   if (MD->isVariadic()) {
9702     if (Diagnose)
9703       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9704     return false;
9705   }
9706 
9707   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9708   //   A copy/move [constructor or assignment operator] is trivial if
9709   //    -- the [member] selected to copy/move each direct base class subobject
9710   //       is trivial
9711   //
9712   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9713   //   A [default constructor or destructor] is trivial if
9714   //    -- all the direct base classes have trivial [default constructors or
9715   //       destructors]
9716   for (const auto &BI : RD->bases())
9717     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9718                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9719       return false;
9720 
9721   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9722   //   A copy/move [constructor or assignment operator] for a class X is
9723   //   trivial if
9724   //    -- for each non-static data member of X that is of class type (or array
9725   //       thereof), the constructor selected to copy/move that member is
9726   //       trivial
9727   //
9728   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9729   //   A [default constructor or destructor] is trivial if
9730   //    -- for all of the non-static data members of its class that are of class
9731   //       type (or array thereof), each such class has a trivial [default
9732   //       constructor or destructor]
9733   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9734     return false;
9735 
9736   // C++11 [class.dtor]p5:
9737   //   A destructor is trivial if [...]
9738   //    -- the destructor is not virtual
9739   if (CSM == CXXDestructor && MD->isVirtual()) {
9740     if (Diagnose)
9741       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9742     return false;
9743   }
9744 
9745   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9746   //   A [special member] for class X is trivial if [...]
9747   //    -- class X has no virtual functions and no virtual base classes
9748   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9749     if (!Diagnose)
9750       return false;
9751 
9752     if (RD->getNumVBases()) {
9753       // Check for virtual bases. We already know that the corresponding
9754       // member in all bases is trivial, so vbases must all be direct.
9755       CXXBaseSpecifier &BS = *RD->vbases_begin();
9756       assert(BS.isVirtual());
9757       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9758       return false;
9759     }
9760 
9761     // Must have a virtual method.
9762     for (const auto *MI : RD->methods()) {
9763       if (MI->isVirtual()) {
9764         SourceLocation MLoc = MI->getBeginLoc();
9765         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9766         return false;
9767       }
9768     }
9769 
9770     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9771   }
9772 
9773   // Looks like it's trivial!
9774   return true;
9775 }
9776 
9777 namespace {
9778 struct FindHiddenVirtualMethod {
9779   Sema *S;
9780   CXXMethodDecl *Method;
9781   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9782   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9783 
9784 private:
9785   /// Check whether any most overridden method from MD in Methods
9786   static bool CheckMostOverridenMethods(
9787       const CXXMethodDecl *MD,
9788       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9789     if (MD->size_overridden_methods() == 0)
9790       return Methods.count(MD->getCanonicalDecl());
9791     for (const CXXMethodDecl *O : MD->overridden_methods())
9792       if (CheckMostOverridenMethods(O, Methods))
9793         return true;
9794     return false;
9795   }
9796 
9797 public:
9798   /// Member lookup function that determines whether a given C++
9799   /// method overloads virtual methods in a base class without overriding any,
9800   /// to be used with CXXRecordDecl::lookupInBases().
9801   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9802     RecordDecl *BaseRecord =
9803         Specifier->getType()->castAs<RecordType>()->getDecl();
9804 
9805     DeclarationName Name = Method->getDeclName();
9806     assert(Name.getNameKind() == DeclarationName::Identifier);
9807 
9808     bool foundSameNameMethod = false;
9809     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9810     for (Path.Decls = BaseRecord->lookup(Name).begin();
9811          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9812       NamedDecl *D = *Path.Decls;
9813       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9814         MD = MD->getCanonicalDecl();
9815         foundSameNameMethod = true;
9816         // Interested only in hidden virtual methods.
9817         if (!MD->isVirtual())
9818           continue;
9819         // If the method we are checking overrides a method from its base
9820         // don't warn about the other overloaded methods. Clang deviates from
9821         // GCC by only diagnosing overloads of inherited virtual functions that
9822         // do not override any other virtual functions in the base. GCC's
9823         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9824         // function from a base class. These cases may be better served by a
9825         // warning (not specific to virtual functions) on call sites when the
9826         // call would select a different function from the base class, were it
9827         // visible.
9828         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9829         if (!S->IsOverload(Method, MD, false))
9830           return true;
9831         // Collect the overload only if its hidden.
9832         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9833           overloadedMethods.push_back(MD);
9834       }
9835     }
9836 
9837     if (foundSameNameMethod)
9838       OverloadedMethods.append(overloadedMethods.begin(),
9839                                overloadedMethods.end());
9840     return foundSameNameMethod;
9841   }
9842 };
9843 } // end anonymous namespace
9844 
9845 /// Add the most overridden methods from MD to Methods
9846 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9847                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9848   if (MD->size_overridden_methods() == 0)
9849     Methods.insert(MD->getCanonicalDecl());
9850   else
9851     for (const CXXMethodDecl *O : MD->overridden_methods())
9852       AddMostOverridenMethods(O, Methods);
9853 }
9854 
9855 /// Check if a method overloads virtual methods in a base class without
9856 /// overriding any.
9857 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9858                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9859   if (!MD->getDeclName().isIdentifier())
9860     return;
9861 
9862   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9863                      /*bool RecordPaths=*/false,
9864                      /*bool DetectVirtual=*/false);
9865   FindHiddenVirtualMethod FHVM;
9866   FHVM.Method = MD;
9867   FHVM.S = this;
9868 
9869   // Keep the base methods that were overridden or introduced in the subclass
9870   // by 'using' in a set. A base method not in this set is hidden.
9871   CXXRecordDecl *DC = MD->getParent();
9872   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9873   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9874     NamedDecl *ND = *I;
9875     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9876       ND = shad->getTargetDecl();
9877     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9878       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9879   }
9880 
9881   if (DC->lookupInBases(FHVM, Paths))
9882     OverloadedMethods = FHVM.OverloadedMethods;
9883 }
9884 
9885 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9886                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9887   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9888     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9889     PartialDiagnostic PD = PDiag(
9890          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9891     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9892     Diag(overloadedMD->getLocation(), PD);
9893   }
9894 }
9895 
9896 /// Diagnose methods which overload virtual methods in a base class
9897 /// without overriding any.
9898 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9899   if (MD->isInvalidDecl())
9900     return;
9901 
9902   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9903     return;
9904 
9905   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9906   FindHiddenVirtualMethods(MD, OverloadedMethods);
9907   if (!OverloadedMethods.empty()) {
9908     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9909       << MD << (OverloadedMethods.size() > 1);
9910 
9911     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9912   }
9913 }
9914 
9915 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9916   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9917     // No diagnostics if this is a template instantiation.
9918     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9919       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9920            diag::ext_cannot_use_trivial_abi) << &RD;
9921       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9922            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9923     }
9924     RD.dropAttr<TrivialABIAttr>();
9925   };
9926 
9927   // Ill-formed if the copy and move constructors are deleted.
9928   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9929     // If the type is dependent, then assume it might have
9930     // implicit copy or move ctor because we won't know yet at this point.
9931     if (RD.isDependentType())
9932       return true;
9933     if (RD.needsImplicitCopyConstructor() &&
9934         !RD.defaultedCopyConstructorIsDeleted())
9935       return true;
9936     if (RD.needsImplicitMoveConstructor() &&
9937         !RD.defaultedMoveConstructorIsDeleted())
9938       return true;
9939     for (const CXXConstructorDecl *CD : RD.ctors())
9940       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9941         return true;
9942     return false;
9943   };
9944 
9945   if (!HasNonDeletedCopyOrMoveConstructor()) {
9946     PrintDiagAndRemoveAttr(0);
9947     return;
9948   }
9949 
9950   // Ill-formed if the struct has virtual functions.
9951   if (RD.isPolymorphic()) {
9952     PrintDiagAndRemoveAttr(1);
9953     return;
9954   }
9955 
9956   for (const auto &B : RD.bases()) {
9957     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9958     // virtual base.
9959     if (!B.getType()->isDependentType() &&
9960         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9961       PrintDiagAndRemoveAttr(2);
9962       return;
9963     }
9964 
9965     if (B.isVirtual()) {
9966       PrintDiagAndRemoveAttr(3);
9967       return;
9968     }
9969   }
9970 
9971   for (const auto *FD : RD.fields()) {
9972     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9973     // non-trivial for the purpose of calls.
9974     QualType FT = FD->getType();
9975     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9976       PrintDiagAndRemoveAttr(4);
9977       return;
9978     }
9979 
9980     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9981       if (!RT->isDependentType() &&
9982           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9983         PrintDiagAndRemoveAttr(5);
9984         return;
9985       }
9986   }
9987 }
9988 
9989 void Sema::ActOnFinishCXXMemberSpecification(
9990     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9991     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9992   if (!TagDecl)
9993     return;
9994 
9995   AdjustDeclIfTemplate(TagDecl);
9996 
9997   for (const ParsedAttr &AL : AttrList) {
9998     if (AL.getKind() != ParsedAttr::AT_Visibility)
9999       continue;
10000     AL.setInvalid();
10001     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10002   }
10003 
10004   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10005               // strict aliasing violation!
10006               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10007               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10008 
10009   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10010 }
10011 
10012 /// Find the equality comparison functions that should be implicitly declared
10013 /// in a given class definition, per C++2a [class.compare.default]p3.
10014 static void findImplicitlyDeclaredEqualityComparisons(
10015     ASTContext &Ctx, CXXRecordDecl *RD,
10016     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10017   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10018   if (!RD->lookup(EqEq).empty())
10019     // Member operator== explicitly declared: no implicit operator==s.
10020     return;
10021 
10022   // Traverse friends looking for an '==' or a '<=>'.
10023   for (FriendDecl *Friend : RD->friends()) {
10024     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10025     if (!FD) continue;
10026 
10027     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10028       // Friend operator== explicitly declared: no implicit operator==s.
10029       Spaceships.clear();
10030       return;
10031     }
10032 
10033     if (FD->getOverloadedOperator() == OO_Spaceship &&
10034         FD->isExplicitlyDefaulted())
10035       Spaceships.push_back(FD);
10036   }
10037 
10038   // Look for members named 'operator<=>'.
10039   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10040   for (NamedDecl *ND : RD->lookup(Cmp)) {
10041     // Note that we could find a non-function here (either a function template
10042     // or a using-declaration). Neither case results in an implicit
10043     // 'operator=='.
10044     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10045       if (FD->isExplicitlyDefaulted())
10046         Spaceships.push_back(FD);
10047   }
10048 }
10049 
10050 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10051 /// special functions, such as the default constructor, copy
10052 /// constructor, or destructor, to the given C++ class (C++
10053 /// [special]p1).  This routine can only be executed just before the
10054 /// definition of the class is complete.
10055 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10056   // Don't add implicit special members to templated classes.
10057   // FIXME: This means unqualified lookups for 'operator=' within a class
10058   // template don't work properly.
10059   if (!ClassDecl->isDependentType()) {
10060     if (ClassDecl->needsImplicitDefaultConstructor()) {
10061       ++getASTContext().NumImplicitDefaultConstructors;
10062 
10063       if (ClassDecl->hasInheritedConstructor())
10064         DeclareImplicitDefaultConstructor(ClassDecl);
10065     }
10066 
10067     if (ClassDecl->needsImplicitCopyConstructor()) {
10068       ++getASTContext().NumImplicitCopyConstructors;
10069 
10070       // If the properties or semantics of the copy constructor couldn't be
10071       // determined while the class was being declared, force a declaration
10072       // of it now.
10073       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10074           ClassDecl->hasInheritedConstructor())
10075         DeclareImplicitCopyConstructor(ClassDecl);
10076       // For the MS ABI we need to know whether the copy ctor is deleted. A
10077       // prerequisite for deleting the implicit copy ctor is that the class has
10078       // a move ctor or move assignment that is either user-declared or whose
10079       // semantics are inherited from a subobject. FIXME: We should provide a
10080       // more direct way for CodeGen to ask whether the constructor was deleted.
10081       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10082                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10083                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10084                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10085                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10086         DeclareImplicitCopyConstructor(ClassDecl);
10087     }
10088 
10089     if (getLangOpts().CPlusPlus11 &&
10090         ClassDecl->needsImplicitMoveConstructor()) {
10091       ++getASTContext().NumImplicitMoveConstructors;
10092 
10093       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10094           ClassDecl->hasInheritedConstructor())
10095         DeclareImplicitMoveConstructor(ClassDecl);
10096     }
10097 
10098     if (ClassDecl->needsImplicitCopyAssignment()) {
10099       ++getASTContext().NumImplicitCopyAssignmentOperators;
10100 
10101       // If we have a dynamic class, then the copy assignment operator may be
10102       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10103       // it shows up in the right place in the vtable and that we diagnose
10104       // problems with the implicit exception specification.
10105       if (ClassDecl->isDynamicClass() ||
10106           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10107           ClassDecl->hasInheritedAssignment())
10108         DeclareImplicitCopyAssignment(ClassDecl);
10109     }
10110 
10111     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10112       ++getASTContext().NumImplicitMoveAssignmentOperators;
10113 
10114       // Likewise for the move assignment operator.
10115       if (ClassDecl->isDynamicClass() ||
10116           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10117           ClassDecl->hasInheritedAssignment())
10118         DeclareImplicitMoveAssignment(ClassDecl);
10119     }
10120 
10121     if (ClassDecl->needsImplicitDestructor()) {
10122       ++getASTContext().NumImplicitDestructors;
10123 
10124       // If we have a dynamic class, then the destructor may be virtual, so we
10125       // have to declare the destructor immediately. This ensures that, e.g., it
10126       // shows up in the right place in the vtable and that we diagnose problems
10127       // with the implicit exception specification.
10128       if (ClassDecl->isDynamicClass() ||
10129           ClassDecl->needsOverloadResolutionForDestructor())
10130         DeclareImplicitDestructor(ClassDecl);
10131     }
10132   }
10133 
10134   // C++2a [class.compare.default]p3:
10135   //   If the member-specification does not explicitly declare any member or
10136   //   friend named operator==, an == operator function is declared implicitly
10137   //   for each defaulted three-way comparison operator function defined in
10138   //   the member-specification
10139   // FIXME: Consider doing this lazily.
10140   // We do this during the initial parse for a class template, not during
10141   // instantiation, so that we can handle unqualified lookups for 'operator=='
10142   // when parsing the template.
10143   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10144     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10145     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10146                                               DefaultedSpaceships);
10147     for (auto *FD : DefaultedSpaceships)
10148       DeclareImplicitEqualityComparison(ClassDecl, FD);
10149   }
10150 }
10151 
10152 unsigned
10153 Sema::ActOnReenterTemplateScope(Decl *D,
10154                                 llvm::function_ref<Scope *()> EnterScope) {
10155   if (!D)
10156     return 0;
10157   AdjustDeclIfTemplate(D);
10158 
10159   // In order to get name lookup right, reenter template scopes in order from
10160   // outermost to innermost.
10161   SmallVector<TemplateParameterList *, 4> ParameterLists;
10162   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10163 
10164   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10165     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10166       ParameterLists.push_back(DD->getTemplateParameterList(i));
10167 
10168     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10169       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10170         ParameterLists.push_back(FTD->getTemplateParameters());
10171     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10172       LookupDC = VD->getDeclContext();
10173 
10174       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10175         ParameterLists.push_back(VTD->getTemplateParameters());
10176       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10177         ParameterLists.push_back(PSD->getTemplateParameters());
10178     }
10179   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10180     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10181       ParameterLists.push_back(TD->getTemplateParameterList(i));
10182 
10183     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10184       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10185         ParameterLists.push_back(CTD->getTemplateParameters());
10186       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10187         ParameterLists.push_back(PSD->getTemplateParameters());
10188     }
10189   }
10190   // FIXME: Alias declarations and concepts.
10191 
10192   unsigned Count = 0;
10193   Scope *InnermostTemplateScope = nullptr;
10194   for (TemplateParameterList *Params : ParameterLists) {
10195     // Ignore explicit specializations; they don't contribute to the template
10196     // depth.
10197     if (Params->size() == 0)
10198       continue;
10199 
10200     InnermostTemplateScope = EnterScope();
10201     for (NamedDecl *Param : *Params) {
10202       if (Param->getDeclName()) {
10203         InnermostTemplateScope->AddDecl(Param);
10204         IdResolver.AddDecl(Param);
10205       }
10206     }
10207     ++Count;
10208   }
10209 
10210   // Associate the new template scopes with the corresponding entities.
10211   if (InnermostTemplateScope) {
10212     assert(LookupDC && "no enclosing DeclContext for template lookup");
10213     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10214   }
10215 
10216   return Count;
10217 }
10218 
10219 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10220   if (!RecordD) return;
10221   AdjustDeclIfTemplate(RecordD);
10222   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10223   PushDeclContext(S, Record);
10224 }
10225 
10226 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10227   if (!RecordD) return;
10228   PopDeclContext();
10229 }
10230 
10231 /// This is used to implement the constant expression evaluation part of the
10232 /// attribute enable_if extension. There is nothing in standard C++ which would
10233 /// require reentering parameters.
10234 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10235   if (!Param)
10236     return;
10237 
10238   S->AddDecl(Param);
10239   if (Param->getDeclName())
10240     IdResolver.AddDecl(Param);
10241 }
10242 
10243 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10244 /// parsing a top-level (non-nested) C++ class, and we are now
10245 /// parsing those parts of the given Method declaration that could
10246 /// not be parsed earlier (C++ [class.mem]p2), such as default
10247 /// arguments. This action should enter the scope of the given
10248 /// Method declaration as if we had just parsed the qualified method
10249 /// name. However, it should not bring the parameters into scope;
10250 /// that will be performed by ActOnDelayedCXXMethodParameter.
10251 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10252 }
10253 
10254 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10255 /// C++ method declaration. We're (re-)introducing the given
10256 /// function parameter into scope for use in parsing later parts of
10257 /// the method declaration. For example, we could see an
10258 /// ActOnParamDefaultArgument event for this parameter.
10259 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10260   if (!ParamD)
10261     return;
10262 
10263   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10264 
10265   S->AddDecl(Param);
10266   if (Param->getDeclName())
10267     IdResolver.AddDecl(Param);
10268 }
10269 
10270 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10271 /// processing the delayed method declaration for Method. The method
10272 /// declaration is now considered finished. There may be a separate
10273 /// ActOnStartOfFunctionDef action later (not necessarily
10274 /// immediately!) for this method, if it was also defined inside the
10275 /// class body.
10276 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10277   if (!MethodD)
10278     return;
10279 
10280   AdjustDeclIfTemplate(MethodD);
10281 
10282   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10283 
10284   // Now that we have our default arguments, check the constructor
10285   // again. It could produce additional diagnostics or affect whether
10286   // the class has implicitly-declared destructors, among other
10287   // things.
10288   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10289     CheckConstructor(Constructor);
10290 
10291   // Check the default arguments, which we may have added.
10292   if (!Method->isInvalidDecl())
10293     CheckCXXDefaultArguments(Method);
10294 }
10295 
10296 // Emit the given diagnostic for each non-address-space qualifier.
10297 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10298 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10299   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10300   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10301     bool DiagOccured = false;
10302     FTI.MethodQualifiers->forEachQualifier(
10303         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10304                                    SourceLocation SL) {
10305           // This diagnostic should be emitted on any qualifier except an addr
10306           // space qualifier. However, forEachQualifier currently doesn't visit
10307           // addr space qualifiers, so there's no way to write this condition
10308           // right now; we just diagnose on everything.
10309           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10310           DiagOccured = true;
10311         });
10312     if (DiagOccured)
10313       D.setInvalidType();
10314   }
10315 }
10316 
10317 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10318 /// the well-formedness of the constructor declarator @p D with type @p
10319 /// R. If there are any errors in the declarator, this routine will
10320 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10321 /// will be updated to reflect a well-formed type for the constructor and
10322 /// returned.
10323 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10324                                           StorageClass &SC) {
10325   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10326 
10327   // C++ [class.ctor]p3:
10328   //   A constructor shall not be virtual (10.3) or static (9.4). A
10329   //   constructor can be invoked for a const, volatile or const
10330   //   volatile object. A constructor shall not be declared const,
10331   //   volatile, or const volatile (9.3.2).
10332   if (isVirtual) {
10333     if (!D.isInvalidType())
10334       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10335         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10336         << SourceRange(D.getIdentifierLoc());
10337     D.setInvalidType();
10338   }
10339   if (SC == SC_Static) {
10340     if (!D.isInvalidType())
10341       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10342         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10343         << SourceRange(D.getIdentifierLoc());
10344     D.setInvalidType();
10345     SC = SC_None;
10346   }
10347 
10348   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10349     diagnoseIgnoredQualifiers(
10350         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10351         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10352         D.getDeclSpec().getRestrictSpecLoc(),
10353         D.getDeclSpec().getAtomicSpecLoc());
10354     D.setInvalidType();
10355   }
10356 
10357   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10358 
10359   // C++0x [class.ctor]p4:
10360   //   A constructor shall not be declared with a ref-qualifier.
10361   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10362   if (FTI.hasRefQualifier()) {
10363     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10364       << FTI.RefQualifierIsLValueRef
10365       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10366     D.setInvalidType();
10367   }
10368 
10369   // Rebuild the function type "R" without any type qualifiers (in
10370   // case any of the errors above fired) and with "void" as the
10371   // return type, since constructors don't have return types.
10372   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10373   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10374     return R;
10375 
10376   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10377   EPI.TypeQuals = Qualifiers();
10378   EPI.RefQualifier = RQ_None;
10379 
10380   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10381 }
10382 
10383 /// CheckConstructor - Checks a fully-formed constructor for
10384 /// well-formedness, issuing any diagnostics required. Returns true if
10385 /// the constructor declarator is invalid.
10386 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10387   CXXRecordDecl *ClassDecl
10388     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10389   if (!ClassDecl)
10390     return Constructor->setInvalidDecl();
10391 
10392   // C++ [class.copy]p3:
10393   //   A declaration of a constructor for a class X is ill-formed if
10394   //   its first parameter is of type (optionally cv-qualified) X and
10395   //   either there are no other parameters or else all other
10396   //   parameters have default arguments.
10397   if (!Constructor->isInvalidDecl() &&
10398       Constructor->hasOneParamOrDefaultArgs() &&
10399       Constructor->getTemplateSpecializationKind() !=
10400           TSK_ImplicitInstantiation) {
10401     QualType ParamType = Constructor->getParamDecl(0)->getType();
10402     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10403     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10404       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10405       const char *ConstRef
10406         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10407                                                         : " const &";
10408       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10409         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10410 
10411       // FIXME: Rather that making the constructor invalid, we should endeavor
10412       // to fix the type.
10413       Constructor->setInvalidDecl();
10414     }
10415   }
10416 }
10417 
10418 /// CheckDestructor - Checks a fully-formed destructor definition for
10419 /// well-formedness, issuing any diagnostics required.  Returns true
10420 /// on error.
10421 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10422   CXXRecordDecl *RD = Destructor->getParent();
10423 
10424   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10425     SourceLocation Loc;
10426 
10427     if (!Destructor->isImplicit())
10428       Loc = Destructor->getLocation();
10429     else
10430       Loc = RD->getLocation();
10431 
10432     // If we have a virtual destructor, look up the deallocation function
10433     if (FunctionDecl *OperatorDelete =
10434             FindDeallocationFunctionForDestructor(Loc, RD)) {
10435       Expr *ThisArg = nullptr;
10436 
10437       // If the notional 'delete this' expression requires a non-trivial
10438       // conversion from 'this' to the type of a destroying operator delete's
10439       // first parameter, perform that conversion now.
10440       if (OperatorDelete->isDestroyingOperatorDelete()) {
10441         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10442         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10443           // C++ [class.dtor]p13:
10444           //   ... as if for the expression 'delete this' appearing in a
10445           //   non-virtual destructor of the destructor's class.
10446           ContextRAII SwitchContext(*this, Destructor);
10447           ExprResult This =
10448               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10449           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10450           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10451           if (This.isInvalid()) {
10452             // FIXME: Register this as a context note so that it comes out
10453             // in the right order.
10454             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10455             return true;
10456           }
10457           ThisArg = This.get();
10458         }
10459       }
10460 
10461       DiagnoseUseOfDecl(OperatorDelete, Loc);
10462       MarkFunctionReferenced(Loc, OperatorDelete);
10463       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10464     }
10465   }
10466 
10467   return false;
10468 }
10469 
10470 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10471 /// the well-formednes of the destructor declarator @p D with type @p
10472 /// R. If there are any errors in the declarator, this routine will
10473 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10474 /// will be updated to reflect a well-formed type for the destructor and
10475 /// returned.
10476 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10477                                          StorageClass& SC) {
10478   // C++ [class.dtor]p1:
10479   //   [...] A typedef-name that names a class is a class-name
10480   //   (7.1.3); however, a typedef-name that names a class shall not
10481   //   be used as the identifier in the declarator for a destructor
10482   //   declaration.
10483   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10484   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10485     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10486       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10487   else if (const TemplateSpecializationType *TST =
10488              DeclaratorType->getAs<TemplateSpecializationType>())
10489     if (TST->isTypeAlias())
10490       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10491         << DeclaratorType << 1;
10492 
10493   // C++ [class.dtor]p2:
10494   //   A destructor is used to destroy objects of its class type. A
10495   //   destructor takes no parameters, and no return type can be
10496   //   specified for it (not even void). The address of a destructor
10497   //   shall not be taken. A destructor shall not be static. A
10498   //   destructor can be invoked for a const, volatile or const
10499   //   volatile object. A destructor shall not be declared const,
10500   //   volatile or const volatile (9.3.2).
10501   if (SC == SC_Static) {
10502     if (!D.isInvalidType())
10503       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10504         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10505         << SourceRange(D.getIdentifierLoc())
10506         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10507 
10508     SC = SC_None;
10509   }
10510   if (!D.isInvalidType()) {
10511     // Destructors don't have return types, but the parser will
10512     // happily parse something like:
10513     //
10514     //   class X {
10515     //     float ~X();
10516     //   };
10517     //
10518     // The return type will be eliminated later.
10519     if (D.getDeclSpec().hasTypeSpecifier())
10520       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10521         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10522         << SourceRange(D.getIdentifierLoc());
10523     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10524       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10525                                 SourceLocation(),
10526                                 D.getDeclSpec().getConstSpecLoc(),
10527                                 D.getDeclSpec().getVolatileSpecLoc(),
10528                                 D.getDeclSpec().getRestrictSpecLoc(),
10529                                 D.getDeclSpec().getAtomicSpecLoc());
10530       D.setInvalidType();
10531     }
10532   }
10533 
10534   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10535 
10536   // C++0x [class.dtor]p2:
10537   //   A destructor shall not be declared with a ref-qualifier.
10538   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10539   if (FTI.hasRefQualifier()) {
10540     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10541       << FTI.RefQualifierIsLValueRef
10542       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10543     D.setInvalidType();
10544   }
10545 
10546   // Make sure we don't have any parameters.
10547   if (FTIHasNonVoidParameters(FTI)) {
10548     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10549 
10550     // Delete the parameters.
10551     FTI.freeParams();
10552     D.setInvalidType();
10553   }
10554 
10555   // Make sure the destructor isn't variadic.
10556   if (FTI.isVariadic) {
10557     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10558     D.setInvalidType();
10559   }
10560 
10561   // Rebuild the function type "R" without any type qualifiers or
10562   // parameters (in case any of the errors above fired) and with
10563   // "void" as the return type, since destructors don't have return
10564   // types.
10565   if (!D.isInvalidType())
10566     return R;
10567 
10568   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10569   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10570   EPI.Variadic = false;
10571   EPI.TypeQuals = Qualifiers();
10572   EPI.RefQualifier = RQ_None;
10573   return Context.getFunctionType(Context.VoidTy, None, EPI);
10574 }
10575 
10576 static void extendLeft(SourceRange &R, SourceRange Before) {
10577   if (Before.isInvalid())
10578     return;
10579   R.setBegin(Before.getBegin());
10580   if (R.getEnd().isInvalid())
10581     R.setEnd(Before.getEnd());
10582 }
10583 
10584 static void extendRight(SourceRange &R, SourceRange After) {
10585   if (After.isInvalid())
10586     return;
10587   if (R.getBegin().isInvalid())
10588     R.setBegin(After.getBegin());
10589   R.setEnd(After.getEnd());
10590 }
10591 
10592 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10593 /// well-formednes of the conversion function declarator @p D with
10594 /// type @p R. If there are any errors in the declarator, this routine
10595 /// will emit diagnostics and return true. Otherwise, it will return
10596 /// false. Either way, the type @p R will be updated to reflect a
10597 /// well-formed type for the conversion operator.
10598 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10599                                      StorageClass& SC) {
10600   // C++ [class.conv.fct]p1:
10601   //   Neither parameter types nor return type can be specified. The
10602   //   type of a conversion function (8.3.5) is "function taking no
10603   //   parameter returning conversion-type-id."
10604   if (SC == SC_Static) {
10605     if (!D.isInvalidType())
10606       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10607         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10608         << D.getName().getSourceRange();
10609     D.setInvalidType();
10610     SC = SC_None;
10611   }
10612 
10613   TypeSourceInfo *ConvTSI = nullptr;
10614   QualType ConvType =
10615       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10616 
10617   const DeclSpec &DS = D.getDeclSpec();
10618   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10619     // Conversion functions don't have return types, but the parser will
10620     // happily parse something like:
10621     //
10622     //   class X {
10623     //     float operator bool();
10624     //   };
10625     //
10626     // The return type will be changed later anyway.
10627     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10628       << SourceRange(DS.getTypeSpecTypeLoc())
10629       << SourceRange(D.getIdentifierLoc());
10630     D.setInvalidType();
10631   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10632     // It's also plausible that the user writes type qualifiers in the wrong
10633     // place, such as:
10634     //   struct S { const operator int(); };
10635     // FIXME: we could provide a fixit to move the qualifiers onto the
10636     // conversion type.
10637     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10638         << SourceRange(D.getIdentifierLoc()) << 0;
10639     D.setInvalidType();
10640   }
10641 
10642   const auto *Proto = R->castAs<FunctionProtoType>();
10643 
10644   // Make sure we don't have any parameters.
10645   if (Proto->getNumParams() > 0) {
10646     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10647 
10648     // Delete the parameters.
10649     D.getFunctionTypeInfo().freeParams();
10650     D.setInvalidType();
10651   } else if (Proto->isVariadic()) {
10652     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10653     D.setInvalidType();
10654   }
10655 
10656   // Diagnose "&operator bool()" and other such nonsense.  This
10657   // is actually a gcc extension which we don't support.
10658   if (Proto->getReturnType() != ConvType) {
10659     bool NeedsTypedef = false;
10660     SourceRange Before, After;
10661 
10662     // Walk the chunks and extract information on them for our diagnostic.
10663     bool PastFunctionChunk = false;
10664     for (auto &Chunk : D.type_objects()) {
10665       switch (Chunk.Kind) {
10666       case DeclaratorChunk::Function:
10667         if (!PastFunctionChunk) {
10668           if (Chunk.Fun.HasTrailingReturnType) {
10669             TypeSourceInfo *TRT = nullptr;
10670             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10671             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10672           }
10673           PastFunctionChunk = true;
10674           break;
10675         }
10676         LLVM_FALLTHROUGH;
10677       case DeclaratorChunk::Array:
10678         NeedsTypedef = true;
10679         extendRight(After, Chunk.getSourceRange());
10680         break;
10681 
10682       case DeclaratorChunk::Pointer:
10683       case DeclaratorChunk::BlockPointer:
10684       case DeclaratorChunk::Reference:
10685       case DeclaratorChunk::MemberPointer:
10686       case DeclaratorChunk::Pipe:
10687         extendLeft(Before, Chunk.getSourceRange());
10688         break;
10689 
10690       case DeclaratorChunk::Paren:
10691         extendLeft(Before, Chunk.Loc);
10692         extendRight(After, Chunk.EndLoc);
10693         break;
10694       }
10695     }
10696 
10697     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10698                          After.isValid()  ? After.getBegin() :
10699                                             D.getIdentifierLoc();
10700     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10701     DB << Before << After;
10702 
10703     if (!NeedsTypedef) {
10704       DB << /*don't need a typedef*/0;
10705 
10706       // If we can provide a correct fix-it hint, do so.
10707       if (After.isInvalid() && ConvTSI) {
10708         SourceLocation InsertLoc =
10709             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10710         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10711            << FixItHint::CreateInsertionFromRange(
10712                   InsertLoc, CharSourceRange::getTokenRange(Before))
10713            << FixItHint::CreateRemoval(Before);
10714       }
10715     } else if (!Proto->getReturnType()->isDependentType()) {
10716       DB << /*typedef*/1 << Proto->getReturnType();
10717     } else if (getLangOpts().CPlusPlus11) {
10718       DB << /*alias template*/2 << Proto->getReturnType();
10719     } else {
10720       DB << /*might not be fixable*/3;
10721     }
10722 
10723     // Recover by incorporating the other type chunks into the result type.
10724     // Note, this does *not* change the name of the function. This is compatible
10725     // with the GCC extension:
10726     //   struct S { &operator int(); } s;
10727     //   int &r = s.operator int(); // ok in GCC
10728     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10729     ConvType = Proto->getReturnType();
10730   }
10731 
10732   // C++ [class.conv.fct]p4:
10733   //   The conversion-type-id shall not represent a function type nor
10734   //   an array type.
10735   if (ConvType->isArrayType()) {
10736     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10737     ConvType = Context.getPointerType(ConvType);
10738     D.setInvalidType();
10739   } else if (ConvType->isFunctionType()) {
10740     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10741     ConvType = Context.getPointerType(ConvType);
10742     D.setInvalidType();
10743   }
10744 
10745   // Rebuild the function type "R" without any parameters (in case any
10746   // of the errors above fired) and with the conversion type as the
10747   // return type.
10748   if (D.isInvalidType())
10749     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10750 
10751   // C++0x explicit conversion operators.
10752   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10753     Diag(DS.getExplicitSpecLoc(),
10754          getLangOpts().CPlusPlus11
10755              ? diag::warn_cxx98_compat_explicit_conversion_functions
10756              : diag::ext_explicit_conversion_functions)
10757         << SourceRange(DS.getExplicitSpecRange());
10758 }
10759 
10760 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10761 /// the declaration of the given C++ conversion function. This routine
10762 /// is responsible for recording the conversion function in the C++
10763 /// class, if possible.
10764 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10765   assert(Conversion && "Expected to receive a conversion function declaration");
10766 
10767   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10768 
10769   // Make sure we aren't redeclaring the conversion function.
10770   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10771   // C++ [class.conv.fct]p1:
10772   //   [...] A conversion function is never used to convert a
10773   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10774   //   same object type (or a reference to it), to a (possibly
10775   //   cv-qualified) base class of that type (or a reference to it),
10776   //   or to (possibly cv-qualified) void.
10777   QualType ClassType
10778     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10779   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10780     ConvType = ConvTypeRef->getPointeeType();
10781   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10782       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10783     /* Suppress diagnostics for instantiations. */;
10784   else if (Conversion->size_overridden_methods() != 0)
10785     /* Suppress diagnostics for overriding virtual function in a base class. */;
10786   else if (ConvType->isRecordType()) {
10787     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10788     if (ConvType == ClassType)
10789       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10790         << ClassType;
10791     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10792       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10793         <<  ClassType << ConvType;
10794   } else if (ConvType->isVoidType()) {
10795     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10796       << ClassType << ConvType;
10797   }
10798 
10799   if (FunctionTemplateDecl *ConversionTemplate
10800                                 = Conversion->getDescribedFunctionTemplate())
10801     return ConversionTemplate;
10802 
10803   return Conversion;
10804 }
10805 
10806 namespace {
10807 /// Utility class to accumulate and print a diagnostic listing the invalid
10808 /// specifier(s) on a declaration.
10809 struct BadSpecifierDiagnoser {
10810   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10811       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10812   ~BadSpecifierDiagnoser() {
10813     Diagnostic << Specifiers;
10814   }
10815 
10816   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10817     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10818   }
10819   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10820     return check(SpecLoc,
10821                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10822   }
10823   void check(SourceLocation SpecLoc, const char *Spec) {
10824     if (SpecLoc.isInvalid()) return;
10825     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10826     if (!Specifiers.empty()) Specifiers += " ";
10827     Specifiers += Spec;
10828   }
10829 
10830   Sema &S;
10831   Sema::SemaDiagnosticBuilder Diagnostic;
10832   std::string Specifiers;
10833 };
10834 }
10835 
10836 /// Check the validity of a declarator that we parsed for a deduction-guide.
10837 /// These aren't actually declarators in the grammar, so we need to check that
10838 /// the user didn't specify any pieces that are not part of the deduction-guide
10839 /// grammar.
10840 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10841                                          StorageClass &SC) {
10842   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10843   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10844   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10845 
10846   // C++ [temp.deduct.guide]p3:
10847   //   A deduction-gide shall be declared in the same scope as the
10848   //   corresponding class template.
10849   if (!CurContext->getRedeclContext()->Equals(
10850           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10851     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10852       << GuidedTemplateDecl;
10853     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10854   }
10855 
10856   auto &DS = D.getMutableDeclSpec();
10857   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10858   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10859       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10860       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10861     BadSpecifierDiagnoser Diagnoser(
10862         *this, D.getIdentifierLoc(),
10863         diag::err_deduction_guide_invalid_specifier);
10864 
10865     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10866     DS.ClearStorageClassSpecs();
10867     SC = SC_None;
10868 
10869     // 'explicit' is permitted.
10870     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10871     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10872     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10873     DS.ClearConstexprSpec();
10874 
10875     Diagnoser.check(DS.getConstSpecLoc(), "const");
10876     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10877     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10878     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10879     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10880     DS.ClearTypeQualifiers();
10881 
10882     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10883     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10884     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10885     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10886     DS.ClearTypeSpecType();
10887   }
10888 
10889   if (D.isInvalidType())
10890     return;
10891 
10892   // Check the declarator is simple enough.
10893   bool FoundFunction = false;
10894   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10895     if (Chunk.Kind == DeclaratorChunk::Paren)
10896       continue;
10897     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10898       Diag(D.getDeclSpec().getBeginLoc(),
10899            diag::err_deduction_guide_with_complex_decl)
10900           << D.getSourceRange();
10901       break;
10902     }
10903     if (!Chunk.Fun.hasTrailingReturnType()) {
10904       Diag(D.getName().getBeginLoc(),
10905            diag::err_deduction_guide_no_trailing_return_type);
10906       break;
10907     }
10908 
10909     // Check that the return type is written as a specialization of
10910     // the template specified as the deduction-guide's name.
10911     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10912     TypeSourceInfo *TSI = nullptr;
10913     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10914     assert(TSI && "deduction guide has valid type but invalid return type?");
10915     bool AcceptableReturnType = false;
10916     bool MightInstantiateToSpecialization = false;
10917     if (auto RetTST =
10918             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10919       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10920       bool TemplateMatches =
10921           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10922       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10923         AcceptableReturnType = true;
10924       else {
10925         // This could still instantiate to the right type, unless we know it
10926         // names the wrong class template.
10927         auto *TD = SpecifiedName.getAsTemplateDecl();
10928         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10929                                              !TemplateMatches);
10930       }
10931     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10932       MightInstantiateToSpecialization = true;
10933     }
10934 
10935     if (!AcceptableReturnType) {
10936       Diag(TSI->getTypeLoc().getBeginLoc(),
10937            diag::err_deduction_guide_bad_trailing_return_type)
10938           << GuidedTemplate << TSI->getType()
10939           << MightInstantiateToSpecialization
10940           << TSI->getTypeLoc().getSourceRange();
10941     }
10942 
10943     // Keep going to check that we don't have any inner declarator pieces (we
10944     // could still have a function returning a pointer to a function).
10945     FoundFunction = true;
10946   }
10947 
10948   if (D.isFunctionDefinition())
10949     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10950 }
10951 
10952 //===----------------------------------------------------------------------===//
10953 // Namespace Handling
10954 //===----------------------------------------------------------------------===//
10955 
10956 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10957 /// reopened.
10958 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10959                                             SourceLocation Loc,
10960                                             IdentifierInfo *II, bool *IsInline,
10961                                             NamespaceDecl *PrevNS) {
10962   assert(*IsInline != PrevNS->isInline());
10963 
10964   if (PrevNS->isInline())
10965     // The user probably just forgot the 'inline', so suggest that it
10966     // be added back.
10967     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10968       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10969   else
10970     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10971 
10972   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10973   *IsInline = PrevNS->isInline();
10974 }
10975 
10976 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10977 /// definition.
10978 Decl *Sema::ActOnStartNamespaceDef(
10979     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10980     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10981     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10982   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10983   // For anonymous namespace, take the location of the left brace.
10984   SourceLocation Loc = II ? IdentLoc : LBrace;
10985   bool IsInline = InlineLoc.isValid();
10986   bool IsInvalid = false;
10987   bool IsStd = false;
10988   bool AddToKnown = false;
10989   Scope *DeclRegionScope = NamespcScope->getParent();
10990 
10991   NamespaceDecl *PrevNS = nullptr;
10992   if (II) {
10993     // C++ [namespace.def]p2:
10994     //   The identifier in an original-namespace-definition shall not
10995     //   have been previously defined in the declarative region in
10996     //   which the original-namespace-definition appears. The
10997     //   identifier in an original-namespace-definition is the name of
10998     //   the namespace. Subsequently in that declarative region, it is
10999     //   treated as an original-namespace-name.
11000     //
11001     // Since namespace names are unique in their scope, and we don't
11002     // look through using directives, just look for any ordinary names
11003     // as if by qualified name lookup.
11004     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11005                    ForExternalRedeclaration);
11006     LookupQualifiedName(R, CurContext->getRedeclContext());
11007     NamedDecl *PrevDecl =
11008         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11009     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11010 
11011     if (PrevNS) {
11012       // This is an extended namespace definition.
11013       if (IsInline != PrevNS->isInline())
11014         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11015                                         &IsInline, PrevNS);
11016     } else if (PrevDecl) {
11017       // This is an invalid name redefinition.
11018       Diag(Loc, diag::err_redefinition_different_kind)
11019         << II;
11020       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11021       IsInvalid = true;
11022       // Continue on to push Namespc as current DeclContext and return it.
11023     } else if (II->isStr("std") &&
11024                CurContext->getRedeclContext()->isTranslationUnit()) {
11025       // This is the first "real" definition of the namespace "std", so update
11026       // our cache of the "std" namespace to point at this definition.
11027       PrevNS = getStdNamespace();
11028       IsStd = true;
11029       AddToKnown = !IsInline;
11030     } else {
11031       // We've seen this namespace for the first time.
11032       AddToKnown = !IsInline;
11033     }
11034   } else {
11035     // Anonymous namespaces.
11036 
11037     // Determine whether the parent already has an anonymous namespace.
11038     DeclContext *Parent = CurContext->getRedeclContext();
11039     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11040       PrevNS = TU->getAnonymousNamespace();
11041     } else {
11042       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11043       PrevNS = ND->getAnonymousNamespace();
11044     }
11045 
11046     if (PrevNS && IsInline != PrevNS->isInline())
11047       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11048                                       &IsInline, PrevNS);
11049   }
11050 
11051   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11052                                                  StartLoc, Loc, II, PrevNS);
11053   if (IsInvalid)
11054     Namespc->setInvalidDecl();
11055 
11056   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11057   AddPragmaAttributes(DeclRegionScope, Namespc);
11058 
11059   // FIXME: Should we be merging attributes?
11060   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11061     PushNamespaceVisibilityAttr(Attr, Loc);
11062 
11063   if (IsStd)
11064     StdNamespace = Namespc;
11065   if (AddToKnown)
11066     KnownNamespaces[Namespc] = false;
11067 
11068   if (II) {
11069     PushOnScopeChains(Namespc, DeclRegionScope);
11070   } else {
11071     // Link the anonymous namespace into its parent.
11072     DeclContext *Parent = CurContext->getRedeclContext();
11073     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11074       TU->setAnonymousNamespace(Namespc);
11075     } else {
11076       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11077     }
11078 
11079     CurContext->addDecl(Namespc);
11080 
11081     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11082     //   behaves as if it were replaced by
11083     //     namespace unique { /* empty body */ }
11084     //     using namespace unique;
11085     //     namespace unique { namespace-body }
11086     //   where all occurrences of 'unique' in a translation unit are
11087     //   replaced by the same identifier and this identifier differs
11088     //   from all other identifiers in the entire program.
11089 
11090     // We just create the namespace with an empty name and then add an
11091     // implicit using declaration, just like the standard suggests.
11092     //
11093     // CodeGen enforces the "universally unique" aspect by giving all
11094     // declarations semantically contained within an anonymous
11095     // namespace internal linkage.
11096 
11097     if (!PrevNS) {
11098       UD = UsingDirectiveDecl::Create(Context, Parent,
11099                                       /* 'using' */ LBrace,
11100                                       /* 'namespace' */ SourceLocation(),
11101                                       /* qualifier */ NestedNameSpecifierLoc(),
11102                                       /* identifier */ SourceLocation(),
11103                                       Namespc,
11104                                       /* Ancestor */ Parent);
11105       UD->setImplicit();
11106       Parent->addDecl(UD);
11107     }
11108   }
11109 
11110   ActOnDocumentableDecl(Namespc);
11111 
11112   // Although we could have an invalid decl (i.e. the namespace name is a
11113   // redefinition), push it as current DeclContext and try to continue parsing.
11114   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11115   // for the namespace has the declarations that showed up in that particular
11116   // namespace definition.
11117   PushDeclContext(NamespcScope, Namespc);
11118   return Namespc;
11119 }
11120 
11121 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11122 /// is a namespace alias, returns the namespace it points to.
11123 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11124   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11125     return AD->getNamespace();
11126   return dyn_cast_or_null<NamespaceDecl>(D);
11127 }
11128 
11129 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11130 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11131 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11132   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11133   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11134   Namespc->setRBraceLoc(RBrace);
11135   PopDeclContext();
11136   if (Namespc->hasAttr<VisibilityAttr>())
11137     PopPragmaVisibility(true, RBrace);
11138   // If this namespace contains an export-declaration, export it now.
11139   if (DeferredExportedNamespaces.erase(Namespc))
11140     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11141 }
11142 
11143 CXXRecordDecl *Sema::getStdBadAlloc() const {
11144   return cast_or_null<CXXRecordDecl>(
11145                                   StdBadAlloc.get(Context.getExternalSource()));
11146 }
11147 
11148 EnumDecl *Sema::getStdAlignValT() const {
11149   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11150 }
11151 
11152 NamespaceDecl *Sema::getStdNamespace() const {
11153   return cast_or_null<NamespaceDecl>(
11154                                  StdNamespace.get(Context.getExternalSource()));
11155 }
11156 
11157 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11158   if (!StdExperimentalNamespaceCache) {
11159     if (auto Std = getStdNamespace()) {
11160       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11161                           SourceLocation(), LookupNamespaceName);
11162       if (!LookupQualifiedName(Result, Std) ||
11163           !(StdExperimentalNamespaceCache =
11164                 Result.getAsSingle<NamespaceDecl>()))
11165         Result.suppressDiagnostics();
11166     }
11167   }
11168   return StdExperimentalNamespaceCache;
11169 }
11170 
11171 namespace {
11172 
11173 enum UnsupportedSTLSelect {
11174   USS_InvalidMember,
11175   USS_MissingMember,
11176   USS_NonTrivial,
11177   USS_Other
11178 };
11179 
11180 struct InvalidSTLDiagnoser {
11181   Sema &S;
11182   SourceLocation Loc;
11183   QualType TyForDiags;
11184 
11185   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11186                       const VarDecl *VD = nullptr) {
11187     {
11188       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11189                << TyForDiags << ((int)Sel);
11190       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11191         assert(!Name.empty());
11192         D << Name;
11193       }
11194     }
11195     if (Sel == USS_InvalidMember) {
11196       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11197           << VD << VD->getSourceRange();
11198     }
11199     return QualType();
11200   }
11201 };
11202 } // namespace
11203 
11204 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11205                                            SourceLocation Loc,
11206                                            ComparisonCategoryUsage Usage) {
11207   assert(getLangOpts().CPlusPlus &&
11208          "Looking for comparison category type outside of C++.");
11209 
11210   // Use an elaborated type for diagnostics which has a name containing the
11211   // prepended 'std' namespace but not any inline namespace names.
11212   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11213     auto *NNS =
11214         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11215     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11216   };
11217 
11218   // Check if we've already successfully checked the comparison category type
11219   // before. If so, skip checking it again.
11220   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11221   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11222     // The only thing we need to check is that the type has a reachable
11223     // definition in the current context.
11224     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11225       return QualType();
11226 
11227     return Info->getType();
11228   }
11229 
11230   // If lookup failed
11231   if (!Info) {
11232     std::string NameForDiags = "std::";
11233     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11234     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11235         << NameForDiags << (int)Usage;
11236     return QualType();
11237   }
11238 
11239   assert(Info->Kind == Kind);
11240   assert(Info->Record);
11241 
11242   // Update the Record decl in case we encountered a forward declaration on our
11243   // first pass. FIXME: This is a bit of a hack.
11244   if (Info->Record->hasDefinition())
11245     Info->Record = Info->Record->getDefinition();
11246 
11247   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11248     return QualType();
11249 
11250   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11251 
11252   if (!Info->Record->isTriviallyCopyable())
11253     return UnsupportedSTLError(USS_NonTrivial);
11254 
11255   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11256     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11257     // Tolerate empty base classes.
11258     if (Base->isEmpty())
11259       continue;
11260     // Reject STL implementations which have at least one non-empty base.
11261     return UnsupportedSTLError();
11262   }
11263 
11264   // Check that the STL has implemented the types using a single integer field.
11265   // This expectation allows better codegen for builtin operators. We require:
11266   //   (1) The class has exactly one field.
11267   //   (2) The field is an integral or enumeration type.
11268   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11269   if (std::distance(FIt, FEnd) != 1 ||
11270       !FIt->getType()->isIntegralOrEnumerationType()) {
11271     return UnsupportedSTLError();
11272   }
11273 
11274   // Build each of the require values and store them in Info.
11275   for (ComparisonCategoryResult CCR :
11276        ComparisonCategories::getPossibleResultsForType(Kind)) {
11277     StringRef MemName = ComparisonCategories::getResultString(CCR);
11278     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11279 
11280     if (!ValInfo)
11281       return UnsupportedSTLError(USS_MissingMember, MemName);
11282 
11283     VarDecl *VD = ValInfo->VD;
11284     assert(VD && "should not be null!");
11285 
11286     // Attempt to diagnose reasons why the STL definition of this type
11287     // might be foobar, including it failing to be a constant expression.
11288     // TODO Handle more ways the lookup or result can be invalid.
11289     if (!VD->isStaticDataMember() ||
11290         !VD->isUsableInConstantExpressions(Context))
11291       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11292 
11293     // Attempt to evaluate the var decl as a constant expression and extract
11294     // the value of its first field as a ICE. If this fails, the STL
11295     // implementation is not supported.
11296     if (!ValInfo->hasValidIntValue())
11297       return UnsupportedSTLError();
11298 
11299     MarkVariableReferenced(Loc, VD);
11300   }
11301 
11302   // We've successfully built the required types and expressions. Update
11303   // the cache and return the newly cached value.
11304   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11305   return Info->getType();
11306 }
11307 
11308 /// Retrieve the special "std" namespace, which may require us to
11309 /// implicitly define the namespace.
11310 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11311   if (!StdNamespace) {
11312     // The "std" namespace has not yet been defined, so build one implicitly.
11313     StdNamespace = NamespaceDecl::Create(Context,
11314                                          Context.getTranslationUnitDecl(),
11315                                          /*Inline=*/false,
11316                                          SourceLocation(), SourceLocation(),
11317                                          &PP.getIdentifierTable().get("std"),
11318                                          /*PrevDecl=*/nullptr);
11319     getStdNamespace()->setImplicit(true);
11320   }
11321 
11322   return getStdNamespace();
11323 }
11324 
11325 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11326   assert(getLangOpts().CPlusPlus &&
11327          "Looking for std::initializer_list outside of C++.");
11328 
11329   // We're looking for implicit instantiations of
11330   // template <typename E> class std::initializer_list.
11331 
11332   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11333     return false;
11334 
11335   ClassTemplateDecl *Template = nullptr;
11336   const TemplateArgument *Arguments = nullptr;
11337 
11338   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11339 
11340     ClassTemplateSpecializationDecl *Specialization =
11341         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11342     if (!Specialization)
11343       return false;
11344 
11345     Template = Specialization->getSpecializedTemplate();
11346     Arguments = Specialization->getTemplateArgs().data();
11347   } else if (const TemplateSpecializationType *TST =
11348                  Ty->getAs<TemplateSpecializationType>()) {
11349     Template = dyn_cast_or_null<ClassTemplateDecl>(
11350         TST->getTemplateName().getAsTemplateDecl());
11351     Arguments = TST->getArgs();
11352   }
11353   if (!Template)
11354     return false;
11355 
11356   if (!StdInitializerList) {
11357     // Haven't recognized std::initializer_list yet, maybe this is it.
11358     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11359     if (TemplateClass->getIdentifier() !=
11360             &PP.getIdentifierTable().get("initializer_list") ||
11361         !getStdNamespace()->InEnclosingNamespaceSetOf(
11362             TemplateClass->getDeclContext()))
11363       return false;
11364     // This is a template called std::initializer_list, but is it the right
11365     // template?
11366     TemplateParameterList *Params = Template->getTemplateParameters();
11367     if (Params->getMinRequiredArguments() != 1)
11368       return false;
11369     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11370       return false;
11371 
11372     // It's the right template.
11373     StdInitializerList = Template;
11374   }
11375 
11376   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11377     return false;
11378 
11379   // This is an instance of std::initializer_list. Find the argument type.
11380   if (Element)
11381     *Element = Arguments[0].getAsType();
11382   return true;
11383 }
11384 
11385 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11386   NamespaceDecl *Std = S.getStdNamespace();
11387   if (!Std) {
11388     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11389     return nullptr;
11390   }
11391 
11392   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11393                       Loc, Sema::LookupOrdinaryName);
11394   if (!S.LookupQualifiedName(Result, Std)) {
11395     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11396     return nullptr;
11397   }
11398   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11399   if (!Template) {
11400     Result.suppressDiagnostics();
11401     // We found something weird. Complain about the first thing we found.
11402     NamedDecl *Found = *Result.begin();
11403     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11404     return nullptr;
11405   }
11406 
11407   // We found some template called std::initializer_list. Now verify that it's
11408   // correct.
11409   TemplateParameterList *Params = Template->getTemplateParameters();
11410   if (Params->getMinRequiredArguments() != 1 ||
11411       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11412     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11413     return nullptr;
11414   }
11415 
11416   return Template;
11417 }
11418 
11419 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11420   if (!StdInitializerList) {
11421     StdInitializerList = LookupStdInitializerList(*this, Loc);
11422     if (!StdInitializerList)
11423       return QualType();
11424   }
11425 
11426   TemplateArgumentListInfo Args(Loc, Loc);
11427   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11428                                        Context.getTrivialTypeSourceInfo(Element,
11429                                                                         Loc)));
11430   return Context.getCanonicalType(
11431       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11432 }
11433 
11434 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11435   // C++ [dcl.init.list]p2:
11436   //   A constructor is an initializer-list constructor if its first parameter
11437   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11438   //   std::initializer_list<E> for some type E, and either there are no other
11439   //   parameters or else all other parameters have default arguments.
11440   if (!Ctor->hasOneParamOrDefaultArgs())
11441     return false;
11442 
11443   QualType ArgType = Ctor->getParamDecl(0)->getType();
11444   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11445     ArgType = RT->getPointeeType().getUnqualifiedType();
11446 
11447   return isStdInitializerList(ArgType, nullptr);
11448 }
11449 
11450 /// Determine whether a using statement is in a context where it will be
11451 /// apply in all contexts.
11452 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11453   switch (CurContext->getDeclKind()) {
11454     case Decl::TranslationUnit:
11455       return true;
11456     case Decl::LinkageSpec:
11457       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11458     default:
11459       return false;
11460   }
11461 }
11462 
11463 namespace {
11464 
11465 // Callback to only accept typo corrections that are namespaces.
11466 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11467 public:
11468   bool ValidateCandidate(const TypoCorrection &candidate) override {
11469     if (NamedDecl *ND = candidate.getCorrectionDecl())
11470       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11471     return false;
11472   }
11473 
11474   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11475     return std::make_unique<NamespaceValidatorCCC>(*this);
11476   }
11477 };
11478 
11479 }
11480 
11481 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11482                                        CXXScopeSpec &SS,
11483                                        SourceLocation IdentLoc,
11484                                        IdentifierInfo *Ident) {
11485   R.clear();
11486   NamespaceValidatorCCC CCC{};
11487   if (TypoCorrection Corrected =
11488           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11489                         Sema::CTK_ErrorRecovery)) {
11490     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11491       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11492       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11493                               Ident->getName().equals(CorrectedStr);
11494       S.diagnoseTypo(Corrected,
11495                      S.PDiag(diag::err_using_directive_member_suggest)
11496                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11497                      S.PDiag(diag::note_namespace_defined_here));
11498     } else {
11499       S.diagnoseTypo(Corrected,
11500                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11501                      S.PDiag(diag::note_namespace_defined_here));
11502     }
11503     R.addDecl(Corrected.getFoundDecl());
11504     return true;
11505   }
11506   return false;
11507 }
11508 
11509 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11510                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11511                                 SourceLocation IdentLoc,
11512                                 IdentifierInfo *NamespcName,
11513                                 const ParsedAttributesView &AttrList) {
11514   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11515   assert(NamespcName && "Invalid NamespcName.");
11516   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11517 
11518   // This can only happen along a recovery path.
11519   while (S->isTemplateParamScope())
11520     S = S->getParent();
11521   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11522 
11523   UsingDirectiveDecl *UDir = nullptr;
11524   NestedNameSpecifier *Qualifier = nullptr;
11525   if (SS.isSet())
11526     Qualifier = SS.getScopeRep();
11527 
11528   // Lookup namespace name.
11529   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11530   LookupParsedName(R, S, &SS);
11531   if (R.isAmbiguous())
11532     return nullptr;
11533 
11534   if (R.empty()) {
11535     R.clear();
11536     // Allow "using namespace std;" or "using namespace ::std;" even if
11537     // "std" hasn't been defined yet, for GCC compatibility.
11538     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11539         NamespcName->isStr("std")) {
11540       Diag(IdentLoc, diag::ext_using_undefined_std);
11541       R.addDecl(getOrCreateStdNamespace());
11542       R.resolveKind();
11543     }
11544     // Otherwise, attempt typo correction.
11545     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11546   }
11547 
11548   if (!R.empty()) {
11549     NamedDecl *Named = R.getRepresentativeDecl();
11550     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11551     assert(NS && "expected namespace decl");
11552 
11553     // The use of a nested name specifier may trigger deprecation warnings.
11554     DiagnoseUseOfDecl(Named, IdentLoc);
11555 
11556     // C++ [namespace.udir]p1:
11557     //   A using-directive specifies that the names in the nominated
11558     //   namespace can be used in the scope in which the
11559     //   using-directive appears after the using-directive. During
11560     //   unqualified name lookup (3.4.1), the names appear as if they
11561     //   were declared in the nearest enclosing namespace which
11562     //   contains both the using-directive and the nominated
11563     //   namespace. [Note: in this context, "contains" means "contains
11564     //   directly or indirectly". ]
11565 
11566     // Find enclosing context containing both using-directive and
11567     // nominated namespace.
11568     DeclContext *CommonAncestor = NS;
11569     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11570       CommonAncestor = CommonAncestor->getParent();
11571 
11572     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11573                                       SS.getWithLocInContext(Context),
11574                                       IdentLoc, Named, CommonAncestor);
11575 
11576     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11577         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11578       Diag(IdentLoc, diag::warn_using_directive_in_header);
11579     }
11580 
11581     PushUsingDirective(S, UDir);
11582   } else {
11583     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11584   }
11585 
11586   if (UDir)
11587     ProcessDeclAttributeList(S, UDir, AttrList);
11588 
11589   return UDir;
11590 }
11591 
11592 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11593   // If the scope has an associated entity and the using directive is at
11594   // namespace or translation unit scope, add the UsingDirectiveDecl into
11595   // its lookup structure so qualified name lookup can find it.
11596   DeclContext *Ctx = S->getEntity();
11597   if (Ctx && !Ctx->isFunctionOrMethod())
11598     Ctx->addDecl(UDir);
11599   else
11600     // Otherwise, it is at block scope. The using-directives will affect lookup
11601     // only to the end of the scope.
11602     S->PushUsingDirective(UDir);
11603 }
11604 
11605 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11606                                   SourceLocation UsingLoc,
11607                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11608                                   UnqualifiedId &Name,
11609                                   SourceLocation EllipsisLoc,
11610                                   const ParsedAttributesView &AttrList) {
11611   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11612 
11613   if (SS.isEmpty()) {
11614     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11615     return nullptr;
11616   }
11617 
11618   switch (Name.getKind()) {
11619   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11620   case UnqualifiedIdKind::IK_Identifier:
11621   case UnqualifiedIdKind::IK_OperatorFunctionId:
11622   case UnqualifiedIdKind::IK_LiteralOperatorId:
11623   case UnqualifiedIdKind::IK_ConversionFunctionId:
11624     break;
11625 
11626   case UnqualifiedIdKind::IK_ConstructorName:
11627   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11628     // C++11 inheriting constructors.
11629     Diag(Name.getBeginLoc(),
11630          getLangOpts().CPlusPlus11
11631              ? diag::warn_cxx98_compat_using_decl_constructor
11632              : diag::err_using_decl_constructor)
11633         << SS.getRange();
11634 
11635     if (getLangOpts().CPlusPlus11) break;
11636 
11637     return nullptr;
11638 
11639   case UnqualifiedIdKind::IK_DestructorName:
11640     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11641     return nullptr;
11642 
11643   case UnqualifiedIdKind::IK_TemplateId:
11644     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11645         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11646     return nullptr;
11647 
11648   case UnqualifiedIdKind::IK_DeductionGuideName:
11649     llvm_unreachable("cannot parse qualified deduction guide name");
11650   }
11651 
11652   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11653   DeclarationName TargetName = TargetNameInfo.getName();
11654   if (!TargetName)
11655     return nullptr;
11656 
11657   // Warn about access declarations.
11658   if (UsingLoc.isInvalid()) {
11659     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11660                                  ? diag::err_access_decl
11661                                  : diag::warn_access_decl_deprecated)
11662         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11663   }
11664 
11665   if (EllipsisLoc.isInvalid()) {
11666     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11667         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11668       return nullptr;
11669   } else {
11670     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11671         !TargetNameInfo.containsUnexpandedParameterPack()) {
11672       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11673         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11674       EllipsisLoc = SourceLocation();
11675     }
11676   }
11677 
11678   NamedDecl *UD =
11679       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11680                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11681                             /*IsInstantiation*/ false,
11682                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11683   if (UD)
11684     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11685 
11686   return UD;
11687 }
11688 
11689 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11690                                       SourceLocation UsingLoc,
11691                                       SourceLocation EnumLoc,
11692                                       const DeclSpec &DS) {
11693   switch (DS.getTypeSpecType()) {
11694   case DeclSpec::TST_error:
11695     // This will already have been diagnosed
11696     return nullptr;
11697 
11698   case DeclSpec::TST_enum:
11699     break;
11700 
11701   case DeclSpec::TST_typename:
11702     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11703     return nullptr;
11704 
11705   default:
11706     llvm_unreachable("unexpected DeclSpec type");
11707   }
11708 
11709   // As with enum-decls, we ignore attributes for now.
11710   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11711   if (auto *Def = Enum->getDefinition())
11712     Enum = Def;
11713 
11714   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11715                                        DS.getTypeSpecTypeNameLoc(), Enum);
11716   if (UD)
11717     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11718 
11719   return UD;
11720 }
11721 
11722 /// Determine whether a using declaration considers the given
11723 /// declarations as "equivalent", e.g., if they are redeclarations of
11724 /// the same entity or are both typedefs of the same type.
11725 static bool
11726 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11727   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11728     return true;
11729 
11730   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11731     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11732       return Context.hasSameType(TD1->getUnderlyingType(),
11733                                  TD2->getUnderlyingType());
11734 
11735   // Two using_if_exists using-declarations are equivalent if both are
11736   // unresolved.
11737   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11738       isa<UnresolvedUsingIfExistsDecl>(D2))
11739     return true;
11740 
11741   return false;
11742 }
11743 
11744 
11745 /// Determines whether to create a using shadow decl for a particular
11746 /// decl, given the set of decls existing prior to this using lookup.
11747 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11748                                 const LookupResult &Previous,
11749                                 UsingShadowDecl *&PrevShadow) {
11750   // Diagnose finding a decl which is not from a base class of the
11751   // current class.  We do this now because there are cases where this
11752   // function will silently decide not to build a shadow decl, which
11753   // will pre-empt further diagnostics.
11754   //
11755   // We don't need to do this in C++11 because we do the check once on
11756   // the qualifier.
11757   //
11758   // FIXME: diagnose the following if we care enough:
11759   //   struct A { int foo; };
11760   //   struct B : A { using A::foo; };
11761   //   template <class T> struct C : A {};
11762   //   template <class T> struct D : C<T> { using B::foo; } // <---
11763   // This is invalid (during instantiation) in C++03 because B::foo
11764   // resolves to the using decl in B, which is not a base class of D<T>.
11765   // We can't diagnose it immediately because C<T> is an unknown
11766   // specialization. The UsingShadowDecl in D<T> then points directly
11767   // to A::foo, which will look well-formed when we instantiate.
11768   // The right solution is to not collapse the shadow-decl chain.
11769   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11770     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11771       DeclContext *OrigDC = Orig->getDeclContext();
11772 
11773       // Handle enums and anonymous structs.
11774       if (isa<EnumDecl>(OrigDC))
11775         OrigDC = OrigDC->getParent();
11776       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11777       while (OrigRec->isAnonymousStructOrUnion())
11778         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11779 
11780       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11781         if (OrigDC == CurContext) {
11782           Diag(Using->getLocation(),
11783                diag::err_using_decl_nested_name_specifier_is_current_class)
11784               << Using->getQualifierLoc().getSourceRange();
11785           Diag(Orig->getLocation(), diag::note_using_decl_target);
11786           Using->setInvalidDecl();
11787           return true;
11788         }
11789 
11790         Diag(Using->getQualifierLoc().getBeginLoc(),
11791              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11792             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11793             << Using->getQualifierLoc().getSourceRange();
11794         Diag(Orig->getLocation(), diag::note_using_decl_target);
11795         Using->setInvalidDecl();
11796         return true;
11797       }
11798     }
11799 
11800   if (Previous.empty()) return false;
11801 
11802   NamedDecl *Target = Orig;
11803   if (isa<UsingShadowDecl>(Target))
11804     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11805 
11806   // If the target happens to be one of the previous declarations, we
11807   // don't have a conflict.
11808   //
11809   // FIXME: but we might be increasing its access, in which case we
11810   // should redeclare it.
11811   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11812   bool FoundEquivalentDecl = false;
11813   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11814          I != E; ++I) {
11815     NamedDecl *D = (*I)->getUnderlyingDecl();
11816     // We can have UsingDecls in our Previous results because we use the same
11817     // LookupResult for checking whether the UsingDecl itself is a valid
11818     // redeclaration.
11819     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11820       continue;
11821 
11822     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11823       // C++ [class.mem]p19:
11824       //   If T is the name of a class, then [every named member other than
11825       //   a non-static data member] shall have a name different from T
11826       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11827           !isa<IndirectFieldDecl>(Target) &&
11828           !isa<UnresolvedUsingValueDecl>(Target) &&
11829           DiagnoseClassNameShadow(
11830               CurContext,
11831               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11832         return true;
11833     }
11834 
11835     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11836       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11837         PrevShadow = Shadow;
11838       FoundEquivalentDecl = true;
11839     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11840       // We don't conflict with an existing using shadow decl of an equivalent
11841       // declaration, but we're not a redeclaration of it.
11842       FoundEquivalentDecl = true;
11843     }
11844 
11845     if (isVisible(D))
11846       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11847   }
11848 
11849   if (FoundEquivalentDecl)
11850     return false;
11851 
11852   // Always emit a diagnostic for a mismatch between an unresolved
11853   // using_if_exists and a resolved using declaration in either direction.
11854   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11855       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11856     if (!NonTag && !Tag)
11857       return false;
11858     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11859     Diag(Target->getLocation(), diag::note_using_decl_target);
11860     Diag((NonTag ? NonTag : Tag)->getLocation(),
11861          diag::note_using_decl_conflict);
11862     BUD->setInvalidDecl();
11863     return true;
11864   }
11865 
11866   if (FunctionDecl *FD = Target->getAsFunction()) {
11867     NamedDecl *OldDecl = nullptr;
11868     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11869                           /*IsForUsingDecl*/ true)) {
11870     case Ovl_Overload:
11871       return false;
11872 
11873     case Ovl_NonFunction:
11874       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11875       break;
11876 
11877     // We found a decl with the exact signature.
11878     case Ovl_Match:
11879       // If we're in a record, we want to hide the target, so we
11880       // return true (without a diagnostic) to tell the caller not to
11881       // build a shadow decl.
11882       if (CurContext->isRecord())
11883         return true;
11884 
11885       // If we're not in a record, this is an error.
11886       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11887       break;
11888     }
11889 
11890     Diag(Target->getLocation(), diag::note_using_decl_target);
11891     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11892     BUD->setInvalidDecl();
11893     return true;
11894   }
11895 
11896   // Target is not a function.
11897 
11898   if (isa<TagDecl>(Target)) {
11899     // No conflict between a tag and a non-tag.
11900     if (!Tag) return false;
11901 
11902     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11903     Diag(Target->getLocation(), diag::note_using_decl_target);
11904     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11905     BUD->setInvalidDecl();
11906     return true;
11907   }
11908 
11909   // No conflict between a tag and a non-tag.
11910   if (!NonTag) return false;
11911 
11912   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11913   Diag(Target->getLocation(), diag::note_using_decl_target);
11914   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11915   BUD->setInvalidDecl();
11916   return true;
11917 }
11918 
11919 /// Determine whether a direct base class is a virtual base class.
11920 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11921   if (!Derived->getNumVBases())
11922     return false;
11923   for (auto &B : Derived->bases())
11924     if (B.getType()->getAsCXXRecordDecl() == Base)
11925       return B.isVirtual();
11926   llvm_unreachable("not a direct base class");
11927 }
11928 
11929 /// Builds a shadow declaration corresponding to a 'using' declaration.
11930 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
11931                                             NamedDecl *Orig,
11932                                             UsingShadowDecl *PrevDecl) {
11933   // If we resolved to another shadow declaration, just coalesce them.
11934   NamedDecl *Target = Orig;
11935   if (isa<UsingShadowDecl>(Target)) {
11936     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11937     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11938   }
11939 
11940   NamedDecl *NonTemplateTarget = Target;
11941   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11942     NonTemplateTarget = TargetTD->getTemplatedDecl();
11943 
11944   UsingShadowDecl *Shadow;
11945   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11946     UsingDecl *Using = cast<UsingDecl>(BUD);
11947     bool IsVirtualBase =
11948         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11949                             Using->getQualifier()->getAsRecordDecl());
11950     Shadow = ConstructorUsingShadowDecl::Create(
11951         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
11952   } else {
11953     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
11954                                      Target->getDeclName(), BUD, Target);
11955   }
11956   BUD->addShadowDecl(Shadow);
11957 
11958   Shadow->setAccess(BUD->getAccess());
11959   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
11960     Shadow->setInvalidDecl();
11961 
11962   Shadow->setPreviousDecl(PrevDecl);
11963 
11964   if (S)
11965     PushOnScopeChains(Shadow, S);
11966   else
11967     CurContext->addDecl(Shadow);
11968 
11969 
11970   return Shadow;
11971 }
11972 
11973 /// Hides a using shadow declaration.  This is required by the current
11974 /// using-decl implementation when a resolvable using declaration in a
11975 /// class is followed by a declaration which would hide or override
11976 /// one or more of the using decl's targets; for example:
11977 ///
11978 ///   struct Base { void foo(int); };
11979 ///   struct Derived : Base {
11980 ///     using Base::foo;
11981 ///     void foo(int);
11982 ///   };
11983 ///
11984 /// The governing language is C++03 [namespace.udecl]p12:
11985 ///
11986 ///   When a using-declaration brings names from a base class into a
11987 ///   derived class scope, member functions in the derived class
11988 ///   override and/or hide member functions with the same name and
11989 ///   parameter types in a base class (rather than conflicting).
11990 ///
11991 /// There are two ways to implement this:
11992 ///   (1) optimistically create shadow decls when they're not hidden
11993 ///       by existing declarations, or
11994 ///   (2) don't create any shadow decls (or at least don't make them
11995 ///       visible) until we've fully parsed/instantiated the class.
11996 /// The problem with (1) is that we might have to retroactively remove
11997 /// a shadow decl, which requires several O(n) operations because the
11998 /// decl structures are (very reasonably) not designed for removal.
11999 /// (2) avoids this but is very fiddly and phase-dependent.
12000 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12001   if (Shadow->getDeclName().getNameKind() ==
12002         DeclarationName::CXXConversionFunctionName)
12003     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12004 
12005   // Remove it from the DeclContext...
12006   Shadow->getDeclContext()->removeDecl(Shadow);
12007 
12008   // ...and the scope, if applicable...
12009   if (S) {
12010     S->RemoveDecl(Shadow);
12011     IdResolver.RemoveDecl(Shadow);
12012   }
12013 
12014   // ...and the using decl.
12015   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12016 
12017   // TODO: complain somehow if Shadow was used.  It shouldn't
12018   // be possible for this to happen, because...?
12019 }
12020 
12021 /// Find the base specifier for a base class with the given type.
12022 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12023                                                 QualType DesiredBase,
12024                                                 bool &AnyDependentBases) {
12025   // Check whether the named type is a direct base class.
12026   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12027     .getUnqualifiedType();
12028   for (auto &Base : Derived->bases()) {
12029     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12030     if (CanonicalDesiredBase == BaseType)
12031       return &Base;
12032     if (BaseType->isDependentType())
12033       AnyDependentBases = true;
12034   }
12035   return nullptr;
12036 }
12037 
12038 namespace {
12039 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12040 public:
12041   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12042                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12043       : HasTypenameKeyword(HasTypenameKeyword),
12044         IsInstantiation(IsInstantiation), OldNNS(NNS),
12045         RequireMemberOf(RequireMemberOf) {}
12046 
12047   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12048     NamedDecl *ND = Candidate.getCorrectionDecl();
12049 
12050     // Keywords are not valid here.
12051     if (!ND || isa<NamespaceDecl>(ND))
12052       return false;
12053 
12054     // Completely unqualified names are invalid for a 'using' declaration.
12055     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12056       return false;
12057 
12058     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12059     // reject.
12060 
12061     if (RequireMemberOf) {
12062       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12063       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12064         // No-one ever wants a using-declaration to name an injected-class-name
12065         // of a base class, unless they're declaring an inheriting constructor.
12066         ASTContext &Ctx = ND->getASTContext();
12067         if (!Ctx.getLangOpts().CPlusPlus11)
12068           return false;
12069         QualType FoundType = Ctx.getRecordType(FoundRecord);
12070 
12071         // Check that the injected-class-name is named as a member of its own
12072         // type; we don't want to suggest 'using Derived::Base;', since that
12073         // means something else.
12074         NestedNameSpecifier *Specifier =
12075             Candidate.WillReplaceSpecifier()
12076                 ? Candidate.getCorrectionSpecifier()
12077                 : OldNNS;
12078         if (!Specifier->getAsType() ||
12079             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12080           return false;
12081 
12082         // Check that this inheriting constructor declaration actually names a
12083         // direct base class of the current class.
12084         bool AnyDependentBases = false;
12085         if (!findDirectBaseWithType(RequireMemberOf,
12086                                     Ctx.getRecordType(FoundRecord),
12087                                     AnyDependentBases) &&
12088             !AnyDependentBases)
12089           return false;
12090       } else {
12091         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12092         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12093           return false;
12094 
12095         // FIXME: Check that the base class member is accessible?
12096       }
12097     } else {
12098       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12099       if (FoundRecord && FoundRecord->isInjectedClassName())
12100         return false;
12101     }
12102 
12103     if (isa<TypeDecl>(ND))
12104       return HasTypenameKeyword || !IsInstantiation;
12105 
12106     return !HasTypenameKeyword;
12107   }
12108 
12109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12110     return std::make_unique<UsingValidatorCCC>(*this);
12111   }
12112 
12113 private:
12114   bool HasTypenameKeyword;
12115   bool IsInstantiation;
12116   NestedNameSpecifier *OldNNS;
12117   CXXRecordDecl *RequireMemberOf;
12118 };
12119 } // end anonymous namespace
12120 
12121 /// Remove decls we can't actually see from a lookup being used to declare
12122 /// shadow using decls.
12123 ///
12124 /// \param S - The scope of the potential shadow decl
12125 /// \param Previous - The lookup of a potential shadow decl's name.
12126 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12127   // It is really dumb that we have to do this.
12128   LookupResult::Filter F = Previous.makeFilter();
12129   while (F.hasNext()) {
12130     NamedDecl *D = F.next();
12131     if (!isDeclInScope(D, CurContext, S))
12132       F.erase();
12133     // If we found a local extern declaration that's not ordinarily visible,
12134     // and this declaration is being added to a non-block scope, ignore it.
12135     // We're only checking for scope conflicts here, not also for violations
12136     // of the linkage rules.
12137     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12138              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12139       F.erase();
12140   }
12141   F.done();
12142 }
12143 
12144 /// Builds a using declaration.
12145 ///
12146 /// \param IsInstantiation - Whether this call arises from an
12147 ///   instantiation of an unresolved using declaration.  We treat
12148 ///   the lookup differently for these declarations.
12149 NamedDecl *Sema::BuildUsingDeclaration(
12150     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12151     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12152     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12153     const ParsedAttributesView &AttrList, bool IsInstantiation,
12154     bool IsUsingIfExists) {
12155   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12156   SourceLocation IdentLoc = NameInfo.getLoc();
12157   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12158 
12159   // FIXME: We ignore attributes for now.
12160 
12161   // For an inheriting constructor declaration, the name of the using
12162   // declaration is the name of a constructor in this class, not in the
12163   // base class.
12164   DeclarationNameInfo UsingName = NameInfo;
12165   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12166     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12167       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12168           Context.getCanonicalType(Context.getRecordType(RD))));
12169 
12170   // Do the redeclaration lookup in the current scope.
12171   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12172                         ForVisibleRedeclaration);
12173   Previous.setHideTags(false);
12174   if (S) {
12175     LookupName(Previous, S);
12176 
12177     FilterUsingLookup(S, Previous);
12178   } else {
12179     assert(IsInstantiation && "no scope in non-instantiation");
12180     if (CurContext->isRecord())
12181       LookupQualifiedName(Previous, CurContext);
12182     else {
12183       // No redeclaration check is needed here; in non-member contexts we
12184       // diagnosed all possible conflicts with other using-declarations when
12185       // building the template:
12186       //
12187       // For a dependent non-type using declaration, the only valid case is
12188       // if we instantiate to a single enumerator. We check for conflicts
12189       // between shadow declarations we introduce, and we check in the template
12190       // definition for conflicts between a non-type using declaration and any
12191       // other declaration, which together covers all cases.
12192       //
12193       // A dependent typename using declaration will never successfully
12194       // instantiate, since it will always name a class member, so we reject
12195       // that in the template definition.
12196     }
12197   }
12198 
12199   // Check for invalid redeclarations.
12200   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12201                                   SS, IdentLoc, Previous))
12202     return nullptr;
12203 
12204   // 'using_if_exists' doesn't make sense on an inherited constructor.
12205   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12206                              DeclarationName::CXXConstructorName) {
12207     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12208     return nullptr;
12209   }
12210 
12211   DeclContext *LookupContext = computeDeclContext(SS);
12212   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12213   if (!LookupContext || EllipsisLoc.isValid()) {
12214     NamedDecl *D;
12215     // Dependent scope, or an unexpanded pack
12216     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12217                                                   SS, NameInfo, IdentLoc))
12218       return nullptr;
12219 
12220     if (HasTypenameKeyword) {
12221       // FIXME: not all declaration name kinds are legal here
12222       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12223                                               UsingLoc, TypenameLoc,
12224                                               QualifierLoc,
12225                                               IdentLoc, NameInfo.getName(),
12226                                               EllipsisLoc);
12227     } else {
12228       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12229                                            QualifierLoc, NameInfo, EllipsisLoc);
12230     }
12231     D->setAccess(AS);
12232     CurContext->addDecl(D);
12233     ProcessDeclAttributeList(S, D, AttrList);
12234     return D;
12235   }
12236 
12237   auto Build = [&](bool Invalid) {
12238     UsingDecl *UD =
12239         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12240                           UsingName, HasTypenameKeyword);
12241     UD->setAccess(AS);
12242     CurContext->addDecl(UD);
12243     ProcessDeclAttributeList(S, UD, AttrList);
12244     UD->setInvalidDecl(Invalid);
12245     return UD;
12246   };
12247   auto BuildInvalid = [&]{ return Build(true); };
12248   auto BuildValid = [&]{ return Build(false); };
12249 
12250   if (RequireCompleteDeclContext(SS, LookupContext))
12251     return BuildInvalid();
12252 
12253   // Look up the target name.
12254   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12255 
12256   // Unlike most lookups, we don't always want to hide tag
12257   // declarations: tag names are visible through the using declaration
12258   // even if hidden by ordinary names, *except* in a dependent context
12259   // where it's important for the sanity of two-phase lookup.
12260   if (!IsInstantiation)
12261     R.setHideTags(false);
12262 
12263   // For the purposes of this lookup, we have a base object type
12264   // equal to that of the current context.
12265   if (CurContext->isRecord()) {
12266     R.setBaseObjectType(
12267                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12268   }
12269 
12270   LookupQualifiedName(R, LookupContext);
12271 
12272   // Validate the context, now we have a lookup
12273   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12274                               IdentLoc, &R))
12275     return nullptr;
12276 
12277   if (R.empty() && IsUsingIfExists)
12278     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12279                                                   UsingName.getName()),
12280               AS_public);
12281 
12282   // Try to correct typos if possible. If constructor name lookup finds no
12283   // results, that means the named class has no explicit constructors, and we
12284   // suppressed declaring implicit ones (probably because it's dependent or
12285   // invalid).
12286   if (R.empty() &&
12287       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12288     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12289     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12290     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12291     auto *II = NameInfo.getName().getAsIdentifierInfo();
12292     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12293         CurContext->isStdNamespace() &&
12294         isa<TranslationUnitDecl>(LookupContext) &&
12295         getSourceManager().isInSystemHeader(UsingLoc))
12296       return nullptr;
12297     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12298                           dyn_cast<CXXRecordDecl>(CurContext));
12299     if (TypoCorrection Corrected =
12300             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12301                         CTK_ErrorRecovery)) {
12302       // We reject candidates where DroppedSpecifier == true, hence the
12303       // literal '0' below.
12304       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12305                                 << NameInfo.getName() << LookupContext << 0
12306                                 << SS.getRange());
12307 
12308       // If we picked a correction with no attached Decl we can't do anything
12309       // useful with it, bail out.
12310       NamedDecl *ND = Corrected.getCorrectionDecl();
12311       if (!ND)
12312         return BuildInvalid();
12313 
12314       // If we corrected to an inheriting constructor, handle it as one.
12315       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12316       if (RD && RD->isInjectedClassName()) {
12317         // The parent of the injected class name is the class itself.
12318         RD = cast<CXXRecordDecl>(RD->getParent());
12319 
12320         // Fix up the information we'll use to build the using declaration.
12321         if (Corrected.WillReplaceSpecifier()) {
12322           NestedNameSpecifierLocBuilder Builder;
12323           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12324                               QualifierLoc.getSourceRange());
12325           QualifierLoc = Builder.getWithLocInContext(Context);
12326         }
12327 
12328         // In this case, the name we introduce is the name of a derived class
12329         // constructor.
12330         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12331         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12332             Context.getCanonicalType(Context.getRecordType(CurClass))));
12333         UsingName.setNamedTypeInfo(nullptr);
12334         for (auto *Ctor : LookupConstructors(RD))
12335           R.addDecl(Ctor);
12336         R.resolveKind();
12337       } else {
12338         // FIXME: Pick up all the declarations if we found an overloaded
12339         // function.
12340         UsingName.setName(ND->getDeclName());
12341         R.addDecl(ND);
12342       }
12343     } else {
12344       Diag(IdentLoc, diag::err_no_member)
12345         << NameInfo.getName() << LookupContext << SS.getRange();
12346       return BuildInvalid();
12347     }
12348   }
12349 
12350   if (R.isAmbiguous())
12351     return BuildInvalid();
12352 
12353   if (HasTypenameKeyword) {
12354     // If we asked for a typename and got a non-type decl, error out.
12355     if (!R.getAsSingle<TypeDecl>() &&
12356         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12357       Diag(IdentLoc, diag::err_using_typename_non_type);
12358       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12359         Diag((*I)->getUnderlyingDecl()->getLocation(),
12360              diag::note_using_decl_target);
12361       return BuildInvalid();
12362     }
12363   } else {
12364     // If we asked for a non-typename and we got a type, error out,
12365     // but only if this is an instantiation of an unresolved using
12366     // decl.  Otherwise just silently find the type name.
12367     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12368       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12369       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12370       return BuildInvalid();
12371     }
12372   }
12373 
12374   // C++14 [namespace.udecl]p6:
12375   // A using-declaration shall not name a namespace.
12376   if (R.getAsSingle<NamespaceDecl>()) {
12377     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12378       << SS.getRange();
12379     return BuildInvalid();
12380   }
12381 
12382   UsingDecl *UD = BuildValid();
12383 
12384   // Some additional rules apply to inheriting constructors.
12385   if (UsingName.getName().getNameKind() ==
12386         DeclarationName::CXXConstructorName) {
12387     // Suppress access diagnostics; the access check is instead performed at the
12388     // point of use for an inheriting constructor.
12389     R.suppressDiagnostics();
12390     if (CheckInheritingConstructorUsingDecl(UD))
12391       return UD;
12392   }
12393 
12394   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12395     UsingShadowDecl *PrevDecl = nullptr;
12396     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12397       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12398   }
12399 
12400   return UD;
12401 }
12402 
12403 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12404                                            SourceLocation UsingLoc,
12405                                            SourceLocation EnumLoc,
12406                                            SourceLocation NameLoc,
12407                                            EnumDecl *ED) {
12408   bool Invalid = false;
12409 
12410   if (CurContext->getRedeclContext()->isRecord()) {
12411     /// In class scope, check if this is a duplicate, for better a diagnostic.
12412     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12413     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12414                           ForVisibleRedeclaration);
12415 
12416     LookupName(Previous, S);
12417 
12418     for (NamedDecl *D : Previous)
12419       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12420         if (UED->getEnumDecl() == ED) {
12421           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12422               << SourceRange(EnumLoc, NameLoc);
12423           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12424           Invalid = true;
12425           break;
12426         }
12427   }
12428 
12429   if (RequireCompleteEnumDecl(ED, NameLoc))
12430     Invalid = true;
12431 
12432   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12433                                             EnumLoc, NameLoc, ED);
12434   UD->setAccess(AS);
12435   CurContext->addDecl(UD);
12436 
12437   if (Invalid) {
12438     UD->setInvalidDecl();
12439     return UD;
12440   }
12441 
12442   // Create the shadow decls for each enumerator
12443   for (EnumConstantDecl *EC : ED->enumerators()) {
12444     UsingShadowDecl *PrevDecl = nullptr;
12445     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12446     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12447                           ForVisibleRedeclaration);
12448     LookupName(Previous, S);
12449     FilterUsingLookup(S, Previous);
12450 
12451     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12452       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12453   }
12454 
12455   return UD;
12456 }
12457 
12458 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12459                                     ArrayRef<NamedDecl *> Expansions) {
12460   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12461          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12462          isa<UsingPackDecl>(InstantiatedFrom));
12463 
12464   auto *UPD =
12465       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12466   UPD->setAccess(InstantiatedFrom->getAccess());
12467   CurContext->addDecl(UPD);
12468   return UPD;
12469 }
12470 
12471 /// Additional checks for a using declaration referring to a constructor name.
12472 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12473   assert(!UD->hasTypename() && "expecting a constructor name");
12474 
12475   const Type *SourceType = UD->getQualifier()->getAsType();
12476   assert(SourceType &&
12477          "Using decl naming constructor doesn't have type in scope spec.");
12478   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12479 
12480   // Check whether the named type is a direct base class.
12481   bool AnyDependentBases = false;
12482   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12483                                       AnyDependentBases);
12484   if (!Base && !AnyDependentBases) {
12485     Diag(UD->getUsingLoc(),
12486          diag::err_using_decl_constructor_not_in_direct_base)
12487       << UD->getNameInfo().getSourceRange()
12488       << QualType(SourceType, 0) << TargetClass;
12489     UD->setInvalidDecl();
12490     return true;
12491   }
12492 
12493   if (Base)
12494     Base->setInheritConstructors();
12495 
12496   return false;
12497 }
12498 
12499 /// Checks that the given using declaration is not an invalid
12500 /// redeclaration.  Note that this is checking only for the using decl
12501 /// itself, not for any ill-formedness among the UsingShadowDecls.
12502 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12503                                        bool HasTypenameKeyword,
12504                                        const CXXScopeSpec &SS,
12505                                        SourceLocation NameLoc,
12506                                        const LookupResult &Prev) {
12507   NestedNameSpecifier *Qual = SS.getScopeRep();
12508 
12509   // C++03 [namespace.udecl]p8:
12510   // C++0x [namespace.udecl]p10:
12511   //   A using-declaration is a declaration and can therefore be used
12512   //   repeatedly where (and only where) multiple declarations are
12513   //   allowed.
12514   //
12515   // That's in non-member contexts.
12516   if (!CurContext->getRedeclContext()->isRecord()) {
12517     // A dependent qualifier outside a class can only ever resolve to an
12518     // enumeration type. Therefore it conflicts with any other non-type
12519     // declaration in the same scope.
12520     // FIXME: How should we check for dependent type-type conflicts at block
12521     // scope?
12522     if (Qual->isDependent() && !HasTypenameKeyword) {
12523       for (auto *D : Prev) {
12524         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12525           bool OldCouldBeEnumerator =
12526               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12527           Diag(NameLoc,
12528                OldCouldBeEnumerator ? diag::err_redefinition
12529                                     : diag::err_redefinition_different_kind)
12530               << Prev.getLookupName();
12531           Diag(D->getLocation(), diag::note_previous_definition);
12532           return true;
12533         }
12534       }
12535     }
12536     return false;
12537   }
12538 
12539   const NestedNameSpecifier *CNNS =
12540       Context.getCanonicalNestedNameSpecifier(Qual);
12541   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12542     NamedDecl *D = *I;
12543 
12544     bool DTypename;
12545     NestedNameSpecifier *DQual;
12546     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12547       DTypename = UD->hasTypename();
12548       DQual = UD->getQualifier();
12549     } else if (UnresolvedUsingValueDecl *UD
12550                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12551       DTypename = false;
12552       DQual = UD->getQualifier();
12553     } else if (UnresolvedUsingTypenameDecl *UD
12554                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12555       DTypename = true;
12556       DQual = UD->getQualifier();
12557     } else continue;
12558 
12559     // using decls differ if one says 'typename' and the other doesn't.
12560     // FIXME: non-dependent using decls?
12561     if (HasTypenameKeyword != DTypename) continue;
12562 
12563     // using decls differ if they name different scopes (but note that
12564     // template instantiation can cause this check to trigger when it
12565     // didn't before instantiation).
12566     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12567       continue;
12568 
12569     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12570     Diag(D->getLocation(), diag::note_using_decl) << 1;
12571     return true;
12572   }
12573 
12574   return false;
12575 }
12576 
12577 /// Checks that the given nested-name qualifier used in a using decl
12578 /// in the current context is appropriately related to the current
12579 /// scope.  If an error is found, diagnoses it and returns true.
12580 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12581 /// result of that lookup. UD is likewise nullptr, except when we have an
12582 /// already-populated UsingDecl whose shadow decls contain the same information
12583 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12584 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12585                                    const CXXScopeSpec &SS,
12586                                    const DeclarationNameInfo &NameInfo,
12587                                    SourceLocation NameLoc,
12588                                    const LookupResult *R, const UsingDecl *UD) {
12589   DeclContext *NamedContext = computeDeclContext(SS);
12590   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12591          "resolvable context must have exactly one set of decls");
12592 
12593   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12594   // relationship.
12595   bool Cxx20Enumerator = false;
12596   if (NamedContext) {
12597     EnumConstantDecl *EC = nullptr;
12598     if (R)
12599       EC = R->getAsSingle<EnumConstantDecl>();
12600     else if (UD && UD->shadow_size() == 1)
12601       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12602     if (EC)
12603       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12604 
12605     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12606       // C++14 [namespace.udecl]p7:
12607       // A using-declaration shall not name a scoped enumerator.
12608       // C++20 p1099 permits enumerators.
12609       if (EC && R && ED->isScoped())
12610         Diag(SS.getBeginLoc(),
12611              getLangOpts().CPlusPlus20
12612                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12613                  : diag::ext_using_decl_scoped_enumerator)
12614             << SS.getRange();
12615 
12616       // We want to consider the scope of the enumerator
12617       NamedContext = ED->getDeclContext();
12618     }
12619   }
12620 
12621   if (!CurContext->isRecord()) {
12622     // C++03 [namespace.udecl]p3:
12623     // C++0x [namespace.udecl]p8:
12624     //   A using-declaration for a class member shall be a member-declaration.
12625     // C++20 [namespace.udecl]p7
12626     //   ... other than an enumerator ...
12627 
12628     // If we weren't able to compute a valid scope, it might validly be a
12629     // dependent class or enumeration scope. If we have a 'typename' keyword,
12630     // the scope must resolve to a class type.
12631     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12632                      : !HasTypename)
12633       return false; // OK
12634 
12635     Diag(NameLoc,
12636          Cxx20Enumerator
12637              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12638              : diag::err_using_decl_can_not_refer_to_class_member)
12639         << SS.getRange();
12640 
12641     if (Cxx20Enumerator)
12642       return false; // OK
12643 
12644     auto *RD = NamedContext
12645                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12646                    : nullptr;
12647     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12648       // See if there's a helpful fixit
12649 
12650       if (!R) {
12651         // We will have already diagnosed the problem on the template
12652         // definition,  Maybe we should do so again?
12653       } else if (R->getAsSingle<TypeDecl>()) {
12654         if (getLangOpts().CPlusPlus11) {
12655           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12656           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12657             << 0 // alias declaration
12658             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12659                                           NameInfo.getName().getAsString() +
12660                                               " = ");
12661         } else {
12662           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12663           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12664           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12665             << 1 // typedef declaration
12666             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12667             << FixItHint::CreateInsertion(
12668                    InsertLoc, " " + NameInfo.getName().getAsString());
12669         }
12670       } else if (R->getAsSingle<VarDecl>()) {
12671         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12672         // repeating the type of the static data member here.
12673         FixItHint FixIt;
12674         if (getLangOpts().CPlusPlus11) {
12675           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12676           FixIt = FixItHint::CreateReplacement(
12677               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12678         }
12679 
12680         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12681           << 2 // reference declaration
12682           << FixIt;
12683       } else if (R->getAsSingle<EnumConstantDecl>()) {
12684         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12685         // repeating the type of the enumeration here, and we can't do so if
12686         // the type is anonymous.
12687         FixItHint FixIt;
12688         if (getLangOpts().CPlusPlus11) {
12689           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12690           FixIt = FixItHint::CreateReplacement(
12691               UsingLoc,
12692               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12693         }
12694 
12695         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12696           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12697           << FixIt;
12698       }
12699     }
12700 
12701     return true; // Fail
12702   }
12703 
12704   // If the named context is dependent, we can't decide much.
12705   if (!NamedContext) {
12706     // FIXME: in C++0x, we can diagnose if we can prove that the
12707     // nested-name-specifier does not refer to a base class, which is
12708     // still possible in some cases.
12709 
12710     // Otherwise we have to conservatively report that things might be
12711     // okay.
12712     return false;
12713   }
12714 
12715   // The current scope is a record.
12716   if (!NamedContext->isRecord()) {
12717     // Ideally this would point at the last name in the specifier,
12718     // but we don't have that level of source info.
12719     Diag(SS.getBeginLoc(),
12720          Cxx20Enumerator
12721              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12722              : diag::err_using_decl_nested_name_specifier_is_not_class)
12723         << SS.getScopeRep() << SS.getRange();
12724 
12725     if (Cxx20Enumerator)
12726       return false; // OK
12727 
12728     return true;
12729   }
12730 
12731   if (!NamedContext->isDependentContext() &&
12732       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12733     return true;
12734 
12735   if (getLangOpts().CPlusPlus11) {
12736     // C++11 [namespace.udecl]p3:
12737     //   In a using-declaration used as a member-declaration, the
12738     //   nested-name-specifier shall name a base class of the class
12739     //   being defined.
12740 
12741     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12742                                  cast<CXXRecordDecl>(NamedContext))) {
12743 
12744       if (Cxx20Enumerator) {
12745         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12746             << SS.getRange();
12747         return false;
12748       }
12749 
12750       if (CurContext == NamedContext) {
12751         Diag(SS.getBeginLoc(),
12752              diag::err_using_decl_nested_name_specifier_is_current_class)
12753             << SS.getRange();
12754         return !getLangOpts().CPlusPlus20;
12755       }
12756 
12757       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12758         Diag(SS.getBeginLoc(),
12759              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12760             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12761             << SS.getRange();
12762       }
12763       return true;
12764     }
12765 
12766     return false;
12767   }
12768 
12769   // C++03 [namespace.udecl]p4:
12770   //   A using-declaration used as a member-declaration shall refer
12771   //   to a member of a base class of the class being defined [etc.].
12772 
12773   // Salient point: SS doesn't have to name a base class as long as
12774   // lookup only finds members from base classes.  Therefore we can
12775   // diagnose here only if we can prove that that can't happen,
12776   // i.e. if the class hierarchies provably don't intersect.
12777 
12778   // TODO: it would be nice if "definitely valid" results were cached
12779   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12780   // need to be repeated.
12781 
12782   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12783   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12784     Bases.insert(Base);
12785     return true;
12786   };
12787 
12788   // Collect all bases. Return false if we find a dependent base.
12789   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12790     return false;
12791 
12792   // Returns true if the base is dependent or is one of the accumulated base
12793   // classes.
12794   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12795     return !Bases.count(Base);
12796   };
12797 
12798   // Return false if the class has a dependent base or if it or one
12799   // of its bases is present in the base set of the current context.
12800   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12801       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12802     return false;
12803 
12804   Diag(SS.getRange().getBegin(),
12805        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12806     << SS.getScopeRep()
12807     << cast<CXXRecordDecl>(CurContext)
12808     << SS.getRange();
12809 
12810   return true;
12811 }
12812 
12813 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12814                                   MultiTemplateParamsArg TemplateParamLists,
12815                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12816                                   const ParsedAttributesView &AttrList,
12817                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12818   // Skip up to the relevant declaration scope.
12819   while (S->isTemplateParamScope())
12820     S = S->getParent();
12821   assert((S->getFlags() & Scope::DeclScope) &&
12822          "got alias-declaration outside of declaration scope");
12823 
12824   if (Type.isInvalid())
12825     return nullptr;
12826 
12827   bool Invalid = false;
12828   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12829   TypeSourceInfo *TInfo = nullptr;
12830   GetTypeFromParser(Type.get(), &TInfo);
12831 
12832   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12833     return nullptr;
12834 
12835   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12836                                       UPPC_DeclarationType)) {
12837     Invalid = true;
12838     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12839                                              TInfo->getTypeLoc().getBeginLoc());
12840   }
12841 
12842   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12843                         TemplateParamLists.size()
12844                             ? forRedeclarationInCurContext()
12845                             : ForVisibleRedeclaration);
12846   LookupName(Previous, S);
12847 
12848   // Warn about shadowing the name of a template parameter.
12849   if (Previous.isSingleResult() &&
12850       Previous.getFoundDecl()->isTemplateParameter()) {
12851     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12852     Previous.clear();
12853   }
12854 
12855   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12856          "name in alias declaration must be an identifier");
12857   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12858                                                Name.StartLocation,
12859                                                Name.Identifier, TInfo);
12860 
12861   NewTD->setAccess(AS);
12862 
12863   if (Invalid)
12864     NewTD->setInvalidDecl();
12865 
12866   ProcessDeclAttributeList(S, NewTD, AttrList);
12867   AddPragmaAttributes(S, NewTD);
12868 
12869   CheckTypedefForVariablyModifiedType(S, NewTD);
12870   Invalid |= NewTD->isInvalidDecl();
12871 
12872   bool Redeclaration = false;
12873 
12874   NamedDecl *NewND;
12875   if (TemplateParamLists.size()) {
12876     TypeAliasTemplateDecl *OldDecl = nullptr;
12877     TemplateParameterList *OldTemplateParams = nullptr;
12878 
12879     if (TemplateParamLists.size() != 1) {
12880       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12881         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12882          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12883     }
12884     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12885 
12886     // Check that we can declare a template here.
12887     if (CheckTemplateDeclScope(S, TemplateParams))
12888       return nullptr;
12889 
12890     // Only consider previous declarations in the same scope.
12891     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12892                          /*ExplicitInstantiationOrSpecialization*/false);
12893     if (!Previous.empty()) {
12894       Redeclaration = true;
12895 
12896       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12897       if (!OldDecl && !Invalid) {
12898         Diag(UsingLoc, diag::err_redefinition_different_kind)
12899           << Name.Identifier;
12900 
12901         NamedDecl *OldD = Previous.getRepresentativeDecl();
12902         if (OldD->getLocation().isValid())
12903           Diag(OldD->getLocation(), diag::note_previous_definition);
12904 
12905         Invalid = true;
12906       }
12907 
12908       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12909         if (TemplateParameterListsAreEqual(TemplateParams,
12910                                            OldDecl->getTemplateParameters(),
12911                                            /*Complain=*/true,
12912                                            TPL_TemplateMatch))
12913           OldTemplateParams =
12914               OldDecl->getMostRecentDecl()->getTemplateParameters();
12915         else
12916           Invalid = true;
12917 
12918         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12919         if (!Invalid &&
12920             !Context.hasSameType(OldTD->getUnderlyingType(),
12921                                  NewTD->getUnderlyingType())) {
12922           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12923           // but we can't reasonably accept it.
12924           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12925             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12926           if (OldTD->getLocation().isValid())
12927             Diag(OldTD->getLocation(), diag::note_previous_definition);
12928           Invalid = true;
12929         }
12930       }
12931     }
12932 
12933     // Merge any previous default template arguments into our parameters,
12934     // and check the parameter list.
12935     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12936                                    TPC_TypeAliasTemplate))
12937       return nullptr;
12938 
12939     TypeAliasTemplateDecl *NewDecl =
12940       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12941                                     Name.Identifier, TemplateParams,
12942                                     NewTD);
12943     NewTD->setDescribedAliasTemplate(NewDecl);
12944 
12945     NewDecl->setAccess(AS);
12946 
12947     if (Invalid)
12948       NewDecl->setInvalidDecl();
12949     else if (OldDecl) {
12950       NewDecl->setPreviousDecl(OldDecl);
12951       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12952     }
12953 
12954     NewND = NewDecl;
12955   } else {
12956     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12957       setTagNameForLinkagePurposes(TD, NewTD);
12958       handleTagNumbering(TD, S);
12959     }
12960     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12961     NewND = NewTD;
12962   }
12963 
12964   PushOnScopeChains(NewND, S);
12965   ActOnDocumentableDecl(NewND);
12966   return NewND;
12967 }
12968 
12969 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12970                                    SourceLocation AliasLoc,
12971                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12972                                    SourceLocation IdentLoc,
12973                                    IdentifierInfo *Ident) {
12974 
12975   // Lookup the namespace name.
12976   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12977   LookupParsedName(R, S, &SS);
12978 
12979   if (R.isAmbiguous())
12980     return nullptr;
12981 
12982   if (R.empty()) {
12983     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12984       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12985       return nullptr;
12986     }
12987   }
12988   assert(!R.isAmbiguous() && !R.empty());
12989   NamedDecl *ND = R.getRepresentativeDecl();
12990 
12991   // Check if we have a previous declaration with the same name.
12992   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12993                      ForVisibleRedeclaration);
12994   LookupName(PrevR, S);
12995 
12996   // Check we're not shadowing a template parameter.
12997   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12998     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12999     PrevR.clear();
13000   }
13001 
13002   // Filter out any other lookup result from an enclosing scope.
13003   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13004                        /*AllowInlineNamespace*/false);
13005 
13006   // Find the previous declaration and check that we can redeclare it.
13007   NamespaceAliasDecl *Prev = nullptr;
13008   if (PrevR.isSingleResult()) {
13009     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13010     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13011       // We already have an alias with the same name that points to the same
13012       // namespace; check that it matches.
13013       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13014         Prev = AD;
13015       } else if (isVisible(PrevDecl)) {
13016         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13017           << Alias;
13018         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13019           << AD->getNamespace();
13020         return nullptr;
13021       }
13022     } else if (isVisible(PrevDecl)) {
13023       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13024                             ? diag::err_redefinition
13025                             : diag::err_redefinition_different_kind;
13026       Diag(AliasLoc, DiagID) << Alias;
13027       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13028       return nullptr;
13029     }
13030   }
13031 
13032   // The use of a nested name specifier may trigger deprecation warnings.
13033   DiagnoseUseOfDecl(ND, IdentLoc);
13034 
13035   NamespaceAliasDecl *AliasDecl =
13036     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13037                                Alias, SS.getWithLocInContext(Context),
13038                                IdentLoc, ND);
13039   if (Prev)
13040     AliasDecl->setPreviousDecl(Prev);
13041 
13042   PushOnScopeChains(AliasDecl, S);
13043   return AliasDecl;
13044 }
13045 
13046 namespace {
13047 struct SpecialMemberExceptionSpecInfo
13048     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13049   SourceLocation Loc;
13050   Sema::ImplicitExceptionSpecification ExceptSpec;
13051 
13052   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13053                                  Sema::CXXSpecialMember CSM,
13054                                  Sema::InheritedConstructorInfo *ICI,
13055                                  SourceLocation Loc)
13056       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13057 
13058   bool visitBase(CXXBaseSpecifier *Base);
13059   bool visitField(FieldDecl *FD);
13060 
13061   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13062                            unsigned Quals);
13063 
13064   void visitSubobjectCall(Subobject Subobj,
13065                           Sema::SpecialMemberOverloadResult SMOR);
13066 };
13067 }
13068 
13069 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13070   auto *RT = Base->getType()->getAs<RecordType>();
13071   if (!RT)
13072     return false;
13073 
13074   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13075   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13076   if (auto *BaseCtor = SMOR.getMethod()) {
13077     visitSubobjectCall(Base, BaseCtor);
13078     return false;
13079   }
13080 
13081   visitClassSubobject(BaseClass, Base, 0);
13082   return false;
13083 }
13084 
13085 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13086   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13087     Expr *E = FD->getInClassInitializer();
13088     if (!E)
13089       // FIXME: It's a little wasteful to build and throw away a
13090       // CXXDefaultInitExpr here.
13091       // FIXME: We should have a single context note pointing at Loc, and
13092       // this location should be MD->getLocation() instead, since that's
13093       // the location where we actually use the default init expression.
13094       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13095     if (E)
13096       ExceptSpec.CalledExpr(E);
13097   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13098                             ->getAs<RecordType>()) {
13099     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13100                         FD->getType().getCVRQualifiers());
13101   }
13102   return false;
13103 }
13104 
13105 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13106                                                          Subobject Subobj,
13107                                                          unsigned Quals) {
13108   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13109   bool IsMutable = Field && Field->isMutable();
13110   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13111 }
13112 
13113 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13114     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13115   // Note, if lookup fails, it doesn't matter what exception specification we
13116   // choose because the special member will be deleted.
13117   if (CXXMethodDecl *MD = SMOR.getMethod())
13118     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13119 }
13120 
13121 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13122   llvm::APSInt Result;
13123   ExprResult Converted = CheckConvertedConstantExpression(
13124       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13125   ExplicitSpec.setExpr(Converted.get());
13126   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13127     ExplicitSpec.setKind(Result.getBoolValue()
13128                              ? ExplicitSpecKind::ResolvedTrue
13129                              : ExplicitSpecKind::ResolvedFalse);
13130     return true;
13131   }
13132   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13133   return false;
13134 }
13135 
13136 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13137   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13138   if (!ExplicitExpr->isTypeDependent())
13139     tryResolveExplicitSpecifier(ES);
13140   return ES;
13141 }
13142 
13143 static Sema::ImplicitExceptionSpecification
13144 ComputeDefaultedSpecialMemberExceptionSpec(
13145     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13146     Sema::InheritedConstructorInfo *ICI) {
13147   ComputingExceptionSpec CES(S, MD, Loc);
13148 
13149   CXXRecordDecl *ClassDecl = MD->getParent();
13150 
13151   // C++ [except.spec]p14:
13152   //   An implicitly declared special member function (Clause 12) shall have an
13153   //   exception-specification. [...]
13154   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13155   if (ClassDecl->isInvalidDecl())
13156     return Info.ExceptSpec;
13157 
13158   // FIXME: If this diagnostic fires, we're probably missing a check for
13159   // attempting to resolve an exception specification before it's known
13160   // at a higher level.
13161   if (S.RequireCompleteType(MD->getLocation(),
13162                             S.Context.getRecordType(ClassDecl),
13163                             diag::err_exception_spec_incomplete_type))
13164     return Info.ExceptSpec;
13165 
13166   // C++1z [except.spec]p7:
13167   //   [Look for exceptions thrown by] a constructor selected [...] to
13168   //   initialize a potentially constructed subobject,
13169   // C++1z [except.spec]p8:
13170   //   The exception specification for an implicitly-declared destructor, or a
13171   //   destructor without a noexcept-specifier, is potentially-throwing if and
13172   //   only if any of the destructors for any of its potentially constructed
13173   //   subojects is potentially throwing.
13174   // FIXME: We respect the first rule but ignore the "potentially constructed"
13175   // in the second rule to resolve a core issue (no number yet) that would have
13176   // us reject:
13177   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13178   //   struct B : A {};
13179   //   struct C : B { void f(); };
13180   // ... due to giving B::~B() a non-throwing exception specification.
13181   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13182                                 : Info.VisitAllBases);
13183 
13184   return Info.ExceptSpec;
13185 }
13186 
13187 namespace {
13188 /// RAII object to register a special member as being currently declared.
13189 struct DeclaringSpecialMember {
13190   Sema &S;
13191   Sema::SpecialMemberDecl D;
13192   Sema::ContextRAII SavedContext;
13193   bool WasAlreadyBeingDeclared;
13194 
13195   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13196       : S(S), D(RD, CSM), SavedContext(S, RD) {
13197     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13198     if (WasAlreadyBeingDeclared)
13199       // This almost never happens, but if it does, ensure that our cache
13200       // doesn't contain a stale result.
13201       S.SpecialMemberCache.clear();
13202     else {
13203       // Register a note to be produced if we encounter an error while
13204       // declaring the special member.
13205       Sema::CodeSynthesisContext Ctx;
13206       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13207       // FIXME: We don't have a location to use here. Using the class's
13208       // location maintains the fiction that we declare all special members
13209       // with the class, but (1) it's not clear that lying about that helps our
13210       // users understand what's going on, and (2) there may be outer contexts
13211       // on the stack (some of which are relevant) and printing them exposes
13212       // our lies.
13213       Ctx.PointOfInstantiation = RD->getLocation();
13214       Ctx.Entity = RD;
13215       Ctx.SpecialMember = CSM;
13216       S.pushCodeSynthesisContext(Ctx);
13217     }
13218   }
13219   ~DeclaringSpecialMember() {
13220     if (!WasAlreadyBeingDeclared) {
13221       S.SpecialMembersBeingDeclared.erase(D);
13222       S.popCodeSynthesisContext();
13223     }
13224   }
13225 
13226   /// Are we already trying to declare this special member?
13227   bool isAlreadyBeingDeclared() const {
13228     return WasAlreadyBeingDeclared;
13229   }
13230 };
13231 }
13232 
13233 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13234   // Look up any existing declarations, but don't trigger declaration of all
13235   // implicit special members with this name.
13236   DeclarationName Name = FD->getDeclName();
13237   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13238                  ForExternalRedeclaration);
13239   for (auto *D : FD->getParent()->lookup(Name))
13240     if (auto *Acceptable = R.getAcceptableDecl(D))
13241       R.addDecl(Acceptable);
13242   R.resolveKind();
13243   R.suppressDiagnostics();
13244 
13245   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13246 }
13247 
13248 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13249                                           QualType ResultTy,
13250                                           ArrayRef<QualType> Args) {
13251   // Build an exception specification pointing back at this constructor.
13252   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13253 
13254   LangAS AS = getDefaultCXXMethodAddrSpace();
13255   if (AS != LangAS::Default) {
13256     EPI.TypeQuals.addAddressSpace(AS);
13257   }
13258 
13259   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13260   SpecialMem->setType(QT);
13261 
13262   // During template instantiation of implicit special member functions we need
13263   // a reliable TypeSourceInfo for the function prototype in order to allow
13264   // functions to be substituted.
13265   if (inTemplateInstantiation() &&
13266       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13267     TypeSourceInfo *TSI =
13268         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13269     SpecialMem->setTypeSourceInfo(TSI);
13270   }
13271 }
13272 
13273 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13274                                                      CXXRecordDecl *ClassDecl) {
13275   // C++ [class.ctor]p5:
13276   //   A default constructor for a class X is a constructor of class X
13277   //   that can be called without an argument. If there is no
13278   //   user-declared constructor for class X, a default constructor is
13279   //   implicitly declared. An implicitly-declared default constructor
13280   //   is an inline public member of its class.
13281   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13282          "Should not build implicit default constructor!");
13283 
13284   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13285   if (DSM.isAlreadyBeingDeclared())
13286     return nullptr;
13287 
13288   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13289                                                      CXXDefaultConstructor,
13290                                                      false);
13291 
13292   // Create the actual constructor declaration.
13293   CanQualType ClassType
13294     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13295   SourceLocation ClassLoc = ClassDecl->getLocation();
13296   DeclarationName Name
13297     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13298   DeclarationNameInfo NameInfo(Name, ClassLoc);
13299   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13300       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13301       /*TInfo=*/nullptr, ExplicitSpecifier(),
13302       getCurFPFeatures().isFPConstrained(),
13303       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13304       Constexpr ? ConstexprSpecKind::Constexpr
13305                 : ConstexprSpecKind::Unspecified);
13306   DefaultCon->setAccess(AS_public);
13307   DefaultCon->setDefaulted();
13308 
13309   if (getLangOpts().CUDA) {
13310     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13311                                             DefaultCon,
13312                                             /* ConstRHS */ false,
13313                                             /* Diagnose */ false);
13314   }
13315 
13316   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13317 
13318   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13319   // constructors is easy to compute.
13320   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13321 
13322   // Note that we have declared this constructor.
13323   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13324 
13325   Scope *S = getScopeForContext(ClassDecl);
13326   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13327 
13328   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13329     SetDeclDeleted(DefaultCon, ClassLoc);
13330 
13331   if (S)
13332     PushOnScopeChains(DefaultCon, S, false);
13333   ClassDecl->addDecl(DefaultCon);
13334 
13335   return DefaultCon;
13336 }
13337 
13338 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13339                                             CXXConstructorDecl *Constructor) {
13340   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13341           !Constructor->doesThisDeclarationHaveABody() &&
13342           !Constructor->isDeleted()) &&
13343     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13344   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13345     return;
13346 
13347   CXXRecordDecl *ClassDecl = Constructor->getParent();
13348   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13349 
13350   SynthesizedFunctionScope Scope(*this, Constructor);
13351 
13352   // The exception specification is needed because we are defining the
13353   // function.
13354   ResolveExceptionSpec(CurrentLocation,
13355                        Constructor->getType()->castAs<FunctionProtoType>());
13356   MarkVTableUsed(CurrentLocation, ClassDecl);
13357 
13358   // Add a context note for diagnostics produced after this point.
13359   Scope.addContextNote(CurrentLocation);
13360 
13361   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13362     Constructor->setInvalidDecl();
13363     return;
13364   }
13365 
13366   SourceLocation Loc = Constructor->getEndLoc().isValid()
13367                            ? Constructor->getEndLoc()
13368                            : Constructor->getLocation();
13369   Constructor->setBody(new (Context) CompoundStmt(Loc));
13370   Constructor->markUsed(Context);
13371 
13372   if (ASTMutationListener *L = getASTMutationListener()) {
13373     L->CompletedImplicitDefinition(Constructor);
13374   }
13375 
13376   DiagnoseUninitializedFields(*this, Constructor);
13377 }
13378 
13379 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13380   // Perform any delayed checks on exception specifications.
13381   CheckDelayedMemberExceptionSpecs();
13382 }
13383 
13384 /// Find or create the fake constructor we synthesize to model constructing an
13385 /// object of a derived class via a constructor of a base class.
13386 CXXConstructorDecl *
13387 Sema::findInheritingConstructor(SourceLocation Loc,
13388                                 CXXConstructorDecl *BaseCtor,
13389                                 ConstructorUsingShadowDecl *Shadow) {
13390   CXXRecordDecl *Derived = Shadow->getParent();
13391   SourceLocation UsingLoc = Shadow->getLocation();
13392 
13393   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13394   // For now we use the name of the base class constructor as a member of the
13395   // derived class to indicate a (fake) inherited constructor name.
13396   DeclarationName Name = BaseCtor->getDeclName();
13397 
13398   // Check to see if we already have a fake constructor for this inherited
13399   // constructor call.
13400   for (NamedDecl *Ctor : Derived->lookup(Name))
13401     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13402                                ->getInheritedConstructor()
13403                                .getConstructor(),
13404                            BaseCtor))
13405       return cast<CXXConstructorDecl>(Ctor);
13406 
13407   DeclarationNameInfo NameInfo(Name, UsingLoc);
13408   TypeSourceInfo *TInfo =
13409       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13410   FunctionProtoTypeLoc ProtoLoc =
13411       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13412 
13413   // Check the inherited constructor is valid and find the list of base classes
13414   // from which it was inherited.
13415   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13416 
13417   bool Constexpr =
13418       BaseCtor->isConstexpr() &&
13419       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13420                                         false, BaseCtor, &ICI);
13421 
13422   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13423       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13424       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13425       /*isInline=*/true,
13426       /*isImplicitlyDeclared=*/true,
13427       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13428       InheritedConstructor(Shadow, BaseCtor),
13429       BaseCtor->getTrailingRequiresClause());
13430   if (Shadow->isInvalidDecl())
13431     DerivedCtor->setInvalidDecl();
13432 
13433   // Build an unevaluated exception specification for this fake constructor.
13434   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13435   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13436   EPI.ExceptionSpec.Type = EST_Unevaluated;
13437   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13438   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13439                                                FPT->getParamTypes(), EPI));
13440 
13441   // Build the parameter declarations.
13442   SmallVector<ParmVarDecl *, 16> ParamDecls;
13443   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13444     TypeSourceInfo *TInfo =
13445         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13446     ParmVarDecl *PD = ParmVarDecl::Create(
13447         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13448         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13449     PD->setScopeInfo(0, I);
13450     PD->setImplicit();
13451     // Ensure attributes are propagated onto parameters (this matters for
13452     // format, pass_object_size, ...).
13453     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13454     ParamDecls.push_back(PD);
13455     ProtoLoc.setParam(I, PD);
13456   }
13457 
13458   // Set up the new constructor.
13459   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13460   DerivedCtor->setAccess(BaseCtor->getAccess());
13461   DerivedCtor->setParams(ParamDecls);
13462   Derived->addDecl(DerivedCtor);
13463 
13464   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13465     SetDeclDeleted(DerivedCtor, UsingLoc);
13466 
13467   return DerivedCtor;
13468 }
13469 
13470 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13471   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13472                                Ctor->getInheritedConstructor().getShadowDecl());
13473   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13474                             /*Diagnose*/true);
13475 }
13476 
13477 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13478                                        CXXConstructorDecl *Constructor) {
13479   CXXRecordDecl *ClassDecl = Constructor->getParent();
13480   assert(Constructor->getInheritedConstructor() &&
13481          !Constructor->doesThisDeclarationHaveABody() &&
13482          !Constructor->isDeleted());
13483   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13484     return;
13485 
13486   // Initializations are performed "as if by a defaulted default constructor",
13487   // so enter the appropriate scope.
13488   SynthesizedFunctionScope Scope(*this, Constructor);
13489 
13490   // The exception specification is needed because we are defining the
13491   // function.
13492   ResolveExceptionSpec(CurrentLocation,
13493                        Constructor->getType()->castAs<FunctionProtoType>());
13494   MarkVTableUsed(CurrentLocation, ClassDecl);
13495 
13496   // Add a context note for diagnostics produced after this point.
13497   Scope.addContextNote(CurrentLocation);
13498 
13499   ConstructorUsingShadowDecl *Shadow =
13500       Constructor->getInheritedConstructor().getShadowDecl();
13501   CXXConstructorDecl *InheritedCtor =
13502       Constructor->getInheritedConstructor().getConstructor();
13503 
13504   // [class.inhctor.init]p1:
13505   //   initialization proceeds as if a defaulted default constructor is used to
13506   //   initialize the D object and each base class subobject from which the
13507   //   constructor was inherited
13508 
13509   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13510   CXXRecordDecl *RD = Shadow->getParent();
13511   SourceLocation InitLoc = Shadow->getLocation();
13512 
13513   // Build explicit initializers for all base classes from which the
13514   // constructor was inherited.
13515   SmallVector<CXXCtorInitializer*, 8> Inits;
13516   for (bool VBase : {false, true}) {
13517     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13518       if (B.isVirtual() != VBase)
13519         continue;
13520 
13521       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13522       if (!BaseRD)
13523         continue;
13524 
13525       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13526       if (!BaseCtor.first)
13527         continue;
13528 
13529       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13530       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13531           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13532 
13533       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13534       Inits.push_back(new (Context) CXXCtorInitializer(
13535           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13536           SourceLocation()));
13537     }
13538   }
13539 
13540   // We now proceed as if for a defaulted default constructor, with the relevant
13541   // initializers replaced.
13542 
13543   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13544     Constructor->setInvalidDecl();
13545     return;
13546   }
13547 
13548   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13549   Constructor->markUsed(Context);
13550 
13551   if (ASTMutationListener *L = getASTMutationListener()) {
13552     L->CompletedImplicitDefinition(Constructor);
13553   }
13554 
13555   DiagnoseUninitializedFields(*this, Constructor);
13556 }
13557 
13558 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13559   // C++ [class.dtor]p2:
13560   //   If a class has no user-declared destructor, a destructor is
13561   //   declared implicitly. An implicitly-declared destructor is an
13562   //   inline public member of its class.
13563   assert(ClassDecl->needsImplicitDestructor());
13564 
13565   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13566   if (DSM.isAlreadyBeingDeclared())
13567     return nullptr;
13568 
13569   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13570                                                      CXXDestructor,
13571                                                      false);
13572 
13573   // Create the actual destructor declaration.
13574   CanQualType ClassType
13575     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13576   SourceLocation ClassLoc = ClassDecl->getLocation();
13577   DeclarationName Name
13578     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13579   DeclarationNameInfo NameInfo(Name, ClassLoc);
13580   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13581       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13582       getCurFPFeatures().isFPConstrained(),
13583       /*isInline=*/true,
13584       /*isImplicitlyDeclared=*/true,
13585       Constexpr ? ConstexprSpecKind::Constexpr
13586                 : ConstexprSpecKind::Unspecified);
13587   Destructor->setAccess(AS_public);
13588   Destructor->setDefaulted();
13589 
13590   if (getLangOpts().CUDA) {
13591     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13592                                             Destructor,
13593                                             /* ConstRHS */ false,
13594                                             /* Diagnose */ false);
13595   }
13596 
13597   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13598 
13599   // We don't need to use SpecialMemberIsTrivial here; triviality for
13600   // destructors is easy to compute.
13601   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13602   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13603                                 ClassDecl->hasTrivialDestructorForCall());
13604 
13605   // Note that we have declared this destructor.
13606   ++getASTContext().NumImplicitDestructorsDeclared;
13607 
13608   Scope *S = getScopeForContext(ClassDecl);
13609   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13610 
13611   // We can't check whether an implicit destructor is deleted before we complete
13612   // the definition of the class, because its validity depends on the alignment
13613   // of the class. We'll check this from ActOnFields once the class is complete.
13614   if (ClassDecl->isCompleteDefinition() &&
13615       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13616     SetDeclDeleted(Destructor, ClassLoc);
13617 
13618   // Introduce this destructor into its scope.
13619   if (S)
13620     PushOnScopeChains(Destructor, S, false);
13621   ClassDecl->addDecl(Destructor);
13622 
13623   return Destructor;
13624 }
13625 
13626 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13627                                     CXXDestructorDecl *Destructor) {
13628   assert((Destructor->isDefaulted() &&
13629           !Destructor->doesThisDeclarationHaveABody() &&
13630           !Destructor->isDeleted()) &&
13631          "DefineImplicitDestructor - call it for implicit default dtor");
13632   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13633     return;
13634 
13635   CXXRecordDecl *ClassDecl = Destructor->getParent();
13636   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13637 
13638   SynthesizedFunctionScope Scope(*this, Destructor);
13639 
13640   // The exception specification is needed because we are defining the
13641   // function.
13642   ResolveExceptionSpec(CurrentLocation,
13643                        Destructor->getType()->castAs<FunctionProtoType>());
13644   MarkVTableUsed(CurrentLocation, ClassDecl);
13645 
13646   // Add a context note for diagnostics produced after this point.
13647   Scope.addContextNote(CurrentLocation);
13648 
13649   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13650                                          Destructor->getParent());
13651 
13652   if (CheckDestructor(Destructor)) {
13653     Destructor->setInvalidDecl();
13654     return;
13655   }
13656 
13657   SourceLocation Loc = Destructor->getEndLoc().isValid()
13658                            ? Destructor->getEndLoc()
13659                            : Destructor->getLocation();
13660   Destructor->setBody(new (Context) CompoundStmt(Loc));
13661   Destructor->markUsed(Context);
13662 
13663   if (ASTMutationListener *L = getASTMutationListener()) {
13664     L->CompletedImplicitDefinition(Destructor);
13665   }
13666 }
13667 
13668 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13669                                           CXXDestructorDecl *Destructor) {
13670   if (Destructor->isInvalidDecl())
13671     return;
13672 
13673   CXXRecordDecl *ClassDecl = Destructor->getParent();
13674   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13675          "implicit complete dtors unneeded outside MS ABI");
13676   assert(ClassDecl->getNumVBases() > 0 &&
13677          "complete dtor only exists for classes with vbases");
13678 
13679   SynthesizedFunctionScope Scope(*this, Destructor);
13680 
13681   // Add a context note for diagnostics produced after this point.
13682   Scope.addContextNote(CurrentLocation);
13683 
13684   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13685 }
13686 
13687 /// Perform any semantic analysis which needs to be delayed until all
13688 /// pending class member declarations have been parsed.
13689 void Sema::ActOnFinishCXXMemberDecls() {
13690   // If the context is an invalid C++ class, just suppress these checks.
13691   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13692     if (Record->isInvalidDecl()) {
13693       DelayedOverridingExceptionSpecChecks.clear();
13694       DelayedEquivalentExceptionSpecChecks.clear();
13695       return;
13696     }
13697     checkForMultipleExportedDefaultConstructors(*this, Record);
13698   }
13699 }
13700 
13701 void Sema::ActOnFinishCXXNonNestedClass() {
13702   referenceDLLExportedClassMethods();
13703 
13704   if (!DelayedDllExportMemberFunctions.empty()) {
13705     SmallVector<CXXMethodDecl*, 4> WorkList;
13706     std::swap(DelayedDllExportMemberFunctions, WorkList);
13707     for (CXXMethodDecl *M : WorkList) {
13708       DefineDefaultedFunction(*this, M, M->getLocation());
13709 
13710       // Pass the method to the consumer to get emitted. This is not necessary
13711       // for explicit instantiation definitions, as they will get emitted
13712       // anyway.
13713       if (M->getParent()->getTemplateSpecializationKind() !=
13714           TSK_ExplicitInstantiationDefinition)
13715         ActOnFinishInlineFunctionDef(M);
13716     }
13717   }
13718 }
13719 
13720 void Sema::referenceDLLExportedClassMethods() {
13721   if (!DelayedDllExportClasses.empty()) {
13722     // Calling ReferenceDllExportedMembers might cause the current function to
13723     // be called again, so use a local copy of DelayedDllExportClasses.
13724     SmallVector<CXXRecordDecl *, 4> WorkList;
13725     std::swap(DelayedDllExportClasses, WorkList);
13726     for (CXXRecordDecl *Class : WorkList)
13727       ReferenceDllExportedMembers(*this, Class);
13728   }
13729 }
13730 
13731 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13732   assert(getLangOpts().CPlusPlus11 &&
13733          "adjusting dtor exception specs was introduced in c++11");
13734 
13735   if (Destructor->isDependentContext())
13736     return;
13737 
13738   // C++11 [class.dtor]p3:
13739   //   A declaration of a destructor that does not have an exception-
13740   //   specification is implicitly considered to have the same exception-
13741   //   specification as an implicit declaration.
13742   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13743   if (DtorType->hasExceptionSpec())
13744     return;
13745 
13746   // Replace the destructor's type, building off the existing one. Fortunately,
13747   // the only thing of interest in the destructor type is its extended info.
13748   // The return and arguments are fixed.
13749   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13750   EPI.ExceptionSpec.Type = EST_Unevaluated;
13751   EPI.ExceptionSpec.SourceDecl = Destructor;
13752   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13753 
13754   // FIXME: If the destructor has a body that could throw, and the newly created
13755   // spec doesn't allow exceptions, we should emit a warning, because this
13756   // change in behavior can break conforming C++03 programs at runtime.
13757   // However, we don't have a body or an exception specification yet, so it
13758   // needs to be done somewhere else.
13759 }
13760 
13761 namespace {
13762 /// An abstract base class for all helper classes used in building the
13763 //  copy/move operators. These classes serve as factory functions and help us
13764 //  avoid using the same Expr* in the AST twice.
13765 class ExprBuilder {
13766   ExprBuilder(const ExprBuilder&) = delete;
13767   ExprBuilder &operator=(const ExprBuilder&) = delete;
13768 
13769 protected:
13770   static Expr *assertNotNull(Expr *E) {
13771     assert(E && "Expression construction must not fail.");
13772     return E;
13773   }
13774 
13775 public:
13776   ExprBuilder() {}
13777   virtual ~ExprBuilder() {}
13778 
13779   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13780 };
13781 
13782 class RefBuilder: public ExprBuilder {
13783   VarDecl *Var;
13784   QualType VarType;
13785 
13786 public:
13787   Expr *build(Sema &S, SourceLocation Loc) const override {
13788     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13789   }
13790 
13791   RefBuilder(VarDecl *Var, QualType VarType)
13792       : Var(Var), VarType(VarType) {}
13793 };
13794 
13795 class ThisBuilder: public ExprBuilder {
13796 public:
13797   Expr *build(Sema &S, SourceLocation Loc) const override {
13798     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13799   }
13800 };
13801 
13802 class CastBuilder: public ExprBuilder {
13803   const ExprBuilder &Builder;
13804   QualType Type;
13805   ExprValueKind Kind;
13806   const CXXCastPath &Path;
13807 
13808 public:
13809   Expr *build(Sema &S, SourceLocation Loc) const override {
13810     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13811                                              CK_UncheckedDerivedToBase, Kind,
13812                                              &Path).get());
13813   }
13814 
13815   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13816               const CXXCastPath &Path)
13817       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13818 };
13819 
13820 class DerefBuilder: public ExprBuilder {
13821   const ExprBuilder &Builder;
13822 
13823 public:
13824   Expr *build(Sema &S, SourceLocation Loc) const override {
13825     return assertNotNull(
13826         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13827   }
13828 
13829   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13830 };
13831 
13832 class MemberBuilder: public ExprBuilder {
13833   const ExprBuilder &Builder;
13834   QualType Type;
13835   CXXScopeSpec SS;
13836   bool IsArrow;
13837   LookupResult &MemberLookup;
13838 
13839 public:
13840   Expr *build(Sema &S, SourceLocation Loc) const override {
13841     return assertNotNull(S.BuildMemberReferenceExpr(
13842         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13843         nullptr, MemberLookup, nullptr, nullptr).get());
13844   }
13845 
13846   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13847                 LookupResult &MemberLookup)
13848       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13849         MemberLookup(MemberLookup) {}
13850 };
13851 
13852 class MoveCastBuilder: public ExprBuilder {
13853   const ExprBuilder &Builder;
13854 
13855 public:
13856   Expr *build(Sema &S, SourceLocation Loc) const override {
13857     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13858   }
13859 
13860   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13861 };
13862 
13863 class LvalueConvBuilder: public ExprBuilder {
13864   const ExprBuilder &Builder;
13865 
13866 public:
13867   Expr *build(Sema &S, SourceLocation Loc) const override {
13868     return assertNotNull(
13869         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13870   }
13871 
13872   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13873 };
13874 
13875 class SubscriptBuilder: public ExprBuilder {
13876   const ExprBuilder &Base;
13877   const ExprBuilder &Index;
13878 
13879 public:
13880   Expr *build(Sema &S, SourceLocation Loc) const override {
13881     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13882         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13883   }
13884 
13885   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13886       : Base(Base), Index(Index) {}
13887 };
13888 
13889 } // end anonymous namespace
13890 
13891 /// When generating a defaulted copy or move assignment operator, if a field
13892 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13893 /// do so. This optimization only applies for arrays of scalars, and for arrays
13894 /// of class type where the selected copy/move-assignment operator is trivial.
13895 static StmtResult
13896 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13897                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13898   // Compute the size of the memory buffer to be copied.
13899   QualType SizeType = S.Context.getSizeType();
13900   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13901                    S.Context.getTypeSizeInChars(T).getQuantity());
13902 
13903   // Take the address of the field references for "from" and "to". We
13904   // directly construct UnaryOperators here because semantic analysis
13905   // does not permit us to take the address of an xvalue.
13906   Expr *From = FromB.build(S, Loc);
13907   From = UnaryOperator::Create(
13908       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13909       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13910   Expr *To = ToB.build(S, Loc);
13911   To = UnaryOperator::Create(
13912       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13913       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13914 
13915   const Type *E = T->getBaseElementTypeUnsafe();
13916   bool NeedsCollectableMemCpy =
13917       E->isRecordType() &&
13918       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13919 
13920   // Create a reference to the __builtin_objc_memmove_collectable function
13921   StringRef MemCpyName = NeedsCollectableMemCpy ?
13922     "__builtin_objc_memmove_collectable" :
13923     "__builtin_memcpy";
13924   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13925                  Sema::LookupOrdinaryName);
13926   S.LookupName(R, S.TUScope, true);
13927 
13928   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13929   if (!MemCpy)
13930     // Something went horribly wrong earlier, and we will have complained
13931     // about it.
13932     return StmtError();
13933 
13934   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13935                                             VK_PRValue, Loc, nullptr);
13936   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13937 
13938   Expr *CallArgs[] = {
13939     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13940   };
13941   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13942                                     Loc, CallArgs, Loc);
13943 
13944   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13945   return Call.getAs<Stmt>();
13946 }
13947 
13948 /// Builds a statement that copies/moves the given entity from \p From to
13949 /// \c To.
13950 ///
13951 /// This routine is used to copy/move the members of a class with an
13952 /// implicitly-declared copy/move assignment operator. When the entities being
13953 /// copied are arrays, this routine builds for loops to copy them.
13954 ///
13955 /// \param S The Sema object used for type-checking.
13956 ///
13957 /// \param Loc The location where the implicit copy/move is being generated.
13958 ///
13959 /// \param T The type of the expressions being copied/moved. Both expressions
13960 /// must have this type.
13961 ///
13962 /// \param To The expression we are copying/moving to.
13963 ///
13964 /// \param From The expression we are copying/moving from.
13965 ///
13966 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13967 /// Otherwise, it's a non-static member subobject.
13968 ///
13969 /// \param Copying Whether we're copying or moving.
13970 ///
13971 /// \param Depth Internal parameter recording the depth of the recursion.
13972 ///
13973 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13974 /// if a memcpy should be used instead.
13975 static StmtResult
13976 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13977                                  const ExprBuilder &To, const ExprBuilder &From,
13978                                  bool CopyingBaseSubobject, bool Copying,
13979                                  unsigned Depth = 0) {
13980   // C++11 [class.copy]p28:
13981   //   Each subobject is assigned in the manner appropriate to its type:
13982   //
13983   //     - if the subobject is of class type, as if by a call to operator= with
13984   //       the subobject as the object expression and the corresponding
13985   //       subobject of x as a single function argument (as if by explicit
13986   //       qualification; that is, ignoring any possible virtual overriding
13987   //       functions in more derived classes);
13988   //
13989   // C++03 [class.copy]p13:
13990   //     - if the subobject is of class type, the copy assignment operator for
13991   //       the class is used (as if by explicit qualification; that is,
13992   //       ignoring any possible virtual overriding functions in more derived
13993   //       classes);
13994   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13995     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13996 
13997     // Look for operator=.
13998     DeclarationName Name
13999       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14000     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14001     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14002 
14003     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14004     // operator.
14005     if (!S.getLangOpts().CPlusPlus11) {
14006       LookupResult::Filter F = OpLookup.makeFilter();
14007       while (F.hasNext()) {
14008         NamedDecl *D = F.next();
14009         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14010           if (Method->isCopyAssignmentOperator() ||
14011               (!Copying && Method->isMoveAssignmentOperator()))
14012             continue;
14013 
14014         F.erase();
14015       }
14016       F.done();
14017     }
14018 
14019     // Suppress the protected check (C++ [class.protected]) for each of the
14020     // assignment operators we found. This strange dance is required when
14021     // we're assigning via a base classes's copy-assignment operator. To
14022     // ensure that we're getting the right base class subobject (without
14023     // ambiguities), we need to cast "this" to that subobject type; to
14024     // ensure that we don't go through the virtual call mechanism, we need
14025     // to qualify the operator= name with the base class (see below). However,
14026     // this means that if the base class has a protected copy assignment
14027     // operator, the protected member access check will fail. So, we
14028     // rewrite "protected" access to "public" access in this case, since we
14029     // know by construction that we're calling from a derived class.
14030     if (CopyingBaseSubobject) {
14031       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14032            L != LEnd; ++L) {
14033         if (L.getAccess() == AS_protected)
14034           L.setAccess(AS_public);
14035       }
14036     }
14037 
14038     // Create the nested-name-specifier that will be used to qualify the
14039     // reference to operator=; this is required to suppress the virtual
14040     // call mechanism.
14041     CXXScopeSpec SS;
14042     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14043     SS.MakeTrivial(S.Context,
14044                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14045                                                CanonicalT),
14046                    Loc);
14047 
14048     // Create the reference to operator=.
14049     ExprResult OpEqualRef
14050       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14051                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14052                                    /*FirstQualifierInScope=*/nullptr,
14053                                    OpLookup,
14054                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14055                                    /*SuppressQualifierCheck=*/true);
14056     if (OpEqualRef.isInvalid())
14057       return StmtError();
14058 
14059     // Build the call to the assignment operator.
14060 
14061     Expr *FromInst = From.build(S, Loc);
14062     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14063                                                   OpEqualRef.getAs<Expr>(),
14064                                                   Loc, FromInst, Loc);
14065     if (Call.isInvalid())
14066       return StmtError();
14067 
14068     // If we built a call to a trivial 'operator=' while copying an array,
14069     // bail out. We'll replace the whole shebang with a memcpy.
14070     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14071     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14072       return StmtResult((Stmt*)nullptr);
14073 
14074     // Convert to an expression-statement, and clean up any produced
14075     // temporaries.
14076     return S.ActOnExprStmt(Call);
14077   }
14078 
14079   //     - if the subobject is of scalar type, the built-in assignment
14080   //       operator is used.
14081   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14082   if (!ArrayTy) {
14083     ExprResult Assignment = S.CreateBuiltinBinOp(
14084         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14085     if (Assignment.isInvalid())
14086       return StmtError();
14087     return S.ActOnExprStmt(Assignment);
14088   }
14089 
14090   //     - if the subobject is an array, each element is assigned, in the
14091   //       manner appropriate to the element type;
14092 
14093   // Construct a loop over the array bounds, e.g.,
14094   //
14095   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14096   //
14097   // that will copy each of the array elements.
14098   QualType SizeType = S.Context.getSizeType();
14099 
14100   // Create the iteration variable.
14101   IdentifierInfo *IterationVarName = nullptr;
14102   {
14103     SmallString<8> Str;
14104     llvm::raw_svector_ostream OS(Str);
14105     OS << "__i" << Depth;
14106     IterationVarName = &S.Context.Idents.get(OS.str());
14107   }
14108   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14109                                           IterationVarName, SizeType,
14110                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14111                                           SC_None);
14112 
14113   // Initialize the iteration variable to zero.
14114   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14115   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14116 
14117   // Creates a reference to the iteration variable.
14118   RefBuilder IterationVarRef(IterationVar, SizeType);
14119   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14120 
14121   // Create the DeclStmt that holds the iteration variable.
14122   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14123 
14124   // Subscript the "from" and "to" expressions with the iteration variable.
14125   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14126   MoveCastBuilder FromIndexMove(FromIndexCopy);
14127   const ExprBuilder *FromIndex;
14128   if (Copying)
14129     FromIndex = &FromIndexCopy;
14130   else
14131     FromIndex = &FromIndexMove;
14132 
14133   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14134 
14135   // Build the copy/move for an individual element of the array.
14136   StmtResult Copy =
14137     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14138                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14139                                      Copying, Depth + 1);
14140   // Bail out if copying fails or if we determined that we should use memcpy.
14141   if (Copy.isInvalid() || !Copy.get())
14142     return Copy;
14143 
14144   // Create the comparison against the array bound.
14145   llvm::APInt Upper
14146     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14147   Expr *Comparison = BinaryOperator::Create(
14148       S.Context, IterationVarRefRVal.build(S, Loc),
14149       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14150       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14151       S.CurFPFeatureOverrides());
14152 
14153   // Create the pre-increment of the iteration variable. We can determine
14154   // whether the increment will overflow based on the value of the array
14155   // bound.
14156   Expr *Increment = UnaryOperator::Create(
14157       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14158       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14159 
14160   // Construct the loop that copies all elements of this array.
14161   return S.ActOnForStmt(
14162       Loc, Loc, InitStmt,
14163       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14164       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14165 }
14166 
14167 static StmtResult
14168 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14169                       const ExprBuilder &To, const ExprBuilder &From,
14170                       bool CopyingBaseSubobject, bool Copying) {
14171   // Maybe we should use a memcpy?
14172   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14173       T.isTriviallyCopyableType(S.Context))
14174     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14175 
14176   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14177                                                      CopyingBaseSubobject,
14178                                                      Copying, 0));
14179 
14180   // If we ended up picking a trivial assignment operator for an array of a
14181   // non-trivially-copyable class type, just emit a memcpy.
14182   if (!Result.isInvalid() && !Result.get())
14183     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14184 
14185   return Result;
14186 }
14187 
14188 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14189   // Note: The following rules are largely analoguous to the copy
14190   // constructor rules. Note that virtual bases are not taken into account
14191   // for determining the argument type of the operator. Note also that
14192   // operators taking an object instead of a reference are allowed.
14193   assert(ClassDecl->needsImplicitCopyAssignment());
14194 
14195   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14196   if (DSM.isAlreadyBeingDeclared())
14197     return nullptr;
14198 
14199   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14200   LangAS AS = getDefaultCXXMethodAddrSpace();
14201   if (AS != LangAS::Default)
14202     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14203   QualType RetType = Context.getLValueReferenceType(ArgType);
14204   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14205   if (Const)
14206     ArgType = ArgType.withConst();
14207 
14208   ArgType = Context.getLValueReferenceType(ArgType);
14209 
14210   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14211                                                      CXXCopyAssignment,
14212                                                      Const);
14213 
14214   //   An implicitly-declared copy assignment operator is an inline public
14215   //   member of its class.
14216   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14217   SourceLocation ClassLoc = ClassDecl->getLocation();
14218   DeclarationNameInfo NameInfo(Name, ClassLoc);
14219   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14220       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14221       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14222       getCurFPFeatures().isFPConstrained(),
14223       /*isInline=*/true,
14224       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14225       SourceLocation());
14226   CopyAssignment->setAccess(AS_public);
14227   CopyAssignment->setDefaulted();
14228   CopyAssignment->setImplicit();
14229 
14230   if (getLangOpts().CUDA) {
14231     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14232                                             CopyAssignment,
14233                                             /* ConstRHS */ Const,
14234                                             /* Diagnose */ false);
14235   }
14236 
14237   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14238 
14239   // Add the parameter to the operator.
14240   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14241                                                ClassLoc, ClassLoc,
14242                                                /*Id=*/nullptr, ArgType,
14243                                                /*TInfo=*/nullptr, SC_None,
14244                                                nullptr);
14245   CopyAssignment->setParams(FromParam);
14246 
14247   CopyAssignment->setTrivial(
14248     ClassDecl->needsOverloadResolutionForCopyAssignment()
14249       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14250       : ClassDecl->hasTrivialCopyAssignment());
14251 
14252   // Note that we have added this copy-assignment operator.
14253   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14254 
14255   Scope *S = getScopeForContext(ClassDecl);
14256   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14257 
14258   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14259     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14260     SetDeclDeleted(CopyAssignment, ClassLoc);
14261   }
14262 
14263   if (S)
14264     PushOnScopeChains(CopyAssignment, S, false);
14265   ClassDecl->addDecl(CopyAssignment);
14266 
14267   return CopyAssignment;
14268 }
14269 
14270 /// Diagnose an implicit copy operation for a class which is odr-used, but
14271 /// which is deprecated because the class has a user-declared copy constructor,
14272 /// copy assignment operator, or destructor.
14273 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14274   assert(CopyOp->isImplicit());
14275 
14276   CXXRecordDecl *RD = CopyOp->getParent();
14277   CXXMethodDecl *UserDeclaredOperation = nullptr;
14278 
14279   // In Microsoft mode, assignment operations don't affect constructors and
14280   // vice versa.
14281   if (RD->hasUserDeclaredDestructor()) {
14282     UserDeclaredOperation = RD->getDestructor();
14283   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14284              RD->hasUserDeclaredCopyConstructor() &&
14285              !S.getLangOpts().MSVCCompat) {
14286     // Find any user-declared copy constructor.
14287     for (auto *I : RD->ctors()) {
14288       if (I->isCopyConstructor()) {
14289         UserDeclaredOperation = I;
14290         break;
14291       }
14292     }
14293     assert(UserDeclaredOperation);
14294   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14295              RD->hasUserDeclaredCopyAssignment() &&
14296              !S.getLangOpts().MSVCCompat) {
14297     // Find any user-declared move assignment operator.
14298     for (auto *I : RD->methods()) {
14299       if (I->isCopyAssignmentOperator()) {
14300         UserDeclaredOperation = I;
14301         break;
14302       }
14303     }
14304     assert(UserDeclaredOperation);
14305   }
14306 
14307   if (UserDeclaredOperation) {
14308     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14309     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14310     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14311     unsigned DiagID =
14312         (UDOIsUserProvided && UDOIsDestructor)
14313             ? diag::warn_deprecated_copy_with_user_provided_dtor
14314         : (UDOIsUserProvided && !UDOIsDestructor)
14315             ? diag::warn_deprecated_copy_with_user_provided_copy
14316         : (!UDOIsUserProvided && UDOIsDestructor)
14317             ? diag::warn_deprecated_copy_with_dtor
14318             : diag::warn_deprecated_copy;
14319     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14320         << RD << IsCopyAssignment;
14321   }
14322 }
14323 
14324 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14325                                         CXXMethodDecl *CopyAssignOperator) {
14326   assert((CopyAssignOperator->isDefaulted() &&
14327           CopyAssignOperator->isOverloadedOperator() &&
14328           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14329           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14330           !CopyAssignOperator->isDeleted()) &&
14331          "DefineImplicitCopyAssignment called for wrong function");
14332   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14333     return;
14334 
14335   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14336   if (ClassDecl->isInvalidDecl()) {
14337     CopyAssignOperator->setInvalidDecl();
14338     return;
14339   }
14340 
14341   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14342 
14343   // The exception specification is needed because we are defining the
14344   // function.
14345   ResolveExceptionSpec(CurrentLocation,
14346                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14347 
14348   // Add a context note for diagnostics produced after this point.
14349   Scope.addContextNote(CurrentLocation);
14350 
14351   // C++11 [class.copy]p18:
14352   //   The [definition of an implicitly declared copy assignment operator] is
14353   //   deprecated if the class has a user-declared copy constructor or a
14354   //   user-declared destructor.
14355   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14356     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14357 
14358   // C++0x [class.copy]p30:
14359   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14360   //   for a non-union class X performs memberwise copy assignment of its
14361   //   subobjects. The direct base classes of X are assigned first, in the
14362   //   order of their declaration in the base-specifier-list, and then the
14363   //   immediate non-static data members of X are assigned, in the order in
14364   //   which they were declared in the class definition.
14365 
14366   // The statements that form the synthesized function body.
14367   SmallVector<Stmt*, 8> Statements;
14368 
14369   // The parameter for the "other" object, which we are copying from.
14370   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14371   Qualifiers OtherQuals = Other->getType().getQualifiers();
14372   QualType OtherRefType = Other->getType();
14373   if (const LValueReferenceType *OtherRef
14374                                 = OtherRefType->getAs<LValueReferenceType>()) {
14375     OtherRefType = OtherRef->getPointeeType();
14376     OtherQuals = OtherRefType.getQualifiers();
14377   }
14378 
14379   // Our location for everything implicitly-generated.
14380   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14381                            ? CopyAssignOperator->getEndLoc()
14382                            : CopyAssignOperator->getLocation();
14383 
14384   // Builds a DeclRefExpr for the "other" object.
14385   RefBuilder OtherRef(Other, OtherRefType);
14386 
14387   // Builds the "this" pointer.
14388   ThisBuilder This;
14389 
14390   // Assign base classes.
14391   bool Invalid = false;
14392   for (auto &Base : ClassDecl->bases()) {
14393     // Form the assignment:
14394     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14395     QualType BaseType = Base.getType().getUnqualifiedType();
14396     if (!BaseType->isRecordType()) {
14397       Invalid = true;
14398       continue;
14399     }
14400 
14401     CXXCastPath BasePath;
14402     BasePath.push_back(&Base);
14403 
14404     // Construct the "from" expression, which is an implicit cast to the
14405     // appropriately-qualified base type.
14406     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14407                      VK_LValue, BasePath);
14408 
14409     // Dereference "this".
14410     DerefBuilder DerefThis(This);
14411     CastBuilder To(DerefThis,
14412                    Context.getQualifiedType(
14413                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14414                    VK_LValue, BasePath);
14415 
14416     // Build the copy.
14417     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14418                                             To, From,
14419                                             /*CopyingBaseSubobject=*/true,
14420                                             /*Copying=*/true);
14421     if (Copy.isInvalid()) {
14422       CopyAssignOperator->setInvalidDecl();
14423       return;
14424     }
14425 
14426     // Success! Record the copy.
14427     Statements.push_back(Copy.getAs<Expr>());
14428   }
14429 
14430   // Assign non-static members.
14431   for (auto *Field : ClassDecl->fields()) {
14432     // FIXME: We should form some kind of AST representation for the implied
14433     // memcpy in a union copy operation.
14434     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14435       continue;
14436 
14437     if (Field->isInvalidDecl()) {
14438       Invalid = true;
14439       continue;
14440     }
14441 
14442     // Check for members of reference type; we can't copy those.
14443     if (Field->getType()->isReferenceType()) {
14444       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14445         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14446       Diag(Field->getLocation(), diag::note_declared_at);
14447       Invalid = true;
14448       continue;
14449     }
14450 
14451     // Check for members of const-qualified, non-class type.
14452     QualType BaseType = Context.getBaseElementType(Field->getType());
14453     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14454       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14455         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14456       Diag(Field->getLocation(), diag::note_declared_at);
14457       Invalid = true;
14458       continue;
14459     }
14460 
14461     // Suppress assigning zero-width bitfields.
14462     if (Field->isZeroLengthBitField(Context))
14463       continue;
14464 
14465     QualType FieldType = Field->getType().getNonReferenceType();
14466     if (FieldType->isIncompleteArrayType()) {
14467       assert(ClassDecl->hasFlexibleArrayMember() &&
14468              "Incomplete array type is not valid");
14469       continue;
14470     }
14471 
14472     // Build references to the field in the object we're copying from and to.
14473     CXXScopeSpec SS; // Intentionally empty
14474     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14475                               LookupMemberName);
14476     MemberLookup.addDecl(Field);
14477     MemberLookup.resolveKind();
14478 
14479     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14480 
14481     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14482 
14483     // Build the copy of this field.
14484     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14485                                             To, From,
14486                                             /*CopyingBaseSubobject=*/false,
14487                                             /*Copying=*/true);
14488     if (Copy.isInvalid()) {
14489       CopyAssignOperator->setInvalidDecl();
14490       return;
14491     }
14492 
14493     // Success! Record the copy.
14494     Statements.push_back(Copy.getAs<Stmt>());
14495   }
14496 
14497   if (!Invalid) {
14498     // Add a "return *this;"
14499     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14500 
14501     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14502     if (Return.isInvalid())
14503       Invalid = true;
14504     else
14505       Statements.push_back(Return.getAs<Stmt>());
14506   }
14507 
14508   if (Invalid) {
14509     CopyAssignOperator->setInvalidDecl();
14510     return;
14511   }
14512 
14513   StmtResult Body;
14514   {
14515     CompoundScopeRAII CompoundScope(*this);
14516     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14517                              /*isStmtExpr=*/false);
14518     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14519   }
14520   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14521   CopyAssignOperator->markUsed(Context);
14522 
14523   if (ASTMutationListener *L = getASTMutationListener()) {
14524     L->CompletedImplicitDefinition(CopyAssignOperator);
14525   }
14526 }
14527 
14528 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14529   assert(ClassDecl->needsImplicitMoveAssignment());
14530 
14531   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14532   if (DSM.isAlreadyBeingDeclared())
14533     return nullptr;
14534 
14535   // Note: The following rules are largely analoguous to the move
14536   // constructor rules.
14537 
14538   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14539   LangAS AS = getDefaultCXXMethodAddrSpace();
14540   if (AS != LangAS::Default)
14541     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14542   QualType RetType = Context.getLValueReferenceType(ArgType);
14543   ArgType = Context.getRValueReferenceType(ArgType);
14544 
14545   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14546                                                      CXXMoveAssignment,
14547                                                      false);
14548 
14549   //   An implicitly-declared move assignment operator is an inline public
14550   //   member of its class.
14551   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14552   SourceLocation ClassLoc = ClassDecl->getLocation();
14553   DeclarationNameInfo NameInfo(Name, ClassLoc);
14554   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14555       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14556       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14557       getCurFPFeatures().isFPConstrained(),
14558       /*isInline=*/true,
14559       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14560       SourceLocation());
14561   MoveAssignment->setAccess(AS_public);
14562   MoveAssignment->setDefaulted();
14563   MoveAssignment->setImplicit();
14564 
14565   if (getLangOpts().CUDA) {
14566     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14567                                             MoveAssignment,
14568                                             /* ConstRHS */ false,
14569                                             /* Diagnose */ false);
14570   }
14571 
14572   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14573 
14574   // Add the parameter to the operator.
14575   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14576                                                ClassLoc, ClassLoc,
14577                                                /*Id=*/nullptr, ArgType,
14578                                                /*TInfo=*/nullptr, SC_None,
14579                                                nullptr);
14580   MoveAssignment->setParams(FromParam);
14581 
14582   MoveAssignment->setTrivial(
14583     ClassDecl->needsOverloadResolutionForMoveAssignment()
14584       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14585       : ClassDecl->hasTrivialMoveAssignment());
14586 
14587   // Note that we have added this copy-assignment operator.
14588   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14589 
14590   Scope *S = getScopeForContext(ClassDecl);
14591   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14592 
14593   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14594     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14595     SetDeclDeleted(MoveAssignment, ClassLoc);
14596   }
14597 
14598   if (S)
14599     PushOnScopeChains(MoveAssignment, S, false);
14600   ClassDecl->addDecl(MoveAssignment);
14601 
14602   return MoveAssignment;
14603 }
14604 
14605 /// Check if we're implicitly defining a move assignment operator for a class
14606 /// with virtual bases. Such a move assignment might move-assign the virtual
14607 /// base multiple times.
14608 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14609                                                SourceLocation CurrentLocation) {
14610   assert(!Class->isDependentContext() && "should not define dependent move");
14611 
14612   // Only a virtual base could get implicitly move-assigned multiple times.
14613   // Only a non-trivial move assignment can observe this. We only want to
14614   // diagnose if we implicitly define an assignment operator that assigns
14615   // two base classes, both of which move-assign the same virtual base.
14616   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14617       Class->getNumBases() < 2)
14618     return;
14619 
14620   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14621   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14622   VBaseMap VBases;
14623 
14624   for (auto &BI : Class->bases()) {
14625     Worklist.push_back(&BI);
14626     while (!Worklist.empty()) {
14627       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14628       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14629 
14630       // If the base has no non-trivial move assignment operators,
14631       // we don't care about moves from it.
14632       if (!Base->hasNonTrivialMoveAssignment())
14633         continue;
14634 
14635       // If there's nothing virtual here, skip it.
14636       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14637         continue;
14638 
14639       // If we're not actually going to call a move assignment for this base,
14640       // or the selected move assignment is trivial, skip it.
14641       Sema::SpecialMemberOverloadResult SMOR =
14642         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14643                               /*ConstArg*/false, /*VolatileArg*/false,
14644                               /*RValueThis*/true, /*ConstThis*/false,
14645                               /*VolatileThis*/false);
14646       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14647           !SMOR.getMethod()->isMoveAssignmentOperator())
14648         continue;
14649 
14650       if (BaseSpec->isVirtual()) {
14651         // We're going to move-assign this virtual base, and its move
14652         // assignment operator is not trivial. If this can happen for
14653         // multiple distinct direct bases of Class, diagnose it. (If it
14654         // only happens in one base, we'll diagnose it when synthesizing
14655         // that base class's move assignment operator.)
14656         CXXBaseSpecifier *&Existing =
14657             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14658                 .first->second;
14659         if (Existing && Existing != &BI) {
14660           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14661             << Class << Base;
14662           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14663               << (Base->getCanonicalDecl() ==
14664                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14665               << Base << Existing->getType() << Existing->getSourceRange();
14666           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14667               << (Base->getCanonicalDecl() ==
14668                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14669               << Base << BI.getType() << BaseSpec->getSourceRange();
14670 
14671           // Only diagnose each vbase once.
14672           Existing = nullptr;
14673         }
14674       } else {
14675         // Only walk over bases that have defaulted move assignment operators.
14676         // We assume that any user-provided move assignment operator handles
14677         // the multiple-moves-of-vbase case itself somehow.
14678         if (!SMOR.getMethod()->isDefaulted())
14679           continue;
14680 
14681         // We're going to move the base classes of Base. Add them to the list.
14682         for (auto &BI : Base->bases())
14683           Worklist.push_back(&BI);
14684       }
14685     }
14686   }
14687 }
14688 
14689 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14690                                         CXXMethodDecl *MoveAssignOperator) {
14691   assert((MoveAssignOperator->isDefaulted() &&
14692           MoveAssignOperator->isOverloadedOperator() &&
14693           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14694           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14695           !MoveAssignOperator->isDeleted()) &&
14696          "DefineImplicitMoveAssignment called for wrong function");
14697   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14698     return;
14699 
14700   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14701   if (ClassDecl->isInvalidDecl()) {
14702     MoveAssignOperator->setInvalidDecl();
14703     return;
14704   }
14705 
14706   // C++0x [class.copy]p28:
14707   //   The implicitly-defined or move assignment operator for a non-union class
14708   //   X performs memberwise move assignment of its subobjects. The direct base
14709   //   classes of X are assigned first, in the order of their declaration in the
14710   //   base-specifier-list, and then the immediate non-static data members of X
14711   //   are assigned, in the order in which they were declared in the class
14712   //   definition.
14713 
14714   // Issue a warning if our implicit move assignment operator will move
14715   // from a virtual base more than once.
14716   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14717 
14718   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14719 
14720   // The exception specification is needed because we are defining the
14721   // function.
14722   ResolveExceptionSpec(CurrentLocation,
14723                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14724 
14725   // Add a context note for diagnostics produced after this point.
14726   Scope.addContextNote(CurrentLocation);
14727 
14728   // The statements that form the synthesized function body.
14729   SmallVector<Stmt*, 8> Statements;
14730 
14731   // The parameter for the "other" object, which we are move from.
14732   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14733   QualType OtherRefType =
14734       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14735 
14736   // Our location for everything implicitly-generated.
14737   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14738                            ? MoveAssignOperator->getEndLoc()
14739                            : MoveAssignOperator->getLocation();
14740 
14741   // Builds a reference to the "other" object.
14742   RefBuilder OtherRef(Other, OtherRefType);
14743   // Cast to rvalue.
14744   MoveCastBuilder MoveOther(OtherRef);
14745 
14746   // Builds the "this" pointer.
14747   ThisBuilder This;
14748 
14749   // Assign base classes.
14750   bool Invalid = false;
14751   for (auto &Base : ClassDecl->bases()) {
14752     // C++11 [class.copy]p28:
14753     //   It is unspecified whether subobjects representing virtual base classes
14754     //   are assigned more than once by the implicitly-defined copy assignment
14755     //   operator.
14756     // FIXME: Do not assign to a vbase that will be assigned by some other base
14757     // class. For a move-assignment, this can result in the vbase being moved
14758     // multiple times.
14759 
14760     // Form the assignment:
14761     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14762     QualType BaseType = Base.getType().getUnqualifiedType();
14763     if (!BaseType->isRecordType()) {
14764       Invalid = true;
14765       continue;
14766     }
14767 
14768     CXXCastPath BasePath;
14769     BasePath.push_back(&Base);
14770 
14771     // Construct the "from" expression, which is an implicit cast to the
14772     // appropriately-qualified base type.
14773     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14774 
14775     // Dereference "this".
14776     DerefBuilder DerefThis(This);
14777 
14778     // Implicitly cast "this" to the appropriately-qualified base type.
14779     CastBuilder To(DerefThis,
14780                    Context.getQualifiedType(
14781                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14782                    VK_LValue, BasePath);
14783 
14784     // Build the move.
14785     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14786                                             To, From,
14787                                             /*CopyingBaseSubobject=*/true,
14788                                             /*Copying=*/false);
14789     if (Move.isInvalid()) {
14790       MoveAssignOperator->setInvalidDecl();
14791       return;
14792     }
14793 
14794     // Success! Record the move.
14795     Statements.push_back(Move.getAs<Expr>());
14796   }
14797 
14798   // Assign non-static members.
14799   for (auto *Field : ClassDecl->fields()) {
14800     // FIXME: We should form some kind of AST representation for the implied
14801     // memcpy in a union copy operation.
14802     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14803       continue;
14804 
14805     if (Field->isInvalidDecl()) {
14806       Invalid = true;
14807       continue;
14808     }
14809 
14810     // Check for members of reference type; we can't move those.
14811     if (Field->getType()->isReferenceType()) {
14812       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14813         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14814       Diag(Field->getLocation(), diag::note_declared_at);
14815       Invalid = true;
14816       continue;
14817     }
14818 
14819     // Check for members of const-qualified, non-class type.
14820     QualType BaseType = Context.getBaseElementType(Field->getType());
14821     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14822       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14823         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14824       Diag(Field->getLocation(), diag::note_declared_at);
14825       Invalid = true;
14826       continue;
14827     }
14828 
14829     // Suppress assigning zero-width bitfields.
14830     if (Field->isZeroLengthBitField(Context))
14831       continue;
14832 
14833     QualType FieldType = Field->getType().getNonReferenceType();
14834     if (FieldType->isIncompleteArrayType()) {
14835       assert(ClassDecl->hasFlexibleArrayMember() &&
14836              "Incomplete array type is not valid");
14837       continue;
14838     }
14839 
14840     // Build references to the field in the object we're copying from and to.
14841     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14842                               LookupMemberName);
14843     MemberLookup.addDecl(Field);
14844     MemberLookup.resolveKind();
14845     MemberBuilder From(MoveOther, OtherRefType,
14846                        /*IsArrow=*/false, MemberLookup);
14847     MemberBuilder To(This, getCurrentThisType(),
14848                      /*IsArrow=*/true, MemberLookup);
14849 
14850     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14851         "Member reference with rvalue base must be rvalue except for reference "
14852         "members, which aren't allowed for move assignment.");
14853 
14854     // Build the move of this field.
14855     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14856                                             To, From,
14857                                             /*CopyingBaseSubobject=*/false,
14858                                             /*Copying=*/false);
14859     if (Move.isInvalid()) {
14860       MoveAssignOperator->setInvalidDecl();
14861       return;
14862     }
14863 
14864     // Success! Record the copy.
14865     Statements.push_back(Move.getAs<Stmt>());
14866   }
14867 
14868   if (!Invalid) {
14869     // Add a "return *this;"
14870     ExprResult ThisObj =
14871         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14872 
14873     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14874     if (Return.isInvalid())
14875       Invalid = true;
14876     else
14877       Statements.push_back(Return.getAs<Stmt>());
14878   }
14879 
14880   if (Invalid) {
14881     MoveAssignOperator->setInvalidDecl();
14882     return;
14883   }
14884 
14885   StmtResult Body;
14886   {
14887     CompoundScopeRAII CompoundScope(*this);
14888     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14889                              /*isStmtExpr=*/false);
14890     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14891   }
14892   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14893   MoveAssignOperator->markUsed(Context);
14894 
14895   if (ASTMutationListener *L = getASTMutationListener()) {
14896     L->CompletedImplicitDefinition(MoveAssignOperator);
14897   }
14898 }
14899 
14900 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14901                                                     CXXRecordDecl *ClassDecl) {
14902   // C++ [class.copy]p4:
14903   //   If the class definition does not explicitly declare a copy
14904   //   constructor, one is declared implicitly.
14905   assert(ClassDecl->needsImplicitCopyConstructor());
14906 
14907   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14908   if (DSM.isAlreadyBeingDeclared())
14909     return nullptr;
14910 
14911   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14912   QualType ArgType = ClassType;
14913   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14914   if (Const)
14915     ArgType = ArgType.withConst();
14916 
14917   LangAS AS = getDefaultCXXMethodAddrSpace();
14918   if (AS != LangAS::Default)
14919     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14920 
14921   ArgType = Context.getLValueReferenceType(ArgType);
14922 
14923   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14924                                                      CXXCopyConstructor,
14925                                                      Const);
14926 
14927   DeclarationName Name
14928     = Context.DeclarationNames.getCXXConstructorName(
14929                                            Context.getCanonicalType(ClassType));
14930   SourceLocation ClassLoc = ClassDecl->getLocation();
14931   DeclarationNameInfo NameInfo(Name, ClassLoc);
14932 
14933   //   An implicitly-declared copy constructor is an inline public
14934   //   member of its class.
14935   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14936       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14937       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14938       /*isInline=*/true,
14939       /*isImplicitlyDeclared=*/true,
14940       Constexpr ? ConstexprSpecKind::Constexpr
14941                 : ConstexprSpecKind::Unspecified);
14942   CopyConstructor->setAccess(AS_public);
14943   CopyConstructor->setDefaulted();
14944 
14945   if (getLangOpts().CUDA) {
14946     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14947                                             CopyConstructor,
14948                                             /* ConstRHS */ Const,
14949                                             /* Diagnose */ false);
14950   }
14951 
14952   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14953 
14954   // During template instantiation of special member functions we need a
14955   // reliable TypeSourceInfo for the parameter types in order to allow functions
14956   // to be substituted.
14957   TypeSourceInfo *TSI = nullptr;
14958   if (inTemplateInstantiation() && ClassDecl->isLambda())
14959     TSI = Context.getTrivialTypeSourceInfo(ArgType);
14960 
14961   // Add the parameter to the constructor.
14962   ParmVarDecl *FromParam =
14963       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
14964                           /*IdentifierInfo=*/nullptr, ArgType,
14965                           /*TInfo=*/TSI, SC_None, nullptr);
14966   CopyConstructor->setParams(FromParam);
14967 
14968   CopyConstructor->setTrivial(
14969       ClassDecl->needsOverloadResolutionForCopyConstructor()
14970           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14971           : ClassDecl->hasTrivialCopyConstructor());
14972 
14973   CopyConstructor->setTrivialForCall(
14974       ClassDecl->hasAttr<TrivialABIAttr>() ||
14975       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14976            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14977              TAH_ConsiderTrivialABI)
14978            : ClassDecl->hasTrivialCopyConstructorForCall()));
14979 
14980   // Note that we have declared this constructor.
14981   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14982 
14983   Scope *S = getScopeForContext(ClassDecl);
14984   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14985 
14986   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14987     ClassDecl->setImplicitCopyConstructorIsDeleted();
14988     SetDeclDeleted(CopyConstructor, ClassLoc);
14989   }
14990 
14991   if (S)
14992     PushOnScopeChains(CopyConstructor, S, false);
14993   ClassDecl->addDecl(CopyConstructor);
14994 
14995   return CopyConstructor;
14996 }
14997 
14998 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14999                                          CXXConstructorDecl *CopyConstructor) {
15000   assert((CopyConstructor->isDefaulted() &&
15001           CopyConstructor->isCopyConstructor() &&
15002           !CopyConstructor->doesThisDeclarationHaveABody() &&
15003           !CopyConstructor->isDeleted()) &&
15004          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15005   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15006     return;
15007 
15008   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15009   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15010 
15011   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15012 
15013   // The exception specification is needed because we are defining the
15014   // function.
15015   ResolveExceptionSpec(CurrentLocation,
15016                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15017   MarkVTableUsed(CurrentLocation, ClassDecl);
15018 
15019   // Add a context note for diagnostics produced after this point.
15020   Scope.addContextNote(CurrentLocation);
15021 
15022   // C++11 [class.copy]p7:
15023   //   The [definition of an implicitly declared copy constructor] is
15024   //   deprecated if the class has a user-declared copy assignment operator
15025   //   or a user-declared destructor.
15026   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15027     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15028 
15029   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15030     CopyConstructor->setInvalidDecl();
15031   }  else {
15032     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15033                              ? CopyConstructor->getEndLoc()
15034                              : CopyConstructor->getLocation();
15035     Sema::CompoundScopeRAII CompoundScope(*this);
15036     CopyConstructor->setBody(
15037         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15038     CopyConstructor->markUsed(Context);
15039   }
15040 
15041   if (ASTMutationListener *L = getASTMutationListener()) {
15042     L->CompletedImplicitDefinition(CopyConstructor);
15043   }
15044 }
15045 
15046 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15047                                                     CXXRecordDecl *ClassDecl) {
15048   assert(ClassDecl->needsImplicitMoveConstructor());
15049 
15050   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15051   if (DSM.isAlreadyBeingDeclared())
15052     return nullptr;
15053 
15054   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15055 
15056   QualType ArgType = ClassType;
15057   LangAS AS = getDefaultCXXMethodAddrSpace();
15058   if (AS != LangAS::Default)
15059     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15060   ArgType = Context.getRValueReferenceType(ArgType);
15061 
15062   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15063                                                      CXXMoveConstructor,
15064                                                      false);
15065 
15066   DeclarationName Name
15067     = Context.DeclarationNames.getCXXConstructorName(
15068                                            Context.getCanonicalType(ClassType));
15069   SourceLocation ClassLoc = ClassDecl->getLocation();
15070   DeclarationNameInfo NameInfo(Name, ClassLoc);
15071 
15072   // C++11 [class.copy]p11:
15073   //   An implicitly-declared copy/move constructor is an inline public
15074   //   member of its class.
15075   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15076       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15077       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15078       /*isInline=*/true,
15079       /*isImplicitlyDeclared=*/true,
15080       Constexpr ? ConstexprSpecKind::Constexpr
15081                 : ConstexprSpecKind::Unspecified);
15082   MoveConstructor->setAccess(AS_public);
15083   MoveConstructor->setDefaulted();
15084 
15085   if (getLangOpts().CUDA) {
15086     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15087                                             MoveConstructor,
15088                                             /* ConstRHS */ false,
15089                                             /* Diagnose */ false);
15090   }
15091 
15092   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15093 
15094   // Add the parameter to the constructor.
15095   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15096                                                ClassLoc, ClassLoc,
15097                                                /*IdentifierInfo=*/nullptr,
15098                                                ArgType, /*TInfo=*/nullptr,
15099                                                SC_None, nullptr);
15100   MoveConstructor->setParams(FromParam);
15101 
15102   MoveConstructor->setTrivial(
15103       ClassDecl->needsOverloadResolutionForMoveConstructor()
15104           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15105           : ClassDecl->hasTrivialMoveConstructor());
15106 
15107   MoveConstructor->setTrivialForCall(
15108       ClassDecl->hasAttr<TrivialABIAttr>() ||
15109       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15110            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15111                                     TAH_ConsiderTrivialABI)
15112            : ClassDecl->hasTrivialMoveConstructorForCall()));
15113 
15114   // Note that we have declared this constructor.
15115   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15116 
15117   Scope *S = getScopeForContext(ClassDecl);
15118   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15119 
15120   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15121     ClassDecl->setImplicitMoveConstructorIsDeleted();
15122     SetDeclDeleted(MoveConstructor, ClassLoc);
15123   }
15124 
15125   if (S)
15126     PushOnScopeChains(MoveConstructor, S, false);
15127   ClassDecl->addDecl(MoveConstructor);
15128 
15129   return MoveConstructor;
15130 }
15131 
15132 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15133                                          CXXConstructorDecl *MoveConstructor) {
15134   assert((MoveConstructor->isDefaulted() &&
15135           MoveConstructor->isMoveConstructor() &&
15136           !MoveConstructor->doesThisDeclarationHaveABody() &&
15137           !MoveConstructor->isDeleted()) &&
15138          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15139   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15140     return;
15141 
15142   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15143   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15144 
15145   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15146 
15147   // The exception specification is needed because we are defining the
15148   // function.
15149   ResolveExceptionSpec(CurrentLocation,
15150                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15151   MarkVTableUsed(CurrentLocation, ClassDecl);
15152 
15153   // Add a context note for diagnostics produced after this point.
15154   Scope.addContextNote(CurrentLocation);
15155 
15156   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15157     MoveConstructor->setInvalidDecl();
15158   } else {
15159     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15160                              ? MoveConstructor->getEndLoc()
15161                              : MoveConstructor->getLocation();
15162     Sema::CompoundScopeRAII CompoundScope(*this);
15163     MoveConstructor->setBody(ActOnCompoundStmt(
15164         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15165     MoveConstructor->markUsed(Context);
15166   }
15167 
15168   if (ASTMutationListener *L = getASTMutationListener()) {
15169     L->CompletedImplicitDefinition(MoveConstructor);
15170   }
15171 }
15172 
15173 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15174   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15175 }
15176 
15177 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15178                             SourceLocation CurrentLocation,
15179                             CXXConversionDecl *Conv) {
15180   SynthesizedFunctionScope Scope(*this, Conv);
15181   assert(!Conv->getReturnType()->isUndeducedType());
15182 
15183   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15184   CallingConv CC =
15185       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15186 
15187   CXXRecordDecl *Lambda = Conv->getParent();
15188   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15189   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15190 
15191   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15192     CallOp = InstantiateFunctionDeclaration(
15193         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15194     if (!CallOp)
15195       return;
15196 
15197     Invoker = InstantiateFunctionDeclaration(
15198         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15199     if (!Invoker)
15200       return;
15201   }
15202 
15203   if (CallOp->isInvalidDecl())
15204     return;
15205 
15206   // Mark the call operator referenced (and add to pending instantiations
15207   // if necessary).
15208   // For both the conversion and static-invoker template specializations
15209   // we construct their body's in this function, so no need to add them
15210   // to the PendingInstantiations.
15211   MarkFunctionReferenced(CurrentLocation, CallOp);
15212 
15213   // Fill in the __invoke function with a dummy implementation. IR generation
15214   // will fill in the actual details. Update its type in case it contained
15215   // an 'auto'.
15216   Invoker->markUsed(Context);
15217   Invoker->setReferenced();
15218   Invoker->setType(Conv->getReturnType()->getPointeeType());
15219   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15220 
15221   // Construct the body of the conversion function { return __invoke; }.
15222   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15223                                        VK_LValue, Conv->getLocation());
15224   assert(FunctionRef && "Can't refer to __invoke function?");
15225   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15226   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15227                                      Conv->getLocation()));
15228   Conv->markUsed(Context);
15229   Conv->setReferenced();
15230 
15231   if (ASTMutationListener *L = getASTMutationListener()) {
15232     L->CompletedImplicitDefinition(Conv);
15233     L->CompletedImplicitDefinition(Invoker);
15234   }
15235 }
15236 
15237 
15238 
15239 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15240        SourceLocation CurrentLocation,
15241        CXXConversionDecl *Conv)
15242 {
15243   assert(!Conv->getParent()->isGenericLambda());
15244 
15245   SynthesizedFunctionScope Scope(*this, Conv);
15246 
15247   // Copy-initialize the lambda object as needed to capture it.
15248   Expr *This = ActOnCXXThis(CurrentLocation).get();
15249   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15250 
15251   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15252                                                         Conv->getLocation(),
15253                                                         Conv, DerefThis);
15254 
15255   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15256   // behavior.  Note that only the general conversion function does this
15257   // (since it's unusable otherwise); in the case where we inline the
15258   // block literal, it has block literal lifetime semantics.
15259   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15260     BuildBlock = ImplicitCastExpr::Create(
15261         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15262         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15263 
15264   if (BuildBlock.isInvalid()) {
15265     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15266     Conv->setInvalidDecl();
15267     return;
15268   }
15269 
15270   // Create the return statement that returns the block from the conversion
15271   // function.
15272   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15273   if (Return.isInvalid()) {
15274     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15275     Conv->setInvalidDecl();
15276     return;
15277   }
15278 
15279   // Set the body of the conversion function.
15280   Stmt *ReturnS = Return.get();
15281   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15282                                      Conv->getLocation()));
15283   Conv->markUsed(Context);
15284 
15285   // We're done; notify the mutation listener, if any.
15286   if (ASTMutationListener *L = getASTMutationListener()) {
15287     L->CompletedImplicitDefinition(Conv);
15288   }
15289 }
15290 
15291 /// Determine whether the given list arguments contains exactly one
15292 /// "real" (non-default) argument.
15293 static bool hasOneRealArgument(MultiExprArg Args) {
15294   switch (Args.size()) {
15295   case 0:
15296     return false;
15297 
15298   default:
15299     if (!Args[1]->isDefaultArgument())
15300       return false;
15301 
15302     LLVM_FALLTHROUGH;
15303   case 1:
15304     return !Args[0]->isDefaultArgument();
15305   }
15306 
15307   return false;
15308 }
15309 
15310 ExprResult
15311 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15312                             NamedDecl *FoundDecl,
15313                             CXXConstructorDecl *Constructor,
15314                             MultiExprArg ExprArgs,
15315                             bool HadMultipleCandidates,
15316                             bool IsListInitialization,
15317                             bool IsStdInitListInitialization,
15318                             bool RequiresZeroInit,
15319                             unsigned ConstructKind,
15320                             SourceRange ParenRange) {
15321   bool Elidable = false;
15322 
15323   // C++0x [class.copy]p34:
15324   //   When certain criteria are met, an implementation is allowed to
15325   //   omit the copy/move construction of a class object, even if the
15326   //   copy/move constructor and/or destructor for the object have
15327   //   side effects. [...]
15328   //     - when a temporary class object that has not been bound to a
15329   //       reference (12.2) would be copied/moved to a class object
15330   //       with the same cv-unqualified type, the copy/move operation
15331   //       can be omitted by constructing the temporary object
15332   //       directly into the target of the omitted copy/move
15333   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15334       // FIXME: Converting constructors should also be accepted.
15335       // But to fix this, the logic that digs down into a CXXConstructExpr
15336       // to find the source object needs to handle it.
15337       // Right now it assumes the source object is passed directly as the
15338       // first argument.
15339       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15340     Expr *SubExpr = ExprArgs[0];
15341     // FIXME: Per above, this is also incorrect if we want to accept
15342     //        converting constructors, as isTemporaryObject will
15343     //        reject temporaries with different type from the
15344     //        CXXRecord itself.
15345     Elidable = SubExpr->isTemporaryObject(
15346         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15347   }
15348 
15349   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15350                                FoundDecl, Constructor,
15351                                Elidable, ExprArgs, HadMultipleCandidates,
15352                                IsListInitialization,
15353                                IsStdInitListInitialization, RequiresZeroInit,
15354                                ConstructKind, ParenRange);
15355 }
15356 
15357 ExprResult
15358 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15359                             NamedDecl *FoundDecl,
15360                             CXXConstructorDecl *Constructor,
15361                             bool Elidable,
15362                             MultiExprArg ExprArgs,
15363                             bool HadMultipleCandidates,
15364                             bool IsListInitialization,
15365                             bool IsStdInitListInitialization,
15366                             bool RequiresZeroInit,
15367                             unsigned ConstructKind,
15368                             SourceRange ParenRange) {
15369   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15370     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15371     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15372       return ExprError();
15373   }
15374 
15375   return BuildCXXConstructExpr(
15376       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15377       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15378       RequiresZeroInit, ConstructKind, ParenRange);
15379 }
15380 
15381 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15382 /// including handling of its default argument expressions.
15383 ExprResult
15384 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15385                             CXXConstructorDecl *Constructor,
15386                             bool Elidable,
15387                             MultiExprArg ExprArgs,
15388                             bool HadMultipleCandidates,
15389                             bool IsListInitialization,
15390                             bool IsStdInitListInitialization,
15391                             bool RequiresZeroInit,
15392                             unsigned ConstructKind,
15393                             SourceRange ParenRange) {
15394   assert(declaresSameEntity(
15395              Constructor->getParent(),
15396              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15397          "given constructor for wrong type");
15398   MarkFunctionReferenced(ConstructLoc, Constructor);
15399   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15400     return ExprError();
15401   if (getLangOpts().SYCLIsDevice &&
15402       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15403     return ExprError();
15404 
15405   return CheckForImmediateInvocation(
15406       CXXConstructExpr::Create(
15407           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15408           HadMultipleCandidates, IsListInitialization,
15409           IsStdInitListInitialization, RequiresZeroInit,
15410           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15411           ParenRange),
15412       Constructor);
15413 }
15414 
15415 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15416   assert(Field->hasInClassInitializer());
15417 
15418   // If we already have the in-class initializer nothing needs to be done.
15419   if (Field->getInClassInitializer())
15420     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15421 
15422   // If we might have already tried and failed to instantiate, don't try again.
15423   if (Field->isInvalidDecl())
15424     return ExprError();
15425 
15426   // Maybe we haven't instantiated the in-class initializer. Go check the
15427   // pattern FieldDecl to see if it has one.
15428   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15429 
15430   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15431     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15432     DeclContext::lookup_result Lookup =
15433         ClassPattern->lookup(Field->getDeclName());
15434 
15435     FieldDecl *Pattern = nullptr;
15436     for (auto L : Lookup) {
15437       if (isa<FieldDecl>(L)) {
15438         Pattern = cast<FieldDecl>(L);
15439         break;
15440       }
15441     }
15442     assert(Pattern && "We must have set the Pattern!");
15443 
15444     if (!Pattern->hasInClassInitializer() ||
15445         InstantiateInClassInitializer(Loc, Field, Pattern,
15446                                       getTemplateInstantiationArgs(Field))) {
15447       // Don't diagnose this again.
15448       Field->setInvalidDecl();
15449       return ExprError();
15450     }
15451     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15452   }
15453 
15454   // DR1351:
15455   //   If the brace-or-equal-initializer of a non-static data member
15456   //   invokes a defaulted default constructor of its class or of an
15457   //   enclosing class in a potentially evaluated subexpression, the
15458   //   program is ill-formed.
15459   //
15460   // This resolution is unworkable: the exception specification of the
15461   // default constructor can be needed in an unevaluated context, in
15462   // particular, in the operand of a noexcept-expression, and we can be
15463   // unable to compute an exception specification for an enclosed class.
15464   //
15465   // Any attempt to resolve the exception specification of a defaulted default
15466   // constructor before the initializer is lexically complete will ultimately
15467   // come here at which point we can diagnose it.
15468   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15469   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15470       << OutermostClass << Field;
15471   Diag(Field->getEndLoc(),
15472        diag::note_default_member_initializer_not_yet_parsed);
15473   // Recover by marking the field invalid, unless we're in a SFINAE context.
15474   if (!isSFINAEContext())
15475     Field->setInvalidDecl();
15476   return ExprError();
15477 }
15478 
15479 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15480   if (VD->isInvalidDecl()) return;
15481   // If initializing the variable failed, don't also diagnose problems with
15482   // the destructor, they're likely related.
15483   if (VD->getInit() && VD->getInit()->containsErrors())
15484     return;
15485 
15486   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15487   if (ClassDecl->isInvalidDecl()) return;
15488   if (ClassDecl->hasIrrelevantDestructor()) return;
15489   if (ClassDecl->isDependentContext()) return;
15490 
15491   if (VD->isNoDestroy(getASTContext()))
15492     return;
15493 
15494   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15495 
15496   // If this is an array, we'll require the destructor during initialization, so
15497   // we can skip over this. We still want to emit exit-time destructor warnings
15498   // though.
15499   if (!VD->getType()->isArrayType()) {
15500     MarkFunctionReferenced(VD->getLocation(), Destructor);
15501     CheckDestructorAccess(VD->getLocation(), Destructor,
15502                           PDiag(diag::err_access_dtor_var)
15503                               << VD->getDeclName() << VD->getType());
15504     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15505   }
15506 
15507   if (Destructor->isTrivial()) return;
15508 
15509   // If the destructor is constexpr, check whether the variable has constant
15510   // destruction now.
15511   if (Destructor->isConstexpr()) {
15512     bool HasConstantInit = false;
15513     if (VD->getInit() && !VD->getInit()->isValueDependent())
15514       HasConstantInit = VD->evaluateValue();
15515     SmallVector<PartialDiagnosticAt, 8> Notes;
15516     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15517         HasConstantInit) {
15518       Diag(VD->getLocation(),
15519            diag::err_constexpr_var_requires_const_destruction) << VD;
15520       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15521         Diag(Notes[I].first, Notes[I].second);
15522     }
15523   }
15524 
15525   if (!VD->hasGlobalStorage()) return;
15526 
15527   // Emit warning for non-trivial dtor in global scope (a real global,
15528   // class-static, function-static).
15529   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15530 
15531   // TODO: this should be re-enabled for static locals by !CXAAtExit
15532   if (!VD->isStaticLocal())
15533     Diag(VD->getLocation(), diag::warn_global_destructor);
15534 }
15535 
15536 /// Given a constructor and the set of arguments provided for the
15537 /// constructor, convert the arguments and add any required default arguments
15538 /// to form a proper call to this constructor.
15539 ///
15540 /// \returns true if an error occurred, false otherwise.
15541 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15542                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15543                                    SourceLocation Loc,
15544                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15545                                    bool AllowExplicit,
15546                                    bool IsListInitialization) {
15547   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15548   unsigned NumArgs = ArgsPtr.size();
15549   Expr **Args = ArgsPtr.data();
15550 
15551   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15552   unsigned NumParams = Proto->getNumParams();
15553 
15554   // If too few arguments are available, we'll fill in the rest with defaults.
15555   if (NumArgs < NumParams)
15556     ConvertedArgs.reserve(NumParams);
15557   else
15558     ConvertedArgs.reserve(NumArgs);
15559 
15560   VariadicCallType CallType =
15561     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15562   SmallVector<Expr *, 8> AllArgs;
15563   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15564                                         Proto, 0,
15565                                         llvm::makeArrayRef(Args, NumArgs),
15566                                         AllArgs,
15567                                         CallType, AllowExplicit,
15568                                         IsListInitialization);
15569   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15570 
15571   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15572 
15573   CheckConstructorCall(Constructor, DeclInitType,
15574                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15575                        Proto, Loc);
15576 
15577   return Invalid;
15578 }
15579 
15580 static inline bool
15581 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15582                                        const FunctionDecl *FnDecl) {
15583   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15584   if (isa<NamespaceDecl>(DC)) {
15585     return SemaRef.Diag(FnDecl->getLocation(),
15586                         diag::err_operator_new_delete_declared_in_namespace)
15587       << FnDecl->getDeclName();
15588   }
15589 
15590   if (isa<TranslationUnitDecl>(DC) &&
15591       FnDecl->getStorageClass() == SC_Static) {
15592     return SemaRef.Diag(FnDecl->getLocation(),
15593                         diag::err_operator_new_delete_declared_static)
15594       << FnDecl->getDeclName();
15595   }
15596 
15597   return false;
15598 }
15599 
15600 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15601                                              const PointerType *PtrTy) {
15602   auto &Ctx = SemaRef.Context;
15603   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15604   PtrQuals.removeAddressSpace();
15605   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15606       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15607 }
15608 
15609 static inline bool
15610 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15611                             CanQualType ExpectedResultType,
15612                             CanQualType ExpectedFirstParamType,
15613                             unsigned DependentParamTypeDiag,
15614                             unsigned InvalidParamTypeDiag) {
15615   QualType ResultType =
15616       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15617 
15618   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15619     // The operator is valid on any address space for OpenCL.
15620     // Drop address space from actual and expected result types.
15621     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15622       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15623 
15624     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15625       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15626   }
15627 
15628   // Check that the result type is what we expect.
15629   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15630     // Reject even if the type is dependent; an operator delete function is
15631     // required to have a non-dependent result type.
15632     return SemaRef.Diag(
15633                FnDecl->getLocation(),
15634                ResultType->isDependentType()
15635                    ? diag::err_operator_new_delete_dependent_result_type
15636                    : diag::err_operator_new_delete_invalid_result_type)
15637            << FnDecl->getDeclName() << ExpectedResultType;
15638   }
15639 
15640   // A function template must have at least 2 parameters.
15641   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15642     return SemaRef.Diag(FnDecl->getLocation(),
15643                       diag::err_operator_new_delete_template_too_few_parameters)
15644         << FnDecl->getDeclName();
15645 
15646   // The function decl must have at least 1 parameter.
15647   if (FnDecl->getNumParams() == 0)
15648     return SemaRef.Diag(FnDecl->getLocation(),
15649                         diag::err_operator_new_delete_too_few_parameters)
15650       << FnDecl->getDeclName();
15651 
15652   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15653   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15654     // The operator is valid on any address space for OpenCL.
15655     // Drop address space from actual and expected first parameter types.
15656     if (const auto *PtrTy =
15657             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15658       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15659 
15660     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15661       ExpectedFirstParamType =
15662           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15663   }
15664 
15665   // Check that the first parameter type is what we expect.
15666   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15667       ExpectedFirstParamType) {
15668     // The first parameter type is not allowed to be dependent. As a tentative
15669     // DR resolution, we allow a dependent parameter type if it is the right
15670     // type anyway, to allow destroying operator delete in class templates.
15671     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15672                                                    ? DependentParamTypeDiag
15673                                                    : InvalidParamTypeDiag)
15674            << FnDecl->getDeclName() << ExpectedFirstParamType;
15675   }
15676 
15677   return false;
15678 }
15679 
15680 static bool
15681 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15682   // C++ [basic.stc.dynamic.allocation]p1:
15683   //   A program is ill-formed if an allocation function is declared in a
15684   //   namespace scope other than global scope or declared static in global
15685   //   scope.
15686   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15687     return true;
15688 
15689   CanQualType SizeTy =
15690     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15691 
15692   // C++ [basic.stc.dynamic.allocation]p1:
15693   //  The return type shall be void*. The first parameter shall have type
15694   //  std::size_t.
15695   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15696                                   SizeTy,
15697                                   diag::err_operator_new_dependent_param_type,
15698                                   diag::err_operator_new_param_type))
15699     return true;
15700 
15701   // C++ [basic.stc.dynamic.allocation]p1:
15702   //  The first parameter shall not have an associated default argument.
15703   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15704     return SemaRef.Diag(FnDecl->getLocation(),
15705                         diag::err_operator_new_default_arg)
15706       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15707 
15708   return false;
15709 }
15710 
15711 static bool
15712 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15713   // C++ [basic.stc.dynamic.deallocation]p1:
15714   //   A program is ill-formed if deallocation functions are declared in a
15715   //   namespace scope other than global scope or declared static in global
15716   //   scope.
15717   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15718     return true;
15719 
15720   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15721 
15722   // C++ P0722:
15723   //   Within a class C, the first parameter of a destroying operator delete
15724   //   shall be of type C *. The first parameter of any other deallocation
15725   //   function shall be of type void *.
15726   CanQualType ExpectedFirstParamType =
15727       MD && MD->isDestroyingOperatorDelete()
15728           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15729                 SemaRef.Context.getRecordType(MD->getParent())))
15730           : SemaRef.Context.VoidPtrTy;
15731 
15732   // C++ [basic.stc.dynamic.deallocation]p2:
15733   //   Each deallocation function shall return void
15734   if (CheckOperatorNewDeleteTypes(
15735           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15736           diag::err_operator_delete_dependent_param_type,
15737           diag::err_operator_delete_param_type))
15738     return true;
15739 
15740   // C++ P0722:
15741   //   A destroying operator delete shall be a usual deallocation function.
15742   if (MD && !MD->getParent()->isDependentContext() &&
15743       MD->isDestroyingOperatorDelete() &&
15744       !SemaRef.isUsualDeallocationFunction(MD)) {
15745     SemaRef.Diag(MD->getLocation(),
15746                  diag::err_destroying_operator_delete_not_usual);
15747     return true;
15748   }
15749 
15750   return false;
15751 }
15752 
15753 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15754 /// of this overloaded operator is well-formed. If so, returns false;
15755 /// otherwise, emits appropriate diagnostics and returns true.
15756 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15757   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15758          "Expected an overloaded operator declaration");
15759 
15760   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15761 
15762   // C++ [over.oper]p5:
15763   //   The allocation and deallocation functions, operator new,
15764   //   operator new[], operator delete and operator delete[], are
15765   //   described completely in 3.7.3. The attributes and restrictions
15766   //   found in the rest of this subclause do not apply to them unless
15767   //   explicitly stated in 3.7.3.
15768   if (Op == OO_Delete || Op == OO_Array_Delete)
15769     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15770 
15771   if (Op == OO_New || Op == OO_Array_New)
15772     return CheckOperatorNewDeclaration(*this, FnDecl);
15773 
15774   // C++ [over.oper]p6:
15775   //   An operator function shall either be a non-static member
15776   //   function or be a non-member function and have at least one
15777   //   parameter whose type is a class, a reference to a class, an
15778   //   enumeration, or a reference to an enumeration.
15779   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15780     if (MethodDecl->isStatic())
15781       return Diag(FnDecl->getLocation(),
15782                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15783   } else {
15784     bool ClassOrEnumParam = false;
15785     for (auto Param : FnDecl->parameters()) {
15786       QualType ParamType = Param->getType().getNonReferenceType();
15787       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15788           ParamType->isEnumeralType()) {
15789         ClassOrEnumParam = true;
15790         break;
15791       }
15792     }
15793 
15794     if (!ClassOrEnumParam)
15795       return Diag(FnDecl->getLocation(),
15796                   diag::err_operator_overload_needs_class_or_enum)
15797         << FnDecl->getDeclName();
15798   }
15799 
15800   // C++ [over.oper]p8:
15801   //   An operator function cannot have default arguments (8.3.6),
15802   //   except where explicitly stated below.
15803   //
15804   // Only the function-call operator allows default arguments
15805   // (C++ [over.call]p1).
15806   if (Op != OO_Call) {
15807     for (auto Param : FnDecl->parameters()) {
15808       if (Param->hasDefaultArg())
15809         return Diag(Param->getLocation(),
15810                     diag::err_operator_overload_default_arg)
15811           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15812     }
15813   }
15814 
15815   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15816     { false, false, false }
15817 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15818     , { Unary, Binary, MemberOnly }
15819 #include "clang/Basic/OperatorKinds.def"
15820   };
15821 
15822   bool CanBeUnaryOperator = OperatorUses[Op][0];
15823   bool CanBeBinaryOperator = OperatorUses[Op][1];
15824   bool MustBeMemberOperator = OperatorUses[Op][2];
15825 
15826   // C++ [over.oper]p8:
15827   //   [...] Operator functions cannot have more or fewer parameters
15828   //   than the number required for the corresponding operator, as
15829   //   described in the rest of this subclause.
15830   unsigned NumParams = FnDecl->getNumParams()
15831                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15832   if (Op != OO_Call &&
15833       ((NumParams == 1 && !CanBeUnaryOperator) ||
15834        (NumParams == 2 && !CanBeBinaryOperator) ||
15835        (NumParams < 1) || (NumParams > 2))) {
15836     // We have the wrong number of parameters.
15837     unsigned ErrorKind;
15838     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15839       ErrorKind = 2;  // 2 -> unary or binary.
15840     } else if (CanBeUnaryOperator) {
15841       ErrorKind = 0;  // 0 -> unary
15842     } else {
15843       assert(CanBeBinaryOperator &&
15844              "All non-call overloaded operators are unary or binary!");
15845       ErrorKind = 1;  // 1 -> binary
15846     }
15847 
15848     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15849       << FnDecl->getDeclName() << NumParams << ErrorKind;
15850   }
15851 
15852   // Overloaded operators other than operator() cannot be variadic.
15853   if (Op != OO_Call &&
15854       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15855     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15856       << FnDecl->getDeclName();
15857   }
15858 
15859   // Some operators must be non-static member functions.
15860   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15861     return Diag(FnDecl->getLocation(),
15862                 diag::err_operator_overload_must_be_member)
15863       << FnDecl->getDeclName();
15864   }
15865 
15866   // C++ [over.inc]p1:
15867   //   The user-defined function called operator++ implements the
15868   //   prefix and postfix ++ operator. If this function is a member
15869   //   function with no parameters, or a non-member function with one
15870   //   parameter of class or enumeration type, it defines the prefix
15871   //   increment operator ++ for objects of that type. If the function
15872   //   is a member function with one parameter (which shall be of type
15873   //   int) or a non-member function with two parameters (the second
15874   //   of which shall be of type int), it defines the postfix
15875   //   increment operator ++ for objects of that type.
15876   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15877     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15878     QualType ParamType = LastParam->getType();
15879 
15880     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15881         !ParamType->isDependentType())
15882       return Diag(LastParam->getLocation(),
15883                   diag::err_operator_overload_post_incdec_must_be_int)
15884         << LastParam->getType() << (Op == OO_MinusMinus);
15885   }
15886 
15887   return false;
15888 }
15889 
15890 static bool
15891 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15892                                           FunctionTemplateDecl *TpDecl) {
15893   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15894 
15895   // Must have one or two template parameters.
15896   if (TemplateParams->size() == 1) {
15897     NonTypeTemplateParmDecl *PmDecl =
15898         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15899 
15900     // The template parameter must be a char parameter pack.
15901     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15902         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15903       return false;
15904 
15905     // C++20 [over.literal]p5:
15906     //   A string literal operator template is a literal operator template
15907     //   whose template-parameter-list comprises a single non-type
15908     //   template-parameter of class type.
15909     //
15910     // As a DR resolution, we also allow placeholders for deduced class
15911     // template specializations.
15912     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
15913         !PmDecl->isTemplateParameterPack() &&
15914         (PmDecl->getType()->isRecordType() ||
15915          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15916       return false;
15917   } else if (TemplateParams->size() == 2) {
15918     TemplateTypeParmDecl *PmType =
15919         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15920     NonTypeTemplateParmDecl *PmArgs =
15921         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15922 
15923     // The second template parameter must be a parameter pack with the
15924     // first template parameter as its type.
15925     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15926         PmArgs->isTemplateParameterPack()) {
15927       const TemplateTypeParmType *TArgs =
15928           PmArgs->getType()->getAs<TemplateTypeParmType>();
15929       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15930           TArgs->getIndex() == PmType->getIndex()) {
15931         if (!SemaRef.inTemplateInstantiation())
15932           SemaRef.Diag(TpDecl->getLocation(),
15933                        diag::ext_string_literal_operator_template);
15934         return false;
15935       }
15936     }
15937   }
15938 
15939   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15940                diag::err_literal_operator_template)
15941       << TpDecl->getTemplateParameters()->getSourceRange();
15942   return true;
15943 }
15944 
15945 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15946 /// of this literal operator function is well-formed. If so, returns
15947 /// false; otherwise, emits appropriate diagnostics and returns true.
15948 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15949   if (isa<CXXMethodDecl>(FnDecl)) {
15950     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15951       << FnDecl->getDeclName();
15952     return true;
15953   }
15954 
15955   if (FnDecl->isExternC()) {
15956     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15957     if (const LinkageSpecDecl *LSD =
15958             FnDecl->getDeclContext()->getExternCContext())
15959       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15960     return true;
15961   }
15962 
15963   // This might be the definition of a literal operator template.
15964   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15965 
15966   // This might be a specialization of a literal operator template.
15967   if (!TpDecl)
15968     TpDecl = FnDecl->getPrimaryTemplate();
15969 
15970   // template <char...> type operator "" name() and
15971   // template <class T, T...> type operator "" name() are the only valid
15972   // template signatures, and the only valid signatures with no parameters.
15973   //
15974   // C++20 also allows template <SomeClass T> type operator "" name().
15975   if (TpDecl) {
15976     if (FnDecl->param_size() != 0) {
15977       Diag(FnDecl->getLocation(),
15978            diag::err_literal_operator_template_with_params);
15979       return true;
15980     }
15981 
15982     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15983       return true;
15984 
15985   } else if (FnDecl->param_size() == 1) {
15986     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15987 
15988     QualType ParamType = Param->getType().getUnqualifiedType();
15989 
15990     // Only unsigned long long int, long double, any character type, and const
15991     // char * are allowed as the only parameters.
15992     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15993         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15994         Context.hasSameType(ParamType, Context.CharTy) ||
15995         Context.hasSameType(ParamType, Context.WideCharTy) ||
15996         Context.hasSameType(ParamType, Context.Char8Ty) ||
15997         Context.hasSameType(ParamType, Context.Char16Ty) ||
15998         Context.hasSameType(ParamType, Context.Char32Ty)) {
15999     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16000       QualType InnerType = Ptr->getPointeeType();
16001 
16002       // Pointer parameter must be a const char *.
16003       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16004                                 Context.CharTy) &&
16005             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16006         Diag(Param->getSourceRange().getBegin(),
16007              diag::err_literal_operator_param)
16008             << ParamType << "'const char *'" << Param->getSourceRange();
16009         return true;
16010       }
16011 
16012     } else if (ParamType->isRealFloatingType()) {
16013       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16014           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16015       return true;
16016 
16017     } else if (ParamType->isIntegerType()) {
16018       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16019           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16020       return true;
16021 
16022     } else {
16023       Diag(Param->getSourceRange().getBegin(),
16024            diag::err_literal_operator_invalid_param)
16025           << ParamType << Param->getSourceRange();
16026       return true;
16027     }
16028 
16029   } else if (FnDecl->param_size() == 2) {
16030     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16031 
16032     // First, verify that the first parameter is correct.
16033 
16034     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16035 
16036     // Two parameter function must have a pointer to const as a
16037     // first parameter; let's strip those qualifiers.
16038     const PointerType *PT = FirstParamType->getAs<PointerType>();
16039 
16040     if (!PT) {
16041       Diag((*Param)->getSourceRange().getBegin(),
16042            diag::err_literal_operator_param)
16043           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16044       return true;
16045     }
16046 
16047     QualType PointeeType = PT->getPointeeType();
16048     // First parameter must be const
16049     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16050       Diag((*Param)->getSourceRange().getBegin(),
16051            diag::err_literal_operator_param)
16052           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16053       return true;
16054     }
16055 
16056     QualType InnerType = PointeeType.getUnqualifiedType();
16057     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16058     // const char32_t* are allowed as the first parameter to a two-parameter
16059     // function
16060     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16061           Context.hasSameType(InnerType, Context.WideCharTy) ||
16062           Context.hasSameType(InnerType, Context.Char8Ty) ||
16063           Context.hasSameType(InnerType, Context.Char16Ty) ||
16064           Context.hasSameType(InnerType, Context.Char32Ty))) {
16065       Diag((*Param)->getSourceRange().getBegin(),
16066            diag::err_literal_operator_param)
16067           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16068       return true;
16069     }
16070 
16071     // Move on to the second and final parameter.
16072     ++Param;
16073 
16074     // The second parameter must be a std::size_t.
16075     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16076     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16077       Diag((*Param)->getSourceRange().getBegin(),
16078            diag::err_literal_operator_param)
16079           << SecondParamType << Context.getSizeType()
16080           << (*Param)->getSourceRange();
16081       return true;
16082     }
16083   } else {
16084     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16085     return true;
16086   }
16087 
16088   // Parameters are good.
16089 
16090   // A parameter-declaration-clause containing a default argument is not
16091   // equivalent to any of the permitted forms.
16092   for (auto Param : FnDecl->parameters()) {
16093     if (Param->hasDefaultArg()) {
16094       Diag(Param->getDefaultArgRange().getBegin(),
16095            diag::err_literal_operator_default_argument)
16096         << Param->getDefaultArgRange();
16097       break;
16098     }
16099   }
16100 
16101   StringRef LiteralName
16102     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16103   if (LiteralName[0] != '_' &&
16104       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16105     // C++11 [usrlit.suffix]p1:
16106     //   Literal suffix identifiers that do not start with an underscore
16107     //   are reserved for future standardization.
16108     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16109       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16110   }
16111 
16112   return false;
16113 }
16114 
16115 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16116 /// linkage specification, including the language and (if present)
16117 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16118 /// language string literal. LBraceLoc, if valid, provides the location of
16119 /// the '{' brace. Otherwise, this linkage specification does not
16120 /// have any braces.
16121 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16122                                            Expr *LangStr,
16123                                            SourceLocation LBraceLoc) {
16124   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16125   if (!Lit->isAscii()) {
16126     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16127       << LangStr->getSourceRange();
16128     return nullptr;
16129   }
16130 
16131   StringRef Lang = Lit->getString();
16132   LinkageSpecDecl::LanguageIDs Language;
16133   if (Lang == "C")
16134     Language = LinkageSpecDecl::lang_c;
16135   else if (Lang == "C++")
16136     Language = LinkageSpecDecl::lang_cxx;
16137   else {
16138     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16139       << LangStr->getSourceRange();
16140     return nullptr;
16141   }
16142 
16143   // FIXME: Add all the various semantics of linkage specifications
16144 
16145   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16146                                                LangStr->getExprLoc(), Language,
16147                                                LBraceLoc.isValid());
16148   CurContext->addDecl(D);
16149   PushDeclContext(S, D);
16150   return D;
16151 }
16152 
16153 /// ActOnFinishLinkageSpecification - Complete the definition of
16154 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16155 /// valid, it's the position of the closing '}' brace in a linkage
16156 /// specification that uses braces.
16157 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16158                                             Decl *LinkageSpec,
16159                                             SourceLocation RBraceLoc) {
16160   if (RBraceLoc.isValid()) {
16161     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16162     LSDecl->setRBraceLoc(RBraceLoc);
16163   }
16164   PopDeclContext();
16165   return LinkageSpec;
16166 }
16167 
16168 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16169                                   const ParsedAttributesView &AttrList,
16170                                   SourceLocation SemiLoc) {
16171   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16172   // Attribute declarations appertain to empty declaration so we handle
16173   // them here.
16174   ProcessDeclAttributeList(S, ED, AttrList);
16175 
16176   CurContext->addDecl(ED);
16177   return ED;
16178 }
16179 
16180 /// Perform semantic analysis for the variable declaration that
16181 /// occurs within a C++ catch clause, returning the newly-created
16182 /// variable.
16183 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16184                                          TypeSourceInfo *TInfo,
16185                                          SourceLocation StartLoc,
16186                                          SourceLocation Loc,
16187                                          IdentifierInfo *Name) {
16188   bool Invalid = false;
16189   QualType ExDeclType = TInfo->getType();
16190 
16191   // Arrays and functions decay.
16192   if (ExDeclType->isArrayType())
16193     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16194   else if (ExDeclType->isFunctionType())
16195     ExDeclType = Context.getPointerType(ExDeclType);
16196 
16197   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16198   // The exception-declaration shall not denote a pointer or reference to an
16199   // incomplete type, other than [cv] void*.
16200   // N2844 forbids rvalue references.
16201   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16202     Diag(Loc, diag::err_catch_rvalue_ref);
16203     Invalid = true;
16204   }
16205 
16206   if (ExDeclType->isVariablyModifiedType()) {
16207     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16208     Invalid = true;
16209   }
16210 
16211   QualType BaseType = ExDeclType;
16212   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16213   unsigned DK = diag::err_catch_incomplete;
16214   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16215     BaseType = Ptr->getPointeeType();
16216     Mode = 1;
16217     DK = diag::err_catch_incomplete_ptr;
16218   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16219     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16220     BaseType = Ref->getPointeeType();
16221     Mode = 2;
16222     DK = diag::err_catch_incomplete_ref;
16223   }
16224   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16225       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16226     Invalid = true;
16227 
16228   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16229     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16230     Invalid = true;
16231   }
16232 
16233   if (!Invalid && !ExDeclType->isDependentType() &&
16234       RequireNonAbstractType(Loc, ExDeclType,
16235                              diag::err_abstract_type_in_decl,
16236                              AbstractVariableType))
16237     Invalid = true;
16238 
16239   // Only the non-fragile NeXT runtime currently supports C++ catches
16240   // of ObjC types, and no runtime supports catching ObjC types by value.
16241   if (!Invalid && getLangOpts().ObjC) {
16242     QualType T = ExDeclType;
16243     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16244       T = RT->getPointeeType();
16245 
16246     if (T->isObjCObjectType()) {
16247       Diag(Loc, diag::err_objc_object_catch);
16248       Invalid = true;
16249     } else if (T->isObjCObjectPointerType()) {
16250       // FIXME: should this be a test for macosx-fragile specifically?
16251       if (getLangOpts().ObjCRuntime.isFragile())
16252         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16253     }
16254   }
16255 
16256   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16257                                     ExDeclType, TInfo, SC_None);
16258   ExDecl->setExceptionVariable(true);
16259 
16260   // In ARC, infer 'retaining' for variables of retainable type.
16261   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16262     Invalid = true;
16263 
16264   if (!Invalid && !ExDeclType->isDependentType()) {
16265     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16266       // Insulate this from anything else we might currently be parsing.
16267       EnterExpressionEvaluationContext scope(
16268           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16269 
16270       // C++ [except.handle]p16:
16271       //   The object declared in an exception-declaration or, if the
16272       //   exception-declaration does not specify a name, a temporary (12.2) is
16273       //   copy-initialized (8.5) from the exception object. [...]
16274       //   The object is destroyed when the handler exits, after the destruction
16275       //   of any automatic objects initialized within the handler.
16276       //
16277       // We just pretend to initialize the object with itself, then make sure
16278       // it can be destroyed later.
16279       QualType initType = Context.getExceptionObjectType(ExDeclType);
16280 
16281       InitializedEntity entity =
16282         InitializedEntity::InitializeVariable(ExDecl);
16283       InitializationKind initKind =
16284         InitializationKind::CreateCopy(Loc, SourceLocation());
16285 
16286       Expr *opaqueValue =
16287         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16288       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16289       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16290       if (result.isInvalid())
16291         Invalid = true;
16292       else {
16293         // If the constructor used was non-trivial, set this as the
16294         // "initializer".
16295         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16296         if (!construct->getConstructor()->isTrivial()) {
16297           Expr *init = MaybeCreateExprWithCleanups(construct);
16298           ExDecl->setInit(init);
16299         }
16300 
16301         // And make sure it's destructable.
16302         FinalizeVarWithDestructor(ExDecl, recordType);
16303       }
16304     }
16305   }
16306 
16307   if (Invalid)
16308     ExDecl->setInvalidDecl();
16309 
16310   return ExDecl;
16311 }
16312 
16313 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16314 /// handler.
16315 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16316   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16317   bool Invalid = D.isInvalidType();
16318 
16319   // Check for unexpanded parameter packs.
16320   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16321                                       UPPC_ExceptionType)) {
16322     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16323                                              D.getIdentifierLoc());
16324     Invalid = true;
16325   }
16326 
16327   IdentifierInfo *II = D.getIdentifier();
16328   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16329                                              LookupOrdinaryName,
16330                                              ForVisibleRedeclaration)) {
16331     // The scope should be freshly made just for us. There is just no way
16332     // it contains any previous declaration, except for function parameters in
16333     // a function-try-block's catch statement.
16334     assert(!S->isDeclScope(PrevDecl));
16335     if (isDeclInScope(PrevDecl, CurContext, S)) {
16336       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16337         << D.getIdentifier();
16338       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16339       Invalid = true;
16340     } else if (PrevDecl->isTemplateParameter())
16341       // Maybe we will complain about the shadowed template parameter.
16342       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16343   }
16344 
16345   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16346     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16347       << D.getCXXScopeSpec().getRange();
16348     Invalid = true;
16349   }
16350 
16351   VarDecl *ExDecl = BuildExceptionDeclaration(
16352       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16353   if (Invalid)
16354     ExDecl->setInvalidDecl();
16355 
16356   // Add the exception declaration into this scope.
16357   if (II)
16358     PushOnScopeChains(ExDecl, S);
16359   else
16360     CurContext->addDecl(ExDecl);
16361 
16362   ProcessDeclAttributes(S, ExDecl, D);
16363   return ExDecl;
16364 }
16365 
16366 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16367                                          Expr *AssertExpr,
16368                                          Expr *AssertMessageExpr,
16369                                          SourceLocation RParenLoc) {
16370   StringLiteral *AssertMessage =
16371       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16372 
16373   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16374     return nullptr;
16375 
16376   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16377                                       AssertMessage, RParenLoc, false);
16378 }
16379 
16380 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16381                                          Expr *AssertExpr,
16382                                          StringLiteral *AssertMessage,
16383                                          SourceLocation RParenLoc,
16384                                          bool Failed) {
16385   assert(AssertExpr != nullptr && "Expected non-null condition");
16386   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16387       !Failed) {
16388     // In a static_assert-declaration, the constant-expression shall be a
16389     // constant expression that can be contextually converted to bool.
16390     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16391     if (Converted.isInvalid())
16392       Failed = true;
16393 
16394     ExprResult FullAssertExpr =
16395         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16396                             /*DiscardedValue*/ false,
16397                             /*IsConstexpr*/ true);
16398     if (FullAssertExpr.isInvalid())
16399       Failed = true;
16400     else
16401       AssertExpr = FullAssertExpr.get();
16402 
16403     llvm::APSInt Cond;
16404     if (!Failed && VerifyIntegerConstantExpression(
16405                        AssertExpr, &Cond,
16406                        diag::err_static_assert_expression_is_not_constant)
16407                        .isInvalid())
16408       Failed = true;
16409 
16410     if (!Failed && !Cond) {
16411       SmallString<256> MsgBuffer;
16412       llvm::raw_svector_ostream Msg(MsgBuffer);
16413       if (AssertMessage)
16414         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16415 
16416       Expr *InnerCond = nullptr;
16417       std::string InnerCondDescription;
16418       std::tie(InnerCond, InnerCondDescription) =
16419         findFailedBooleanCondition(Converted.get());
16420       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16421         // Drill down into concept specialization expressions to see why they
16422         // weren't satisfied.
16423         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16424           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16425         ConstraintSatisfaction Satisfaction;
16426         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16427           DiagnoseUnsatisfiedConstraint(Satisfaction);
16428       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16429                            && !isa<IntegerLiteral>(InnerCond)) {
16430         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16431           << InnerCondDescription << !AssertMessage
16432           << Msg.str() << InnerCond->getSourceRange();
16433       } else {
16434         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16435           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16436       }
16437       Failed = true;
16438     }
16439   } else {
16440     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16441                                                     /*DiscardedValue*/false,
16442                                                     /*IsConstexpr*/true);
16443     if (FullAssertExpr.isInvalid())
16444       Failed = true;
16445     else
16446       AssertExpr = FullAssertExpr.get();
16447   }
16448 
16449   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16450                                         AssertExpr, AssertMessage, RParenLoc,
16451                                         Failed);
16452 
16453   CurContext->addDecl(Decl);
16454   return Decl;
16455 }
16456 
16457 /// Perform semantic analysis of the given friend type declaration.
16458 ///
16459 /// \returns A friend declaration that.
16460 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16461                                       SourceLocation FriendLoc,
16462                                       TypeSourceInfo *TSInfo) {
16463   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16464 
16465   QualType T = TSInfo->getType();
16466   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16467 
16468   // C++03 [class.friend]p2:
16469   //   An elaborated-type-specifier shall be used in a friend declaration
16470   //   for a class.*
16471   //
16472   //   * The class-key of the elaborated-type-specifier is required.
16473   if (!CodeSynthesisContexts.empty()) {
16474     // Do not complain about the form of friend template types during any kind
16475     // of code synthesis. For template instantiation, we will have complained
16476     // when the template was defined.
16477   } else {
16478     if (!T->isElaboratedTypeSpecifier()) {
16479       // If we evaluated the type to a record type, suggest putting
16480       // a tag in front.
16481       if (const RecordType *RT = T->getAs<RecordType>()) {
16482         RecordDecl *RD = RT->getDecl();
16483 
16484         SmallString<16> InsertionText(" ");
16485         InsertionText += RD->getKindName();
16486 
16487         Diag(TypeRange.getBegin(),
16488              getLangOpts().CPlusPlus11 ?
16489                diag::warn_cxx98_compat_unelaborated_friend_type :
16490                diag::ext_unelaborated_friend_type)
16491           << (unsigned) RD->getTagKind()
16492           << T
16493           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16494                                         InsertionText);
16495       } else {
16496         Diag(FriendLoc,
16497              getLangOpts().CPlusPlus11 ?
16498                diag::warn_cxx98_compat_nonclass_type_friend :
16499                diag::ext_nonclass_type_friend)
16500           << T
16501           << TypeRange;
16502       }
16503     } else if (T->getAs<EnumType>()) {
16504       Diag(FriendLoc,
16505            getLangOpts().CPlusPlus11 ?
16506              diag::warn_cxx98_compat_enum_friend :
16507              diag::ext_enum_friend)
16508         << T
16509         << TypeRange;
16510     }
16511 
16512     // C++11 [class.friend]p3:
16513     //   A friend declaration that does not declare a function shall have one
16514     //   of the following forms:
16515     //     friend elaborated-type-specifier ;
16516     //     friend simple-type-specifier ;
16517     //     friend typename-specifier ;
16518     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16519       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16520   }
16521 
16522   //   If the type specifier in a friend declaration designates a (possibly
16523   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16524   //   the friend declaration is ignored.
16525   return FriendDecl::Create(Context, CurContext,
16526                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16527                             FriendLoc);
16528 }
16529 
16530 /// Handle a friend tag declaration where the scope specifier was
16531 /// templated.
16532 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16533                                     unsigned TagSpec, SourceLocation TagLoc,
16534                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16535                                     SourceLocation NameLoc,
16536                                     const ParsedAttributesView &Attr,
16537                                     MultiTemplateParamsArg TempParamLists) {
16538   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16539 
16540   bool IsMemberSpecialization = false;
16541   bool Invalid = false;
16542 
16543   if (TemplateParameterList *TemplateParams =
16544           MatchTemplateParametersToScopeSpecifier(
16545               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16546               IsMemberSpecialization, Invalid)) {
16547     if (TemplateParams->size() > 0) {
16548       // This is a declaration of a class template.
16549       if (Invalid)
16550         return nullptr;
16551 
16552       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16553                                 NameLoc, Attr, TemplateParams, AS_public,
16554                                 /*ModulePrivateLoc=*/SourceLocation(),
16555                                 FriendLoc, TempParamLists.size() - 1,
16556                                 TempParamLists.data()).get();
16557     } else {
16558       // The "template<>" header is extraneous.
16559       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16560         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16561       IsMemberSpecialization = true;
16562     }
16563   }
16564 
16565   if (Invalid) return nullptr;
16566 
16567   bool isAllExplicitSpecializations = true;
16568   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16569     if (TempParamLists[I]->size()) {
16570       isAllExplicitSpecializations = false;
16571       break;
16572     }
16573   }
16574 
16575   // FIXME: don't ignore attributes.
16576 
16577   // If it's explicit specializations all the way down, just forget
16578   // about the template header and build an appropriate non-templated
16579   // friend.  TODO: for source fidelity, remember the headers.
16580   if (isAllExplicitSpecializations) {
16581     if (SS.isEmpty()) {
16582       bool Owned = false;
16583       bool IsDependent = false;
16584       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16585                       Attr, AS_public,
16586                       /*ModulePrivateLoc=*/SourceLocation(),
16587                       MultiTemplateParamsArg(), Owned, IsDependent,
16588                       /*ScopedEnumKWLoc=*/SourceLocation(),
16589                       /*ScopedEnumUsesClassTag=*/false,
16590                       /*UnderlyingType=*/TypeResult(),
16591                       /*IsTypeSpecifier=*/false,
16592                       /*IsTemplateParamOrArg=*/false);
16593     }
16594 
16595     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16596     ElaboratedTypeKeyword Keyword
16597       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16598     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16599                                    *Name, NameLoc);
16600     if (T.isNull())
16601       return nullptr;
16602 
16603     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16604     if (isa<DependentNameType>(T)) {
16605       DependentNameTypeLoc TL =
16606           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16607       TL.setElaboratedKeywordLoc(TagLoc);
16608       TL.setQualifierLoc(QualifierLoc);
16609       TL.setNameLoc(NameLoc);
16610     } else {
16611       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16612       TL.setElaboratedKeywordLoc(TagLoc);
16613       TL.setQualifierLoc(QualifierLoc);
16614       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16615     }
16616 
16617     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16618                                             TSI, FriendLoc, TempParamLists);
16619     Friend->setAccess(AS_public);
16620     CurContext->addDecl(Friend);
16621     return Friend;
16622   }
16623 
16624   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16625 
16626 
16627 
16628   // Handle the case of a templated-scope friend class.  e.g.
16629   //   template <class T> class A<T>::B;
16630   // FIXME: we don't support these right now.
16631   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16632     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16633   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16634   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16635   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16636   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16637   TL.setElaboratedKeywordLoc(TagLoc);
16638   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16639   TL.setNameLoc(NameLoc);
16640 
16641   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16642                                           TSI, FriendLoc, TempParamLists);
16643   Friend->setAccess(AS_public);
16644   Friend->setUnsupportedFriend(true);
16645   CurContext->addDecl(Friend);
16646   return Friend;
16647 }
16648 
16649 /// Handle a friend type declaration.  This works in tandem with
16650 /// ActOnTag.
16651 ///
16652 /// Notes on friend class templates:
16653 ///
16654 /// We generally treat friend class declarations as if they were
16655 /// declaring a class.  So, for example, the elaborated type specifier
16656 /// in a friend declaration is required to obey the restrictions of a
16657 /// class-head (i.e. no typedefs in the scope chain), template
16658 /// parameters are required to match up with simple template-ids, &c.
16659 /// However, unlike when declaring a template specialization, it's
16660 /// okay to refer to a template specialization without an empty
16661 /// template parameter declaration, e.g.
16662 ///   friend class A<T>::B<unsigned>;
16663 /// We permit this as a special case; if there are any template
16664 /// parameters present at all, require proper matching, i.e.
16665 ///   template <> template \<class T> friend class A<int>::B;
16666 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16667                                 MultiTemplateParamsArg TempParams) {
16668   SourceLocation Loc = DS.getBeginLoc();
16669 
16670   assert(DS.isFriendSpecified());
16671   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16672 
16673   // C++ [class.friend]p3:
16674   // A friend declaration that does not declare a function shall have one of
16675   // the following forms:
16676   //     friend elaborated-type-specifier ;
16677   //     friend simple-type-specifier ;
16678   //     friend typename-specifier ;
16679   //
16680   // Any declaration with a type qualifier does not have that form. (It's
16681   // legal to specify a qualified type as a friend, you just can't write the
16682   // keywords.)
16683   if (DS.getTypeQualifiers()) {
16684     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16685       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16686     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16687       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16688     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16689       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16690     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16691       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16692     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16693       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16694   }
16695 
16696   // Try to convert the decl specifier to a type.  This works for
16697   // friend templates because ActOnTag never produces a ClassTemplateDecl
16698   // for a TUK_Friend.
16699   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16700   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16701   QualType T = TSI->getType();
16702   if (TheDeclarator.isInvalidType())
16703     return nullptr;
16704 
16705   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16706     return nullptr;
16707 
16708   // This is definitely an error in C++98.  It's probably meant to
16709   // be forbidden in C++0x, too, but the specification is just
16710   // poorly written.
16711   //
16712   // The problem is with declarations like the following:
16713   //   template <T> friend A<T>::foo;
16714   // where deciding whether a class C is a friend or not now hinges
16715   // on whether there exists an instantiation of A that causes
16716   // 'foo' to equal C.  There are restrictions on class-heads
16717   // (which we declare (by fiat) elaborated friend declarations to
16718   // be) that makes this tractable.
16719   //
16720   // FIXME: handle "template <> friend class A<T>;", which
16721   // is possibly well-formed?  Who even knows?
16722   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16723     Diag(Loc, diag::err_tagless_friend_type_template)
16724       << DS.getSourceRange();
16725     return nullptr;
16726   }
16727 
16728   // C++98 [class.friend]p1: A friend of a class is a function
16729   //   or class that is not a member of the class . . .
16730   // This is fixed in DR77, which just barely didn't make the C++03
16731   // deadline.  It's also a very silly restriction that seriously
16732   // affects inner classes and which nobody else seems to implement;
16733   // thus we never diagnose it, not even in -pedantic.
16734   //
16735   // But note that we could warn about it: it's always useless to
16736   // friend one of your own members (it's not, however, worthless to
16737   // friend a member of an arbitrary specialization of your template).
16738 
16739   Decl *D;
16740   if (!TempParams.empty())
16741     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16742                                    TempParams,
16743                                    TSI,
16744                                    DS.getFriendSpecLoc());
16745   else
16746     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16747 
16748   if (!D)
16749     return nullptr;
16750 
16751   D->setAccess(AS_public);
16752   CurContext->addDecl(D);
16753 
16754   return D;
16755 }
16756 
16757 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16758                                         MultiTemplateParamsArg TemplateParams) {
16759   const DeclSpec &DS = D.getDeclSpec();
16760 
16761   assert(DS.isFriendSpecified());
16762   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16763 
16764   SourceLocation Loc = D.getIdentifierLoc();
16765   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16766 
16767   // C++ [class.friend]p1
16768   //   A friend of a class is a function or class....
16769   // Note that this sees through typedefs, which is intended.
16770   // It *doesn't* see through dependent types, which is correct
16771   // according to [temp.arg.type]p3:
16772   //   If a declaration acquires a function type through a
16773   //   type dependent on a template-parameter and this causes
16774   //   a declaration that does not use the syntactic form of a
16775   //   function declarator to have a function type, the program
16776   //   is ill-formed.
16777   if (!TInfo->getType()->isFunctionType()) {
16778     Diag(Loc, diag::err_unexpected_friend);
16779 
16780     // It might be worthwhile to try to recover by creating an
16781     // appropriate declaration.
16782     return nullptr;
16783   }
16784 
16785   // C++ [namespace.memdef]p3
16786   //  - If a friend declaration in a non-local class first declares a
16787   //    class or function, the friend class or function is a member
16788   //    of the innermost enclosing namespace.
16789   //  - The name of the friend is not found by simple name lookup
16790   //    until a matching declaration is provided in that namespace
16791   //    scope (either before or after the class declaration granting
16792   //    friendship).
16793   //  - If a friend function is called, its name may be found by the
16794   //    name lookup that considers functions from namespaces and
16795   //    classes associated with the types of the function arguments.
16796   //  - When looking for a prior declaration of a class or a function
16797   //    declared as a friend, scopes outside the innermost enclosing
16798   //    namespace scope are not considered.
16799 
16800   CXXScopeSpec &SS = D.getCXXScopeSpec();
16801   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16802   assert(NameInfo.getName());
16803 
16804   // Check for unexpanded parameter packs.
16805   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16806       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16807       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16808     return nullptr;
16809 
16810   // The context we found the declaration in, or in which we should
16811   // create the declaration.
16812   DeclContext *DC;
16813   Scope *DCScope = S;
16814   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16815                         ForExternalRedeclaration);
16816 
16817   // There are five cases here.
16818   //   - There's no scope specifier and we're in a local class. Only look
16819   //     for functions declared in the immediately-enclosing block scope.
16820   // We recover from invalid scope qualifiers as if they just weren't there.
16821   FunctionDecl *FunctionContainingLocalClass = nullptr;
16822   if ((SS.isInvalid() || !SS.isSet()) &&
16823       (FunctionContainingLocalClass =
16824            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16825     // C++11 [class.friend]p11:
16826     //   If a friend declaration appears in a local class and the name
16827     //   specified is an unqualified name, a prior declaration is
16828     //   looked up without considering scopes that are outside the
16829     //   innermost enclosing non-class scope. For a friend function
16830     //   declaration, if there is no prior declaration, the program is
16831     //   ill-formed.
16832 
16833     // Find the innermost enclosing non-class scope. This is the block
16834     // scope containing the local class definition (or for a nested class,
16835     // the outer local class).
16836     DCScope = S->getFnParent();
16837 
16838     // Look up the function name in the scope.
16839     Previous.clear(LookupLocalFriendName);
16840     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16841 
16842     if (!Previous.empty()) {
16843       // All possible previous declarations must have the same context:
16844       // either they were declared at block scope or they are members of
16845       // one of the enclosing local classes.
16846       DC = Previous.getRepresentativeDecl()->getDeclContext();
16847     } else {
16848       // This is ill-formed, but provide the context that we would have
16849       // declared the function in, if we were permitted to, for error recovery.
16850       DC = FunctionContainingLocalClass;
16851     }
16852     adjustContextForLocalExternDecl(DC);
16853 
16854     // C++ [class.friend]p6:
16855     //   A function can be defined in a friend declaration of a class if and
16856     //   only if the class is a non-local class (9.8), the function name is
16857     //   unqualified, and the function has namespace scope.
16858     if (D.isFunctionDefinition()) {
16859       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16860     }
16861 
16862   //   - There's no scope specifier, in which case we just go to the
16863   //     appropriate scope and look for a function or function template
16864   //     there as appropriate.
16865   } else if (SS.isInvalid() || !SS.isSet()) {
16866     // C++11 [namespace.memdef]p3:
16867     //   If the name in a friend declaration is neither qualified nor
16868     //   a template-id and the declaration is a function or an
16869     //   elaborated-type-specifier, the lookup to determine whether
16870     //   the entity has been previously declared shall not consider
16871     //   any scopes outside the innermost enclosing namespace.
16872     bool isTemplateId =
16873         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16874 
16875     // Find the appropriate context according to the above.
16876     DC = CurContext;
16877 
16878     // Skip class contexts.  If someone can cite chapter and verse
16879     // for this behavior, that would be nice --- it's what GCC and
16880     // EDG do, and it seems like a reasonable intent, but the spec
16881     // really only says that checks for unqualified existing
16882     // declarations should stop at the nearest enclosing namespace,
16883     // not that they should only consider the nearest enclosing
16884     // namespace.
16885     while (DC->isRecord())
16886       DC = DC->getParent();
16887 
16888     DeclContext *LookupDC = DC->getNonTransparentContext();
16889     while (true) {
16890       LookupQualifiedName(Previous, LookupDC);
16891 
16892       if (!Previous.empty()) {
16893         DC = LookupDC;
16894         break;
16895       }
16896 
16897       if (isTemplateId) {
16898         if (isa<TranslationUnitDecl>(LookupDC)) break;
16899       } else {
16900         if (LookupDC->isFileContext()) break;
16901       }
16902       LookupDC = LookupDC->getParent();
16903     }
16904 
16905     DCScope = getScopeForDeclContext(S, DC);
16906 
16907   //   - There's a non-dependent scope specifier, in which case we
16908   //     compute it and do a previous lookup there for a function
16909   //     or function template.
16910   } else if (!SS.getScopeRep()->isDependent()) {
16911     DC = computeDeclContext(SS);
16912     if (!DC) return nullptr;
16913 
16914     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16915 
16916     LookupQualifiedName(Previous, DC);
16917 
16918     // C++ [class.friend]p1: A friend of a class is a function or
16919     //   class that is not a member of the class . . .
16920     if (DC->Equals(CurContext))
16921       Diag(DS.getFriendSpecLoc(),
16922            getLangOpts().CPlusPlus11 ?
16923              diag::warn_cxx98_compat_friend_is_member :
16924              diag::err_friend_is_member);
16925 
16926     if (D.isFunctionDefinition()) {
16927       // C++ [class.friend]p6:
16928       //   A function can be defined in a friend declaration of a class if and
16929       //   only if the class is a non-local class (9.8), the function name is
16930       //   unqualified, and the function has namespace scope.
16931       //
16932       // FIXME: We should only do this if the scope specifier names the
16933       // innermost enclosing namespace; otherwise the fixit changes the
16934       // meaning of the code.
16935       SemaDiagnosticBuilder DB
16936         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16937 
16938       DB << SS.getScopeRep();
16939       if (DC->isFileContext())
16940         DB << FixItHint::CreateRemoval(SS.getRange());
16941       SS.clear();
16942     }
16943 
16944   //   - There's a scope specifier that does not match any template
16945   //     parameter lists, in which case we use some arbitrary context,
16946   //     create a method or method template, and wait for instantiation.
16947   //   - There's a scope specifier that does match some template
16948   //     parameter lists, which we don't handle right now.
16949   } else {
16950     if (D.isFunctionDefinition()) {
16951       // C++ [class.friend]p6:
16952       //   A function can be defined in a friend declaration of a class if and
16953       //   only if the class is a non-local class (9.8), the function name is
16954       //   unqualified, and the function has namespace scope.
16955       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16956         << SS.getScopeRep();
16957     }
16958 
16959     DC = CurContext;
16960     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16961   }
16962 
16963   if (!DC->isRecord()) {
16964     int DiagArg = -1;
16965     switch (D.getName().getKind()) {
16966     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16967     case UnqualifiedIdKind::IK_ConstructorName:
16968       DiagArg = 0;
16969       break;
16970     case UnqualifiedIdKind::IK_DestructorName:
16971       DiagArg = 1;
16972       break;
16973     case UnqualifiedIdKind::IK_ConversionFunctionId:
16974       DiagArg = 2;
16975       break;
16976     case UnqualifiedIdKind::IK_DeductionGuideName:
16977       DiagArg = 3;
16978       break;
16979     case UnqualifiedIdKind::IK_Identifier:
16980     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16981     case UnqualifiedIdKind::IK_LiteralOperatorId:
16982     case UnqualifiedIdKind::IK_OperatorFunctionId:
16983     case UnqualifiedIdKind::IK_TemplateId:
16984       break;
16985     }
16986     // This implies that it has to be an operator or function.
16987     if (DiagArg >= 0) {
16988       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16989       return nullptr;
16990     }
16991   }
16992 
16993   // FIXME: This is an egregious hack to cope with cases where the scope stack
16994   // does not contain the declaration context, i.e., in an out-of-line
16995   // definition of a class.
16996   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16997   if (!DCScope) {
16998     FakeDCScope.setEntity(DC);
16999     DCScope = &FakeDCScope;
17000   }
17001 
17002   bool AddToScope = true;
17003   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17004                                           TemplateParams, AddToScope);
17005   if (!ND) return nullptr;
17006 
17007   assert(ND->getLexicalDeclContext() == CurContext);
17008 
17009   // If we performed typo correction, we might have added a scope specifier
17010   // and changed the decl context.
17011   DC = ND->getDeclContext();
17012 
17013   // Add the function declaration to the appropriate lookup tables,
17014   // adjusting the redeclarations list as necessary.  We don't
17015   // want to do this yet if the friending class is dependent.
17016   //
17017   // Also update the scope-based lookup if the target context's
17018   // lookup context is in lexical scope.
17019   if (!CurContext->isDependentContext()) {
17020     DC = DC->getRedeclContext();
17021     DC->makeDeclVisibleInContext(ND);
17022     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17023       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17024   }
17025 
17026   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17027                                        D.getIdentifierLoc(), ND,
17028                                        DS.getFriendSpecLoc());
17029   FrD->setAccess(AS_public);
17030   CurContext->addDecl(FrD);
17031 
17032   if (ND->isInvalidDecl()) {
17033     FrD->setInvalidDecl();
17034   } else {
17035     if (DC->isRecord()) CheckFriendAccess(ND);
17036 
17037     FunctionDecl *FD;
17038     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17039       FD = FTD->getTemplatedDecl();
17040     else
17041       FD = cast<FunctionDecl>(ND);
17042 
17043     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17044     // default argument expression, that declaration shall be a definition
17045     // and shall be the only declaration of the function or function
17046     // template in the translation unit.
17047     if (functionDeclHasDefaultArgument(FD)) {
17048       // We can't look at FD->getPreviousDecl() because it may not have been set
17049       // if we're in a dependent context. If the function is known to be a
17050       // redeclaration, we will have narrowed Previous down to the right decl.
17051       if (D.isRedeclaration()) {
17052         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17053         Diag(Previous.getRepresentativeDecl()->getLocation(),
17054              diag::note_previous_declaration);
17055       } else if (!D.isFunctionDefinition())
17056         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17057     }
17058 
17059     // Mark templated-scope function declarations as unsupported.
17060     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17061       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17062         << SS.getScopeRep() << SS.getRange()
17063         << cast<CXXRecordDecl>(CurContext);
17064       FrD->setUnsupportedFriend(true);
17065     }
17066   }
17067 
17068   warnOnReservedIdentifier(ND);
17069 
17070   return ND;
17071 }
17072 
17073 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17074   AdjustDeclIfTemplate(Dcl);
17075 
17076   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17077   if (!Fn) {
17078     Diag(DelLoc, diag::err_deleted_non_function);
17079     return;
17080   }
17081 
17082   // Deleted function does not have a body.
17083   Fn->setWillHaveBody(false);
17084 
17085   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17086     // Don't consider the implicit declaration we generate for explicit
17087     // specializations. FIXME: Do not generate these implicit declarations.
17088     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17089          Prev->getPreviousDecl()) &&
17090         !Prev->isDefined()) {
17091       Diag(DelLoc, diag::err_deleted_decl_not_first);
17092       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17093            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17094                               : diag::note_previous_declaration);
17095       // We can't recover from this; the declaration might have already
17096       // been used.
17097       Fn->setInvalidDecl();
17098       return;
17099     }
17100 
17101     // To maintain the invariant that functions are only deleted on their first
17102     // declaration, mark the implicitly-instantiated declaration of the
17103     // explicitly-specialized function as deleted instead of marking the
17104     // instantiated redeclaration.
17105     Fn = Fn->getCanonicalDecl();
17106   }
17107 
17108   // dllimport/dllexport cannot be deleted.
17109   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17110     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17111     Fn->setInvalidDecl();
17112   }
17113 
17114   // C++11 [basic.start.main]p3:
17115   //   A program that defines main as deleted [...] is ill-formed.
17116   if (Fn->isMain())
17117     Diag(DelLoc, diag::err_deleted_main);
17118 
17119   // C++11 [dcl.fct.def.delete]p4:
17120   //  A deleted function is implicitly inline.
17121   Fn->setImplicitlyInline();
17122   Fn->setDeletedAsWritten();
17123 }
17124 
17125 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17126   if (!Dcl || Dcl->isInvalidDecl())
17127     return;
17128 
17129   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17130   if (!FD) {
17131     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17132       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17133         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17134         return;
17135       }
17136     }
17137 
17138     Diag(DefaultLoc, diag::err_default_special_members)
17139         << getLangOpts().CPlusPlus20;
17140     return;
17141   }
17142 
17143   // Reject if this can't possibly be a defaultable function.
17144   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17145   if (!DefKind &&
17146       // A dependent function that doesn't locally look defaultable can
17147       // still instantiate to a defaultable function if it's a constructor
17148       // or assignment operator.
17149       (!FD->isDependentContext() ||
17150        (!isa<CXXConstructorDecl>(FD) &&
17151         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17152     Diag(DefaultLoc, diag::err_default_special_members)
17153         << getLangOpts().CPlusPlus20;
17154     return;
17155   }
17156 
17157   if (DefKind.isComparison() &&
17158       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
17159     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
17160         << (int)DefKind.asComparison();
17161     return;
17162   }
17163 
17164   // Issue compatibility warning. We already warned if the operator is
17165   // 'operator<=>' when parsing the '<=>' token.
17166   if (DefKind.isComparison() &&
17167       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17168     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17169                          ? diag::warn_cxx17_compat_defaulted_comparison
17170                          : diag::ext_defaulted_comparison);
17171   }
17172 
17173   FD->setDefaulted();
17174   FD->setExplicitlyDefaulted();
17175 
17176   // Defer checking functions that are defaulted in a dependent context.
17177   if (FD->isDependentContext())
17178     return;
17179 
17180   // Unset that we will have a body for this function. We might not,
17181   // if it turns out to be trivial, and we don't need this marking now
17182   // that we've marked it as defaulted.
17183   FD->setWillHaveBody(false);
17184 
17185   // If this definition appears within the record, do the checking when
17186   // the record is complete. This is always the case for a defaulted
17187   // comparison.
17188   if (DefKind.isComparison())
17189     return;
17190   auto *MD = cast<CXXMethodDecl>(FD);
17191 
17192   const FunctionDecl *Primary = FD;
17193   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17194     // Ask the template instantiation pattern that actually had the
17195     // '= default' on it.
17196     Primary = Pattern;
17197 
17198   // If the method was defaulted on its first declaration, we will have
17199   // already performed the checking in CheckCompletedCXXClass. Such a
17200   // declaration doesn't trigger an implicit definition.
17201   if (Primary->getCanonicalDecl()->isDefaulted())
17202     return;
17203 
17204   // FIXME: Once we support defining comparisons out of class, check for a
17205   // defaulted comparison here.
17206   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17207     MD->setInvalidDecl();
17208   else
17209     DefineDefaultedFunction(*this, MD, DefaultLoc);
17210 }
17211 
17212 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17213   for (Stmt *SubStmt : S->children()) {
17214     if (!SubStmt)
17215       continue;
17216     if (isa<ReturnStmt>(SubStmt))
17217       Self.Diag(SubStmt->getBeginLoc(),
17218                 diag::err_return_in_constructor_handler);
17219     if (!isa<Expr>(SubStmt))
17220       SearchForReturnInStmt(Self, SubStmt);
17221   }
17222 }
17223 
17224 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17225   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17226     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17227     SearchForReturnInStmt(*this, Handler);
17228   }
17229 }
17230 
17231 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17232                                              const CXXMethodDecl *Old) {
17233   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17234   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17235 
17236   if (OldFT->hasExtParameterInfos()) {
17237     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17238       // A parameter of the overriding method should be annotated with noescape
17239       // if the corresponding parameter of the overridden method is annotated.
17240       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17241           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17242         Diag(New->getParamDecl(I)->getLocation(),
17243              diag::warn_overriding_method_missing_noescape);
17244         Diag(Old->getParamDecl(I)->getLocation(),
17245              diag::note_overridden_marked_noescape);
17246       }
17247   }
17248 
17249   // Virtual overrides must have the same code_seg.
17250   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17251   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17252   if ((NewCSA || OldCSA) &&
17253       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17254     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17255     Diag(Old->getLocation(), diag::note_previous_declaration);
17256     return true;
17257   }
17258 
17259   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17260 
17261   // If the calling conventions match, everything is fine
17262   if (NewCC == OldCC)
17263     return false;
17264 
17265   // If the calling conventions mismatch because the new function is static,
17266   // suppress the calling convention mismatch error; the error about static
17267   // function override (err_static_overrides_virtual from
17268   // Sema::CheckFunctionDeclaration) is more clear.
17269   if (New->getStorageClass() == SC_Static)
17270     return false;
17271 
17272   Diag(New->getLocation(),
17273        diag::err_conflicting_overriding_cc_attributes)
17274     << New->getDeclName() << New->getType() << Old->getType();
17275   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17276   return true;
17277 }
17278 
17279 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17280                                              const CXXMethodDecl *Old) {
17281   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17282   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17283 
17284   if (Context.hasSameType(NewTy, OldTy) ||
17285       NewTy->isDependentType() || OldTy->isDependentType())
17286     return false;
17287 
17288   // Check if the return types are covariant
17289   QualType NewClassTy, OldClassTy;
17290 
17291   /// Both types must be pointers or references to classes.
17292   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17293     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17294       NewClassTy = NewPT->getPointeeType();
17295       OldClassTy = OldPT->getPointeeType();
17296     }
17297   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17298     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17299       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17300         NewClassTy = NewRT->getPointeeType();
17301         OldClassTy = OldRT->getPointeeType();
17302       }
17303     }
17304   }
17305 
17306   // The return types aren't either both pointers or references to a class type.
17307   if (NewClassTy.isNull()) {
17308     Diag(New->getLocation(),
17309          diag::err_different_return_type_for_overriding_virtual_function)
17310         << New->getDeclName() << NewTy << OldTy
17311         << New->getReturnTypeSourceRange();
17312     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17313         << Old->getReturnTypeSourceRange();
17314 
17315     return true;
17316   }
17317 
17318   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17319     // C++14 [class.virtual]p8:
17320     //   If the class type in the covariant return type of D::f differs from
17321     //   that of B::f, the class type in the return type of D::f shall be
17322     //   complete at the point of declaration of D::f or shall be the class
17323     //   type D.
17324     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17325       if (!RT->isBeingDefined() &&
17326           RequireCompleteType(New->getLocation(), NewClassTy,
17327                               diag::err_covariant_return_incomplete,
17328                               New->getDeclName()))
17329         return true;
17330     }
17331 
17332     // Check if the new class derives from the old class.
17333     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17334       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17335           << New->getDeclName() << NewTy << OldTy
17336           << New->getReturnTypeSourceRange();
17337       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17338           << Old->getReturnTypeSourceRange();
17339       return true;
17340     }
17341 
17342     // Check if we the conversion from derived to base is valid.
17343     if (CheckDerivedToBaseConversion(
17344             NewClassTy, OldClassTy,
17345             diag::err_covariant_return_inaccessible_base,
17346             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17347             New->getLocation(), New->getReturnTypeSourceRange(),
17348             New->getDeclName(), nullptr)) {
17349       // FIXME: this note won't trigger for delayed access control
17350       // diagnostics, and it's impossible to get an undelayed error
17351       // here from access control during the original parse because
17352       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17353       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17354           << Old->getReturnTypeSourceRange();
17355       return true;
17356     }
17357   }
17358 
17359   // The qualifiers of the return types must be the same.
17360   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17361     Diag(New->getLocation(),
17362          diag::err_covariant_return_type_different_qualifications)
17363         << New->getDeclName() << NewTy << OldTy
17364         << New->getReturnTypeSourceRange();
17365     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17366         << Old->getReturnTypeSourceRange();
17367     return true;
17368   }
17369 
17370 
17371   // The new class type must have the same or less qualifiers as the old type.
17372   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17373     Diag(New->getLocation(),
17374          diag::err_covariant_return_type_class_type_more_qualified)
17375         << New->getDeclName() << NewTy << OldTy
17376         << New->getReturnTypeSourceRange();
17377     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17378         << Old->getReturnTypeSourceRange();
17379     return true;
17380   }
17381 
17382   return false;
17383 }
17384 
17385 /// Mark the given method pure.
17386 ///
17387 /// \param Method the method to be marked pure.
17388 ///
17389 /// \param InitRange the source range that covers the "0" initializer.
17390 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17391   SourceLocation EndLoc = InitRange.getEnd();
17392   if (EndLoc.isValid())
17393     Method->setRangeEnd(EndLoc);
17394 
17395   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17396     Method->setPure();
17397     return false;
17398   }
17399 
17400   if (!Method->isInvalidDecl())
17401     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17402       << Method->getDeclName() << InitRange;
17403   return true;
17404 }
17405 
17406 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17407   if (D->getFriendObjectKind())
17408     Diag(D->getLocation(), diag::err_pure_friend);
17409   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17410     CheckPureMethod(M, ZeroLoc);
17411   else
17412     Diag(D->getLocation(), diag::err_illegal_initializer);
17413 }
17414 
17415 /// Determine whether the given declaration is a global variable or
17416 /// static data member.
17417 static bool isNonlocalVariable(const Decl *D) {
17418   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17419     return Var->hasGlobalStorage();
17420 
17421   return false;
17422 }
17423 
17424 /// Invoked when we are about to parse an initializer for the declaration
17425 /// 'Dcl'.
17426 ///
17427 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17428 /// static data member of class X, names should be looked up in the scope of
17429 /// class X. If the declaration had a scope specifier, a scope will have
17430 /// been created and passed in for this purpose. Otherwise, S will be null.
17431 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17432   // If there is no declaration, there was an error parsing it.
17433   if (!D || D->isInvalidDecl())
17434     return;
17435 
17436   // We will always have a nested name specifier here, but this declaration
17437   // might not be out of line if the specifier names the current namespace:
17438   //   extern int n;
17439   //   int ::n = 0;
17440   if (S && D->isOutOfLine())
17441     EnterDeclaratorContext(S, D->getDeclContext());
17442 
17443   // If we are parsing the initializer for a static data member, push a
17444   // new expression evaluation context that is associated with this static
17445   // data member.
17446   if (isNonlocalVariable(D))
17447     PushExpressionEvaluationContext(
17448         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17449 }
17450 
17451 /// Invoked after we are finished parsing an initializer for the declaration D.
17452 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17453   // If there is no declaration, there was an error parsing it.
17454   if (!D || D->isInvalidDecl())
17455     return;
17456 
17457   if (isNonlocalVariable(D))
17458     PopExpressionEvaluationContext();
17459 
17460   if (S && D->isOutOfLine())
17461     ExitDeclaratorContext(S);
17462 }
17463 
17464 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17465 /// C++ if/switch/while/for statement.
17466 /// e.g: "if (int x = f()) {...}"
17467 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17468   // C++ 6.4p2:
17469   // The declarator shall not specify a function or an array.
17470   // The type-specifier-seq shall not contain typedef and shall not declare a
17471   // new class or enumeration.
17472   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17473          "Parser allowed 'typedef' as storage class of condition decl.");
17474 
17475   Decl *Dcl = ActOnDeclarator(S, D);
17476   if (!Dcl)
17477     return true;
17478 
17479   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17480     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17481       << D.getSourceRange();
17482     return true;
17483   }
17484 
17485   return Dcl;
17486 }
17487 
17488 void Sema::LoadExternalVTableUses() {
17489   if (!ExternalSource)
17490     return;
17491 
17492   SmallVector<ExternalVTableUse, 4> VTables;
17493   ExternalSource->ReadUsedVTables(VTables);
17494   SmallVector<VTableUse, 4> NewUses;
17495   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17496     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17497       = VTablesUsed.find(VTables[I].Record);
17498     // Even if a definition wasn't required before, it may be required now.
17499     if (Pos != VTablesUsed.end()) {
17500       if (!Pos->second && VTables[I].DefinitionRequired)
17501         Pos->second = true;
17502       continue;
17503     }
17504 
17505     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17506     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17507   }
17508 
17509   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17510 }
17511 
17512 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17513                           bool DefinitionRequired) {
17514   // Ignore any vtable uses in unevaluated operands or for classes that do
17515   // not have a vtable.
17516   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17517       CurContext->isDependentContext() || isUnevaluatedContext())
17518     return;
17519   // Do not mark as used if compiling for the device outside of the target
17520   // region.
17521   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17522       !isInOpenMPDeclareTargetContext() &&
17523       !isInOpenMPTargetExecutionDirective()) {
17524     if (!DefinitionRequired)
17525       MarkVirtualMembersReferenced(Loc, Class);
17526     return;
17527   }
17528 
17529   // Try to insert this class into the map.
17530   LoadExternalVTableUses();
17531   Class = Class->getCanonicalDecl();
17532   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17533     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17534   if (!Pos.second) {
17535     // If we already had an entry, check to see if we are promoting this vtable
17536     // to require a definition. If so, we need to reappend to the VTableUses
17537     // list, since we may have already processed the first entry.
17538     if (DefinitionRequired && !Pos.first->second) {
17539       Pos.first->second = true;
17540     } else {
17541       // Otherwise, we can early exit.
17542       return;
17543     }
17544   } else {
17545     // The Microsoft ABI requires that we perform the destructor body
17546     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17547     // the deleting destructor is emitted with the vtable, not with the
17548     // destructor definition as in the Itanium ABI.
17549     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17550       CXXDestructorDecl *DD = Class->getDestructor();
17551       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17552         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17553           // If this is an out-of-line declaration, marking it referenced will
17554           // not do anything. Manually call CheckDestructor to look up operator
17555           // delete().
17556           ContextRAII SavedContext(*this, DD);
17557           CheckDestructor(DD);
17558         } else {
17559           MarkFunctionReferenced(Loc, Class->getDestructor());
17560         }
17561       }
17562     }
17563   }
17564 
17565   // Local classes need to have their virtual members marked
17566   // immediately. For all other classes, we mark their virtual members
17567   // at the end of the translation unit.
17568   if (Class->isLocalClass())
17569     MarkVirtualMembersReferenced(Loc, Class);
17570   else
17571     VTableUses.push_back(std::make_pair(Class, Loc));
17572 }
17573 
17574 bool Sema::DefineUsedVTables() {
17575   LoadExternalVTableUses();
17576   if (VTableUses.empty())
17577     return false;
17578 
17579   // Note: The VTableUses vector could grow as a result of marking
17580   // the members of a class as "used", so we check the size each
17581   // time through the loop and prefer indices (which are stable) to
17582   // iterators (which are not).
17583   bool DefinedAnything = false;
17584   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17585     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17586     if (!Class)
17587       continue;
17588     TemplateSpecializationKind ClassTSK =
17589         Class->getTemplateSpecializationKind();
17590 
17591     SourceLocation Loc = VTableUses[I].second;
17592 
17593     bool DefineVTable = true;
17594 
17595     // If this class has a key function, but that key function is
17596     // defined in another translation unit, we don't need to emit the
17597     // vtable even though we're using it.
17598     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17599     if (KeyFunction && !KeyFunction->hasBody()) {
17600       // The key function is in another translation unit.
17601       DefineVTable = false;
17602       TemplateSpecializationKind TSK =
17603           KeyFunction->getTemplateSpecializationKind();
17604       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17605              TSK != TSK_ImplicitInstantiation &&
17606              "Instantiations don't have key functions");
17607       (void)TSK;
17608     } else if (!KeyFunction) {
17609       // If we have a class with no key function that is the subject
17610       // of an explicit instantiation declaration, suppress the
17611       // vtable; it will live with the explicit instantiation
17612       // definition.
17613       bool IsExplicitInstantiationDeclaration =
17614           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17615       for (auto R : Class->redecls()) {
17616         TemplateSpecializationKind TSK
17617           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17618         if (TSK == TSK_ExplicitInstantiationDeclaration)
17619           IsExplicitInstantiationDeclaration = true;
17620         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17621           IsExplicitInstantiationDeclaration = false;
17622           break;
17623         }
17624       }
17625 
17626       if (IsExplicitInstantiationDeclaration)
17627         DefineVTable = false;
17628     }
17629 
17630     // The exception specifications for all virtual members may be needed even
17631     // if we are not providing an authoritative form of the vtable in this TU.
17632     // We may choose to emit it available_externally anyway.
17633     if (!DefineVTable) {
17634       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17635       continue;
17636     }
17637 
17638     // Mark all of the virtual members of this class as referenced, so
17639     // that we can build a vtable. Then, tell the AST consumer that a
17640     // vtable for this class is required.
17641     DefinedAnything = true;
17642     MarkVirtualMembersReferenced(Loc, Class);
17643     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17644     if (VTablesUsed[Canonical])
17645       Consumer.HandleVTable(Class);
17646 
17647     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17648     // no key function or the key function is inlined. Don't warn in C++ ABIs
17649     // that lack key functions, since the user won't be able to make one.
17650     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17651         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17652         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17653       const FunctionDecl *KeyFunctionDef = nullptr;
17654       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17655                            KeyFunctionDef->isInlined()))
17656         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17657     }
17658   }
17659   VTableUses.clear();
17660 
17661   return DefinedAnything;
17662 }
17663 
17664 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17665                                                  const CXXRecordDecl *RD) {
17666   for (const auto *I : RD->methods())
17667     if (I->isVirtual() && !I->isPure())
17668       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17669 }
17670 
17671 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17672                                         const CXXRecordDecl *RD,
17673                                         bool ConstexprOnly) {
17674   // Mark all functions which will appear in RD's vtable as used.
17675   CXXFinalOverriderMap FinalOverriders;
17676   RD->getFinalOverriders(FinalOverriders);
17677   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17678                                             E = FinalOverriders.end();
17679        I != E; ++I) {
17680     for (OverridingMethods::const_iterator OI = I->second.begin(),
17681                                            OE = I->second.end();
17682          OI != OE; ++OI) {
17683       assert(OI->second.size() > 0 && "no final overrider");
17684       CXXMethodDecl *Overrider = OI->second.front().Method;
17685 
17686       // C++ [basic.def.odr]p2:
17687       //   [...] A virtual member function is used if it is not pure. [...]
17688       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17689         MarkFunctionReferenced(Loc, Overrider);
17690     }
17691   }
17692 
17693   // Only classes that have virtual bases need a VTT.
17694   if (RD->getNumVBases() == 0)
17695     return;
17696 
17697   for (const auto &I : RD->bases()) {
17698     const auto *Base =
17699         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17700     if (Base->getNumVBases() == 0)
17701       continue;
17702     MarkVirtualMembersReferenced(Loc, Base);
17703   }
17704 }
17705 
17706 /// SetIvarInitializers - This routine builds initialization ASTs for the
17707 /// Objective-C implementation whose ivars need be initialized.
17708 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17709   if (!getLangOpts().CPlusPlus)
17710     return;
17711   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17712     SmallVector<ObjCIvarDecl*, 8> ivars;
17713     CollectIvarsToConstructOrDestruct(OID, ivars);
17714     if (ivars.empty())
17715       return;
17716     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17717     for (unsigned i = 0; i < ivars.size(); i++) {
17718       FieldDecl *Field = ivars[i];
17719       if (Field->isInvalidDecl())
17720         continue;
17721 
17722       CXXCtorInitializer *Member;
17723       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17724       InitializationKind InitKind =
17725         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17726 
17727       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17728       ExprResult MemberInit =
17729         InitSeq.Perform(*this, InitEntity, InitKind, None);
17730       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17731       // Note, MemberInit could actually come back empty if no initialization
17732       // is required (e.g., because it would call a trivial default constructor)
17733       if (!MemberInit.get() || MemberInit.isInvalid())
17734         continue;
17735 
17736       Member =
17737         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17738                                          SourceLocation(),
17739                                          MemberInit.getAs<Expr>(),
17740                                          SourceLocation());
17741       AllToInit.push_back(Member);
17742 
17743       // Be sure that the destructor is accessible and is marked as referenced.
17744       if (const RecordType *RecordTy =
17745               Context.getBaseElementType(Field->getType())
17746                   ->getAs<RecordType>()) {
17747         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17748         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17749           MarkFunctionReferenced(Field->getLocation(), Destructor);
17750           CheckDestructorAccess(Field->getLocation(), Destructor,
17751                             PDiag(diag::err_access_dtor_ivar)
17752                               << Context.getBaseElementType(Field->getType()));
17753         }
17754       }
17755     }
17756     ObjCImplementation->setIvarInitializers(Context,
17757                                             AllToInit.data(), AllToInit.size());
17758   }
17759 }
17760 
17761 static
17762 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17763                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17764                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17765                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17766                            Sema &S) {
17767   if (Ctor->isInvalidDecl())
17768     return;
17769 
17770   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17771 
17772   // Target may not be determinable yet, for instance if this is a dependent
17773   // call in an uninstantiated template.
17774   if (Target) {
17775     const FunctionDecl *FNTarget = nullptr;
17776     (void)Target->hasBody(FNTarget);
17777     Target = const_cast<CXXConstructorDecl*>(
17778       cast_or_null<CXXConstructorDecl>(FNTarget));
17779   }
17780 
17781   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17782                      // Avoid dereferencing a null pointer here.
17783                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17784 
17785   if (!Current.insert(Canonical).second)
17786     return;
17787 
17788   // We know that beyond here, we aren't chaining into a cycle.
17789   if (!Target || !Target->isDelegatingConstructor() ||
17790       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17791     Valid.insert(Current.begin(), Current.end());
17792     Current.clear();
17793   // We've hit a cycle.
17794   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17795              Current.count(TCanonical)) {
17796     // If we haven't diagnosed this cycle yet, do so now.
17797     if (!Invalid.count(TCanonical)) {
17798       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17799              diag::warn_delegating_ctor_cycle)
17800         << Ctor;
17801 
17802       // Don't add a note for a function delegating directly to itself.
17803       if (TCanonical != Canonical)
17804         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17805 
17806       CXXConstructorDecl *C = Target;
17807       while (C->getCanonicalDecl() != Canonical) {
17808         const FunctionDecl *FNTarget = nullptr;
17809         (void)C->getTargetConstructor()->hasBody(FNTarget);
17810         assert(FNTarget && "Ctor cycle through bodiless function");
17811 
17812         C = const_cast<CXXConstructorDecl*>(
17813           cast<CXXConstructorDecl>(FNTarget));
17814         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17815       }
17816     }
17817 
17818     Invalid.insert(Current.begin(), Current.end());
17819     Current.clear();
17820   } else {
17821     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17822   }
17823 }
17824 
17825 
17826 void Sema::CheckDelegatingCtorCycles() {
17827   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17828 
17829   for (DelegatingCtorDeclsType::iterator
17830          I = DelegatingCtorDecls.begin(ExternalSource),
17831          E = DelegatingCtorDecls.end();
17832        I != E; ++I)
17833     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17834 
17835   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17836     (*CI)->setInvalidDecl();
17837 }
17838 
17839 namespace {
17840   /// AST visitor that finds references to the 'this' expression.
17841   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17842     Sema &S;
17843 
17844   public:
17845     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17846 
17847     bool VisitCXXThisExpr(CXXThisExpr *E) {
17848       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17849         << E->isImplicit();
17850       return false;
17851     }
17852   };
17853 }
17854 
17855 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17856   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17857   if (!TSInfo)
17858     return false;
17859 
17860   TypeLoc TL = TSInfo->getTypeLoc();
17861   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17862   if (!ProtoTL)
17863     return false;
17864 
17865   // C++11 [expr.prim.general]p3:
17866   //   [The expression this] shall not appear before the optional
17867   //   cv-qualifier-seq and it shall not appear within the declaration of a
17868   //   static member function (although its type and value category are defined
17869   //   within a static member function as they are within a non-static member
17870   //   function). [ Note: this is because declaration matching does not occur
17871   //  until the complete declarator is known. - end note ]
17872   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17873   FindCXXThisExpr Finder(*this);
17874 
17875   // If the return type came after the cv-qualifier-seq, check it now.
17876   if (Proto->hasTrailingReturn() &&
17877       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17878     return true;
17879 
17880   // Check the exception specification.
17881   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17882     return true;
17883 
17884   // Check the trailing requires clause
17885   if (Expr *E = Method->getTrailingRequiresClause())
17886     if (!Finder.TraverseStmt(E))
17887       return true;
17888 
17889   return checkThisInStaticMemberFunctionAttributes(Method);
17890 }
17891 
17892 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17893   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17894   if (!TSInfo)
17895     return false;
17896 
17897   TypeLoc TL = TSInfo->getTypeLoc();
17898   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17899   if (!ProtoTL)
17900     return false;
17901 
17902   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17903   FindCXXThisExpr Finder(*this);
17904 
17905   switch (Proto->getExceptionSpecType()) {
17906   case EST_Unparsed:
17907   case EST_Uninstantiated:
17908   case EST_Unevaluated:
17909   case EST_BasicNoexcept:
17910   case EST_NoThrow:
17911   case EST_DynamicNone:
17912   case EST_MSAny:
17913   case EST_None:
17914     break;
17915 
17916   case EST_DependentNoexcept:
17917   case EST_NoexceptFalse:
17918   case EST_NoexceptTrue:
17919     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17920       return true;
17921     LLVM_FALLTHROUGH;
17922 
17923   case EST_Dynamic:
17924     for (const auto &E : Proto->exceptions()) {
17925       if (!Finder.TraverseType(E))
17926         return true;
17927     }
17928     break;
17929   }
17930 
17931   return false;
17932 }
17933 
17934 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17935   FindCXXThisExpr Finder(*this);
17936 
17937   // Check attributes.
17938   for (const auto *A : Method->attrs()) {
17939     // FIXME: This should be emitted by tblgen.
17940     Expr *Arg = nullptr;
17941     ArrayRef<Expr *> Args;
17942     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17943       Arg = G->getArg();
17944     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17945       Arg = G->getArg();
17946     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17947       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17948     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17949       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17950     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17951       Arg = ETLF->getSuccessValue();
17952       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17953     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17954       Arg = STLF->getSuccessValue();
17955       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17956     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17957       Arg = LR->getArg();
17958     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17959       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17960     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17961       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17962     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17963       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17964     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17965       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17966     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17967       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17968 
17969     if (Arg && !Finder.TraverseStmt(Arg))
17970       return true;
17971 
17972     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17973       if (!Finder.TraverseStmt(Args[I]))
17974         return true;
17975     }
17976   }
17977 
17978   return false;
17979 }
17980 
17981 void Sema::checkExceptionSpecification(
17982     bool IsTopLevel, ExceptionSpecificationType EST,
17983     ArrayRef<ParsedType> DynamicExceptions,
17984     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17985     SmallVectorImpl<QualType> &Exceptions,
17986     FunctionProtoType::ExceptionSpecInfo &ESI) {
17987   Exceptions.clear();
17988   ESI.Type = EST;
17989   if (EST == EST_Dynamic) {
17990     Exceptions.reserve(DynamicExceptions.size());
17991     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17992       // FIXME: Preserve type source info.
17993       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17994 
17995       if (IsTopLevel) {
17996         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17997         collectUnexpandedParameterPacks(ET, Unexpanded);
17998         if (!Unexpanded.empty()) {
17999           DiagnoseUnexpandedParameterPacks(
18000               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18001               Unexpanded);
18002           continue;
18003         }
18004       }
18005 
18006       // Check that the type is valid for an exception spec, and
18007       // drop it if not.
18008       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18009         Exceptions.push_back(ET);
18010     }
18011     ESI.Exceptions = Exceptions;
18012     return;
18013   }
18014 
18015   if (isComputedNoexcept(EST)) {
18016     assert((NoexceptExpr->isTypeDependent() ||
18017             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18018             Context.BoolTy) &&
18019            "Parser should have made sure that the expression is boolean");
18020     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18021       ESI.Type = EST_BasicNoexcept;
18022       return;
18023     }
18024 
18025     ESI.NoexceptExpr = NoexceptExpr;
18026     return;
18027   }
18028 }
18029 
18030 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18031              ExceptionSpecificationType EST,
18032              SourceRange SpecificationRange,
18033              ArrayRef<ParsedType> DynamicExceptions,
18034              ArrayRef<SourceRange> DynamicExceptionRanges,
18035              Expr *NoexceptExpr) {
18036   if (!MethodD)
18037     return;
18038 
18039   // Dig out the method we're referring to.
18040   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18041     MethodD = FunTmpl->getTemplatedDecl();
18042 
18043   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18044   if (!Method)
18045     return;
18046 
18047   // Check the exception specification.
18048   llvm::SmallVector<QualType, 4> Exceptions;
18049   FunctionProtoType::ExceptionSpecInfo ESI;
18050   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18051                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18052                               ESI);
18053 
18054   // Update the exception specification on the function type.
18055   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18056 
18057   if (Method->isStatic())
18058     checkThisInStaticMemberFunctionExceptionSpec(Method);
18059 
18060   if (Method->isVirtual()) {
18061     // Check overrides, which we previously had to delay.
18062     for (const CXXMethodDecl *O : Method->overridden_methods())
18063       CheckOverridingFunctionExceptionSpec(Method, O);
18064   }
18065 }
18066 
18067 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18068 ///
18069 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18070                                        SourceLocation DeclStart, Declarator &D,
18071                                        Expr *BitWidth,
18072                                        InClassInitStyle InitStyle,
18073                                        AccessSpecifier AS,
18074                                        const ParsedAttr &MSPropertyAttr) {
18075   IdentifierInfo *II = D.getIdentifier();
18076   if (!II) {
18077     Diag(DeclStart, diag::err_anonymous_property);
18078     return nullptr;
18079   }
18080   SourceLocation Loc = D.getIdentifierLoc();
18081 
18082   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18083   QualType T = TInfo->getType();
18084   if (getLangOpts().CPlusPlus) {
18085     CheckExtraCXXDefaultArguments(D);
18086 
18087     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18088                                         UPPC_DataMemberType)) {
18089       D.setInvalidType();
18090       T = Context.IntTy;
18091       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18092     }
18093   }
18094 
18095   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18096 
18097   if (D.getDeclSpec().isInlineSpecified())
18098     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18099         << getLangOpts().CPlusPlus17;
18100   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18101     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18102          diag::err_invalid_thread)
18103       << DeclSpec::getSpecifierName(TSCS);
18104 
18105   // Check to see if this name was declared as a member previously
18106   NamedDecl *PrevDecl = nullptr;
18107   LookupResult Previous(*this, II, Loc, LookupMemberName,
18108                         ForVisibleRedeclaration);
18109   LookupName(Previous, S);
18110   switch (Previous.getResultKind()) {
18111   case LookupResult::Found:
18112   case LookupResult::FoundUnresolvedValue:
18113     PrevDecl = Previous.getAsSingle<NamedDecl>();
18114     break;
18115 
18116   case LookupResult::FoundOverloaded:
18117     PrevDecl = Previous.getRepresentativeDecl();
18118     break;
18119 
18120   case LookupResult::NotFound:
18121   case LookupResult::NotFoundInCurrentInstantiation:
18122   case LookupResult::Ambiguous:
18123     break;
18124   }
18125 
18126   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18127     // Maybe we will complain about the shadowed template parameter.
18128     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18129     // Just pretend that we didn't see the previous declaration.
18130     PrevDecl = nullptr;
18131   }
18132 
18133   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18134     PrevDecl = nullptr;
18135 
18136   SourceLocation TSSL = D.getBeginLoc();
18137   MSPropertyDecl *NewPD =
18138       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18139                              MSPropertyAttr.getPropertyDataGetter(),
18140                              MSPropertyAttr.getPropertyDataSetter());
18141   ProcessDeclAttributes(TUScope, NewPD, D);
18142   NewPD->setAccess(AS);
18143 
18144   if (NewPD->isInvalidDecl())
18145     Record->setInvalidDecl();
18146 
18147   if (D.getDeclSpec().isModulePrivateSpecified())
18148     NewPD->setModulePrivate();
18149 
18150   if (NewPD->isInvalidDecl() && PrevDecl) {
18151     // Don't introduce NewFD into scope; there's already something
18152     // with the same name in the same scope.
18153   } else if (II) {
18154     PushOnScopeChains(NewPD, S);
18155   } else
18156     Record->addDecl(NewPD);
18157 
18158   return NewPD;
18159 }
18160 
18161 void Sema::ActOnStartFunctionDeclarationDeclarator(
18162     Declarator &Declarator, unsigned TemplateParameterDepth) {
18163   auto &Info = InventedParameterInfos.emplace_back();
18164   TemplateParameterList *ExplicitParams = nullptr;
18165   ArrayRef<TemplateParameterList *> ExplicitLists =
18166       Declarator.getTemplateParameterLists();
18167   if (!ExplicitLists.empty()) {
18168     bool IsMemberSpecialization, IsInvalid;
18169     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18170         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18171         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18172         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18173         /*SuppressDiagnostic=*/true);
18174   }
18175   if (ExplicitParams) {
18176     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18177     for (NamedDecl *Param : *ExplicitParams)
18178       Info.TemplateParams.push_back(Param);
18179     Info.NumExplicitTemplateParams = ExplicitParams->size();
18180   } else {
18181     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18182     Info.NumExplicitTemplateParams = 0;
18183   }
18184 }
18185 
18186 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18187   auto &FSI = InventedParameterInfos.back();
18188   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18189     if (FSI.NumExplicitTemplateParams != 0) {
18190       TemplateParameterList *ExplicitParams =
18191           Declarator.getTemplateParameterLists().back();
18192       Declarator.setInventedTemplateParameterList(
18193           TemplateParameterList::Create(
18194               Context, ExplicitParams->getTemplateLoc(),
18195               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18196               ExplicitParams->getRAngleLoc(),
18197               ExplicitParams->getRequiresClause()));
18198     } else {
18199       Declarator.setInventedTemplateParameterList(
18200           TemplateParameterList::Create(
18201               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18202               SourceLocation(), /*RequiresClause=*/nullptr));
18203     }
18204   }
18205   InventedParameterInfos.pop_back();
18206 }
18207