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/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <map>
46 #include <set>
47 
48 using namespace clang;
49 
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62   Sema &S;
63   const Expr *DefaultArg;
64 
65 public:
66   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67       : S(S), DefaultArg(DefaultArg) {}
68 
69   bool VisitExpr(const Expr *Node);
70   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72   bool VisitLambdaExpr(const LambdaExpr *Lambda);
73   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74 };
75 
76 /// VisitExpr - Visit all of the children of this expression.
77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78   bool IsInvalid = false;
79   for (const Stmt *SubStmt : Node->children())
80     IsInvalid |= Visit(SubStmt);
81   return IsInvalid;
82 }
83 
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88   const NamedDecl *Decl = DRE->getDecl();
89   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90     // C++ [dcl.fct.default]p9:
91     //   [...] parameters of a function shall not be used in default
92     //   argument expressions, even if they are not evaluated. [...]
93     //
94     // C++17 [dcl.fct.default]p9 (by CWG 2082):
95     //   [...] A parameter shall not appear as a potentially-evaluated
96     //   expression in a default argument. [...]
97     //
98     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99       return S.Diag(DRE->getBeginLoc(),
100                     diag::err_param_default_argument_references_param)
101              << Param->getDeclName() << DefaultArg->getSourceRange();
102   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103     // C++ [dcl.fct.default]p7:
104     //   Local variables shall not be used in default argument
105     //   expressions.
106     //
107     // C++17 [dcl.fct.default]p7 (by CWG 2082):
108     //   A local variable shall not appear as a potentially-evaluated
109     //   expression in a default argument.
110     //
111     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113     //
114     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_local)
117              << VDecl->getDeclName() << DefaultArg->getSourceRange();
118   }
119 
120   return false;
121 }
122 
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125   // C++ [dcl.fct.default]p8:
126   //   The keyword this shall not be used in a default argument of a
127   //   member function.
128   return S.Diag(ThisE->getBeginLoc(),
129                 diag::err_param_default_argument_references_this)
130          << ThisE->getSourceRange();
131 }
132 
133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134     const PseudoObjectExpr *POE) {
135   bool Invalid = false;
136   for (const Expr *E : POE->semantics()) {
137     // Look through bindings.
138     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139       E = OVE->getSourceExpr();
140       assert(E && "pseudo-object binding without source expression?");
141     }
142 
143     Invalid |= Visit(E);
144   }
145   return Invalid;
146 }
147 
148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149   // C++11 [expr.lambda.prim]p13:
150   //   A lambda-expression appearing in a default argument shall not
151   //   implicitly or explicitly capture any entity.
152   if (Lambda->capture_begin() == Lambda->capture_end())
153     return false;
154 
155   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156 }
157 } // namespace
158 
159 void
160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                  const CXXMethodDecl *Method) {
162   // If we have an MSAny spec already, don't bother.
163   if (!Method || ComputedEST == EST_MSAny)
164     return;
165 
166   const FunctionProtoType *Proto
167     = Method->getType()->getAs<FunctionProtoType>();
168   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169   if (!Proto)
170     return;
171 
172   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173 
174   // If we have a throw-all spec at this point, ignore the function.
175   if (ComputedEST == EST_None)
176     return;
177 
178   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179     EST = EST_BasicNoexcept;
180 
181   switch (EST) {
182   case EST_Unparsed:
183   case EST_Uninstantiated:
184   case EST_Unevaluated:
185     llvm_unreachable("should not see unresolved exception specs here");
186 
187   // If this function can throw any exceptions, make a note of that.
188   case EST_MSAny:
189   case EST_None:
190     // FIXME: Whichever we see last of MSAny and None determines our result.
191     // We should make a consistent, order-independent choice here.
192     ClearExceptions();
193     ComputedEST = EST;
194     return;
195   case EST_NoexceptFalse:
196     ClearExceptions();
197     ComputedEST = EST_None;
198     return;
199   // FIXME: If the call to this decl is using any of its default arguments, we
200   // need to search them for potentially-throwing calls.
201   // If this function has a basic noexcept, it doesn't affect the outcome.
202   case EST_BasicNoexcept:
203   case EST_NoexceptTrue:
204   case EST_NoThrow:
205     return;
206   // If we're still at noexcept(true) and there's a throw() callee,
207   // change to that specification.
208   case EST_DynamicNone:
209     if (ComputedEST == EST_BasicNoexcept)
210       ComputedEST = EST_DynamicNone;
211     return;
212   case EST_DependentNoexcept:
213     llvm_unreachable(
214         "should not generate implicit declarations for dependent cases");
215   case EST_Dynamic:
216     break;
217   }
218   assert(EST == EST_Dynamic && "EST case not considered earlier.");
219   assert(ComputedEST != EST_None &&
220          "Shouldn't collect exceptions when throw-all is guaranteed.");
221   ComputedEST = EST_Dynamic;
222   // Record the exceptions in this function's exception specification.
223   for (const auto &E : Proto->exceptions())
224     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225       Exceptions.push_back(E);
226 }
227 
228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229   if (!S || ComputedEST == EST_MSAny)
230     return;
231 
232   // FIXME:
233   //
234   // C++0x [except.spec]p14:
235   //   [An] implicit exception-specification specifies the type-id T if and
236   // only if T is allowed by the exception-specification of a function directly
237   // invoked by f's implicit definition; f shall allow all exceptions if any
238   // function it directly invokes allows all exceptions, and f shall allow no
239   // exceptions if every function it directly invokes allows no exceptions.
240   //
241   // Note in particular that if an implicit exception-specification is generated
242   // for a function containing a throw-expression, that specification can still
243   // be noexcept(true).
244   //
245   // Note also that 'directly invoked' is not defined in the standard, and there
246   // is no indication that we should only consider potentially-evaluated calls.
247   //
248   // Ultimately we should implement the intent of the standard: the exception
249   // specification should be the set of exceptions which can be thrown by the
250   // implicit definition. For now, we assume that any non-nothrow expression can
251   // throw any exception.
252 
253   if (Self->canThrow(S))
254     ComputedEST = EST_None;
255 }
256 
257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258                                              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_RValue));
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)
385                        OpaqueValueExpr(EqualLoc,
386                                        Param->getType().getNonReferenceType(),
387                                        VK_RValue));
388 }
389 
390 /// CheckExtraCXXDefaultArguments - Check for any extra default
391 /// arguments in the declarator, which is not a function declaration
392 /// or definition and therefore is not permitted to have default
393 /// arguments. This routine should be invoked for every declarator
394 /// that is not a function declaration or definition.
395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396   // C++ [dcl.fct.default]p3
397   //   A default argument expression shall be specified only in the
398   //   parameter-declaration-clause of a function declaration or in a
399   //   template-parameter (14.1). It shall not be specified for a
400   //   parameter pack. If it is specified in a
401   //   parameter-declaration-clause, it shall not occur within a
402   //   declarator or abstract-declarator of a parameter-declaration.
403   bool MightBeFunction = D.isFunctionDeclarationContext();
404   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405     DeclaratorChunk &chunk = D.getTypeObject(i);
406     if (chunk.Kind == DeclaratorChunk::Function) {
407       if (MightBeFunction) {
408         // This is a function declaration. It can have default arguments, but
409         // keep looking in case its return type is a function type with default
410         // arguments.
411         MightBeFunction = false;
412         continue;
413       }
414       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415            ++argIdx) {
416         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417         if (Param->hasUnparsedDefaultArg()) {
418           std::unique_ptr<CachedTokens> Toks =
419               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420           SourceRange SR;
421           if (Toks->size() > 1)
422             SR = SourceRange((*Toks)[1].getLocation(),
423                              Toks->back().getLocation());
424           else
425             SR = UnparsedDefaultArgLocs[Param];
426           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427             << SR;
428         } else if (Param->getDefaultArg()) {
429           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430             << Param->getDefaultArg()->getSourceRange();
431           Param->setDefaultArg(nullptr);
432         }
433       }
434     } else if (chunk.Kind != DeclaratorChunk::Paren) {
435       MightBeFunction = false;
436     }
437   }
438 }
439 
440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441   return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443   });
444 }
445 
446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
447 /// function, once we already know that they have the same
448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449 /// error, false otherwise.
450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451                                 Scope *S) {
452   bool Invalid = false;
453 
454   // The declaration context corresponding to the scope is the semantic
455   // parent, unless this is a local function declaration, in which case
456   // it is that surrounding function.
457   DeclContext *ScopeDC = New->isLocalExternDecl()
458                              ? New->getLexicalDeclContext()
459                              : New->getDeclContext();
460 
461   // Find the previous declaration for the purpose of default arguments.
462   FunctionDecl *PrevForDefaultArgs = Old;
463   for (/**/; PrevForDefaultArgs;
464        // Don't bother looking back past the latest decl if this is a local
465        // extern declaration; nothing else could work.
466        PrevForDefaultArgs = New->isLocalExternDecl()
467                                 ? nullptr
468                                 : PrevForDefaultArgs->getPreviousDecl()) {
469     // Ignore hidden declarations.
470     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471       continue;
472 
473     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474         !New->isCXXClassMember()) {
475       // Ignore default arguments of old decl if they are not in
476       // the same scope and this is not an out-of-line definition of
477       // a member function.
478       continue;
479     }
480 
481     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482       // If only one of these is a local function declaration, then they are
483       // declared in different scopes, even though isDeclInScope may think
484       // they're in the same scope. (If both are local, the scope check is
485       // sufficient, and if neither is local, then they are in the same scope.)
486       continue;
487     }
488 
489     // We found the right previous declaration.
490     break;
491   }
492 
493   // C++ [dcl.fct.default]p4:
494   //   For non-template functions, default arguments can be added in
495   //   later declarations of a function in the same
496   //   scope. Declarations in different scopes have completely
497   //   distinct sets of default arguments. That is, declarations in
498   //   inner scopes do not acquire default arguments from
499   //   declarations in outer scopes, and vice versa. In a given
500   //   function declaration, all parameters subsequent to a
501   //   parameter with a default argument shall have default
502   //   arguments supplied in this or previous declarations. A
503   //   default argument shall not be redefined by a later
504   //   declaration (not even to the same value).
505   //
506   // C++ [dcl.fct.default]p6:
507   //   Except for member functions of class templates, the default arguments
508   //   in a member function definition that appears outside of the class
509   //   definition are added to the set of default arguments provided by the
510   //   member function declaration in the class definition.
511   for (unsigned p = 0, NumParams = PrevForDefaultArgs
512                                        ? PrevForDefaultArgs->getNumParams()
513                                        : 0;
514        p < NumParams; ++p) {
515     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516     ParmVarDecl *NewParam = New->getParamDecl(p);
517 
518     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519     bool NewParamHasDfl = NewParam->hasDefaultArg();
520 
521     if (OldParamHasDfl && NewParamHasDfl) {
522       unsigned DiagDefaultParamID =
523         diag::err_param_default_argument_redefinition;
524 
525       // MSVC accepts that default parameters be redefined for member functions
526       // of template class. The new default parameter's value is ignored.
527       Invalid = true;
528       if (getLangOpts().MicrosoftExt) {
529         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530         if (MD && MD->getParent()->getDescribedClassTemplate()) {
531           // Merge the old default argument into the new parameter.
532           NewParam->setHasInheritedDefaultArg();
533           if (OldParam->hasUninstantiatedDefaultArg())
534             NewParam->setUninstantiatedDefaultArg(
535                                       OldParam->getUninstantiatedDefaultArg());
536           else
537             NewParam->setDefaultArg(OldParam->getInit());
538           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539           Invalid = false;
540         }
541       }
542 
543       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544       // hint here. Alternatively, we could walk the type-source information
545       // for NewParam to find the last source location in the type... but it
546       // isn't worth the effort right now. This is the kind of test case that
547       // is hard to get right:
548       //   int f(int);
549       //   void g(int (*fp)(int) = f);
550       //   void g(int (*fp)(int) = &f);
551       Diag(NewParam->getLocation(), DiagDefaultParamID)
552         << NewParam->getDefaultArgRange();
553 
554       // Look for the function declaration where the default argument was
555       // actually written, which may be a declaration prior to Old.
556       for (auto Older = PrevForDefaultArgs;
557            OldParam->hasInheritedDefaultArg(); /**/) {
558         Older = Older->getPreviousDecl();
559         OldParam = Older->getParamDecl(p);
560       }
561 
562       Diag(OldParam->getLocation(), diag::note_previous_definition)
563         << OldParam->getDefaultArgRange();
564     } else if (OldParamHasDfl) {
565       // Merge the old default argument into the new parameter unless the new
566       // function is a friend declaration in a template class. In the latter
567       // case the default arguments will be inherited when the friend
568       // declaration will be instantiated.
569       if (New->getFriendObjectKind() == Decl::FOK_None ||
570           !New->getLexicalDeclContext()->isDependentContext()) {
571         // It's important to use getInit() here;  getDefaultArg()
572         // strips off any top-level ExprWithCleanups.
573         NewParam->setHasInheritedDefaultArg();
574         if (OldParam->hasUnparsedDefaultArg())
575           NewParam->setUnparsedDefaultArg();
576         else if (OldParam->hasUninstantiatedDefaultArg())
577           NewParam->setUninstantiatedDefaultArg(
578                                        OldParam->getUninstantiatedDefaultArg());
579         else
580           NewParam->setDefaultArg(OldParam->getInit());
581       }
582     } else if (NewParamHasDfl) {
583       if (New->getDescribedFunctionTemplate()) {
584         // Paragraph 4, quoted above, only applies to non-template functions.
585         Diag(NewParam->getLocation(),
586              diag::err_param_default_argument_template_redecl)
587           << NewParam->getDefaultArgRange();
588         Diag(PrevForDefaultArgs->getLocation(),
589              diag::note_template_prev_declaration)
590             << false;
591       } else if (New->getTemplateSpecializationKind()
592                    != TSK_ImplicitInstantiation &&
593                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
594         // C++ [temp.expr.spec]p21:
595         //   Default function arguments shall not be specified in a declaration
596         //   or a definition for one of the following explicit specializations:
597         //     - the explicit specialization of a function template;
598         //     - the explicit specialization of a member function template;
599         //     - the explicit specialization of a member function of a class
600         //       template where the class template specialization to which the
601         //       member function specialization belongs is implicitly
602         //       instantiated.
603         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605           << New->getDeclName()
606           << NewParam->getDefaultArgRange();
607       } else if (New->getDeclContext()->isDependentContext()) {
608         // C++ [dcl.fct.default]p6 (DR217):
609         //   Default arguments for a member function of a class template shall
610         //   be specified on the initial declaration of the member function
611         //   within the class template.
612         //
613         // Reading the tea leaves a bit in DR217 and its reference to DR205
614         // leads me to the conclusion that one cannot add default function
615         // arguments for an out-of-line definition of a member function of a
616         // dependent type.
617         int WhichKind = 2;
618         if (CXXRecordDecl *Record
619               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620           if (Record->getDescribedClassTemplate())
621             WhichKind = 0;
622           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623             WhichKind = 1;
624           else
625             WhichKind = 2;
626         }
627 
628         Diag(NewParam->getLocation(),
629              diag::err_param_default_argument_member_template_redecl)
630           << WhichKind
631           << NewParam->getDefaultArgRange();
632       }
633     }
634   }
635 
636   // DR1344: If a default argument is added outside a class definition and that
637   // default argument makes the function a special member function, the program
638   // is ill-formed. This can only happen for constructors.
639   if (isa<CXXConstructorDecl>(New) &&
640       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643     if (NewSM != OldSM) {
644       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645       assert(NewParam->hasDefaultArg());
646       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647         << NewParam->getDefaultArgRange() << NewSM;
648       Diag(Old->getLocation(), diag::note_previous_declaration);
649     }
650   }
651 
652   const FunctionDecl *Def;
653   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654   // template has a constexpr specifier then all its declarations shall
655   // contain the constexpr specifier.
656   if (New->getConstexprKind() != Old->getConstexprKind()) {
657     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658         << New << New->getConstexprKind() << Old->getConstexprKind();
659     Diag(Old->getLocation(), diag::note_previous_declaration);
660     Invalid = true;
661   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662              Old->isDefined(Def) &&
663              // If a friend function is inlined but does not have 'inline'
664              // specifier, it is a definition. Do not report attribute conflict
665              // in this case, redefinition will be diagnosed later.
666              (New->isInlineSpecified() ||
667               New->getFriendObjectKind() == Decl::FOK_None)) {
668     // C++11 [dcl.fcn.spec]p4:
669     //   If the definition of a function appears in a translation unit before its
670     //   first declaration as inline, the program is ill-formed.
671     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672     Diag(Def->getLocation(), diag::note_previous_definition);
673     Invalid = true;
674   }
675 
676   // C++17 [temp.deduct.guide]p3:
677   //   Two deduction guide declarations in the same translation unit
678   //   for the same class template shall not have equivalent
679   //   parameter-declaration-clauses.
680   if (isa<CXXDeductionGuideDecl>(New) &&
681       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683     Diag(Old->getLocation(), diag::note_previous_declaration);
684   }
685 
686   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687   // argument expression, that declaration shall be a definition and shall be
688   // the only declaration of the function or function template in the
689   // translation unit.
690   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691       functionDeclHasDefaultArgument(Old)) {
692     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693     Diag(Old->getLocation(), diag::note_previous_declaration);
694     Invalid = true;
695   }
696 
697   return Invalid;
698 }
699 
700 NamedDecl *
701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
702                                    MultiTemplateParamsArg TemplateParamLists) {
703   assert(D.isDecompositionDeclarator());
704   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
705 
706   // The syntax only allows a decomposition declarator as a simple-declaration,
707   // a for-range-declaration, or a condition in Clang, but we parse it in more
708   // cases than that.
709   if (!D.mayHaveDecompositionDeclarator()) {
710     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
711       << Decomp.getSourceRange();
712     return nullptr;
713   }
714 
715   if (!TemplateParamLists.empty()) {
716     // FIXME: There's no rule against this, but there are also no rules that
717     // would actually make it usable, so we reject it for now.
718     Diag(TemplateParamLists.front()->getTemplateLoc(),
719          diag::err_decomp_decl_template);
720     return nullptr;
721   }
722 
723   Diag(Decomp.getLSquareLoc(),
724        !getLangOpts().CPlusPlus17
725            ? diag::ext_decomp_decl
726            : D.getContext() == DeclaratorContext::ConditionContext
727                  ? diag::ext_decomp_decl_cond
728                  : diag::warn_cxx14_compat_decomp_decl)
729       << Decomp.getSourceRange();
730 
731   // The semantic context is always just the current context.
732   DeclContext *const DC = CurContext;
733 
734   // C++17 [dcl.dcl]/8:
735   //   The decl-specifier-seq shall contain only the type-specifier auto
736   //   and cv-qualifiers.
737   // C++2a [dcl.dcl]/8:
738   //   If decl-specifier-seq contains any decl-specifier other than static,
739   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
740   auto &DS = D.getDeclSpec();
741   {
742     SmallVector<StringRef, 8> BadSpecifiers;
743     SmallVector<SourceLocation, 8> BadSpecifierLocs;
744     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
745     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
746     if (auto SCS = DS.getStorageClassSpec()) {
747       if (SCS == DeclSpec::SCS_static) {
748         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
749         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
750       } else {
751         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
752         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
753       }
754     }
755     if (auto TSCS = DS.getThreadStorageClassSpec()) {
756       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
757       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
758     }
759     if (DS.hasConstexprSpecifier()) {
760       BadSpecifiers.push_back(
761           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
762       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
763     }
764     if (DS.isInlineSpecified()) {
765       BadSpecifiers.push_back("inline");
766       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
767     }
768     if (!BadSpecifiers.empty()) {
769       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
770       Err << (int)BadSpecifiers.size()
771           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
772       // Don't add FixItHints to remove the specifiers; we do still respect
773       // them when building the underlying variable.
774       for (auto Loc : BadSpecifierLocs)
775         Err << SourceRange(Loc, Loc);
776     } else if (!CPlusPlus20Specifiers.empty()) {
777       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
778                          getLangOpts().CPlusPlus20
779                              ? diag::warn_cxx17_compat_decomp_decl_spec
780                              : diag::ext_decomp_decl_spec);
781       Warn << (int)CPlusPlus20Specifiers.size()
782            << llvm::join(CPlusPlus20Specifiers.begin(),
783                          CPlusPlus20Specifiers.end(), " ");
784       for (auto Loc : CPlusPlus20SpecifierLocs)
785         Warn << SourceRange(Loc, Loc);
786     }
787     // We can't recover from it being declared as a typedef.
788     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
789       return nullptr;
790   }
791 
792   // C++2a [dcl.struct.bind]p1:
793   //   A cv that includes volatile is deprecated
794   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
795       getLangOpts().CPlusPlus20)
796     Diag(DS.getVolatileSpecLoc(),
797          diag::warn_deprecated_volatile_structured_binding);
798 
799   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
800   QualType R = TInfo->getType();
801 
802   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
803                                       UPPC_DeclarationType))
804     D.setInvalidType();
805 
806   // The syntax only allows a single ref-qualifier prior to the decomposition
807   // declarator. No other declarator chunks are permitted. Also check the type
808   // specifier here.
809   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
810       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
811       (D.getNumTypeObjects() == 1 &&
812        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
813     Diag(Decomp.getLSquareLoc(),
814          (D.hasGroupingParens() ||
815           (D.getNumTypeObjects() &&
816            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
817              ? diag::err_decomp_decl_parens
818              : diag::err_decomp_decl_type)
819         << R;
820 
821     // In most cases, there's no actual problem with an explicitly-specified
822     // type, but a function type won't work here, and ActOnVariableDeclarator
823     // shouldn't be called for such a type.
824     if (R->isFunctionType())
825       D.setInvalidType();
826   }
827 
828   // Build the BindingDecls.
829   SmallVector<BindingDecl*, 8> Bindings;
830 
831   // Build the BindingDecls.
832   for (auto &B : D.getDecompositionDeclarator().bindings()) {
833     // Check for name conflicts.
834     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
835     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
836                           ForVisibleRedeclaration);
837     LookupName(Previous, S,
838                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
839 
840     // It's not permitted to shadow a template parameter name.
841     if (Previous.isSingleResult() &&
842         Previous.getFoundDecl()->isTemplateParameter()) {
843       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
844                                       Previous.getFoundDecl());
845       Previous.clear();
846     }
847 
848     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
849                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
850     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
851                          /*AllowInlineNamespace*/false);
852     if (!Previous.empty()) {
853       auto *Old = Previous.getRepresentativeDecl();
854       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
855       Diag(Old->getLocation(), diag::note_previous_definition);
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859     PushOnScopeChains(BD, S, true);
860     Bindings.push_back(BD);
861     ParsingInitForAutoVars.insert(BD);
862   }
863 
864   // There are no prior lookup results for the variable itself, because it
865   // is unnamed.
866   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
867                                Decomp.getLSquareLoc());
868   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
869                         ForVisibleRedeclaration);
870 
871   // Build the variable that holds the non-decomposed object.
872   bool AddToScope = true;
873   NamedDecl *New =
874       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
875                               MultiTemplateParamsArg(), AddToScope, Bindings);
876   if (AddToScope) {
877     S->AddDecl(New);
878     CurContext->addHiddenDecl(New);
879   }
880 
881   if (isInOpenMPDeclareTargetContext())
882     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
883 
884   return New;
885 }
886 
887 static bool checkSimpleDecomposition(
888     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
889     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
890     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
891   if ((int64_t)Bindings.size() != NumElems) {
892     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
893         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
894         << (NumElems < Bindings.size());
895     return true;
896   }
897 
898   unsigned I = 0;
899   for (auto *B : Bindings) {
900     SourceLocation Loc = B->getLocation();
901     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
902     if (E.isInvalid())
903       return true;
904     E = GetInit(Loc, E.get(), I++);
905     if (E.isInvalid())
906       return true;
907     B->setBinding(ElemType, E.get());
908   }
909 
910   return false;
911 }
912 
913 static bool checkArrayLikeDecomposition(Sema &S,
914                                         ArrayRef<BindingDecl *> Bindings,
915                                         ValueDecl *Src, QualType DecompType,
916                                         const llvm::APSInt &NumElems,
917                                         QualType ElemType) {
918   return checkSimpleDecomposition(
919       S, Bindings, Src, DecompType, NumElems, ElemType,
920       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
921         ExprResult E = S.ActOnIntegerConstant(Loc, I);
922         if (E.isInvalid())
923           return ExprError();
924         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
925       });
926 }
927 
928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
929                                     ValueDecl *Src, QualType DecompType,
930                                     const ConstantArrayType *CAT) {
931   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
932                                      llvm::APSInt(CAT->getSize()),
933                                      CAT->getElementType());
934 }
935 
936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
937                                      ValueDecl *Src, QualType DecompType,
938                                      const VectorType *VT) {
939   return checkArrayLikeDecomposition(
940       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
941       S.Context.getQualifiedType(VT->getElementType(),
942                                  DecompType.getQualifiers()));
943 }
944 
945 static bool checkComplexDecomposition(Sema &S,
946                                       ArrayRef<BindingDecl *> Bindings,
947                                       ValueDecl *Src, QualType DecompType,
948                                       const ComplexType *CT) {
949   return checkSimpleDecomposition(
950       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
951       S.Context.getQualifiedType(CT->getElementType(),
952                                  DecompType.getQualifiers()),
953       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
954         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
955       });
956 }
957 
958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
959                                      TemplateArgumentListInfo &Args) {
960   SmallString<128> SS;
961   llvm::raw_svector_ostream OS(SS);
962   bool First = true;
963   for (auto &Arg : Args.arguments()) {
964     if (!First)
965       OS << ", ";
966     Arg.getArgument().print(PrintingPolicy, OS);
967     First = false;
968   }
969   return std::string(OS.str());
970 }
971 
972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
973                                      SourceLocation Loc, StringRef Trait,
974                                      TemplateArgumentListInfo &Args,
975                                      unsigned DiagID) {
976   auto DiagnoseMissing = [&] {
977     if (DiagID)
978       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
979                                                Args);
980     return true;
981   };
982 
983   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
984   NamespaceDecl *Std = S.getStdNamespace();
985   if (!Std)
986     return DiagnoseMissing();
987 
988   // Look up the trait itself, within namespace std. We can diagnose various
989   // problems with this lookup even if we've been asked to not diagnose a
990   // missing specialization, because this can only fail if the user has been
991   // declaring their own names in namespace std or we don't support the
992   // standard library implementation in use.
993   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
994                       Loc, Sema::LookupOrdinaryName);
995   if (!S.LookupQualifiedName(Result, Std))
996     return DiagnoseMissing();
997   if (Result.isAmbiguous())
998     return true;
999 
1000   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1001   if (!TraitTD) {
1002     Result.suppressDiagnostics();
1003     NamedDecl *Found = *Result.begin();
1004     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1005     S.Diag(Found->getLocation(), diag::note_declared_at);
1006     return true;
1007   }
1008 
1009   // Build the template-id.
1010   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1011   if (TraitTy.isNull())
1012     return true;
1013   if (!S.isCompleteType(Loc, TraitTy)) {
1014     if (DiagID)
1015       S.RequireCompleteType(
1016           Loc, TraitTy, DiagID,
1017           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1018     return true;
1019   }
1020 
1021   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1022   assert(RD && "specialization of class template is not a class?");
1023 
1024   // Look up the member of the trait type.
1025   S.LookupQualifiedName(TraitMemberLookup, RD);
1026   return TraitMemberLookup.isAmbiguous();
1027 }
1028 
1029 static TemplateArgumentLoc
1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1031                                    uint64_t I) {
1032   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1033   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1034 }
1035 
1036 static TemplateArgumentLoc
1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1038   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1039 }
1040 
1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1042 
1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1044                                llvm::APSInt &Size) {
1045   EnterExpressionEvaluationContext ContextRAII(
1046       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1047 
1048   DeclarationName Value = S.PP.getIdentifierInfo("value");
1049   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1050 
1051   // Form template argument list for tuple_size<T>.
1052   TemplateArgumentListInfo Args(Loc, Loc);
1053   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054 
1055   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1056   // it's not tuple-like.
1057   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1058       R.empty())
1059     return IsTupleLike::NotTupleLike;
1060 
1061   // If we get this far, we've committed to the tuple interpretation, but
1062   // we can still fail if there actually isn't a usable ::value.
1063 
1064   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1065     LookupResult &R;
1066     TemplateArgumentListInfo &Args;
1067     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1068         : R(R), Args(Args) {}
1069     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1070       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1071           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1072     }
1073   } Diagnoser(R, Args);
1074 
1075   ExprResult E =
1076       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1077   if (E.isInvalid())
1078     return IsTupleLike::Error;
1079 
1080   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1081   if (E.isInvalid())
1082     return IsTupleLike::Error;
1083 
1084   return IsTupleLike::TupleLike;
1085 }
1086 
1087 /// \return std::tuple_element<I, T>::type.
1088 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1089                                         unsigned I, QualType T) {
1090   // Form template argument list for tuple_element<I, T>.
1091   TemplateArgumentListInfo Args(Loc, Loc);
1092   Args.addArgument(
1093       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1094   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1095 
1096   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1097   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1098   if (lookupStdTypeTraitMember(
1099           S, R, Loc, "tuple_element", Args,
1100           diag::err_decomp_decl_std_tuple_element_not_specialized))
1101     return QualType();
1102 
1103   auto *TD = R.getAsSingle<TypeDecl>();
1104   if (!TD) {
1105     R.suppressDiagnostics();
1106     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1107       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1108     if (!R.empty())
1109       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1110     return QualType();
1111   }
1112 
1113   return S.Context.getTypeDeclType(TD);
1114 }
1115 
1116 namespace {
1117 struct InitializingBinding {
1118   Sema &S;
1119   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1120     Sema::CodeSynthesisContext Ctx;
1121     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1122     Ctx.PointOfInstantiation = BD->getLocation();
1123     Ctx.Entity = BD;
1124     S.pushCodeSynthesisContext(Ctx);
1125   }
1126   ~InitializingBinding() {
1127     S.popCodeSynthesisContext();
1128   }
1129 };
1130 }
1131 
1132 static bool checkTupleLikeDecomposition(Sema &S,
1133                                         ArrayRef<BindingDecl *> Bindings,
1134                                         VarDecl *Src, QualType DecompType,
1135                                         const llvm::APSInt &TupleSize) {
1136   if ((int64_t)Bindings.size() != TupleSize) {
1137     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1138         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1139         << (TupleSize < Bindings.size());
1140     return true;
1141   }
1142 
1143   if (Bindings.empty())
1144     return false;
1145 
1146   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1147 
1148   // [dcl.decomp]p3:
1149   //   The unqualified-id get is looked up in the scope of E by class member
1150   //   access lookup ...
1151   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1152   bool UseMemberGet = false;
1153   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1154     if (auto *RD = DecompType->getAsCXXRecordDecl())
1155       S.LookupQualifiedName(MemberGet, RD);
1156     if (MemberGet.isAmbiguous())
1157       return true;
1158     //   ... and if that finds at least one declaration that is a function
1159     //   template whose first template parameter is a non-type parameter ...
1160     for (NamedDecl *D : MemberGet) {
1161       if (FunctionTemplateDecl *FTD =
1162               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1163         TemplateParameterList *TPL = FTD->getTemplateParameters();
1164         if (TPL->size() != 0 &&
1165             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1166           //   ... the initializer is e.get<i>().
1167           UseMemberGet = true;
1168           break;
1169         }
1170       }
1171     }
1172   }
1173 
1174   unsigned I = 0;
1175   for (auto *B : Bindings) {
1176     InitializingBinding InitContext(S, B);
1177     SourceLocation Loc = B->getLocation();
1178 
1179     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1180     if (E.isInvalid())
1181       return true;
1182 
1183     //   e is an lvalue if the type of the entity is an lvalue reference and
1184     //   an xvalue otherwise
1185     if (!Src->getType()->isLValueReferenceType())
1186       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1187                                    E.get(), nullptr, VK_XValue);
1188 
1189     TemplateArgumentListInfo Args(Loc, Loc);
1190     Args.addArgument(
1191         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1192 
1193     if (UseMemberGet) {
1194       //   if [lookup of member get] finds at least one declaration, the
1195       //   initializer is e.get<i-1>().
1196       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1197                                      CXXScopeSpec(), SourceLocation(), nullptr,
1198                                      MemberGet, &Args, nullptr);
1199       if (E.isInvalid())
1200         return true;
1201 
1202       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1203     } else {
1204       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1205       //   in the associated namespaces.
1206       Expr *Get = UnresolvedLookupExpr::Create(
1207           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1208           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1209           UnresolvedSetIterator(), UnresolvedSetIterator());
1210 
1211       Expr *Arg = E.get();
1212       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1213     }
1214     if (E.isInvalid())
1215       return true;
1216     Expr *Init = E.get();
1217 
1218     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1219     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1220     if (T.isNull())
1221       return true;
1222 
1223     //   each vi is a variable of type "reference to T" initialized with the
1224     //   initializer, where the reference is an lvalue reference if the
1225     //   initializer is an lvalue and an rvalue reference otherwise
1226     QualType RefType =
1227         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1228     if (RefType.isNull())
1229       return true;
1230     auto *RefVD = VarDecl::Create(
1231         S.Context, Src->getDeclContext(), Loc, Loc,
1232         B->getDeclName().getAsIdentifierInfo(), RefType,
1233         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1234     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1235     RefVD->setTSCSpec(Src->getTSCSpec());
1236     RefVD->setImplicit();
1237     if (Src->isInlineSpecified())
1238       RefVD->setInlineSpecified();
1239     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1240 
1241     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1242     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1243     InitializationSequence Seq(S, Entity, Kind, Init);
1244     E = Seq.Perform(S, Entity, Kind, Init);
1245     if (E.isInvalid())
1246       return true;
1247     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1248     if (E.isInvalid())
1249       return true;
1250     RefVD->setInit(E.get());
1251     if (!E.get()->isValueDependent())
1252       RefVD->checkInitIsICE();
1253 
1254     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1255                                    DeclarationNameInfo(B->getDeclName(), Loc),
1256                                    RefVD);
1257     if (E.isInvalid())
1258       return true;
1259 
1260     B->setBinding(T, E.get());
1261     I++;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 /// Find the base class to decompose in a built-in decomposition of a class type.
1268 /// This base class search is, unfortunately, not quite like any other that we
1269 /// perform anywhere else in C++.
1270 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1271                                                 const CXXRecordDecl *RD,
1272                                                 CXXCastPath &BasePath) {
1273   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1274                           CXXBasePath &Path) {
1275     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1276   };
1277 
1278   const CXXRecordDecl *ClassWithFields = nullptr;
1279   AccessSpecifier AS = AS_public;
1280   if (RD->hasDirectFields())
1281     // [dcl.decomp]p4:
1282     //   Otherwise, all of E's non-static data members shall be public direct
1283     //   members of E ...
1284     ClassWithFields = RD;
1285   else {
1286     //   ... or of ...
1287     CXXBasePaths Paths;
1288     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1289     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1290       // If no classes have fields, just decompose RD itself. (This will work
1291       // if and only if zero bindings were provided.)
1292       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1293     }
1294 
1295     CXXBasePath *BestPath = nullptr;
1296     for (auto &P : Paths) {
1297       if (!BestPath)
1298         BestPath = &P;
1299       else if (!S.Context.hasSameType(P.back().Base->getType(),
1300                                       BestPath->back().Base->getType())) {
1301         //   ... the same ...
1302         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303           << false << RD << BestPath->back().Base->getType()
1304           << P.back().Base->getType();
1305         return DeclAccessPair();
1306       } else if (P.Access < BestPath->Access) {
1307         BestPath = &P;
1308       }
1309     }
1310 
1311     //   ... unambiguous ...
1312     QualType BaseType = BestPath->back().Base->getType();
1313     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1314       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1315         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1316       return DeclAccessPair();
1317     }
1318 
1319     //   ... [accessible, implied by other rules] base class of E.
1320     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1321                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1322     AS = BestPath->Access;
1323 
1324     ClassWithFields = BaseType->getAsCXXRecordDecl();
1325     S.BuildBasePathArray(Paths, BasePath);
1326   }
1327 
1328   // The above search did not check whether the selected class itself has base
1329   // classes with fields, so check that now.
1330   CXXBasePaths Paths;
1331   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1332     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333       << (ClassWithFields == RD) << RD << ClassWithFields
1334       << Paths.front().back().Base->getType();
1335     return DeclAccessPair();
1336   }
1337 
1338   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1339 }
1340 
1341 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1342                                      ValueDecl *Src, QualType DecompType,
1343                                      const CXXRecordDecl *OrigRD) {
1344   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1345                             diag::err_incomplete_type))
1346     return true;
1347 
1348   CXXCastPath BasePath;
1349   DeclAccessPair BasePair =
1350       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1351   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1352   if (!RD)
1353     return true;
1354   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1355                                                  DecompType.getQualifiers());
1356 
1357   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1358     unsigned NumFields =
1359         std::count_if(RD->field_begin(), RD->field_end(),
1360                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1361     assert(Bindings.size() != NumFields);
1362     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1363         << DecompType << (unsigned)Bindings.size() << NumFields
1364         << (NumFields < Bindings.size());
1365     return true;
1366   };
1367 
1368   //   all of E's non-static data members shall be [...] well-formed
1369   //   when named as e.name in the context of the structured binding,
1370   //   E shall not have an anonymous union member, ...
1371   unsigned I = 0;
1372   for (auto *FD : RD->fields()) {
1373     if (FD->isUnnamedBitfield())
1374       continue;
1375 
1376     if (FD->isAnonymousStructOrUnion()) {
1377       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1378         << DecompType << FD->getType()->isUnionType();
1379       S.Diag(FD->getLocation(), diag::note_declared_at);
1380       return true;
1381     }
1382 
1383     // We have a real field to bind.
1384     if (I >= Bindings.size())
1385       return DiagnoseBadNumberOfBindings();
1386     auto *B = Bindings[I++];
1387     SourceLocation Loc = B->getLocation();
1388 
1389     // The field must be accessible in the context of the structured binding.
1390     // We already checked that the base class is accessible.
1391     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1392     // const_cast here.
1393     S.CheckStructuredBindingMemberAccess(
1394         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1395         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1396                                      BasePair.getAccess(), FD->getAccess())));
1397 
1398     // Initialize the binding to Src.FD.
1399     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1400     if (E.isInvalid())
1401       return true;
1402     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1403                             VK_LValue, &BasePath);
1404     if (E.isInvalid())
1405       return true;
1406     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1407                                   CXXScopeSpec(), FD,
1408                                   DeclAccessPair::make(FD, FD->getAccess()),
1409                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1410     if (E.isInvalid())
1411       return true;
1412 
1413     // If the type of the member is T, the referenced type is cv T, where cv is
1414     // the cv-qualification of the decomposition expression.
1415     //
1416     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1417     // 'const' to the type of the field.
1418     Qualifiers Q = DecompType.getQualifiers();
1419     if (FD->isMutable())
1420       Q.removeConst();
1421     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1422   }
1423 
1424   if (I != Bindings.size())
1425     return DiagnoseBadNumberOfBindings();
1426 
1427   return false;
1428 }
1429 
1430 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1431   QualType DecompType = DD->getType();
1432 
1433   // If the type of the decomposition is dependent, then so is the type of
1434   // each binding.
1435   if (DecompType->isDependentType()) {
1436     for (auto *B : DD->bindings())
1437       B->setType(Context.DependentTy);
1438     return;
1439   }
1440 
1441   DecompType = DecompType.getNonReferenceType();
1442   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1443 
1444   // C++1z [dcl.decomp]/2:
1445   //   If E is an array type [...]
1446   // As an extension, we also support decomposition of built-in complex and
1447   // vector types.
1448   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1449     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1450       DD->setInvalidDecl();
1451     return;
1452   }
1453   if (auto *VT = DecompType->getAs<VectorType>()) {
1454     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1455       DD->setInvalidDecl();
1456     return;
1457   }
1458   if (auto *CT = DecompType->getAs<ComplexType>()) {
1459     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1460       DD->setInvalidDecl();
1461     return;
1462   }
1463 
1464   // C++1z [dcl.decomp]/3:
1465   //   if the expression std::tuple_size<E>::value is a well-formed integral
1466   //   constant expression, [...]
1467   llvm::APSInt TupleSize(32);
1468   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1469   case IsTupleLike::Error:
1470     DD->setInvalidDecl();
1471     return;
1472 
1473   case IsTupleLike::TupleLike:
1474     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1475       DD->setInvalidDecl();
1476     return;
1477 
1478   case IsTupleLike::NotTupleLike:
1479     break;
1480   }
1481 
1482   // C++1z [dcl.dcl]/8:
1483   //   [E shall be of array or non-union class type]
1484   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1485   if (!RD || RD->isUnion()) {
1486     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1487         << DD << !RD << DecompType;
1488     DD->setInvalidDecl();
1489     return;
1490   }
1491 
1492   // C++1z [dcl.decomp]/4:
1493   //   all of E's non-static data members shall be [...] direct members of
1494   //   E or of the same unambiguous public base class of E, ...
1495   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1496     DD->setInvalidDecl();
1497 }
1498 
1499 /// Merge the exception specifications of two variable declarations.
1500 ///
1501 /// This is called when there's a redeclaration of a VarDecl. The function
1502 /// checks if the redeclaration might have an exception specification and
1503 /// validates compatibility and merges the specs if necessary.
1504 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1505   // Shortcut if exceptions are disabled.
1506   if (!getLangOpts().CXXExceptions)
1507     return;
1508 
1509   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1510          "Should only be called if types are otherwise the same.");
1511 
1512   QualType NewType = New->getType();
1513   QualType OldType = Old->getType();
1514 
1515   // We're only interested in pointers and references to functions, as well
1516   // as pointers to member functions.
1517   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1518     NewType = R->getPointeeType();
1519     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1520   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1521     NewType = P->getPointeeType();
1522     OldType = OldType->castAs<PointerType>()->getPointeeType();
1523   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1524     NewType = M->getPointeeType();
1525     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1526   }
1527 
1528   if (!NewType->isFunctionProtoType())
1529     return;
1530 
1531   // There's lots of special cases for functions. For function pointers, system
1532   // libraries are hopefully not as broken so that we don't need these
1533   // workarounds.
1534   if (CheckEquivalentExceptionSpec(
1535         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1536         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1537     New->setInvalidDecl();
1538   }
1539 }
1540 
1541 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1542 /// function declaration are well-formed according to C++
1543 /// [dcl.fct.default].
1544 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1545   unsigned NumParams = FD->getNumParams();
1546   unsigned ParamIdx = 0;
1547 
1548   // This checking doesn't make sense for explicit specializations; their
1549   // default arguments are determined by the declaration we're specializing,
1550   // not by FD.
1551   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1552     return;
1553   if (auto *FTD = FD->getDescribedFunctionTemplate())
1554     if (FTD->isMemberSpecialization())
1555       return;
1556 
1557   // Find first parameter with a default argument
1558   for (; ParamIdx < NumParams; ++ParamIdx) {
1559     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1560     if (Param->hasDefaultArg())
1561       break;
1562   }
1563 
1564   // C++20 [dcl.fct.default]p4:
1565   //   In a given function declaration, each parameter subsequent to a parameter
1566   //   with a default argument shall have a default argument supplied in this or
1567   //   a previous declaration, unless the parameter was expanded from a
1568   //   parameter pack, or shall be a function parameter pack.
1569   for (; ParamIdx < NumParams; ++ParamIdx) {
1570     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1571     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1572         !(CurrentInstantiationScope &&
1573           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1574       if (Param->isInvalidDecl())
1575         /* We already complained about this parameter. */;
1576       else if (Param->getIdentifier())
1577         Diag(Param->getLocation(),
1578              diag::err_param_default_argument_missing_name)
1579           << Param->getIdentifier();
1580       else
1581         Diag(Param->getLocation(),
1582              diag::err_param_default_argument_missing);
1583     }
1584   }
1585 }
1586 
1587 /// Check that the given type is a literal type. Issue a diagnostic if not,
1588 /// if Kind is Diagnose.
1589 /// \return \c true if a problem has been found (and optionally diagnosed).
1590 template <typename... Ts>
1591 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1592                              SourceLocation Loc, QualType T, unsigned DiagID,
1593                              Ts &&...DiagArgs) {
1594   if (T->isDependentType())
1595     return false;
1596 
1597   switch (Kind) {
1598   case Sema::CheckConstexprKind::Diagnose:
1599     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1600                                       std::forward<Ts>(DiagArgs)...);
1601 
1602   case Sema::CheckConstexprKind::CheckValid:
1603     return !T->isLiteralType(SemaRef.Context);
1604   }
1605 
1606   llvm_unreachable("unknown CheckConstexprKind");
1607 }
1608 
1609 /// Determine whether a destructor cannot be constexpr due to
1610 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1611                                                const CXXDestructorDecl *DD,
1612                                                Sema::CheckConstexprKind Kind) {
1613   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1614     const CXXRecordDecl *RD =
1615         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1616     if (!RD || RD->hasConstexprDestructor())
1617       return true;
1618 
1619     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1620       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1621           << DD->getConstexprKind() << !FD
1622           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1623       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1624           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1625     }
1626     return false;
1627   };
1628 
1629   const CXXRecordDecl *RD = DD->getParent();
1630   for (const CXXBaseSpecifier &B : RD->bases())
1631     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1632       return false;
1633   for (const FieldDecl *FD : RD->fields())
1634     if (!Check(FD->getLocation(), FD->getType(), FD))
1635       return false;
1636   return true;
1637 }
1638 
1639 /// Check whether a function's parameter types are all literal types. If so,
1640 /// return true. If not, produce a suitable diagnostic and return false.
1641 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1642                                          const FunctionDecl *FD,
1643                                          Sema::CheckConstexprKind Kind) {
1644   unsigned ArgIndex = 0;
1645   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1646   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1647                                               e = FT->param_type_end();
1648        i != e; ++i, ++ArgIndex) {
1649     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1650     SourceLocation ParamLoc = PD->getLocation();
1651     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1652                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1653                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1654                          FD->isConsteval()))
1655       return false;
1656   }
1657   return true;
1658 }
1659 
1660 /// Check whether a function's return type is a literal type. If so, return
1661 /// true. If not, produce a suitable diagnostic and return false.
1662 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1663                                      Sema::CheckConstexprKind Kind) {
1664   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1665                        diag::err_constexpr_non_literal_return,
1666                        FD->isConsteval()))
1667     return false;
1668   return true;
1669 }
1670 
1671 /// Get diagnostic %select index for tag kind for
1672 /// record diagnostic message.
1673 /// WARNING: Indexes apply to particular diagnostics only!
1674 ///
1675 /// \returns diagnostic %select index.
1676 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1677   switch (Tag) {
1678   case TTK_Struct: return 0;
1679   case TTK_Interface: return 1;
1680   case TTK_Class:  return 2;
1681   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1682   }
1683 }
1684 
1685 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1686                                        Stmt *Body,
1687                                        Sema::CheckConstexprKind Kind);
1688 
1689 // Check whether a function declaration satisfies the requirements of a
1690 // constexpr function definition or a constexpr constructor definition. If so,
1691 // return true. If not, produce appropriate diagnostics (unless asked not to by
1692 // Kind) and return false.
1693 //
1694 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1695 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1696                                             CheckConstexprKind Kind) {
1697   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1698   if (MD && MD->isInstance()) {
1699     // C++11 [dcl.constexpr]p4:
1700     //  The definition of a constexpr constructor shall satisfy the following
1701     //  constraints:
1702     //  - the class shall not have any virtual base classes;
1703     //
1704     // FIXME: This only applies to constructors and destructors, not arbitrary
1705     // member functions.
1706     const CXXRecordDecl *RD = MD->getParent();
1707     if (RD->getNumVBases()) {
1708       if (Kind == CheckConstexprKind::CheckValid)
1709         return false;
1710 
1711       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1712         << isa<CXXConstructorDecl>(NewFD)
1713         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1714       for (const auto &I : RD->vbases())
1715         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1716             << I.getSourceRange();
1717       return false;
1718     }
1719   }
1720 
1721   if (!isa<CXXConstructorDecl>(NewFD)) {
1722     // C++11 [dcl.constexpr]p3:
1723     //  The definition of a constexpr function shall satisfy the following
1724     //  constraints:
1725     // - it shall not be virtual; (removed in C++20)
1726     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1727     if (Method && Method->isVirtual()) {
1728       if (getLangOpts().CPlusPlus20) {
1729         if (Kind == CheckConstexprKind::Diagnose)
1730           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1731       } else {
1732         if (Kind == CheckConstexprKind::CheckValid)
1733           return false;
1734 
1735         Method = Method->getCanonicalDecl();
1736         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1737 
1738         // If it's not obvious why this function is virtual, find an overridden
1739         // function which uses the 'virtual' keyword.
1740         const CXXMethodDecl *WrittenVirtual = Method;
1741         while (!WrittenVirtual->isVirtualAsWritten())
1742           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1743         if (WrittenVirtual != Method)
1744           Diag(WrittenVirtual->getLocation(),
1745                diag::note_overridden_virtual_function);
1746         return false;
1747       }
1748     }
1749 
1750     // - its return type shall be a literal type;
1751     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1752       return false;
1753   }
1754 
1755   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1756     // A destructor can be constexpr only if the defaulted destructor could be;
1757     // we don't need to check the members and bases if we already know they all
1758     // have constexpr destructors.
1759     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1760       if (Kind == CheckConstexprKind::CheckValid)
1761         return false;
1762       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1763         return false;
1764     }
1765   }
1766 
1767   // - each of its parameter types shall be a literal type;
1768   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1769     return false;
1770 
1771   Stmt *Body = NewFD->getBody();
1772   assert(Body &&
1773          "CheckConstexprFunctionDefinition called on function with no body");
1774   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1775 }
1776 
1777 /// Check the given declaration statement is legal within a constexpr function
1778 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1779 ///
1780 /// \return true if the body is OK (maybe only as an extension), false if we
1781 ///         have diagnosed a problem.
1782 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1783                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1784                                    Sema::CheckConstexprKind Kind) {
1785   // C++11 [dcl.constexpr]p3 and p4:
1786   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1787   //  contain only
1788   for (const auto *DclIt : DS->decls()) {
1789     switch (DclIt->getKind()) {
1790     case Decl::StaticAssert:
1791     case Decl::Using:
1792     case Decl::UsingShadow:
1793     case Decl::UsingDirective:
1794     case Decl::UnresolvedUsingTypename:
1795     case Decl::UnresolvedUsingValue:
1796       //   - static_assert-declarations
1797       //   - using-declarations,
1798       //   - using-directives,
1799       continue;
1800 
1801     case Decl::Typedef:
1802     case Decl::TypeAlias: {
1803       //   - typedef declarations and alias-declarations that do not define
1804       //     classes or enumerations,
1805       const auto *TN = cast<TypedefNameDecl>(DclIt);
1806       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1807         // Don't allow variably-modified types in constexpr functions.
1808         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1809           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1810           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1811             << TL.getSourceRange() << TL.getType()
1812             << isa<CXXConstructorDecl>(Dcl);
1813         }
1814         return false;
1815       }
1816       continue;
1817     }
1818 
1819     case Decl::Enum:
1820     case Decl::CXXRecord:
1821       // C++1y allows types to be defined, not just declared.
1822       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1823         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1824           SemaRef.Diag(DS->getBeginLoc(),
1825                        SemaRef.getLangOpts().CPlusPlus14
1826                            ? diag::warn_cxx11_compat_constexpr_type_definition
1827                            : diag::ext_constexpr_type_definition)
1828               << isa<CXXConstructorDecl>(Dcl);
1829         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1830           return false;
1831         }
1832       }
1833       continue;
1834 
1835     case Decl::EnumConstant:
1836     case Decl::IndirectField:
1837     case Decl::ParmVar:
1838       // These can only appear with other declarations which are banned in
1839       // C++11 and permitted in C++1y, so ignore them.
1840       continue;
1841 
1842     case Decl::Var:
1843     case Decl::Decomposition: {
1844       // C++1y [dcl.constexpr]p3 allows anything except:
1845       //   a definition of a variable of non-literal type or of static or
1846       //   thread storage duration or [before C++2a] for which no
1847       //   initialization is performed.
1848       const auto *VD = cast<VarDecl>(DclIt);
1849       if (VD->isThisDeclarationADefinition()) {
1850         if (VD->isStaticLocal()) {
1851           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852             SemaRef.Diag(VD->getLocation(),
1853                          diag::err_constexpr_local_var_static)
1854               << isa<CXXConstructorDecl>(Dcl)
1855               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1856           }
1857           return false;
1858         }
1859         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1860                              diag::err_constexpr_local_var_non_literal_type,
1861                              isa<CXXConstructorDecl>(Dcl)))
1862           return false;
1863         if (!VD->getType()->isDependentType() &&
1864             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1865           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866             SemaRef.Diag(
1867                 VD->getLocation(),
1868                 SemaRef.getLangOpts().CPlusPlus20
1869                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1870                     : diag::ext_constexpr_local_var_no_init)
1871                 << isa<CXXConstructorDecl>(Dcl);
1872           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1873             return false;
1874           }
1875           continue;
1876         }
1877       }
1878       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879         SemaRef.Diag(VD->getLocation(),
1880                      SemaRef.getLangOpts().CPlusPlus14
1881                       ? diag::warn_cxx11_compat_constexpr_local_var
1882                       : diag::ext_constexpr_local_var)
1883           << isa<CXXConstructorDecl>(Dcl);
1884       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1885         return false;
1886       }
1887       continue;
1888     }
1889 
1890     case Decl::NamespaceAlias:
1891     case Decl::Function:
1892       // These are disallowed in C++11 and permitted in C++1y. Allow them
1893       // everywhere as an extension.
1894       if (!Cxx1yLoc.isValid())
1895         Cxx1yLoc = DS->getBeginLoc();
1896       continue;
1897 
1898     default:
1899       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1901             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1902       }
1903       return false;
1904     }
1905   }
1906 
1907   return true;
1908 }
1909 
1910 /// Check that the given field is initialized within a constexpr constructor.
1911 ///
1912 /// \param Dcl The constexpr constructor being checked.
1913 /// \param Field The field being checked. This may be a member of an anonymous
1914 ///        struct or union nested within the class being checked.
1915 /// \param Inits All declarations, including anonymous struct/union members and
1916 ///        indirect members, for which any initialization was provided.
1917 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1918 ///        multiple notes for different members to the same error.
1919 /// \param Kind Whether we're diagnosing a constructor as written or determining
1920 ///        whether the formal requirements are satisfied.
1921 /// \return \c false if we're checking for validity and the constructor does
1922 ///         not satisfy the requirements on a constexpr constructor.
1923 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1924                                           const FunctionDecl *Dcl,
1925                                           FieldDecl *Field,
1926                                           llvm::SmallSet<Decl*, 16> &Inits,
1927                                           bool &Diagnosed,
1928                                           Sema::CheckConstexprKind Kind) {
1929   // In C++20 onwards, there's nothing to check for validity.
1930   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1931       SemaRef.getLangOpts().CPlusPlus20)
1932     return true;
1933 
1934   if (Field->isInvalidDecl())
1935     return true;
1936 
1937   if (Field->isUnnamedBitfield())
1938     return true;
1939 
1940   // Anonymous unions with no variant members and empty anonymous structs do not
1941   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1942   // indirect fields don't need initializing.
1943   if (Field->isAnonymousStructOrUnion() &&
1944       (Field->getType()->isUnionType()
1945            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1946            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1947     return true;
1948 
1949   if (!Inits.count(Field)) {
1950     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1951       if (!Diagnosed) {
1952         SemaRef.Diag(Dcl->getLocation(),
1953                      SemaRef.getLangOpts().CPlusPlus20
1954                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1955                          : diag::ext_constexpr_ctor_missing_init);
1956         Diagnosed = true;
1957       }
1958       SemaRef.Diag(Field->getLocation(),
1959                    diag::note_constexpr_ctor_missing_init);
1960     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1961       return false;
1962     }
1963   } else if (Field->isAnonymousStructOrUnion()) {
1964     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1965     for (auto *I : RD->fields())
1966       // If an anonymous union contains an anonymous struct of which any member
1967       // is initialized, all members must be initialized.
1968       if (!RD->isUnion() || Inits.count(I))
1969         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1970                                            Kind))
1971           return false;
1972   }
1973   return true;
1974 }
1975 
1976 /// Check the provided statement is allowed in a constexpr function
1977 /// definition.
1978 static bool
1979 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1980                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1981                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1982                            Sema::CheckConstexprKind Kind) {
1983   // - its function-body shall be [...] a compound-statement that contains only
1984   switch (S->getStmtClass()) {
1985   case Stmt::NullStmtClass:
1986     //   - null statements,
1987     return true;
1988 
1989   case Stmt::DeclStmtClass:
1990     //   - static_assert-declarations
1991     //   - using-declarations,
1992     //   - using-directives,
1993     //   - typedef declarations and alias-declarations that do not define
1994     //     classes or enumerations,
1995     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1996       return false;
1997     return true;
1998 
1999   case Stmt::ReturnStmtClass:
2000     //   - and exactly one return statement;
2001     if (isa<CXXConstructorDecl>(Dcl)) {
2002       // C++1y allows return statements in constexpr constructors.
2003       if (!Cxx1yLoc.isValid())
2004         Cxx1yLoc = S->getBeginLoc();
2005       return true;
2006     }
2007 
2008     ReturnStmts.push_back(S->getBeginLoc());
2009     return true;
2010 
2011   case Stmt::CompoundStmtClass: {
2012     // C++1y allows compound-statements.
2013     if (!Cxx1yLoc.isValid())
2014       Cxx1yLoc = S->getBeginLoc();
2015 
2016     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2017     for (auto *BodyIt : CompStmt->body()) {
2018       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2019                                       Cxx1yLoc, Cxx2aLoc, Kind))
2020         return false;
2021     }
2022     return true;
2023   }
2024 
2025   case Stmt::AttributedStmtClass:
2026     if (!Cxx1yLoc.isValid())
2027       Cxx1yLoc = S->getBeginLoc();
2028     return true;
2029 
2030   case Stmt::IfStmtClass: {
2031     // C++1y allows if-statements.
2032     if (!Cxx1yLoc.isValid())
2033       Cxx1yLoc = S->getBeginLoc();
2034 
2035     IfStmt *If = cast<IfStmt>(S);
2036     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2037                                     Cxx1yLoc, Cxx2aLoc, Kind))
2038       return false;
2039     if (If->getElse() &&
2040         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2041                                     Cxx1yLoc, Cxx2aLoc, Kind))
2042       return false;
2043     return true;
2044   }
2045 
2046   case Stmt::WhileStmtClass:
2047   case Stmt::DoStmtClass:
2048   case Stmt::ForStmtClass:
2049   case Stmt::CXXForRangeStmtClass:
2050   case Stmt::ContinueStmtClass:
2051     // C++1y allows all of these. We don't allow them as extensions in C++11,
2052     // because they don't make sense without variable mutation.
2053     if (!SemaRef.getLangOpts().CPlusPlus14)
2054       break;
2055     if (!Cxx1yLoc.isValid())
2056       Cxx1yLoc = S->getBeginLoc();
2057     for (Stmt *SubStmt : S->children())
2058       if (SubStmt &&
2059           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2060                                       Cxx1yLoc, Cxx2aLoc, Kind))
2061         return false;
2062     return true;
2063 
2064   case Stmt::SwitchStmtClass:
2065   case Stmt::CaseStmtClass:
2066   case Stmt::DefaultStmtClass:
2067   case Stmt::BreakStmtClass:
2068     // C++1y allows switch-statements, and since they don't need variable
2069     // mutation, we can reasonably allow them in C++11 as an extension.
2070     if (!Cxx1yLoc.isValid())
2071       Cxx1yLoc = S->getBeginLoc();
2072     for (Stmt *SubStmt : S->children())
2073       if (SubStmt &&
2074           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2075                                       Cxx1yLoc, Cxx2aLoc, Kind))
2076         return false;
2077     return true;
2078 
2079   case Stmt::GCCAsmStmtClass:
2080   case Stmt::MSAsmStmtClass:
2081     // C++2a allows inline assembly statements.
2082   case Stmt::CXXTryStmtClass:
2083     if (Cxx2aLoc.isInvalid())
2084       Cxx2aLoc = S->getBeginLoc();
2085     for (Stmt *SubStmt : S->children()) {
2086       if (SubStmt &&
2087           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2088                                       Cxx1yLoc, Cxx2aLoc, Kind))
2089         return false;
2090     }
2091     return true;
2092 
2093   case Stmt::CXXCatchStmtClass:
2094     // Do not bother checking the language mode (already covered by the
2095     // try block check).
2096     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2097                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2098                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2099       return false;
2100     return true;
2101 
2102   default:
2103     if (!isa<Expr>(S))
2104       break;
2105 
2106     // C++1y allows expression-statements.
2107     if (!Cxx1yLoc.isValid())
2108       Cxx1yLoc = S->getBeginLoc();
2109     return true;
2110   }
2111 
2112   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2113     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2114         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2115   }
2116   return false;
2117 }
2118 
2119 /// Check the body for the given constexpr function declaration only contains
2120 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2121 ///
2122 /// \return true if the body is OK, false if we have found or diagnosed a
2123 /// problem.
2124 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2125                                        Stmt *Body,
2126                                        Sema::CheckConstexprKind Kind) {
2127   SmallVector<SourceLocation, 4> ReturnStmts;
2128 
2129   if (isa<CXXTryStmt>(Body)) {
2130     // C++11 [dcl.constexpr]p3:
2131     //  The definition of a constexpr function shall satisfy the following
2132     //  constraints: [...]
2133     // - its function-body shall be = delete, = default, or a
2134     //   compound-statement
2135     //
2136     // C++11 [dcl.constexpr]p4:
2137     //  In the definition of a constexpr constructor, [...]
2138     // - its function-body shall not be a function-try-block;
2139     //
2140     // This restriction is lifted in C++2a, as long as inner statements also
2141     // apply the general constexpr rules.
2142     switch (Kind) {
2143     case Sema::CheckConstexprKind::CheckValid:
2144       if (!SemaRef.getLangOpts().CPlusPlus20)
2145         return false;
2146       break;
2147 
2148     case Sema::CheckConstexprKind::Diagnose:
2149       SemaRef.Diag(Body->getBeginLoc(),
2150            !SemaRef.getLangOpts().CPlusPlus20
2151                ? diag::ext_constexpr_function_try_block_cxx20
2152                : diag::warn_cxx17_compat_constexpr_function_try_block)
2153           << isa<CXXConstructorDecl>(Dcl);
2154       break;
2155     }
2156   }
2157 
2158   // - its function-body shall be [...] a compound-statement that contains only
2159   //   [... list of cases ...]
2160   //
2161   // Note that walking the children here is enough to properly check for
2162   // CompoundStmt and CXXTryStmt body.
2163   SourceLocation Cxx1yLoc, Cxx2aLoc;
2164   for (Stmt *SubStmt : Body->children()) {
2165     if (SubStmt &&
2166         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2167                                     Cxx1yLoc, Cxx2aLoc, Kind))
2168       return false;
2169   }
2170 
2171   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2172     // If this is only valid as an extension, report that we don't satisfy the
2173     // constraints of the current language.
2174     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2175         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2176       return false;
2177   } else if (Cxx2aLoc.isValid()) {
2178     SemaRef.Diag(Cxx2aLoc,
2179          SemaRef.getLangOpts().CPlusPlus20
2180            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2181            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2182       << isa<CXXConstructorDecl>(Dcl);
2183   } else if (Cxx1yLoc.isValid()) {
2184     SemaRef.Diag(Cxx1yLoc,
2185          SemaRef.getLangOpts().CPlusPlus14
2186            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2187            : diag::ext_constexpr_body_invalid_stmt)
2188       << isa<CXXConstructorDecl>(Dcl);
2189   }
2190 
2191   if (const CXXConstructorDecl *Constructor
2192         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2193     const CXXRecordDecl *RD = Constructor->getParent();
2194     // DR1359:
2195     // - every non-variant non-static data member and base class sub-object
2196     //   shall be initialized;
2197     // DR1460:
2198     // - if the class is a union having variant members, exactly one of them
2199     //   shall be initialized;
2200     if (RD->isUnion()) {
2201       if (Constructor->getNumCtorInitializers() == 0 &&
2202           RD->hasVariantMembers()) {
2203         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2204           SemaRef.Diag(
2205               Dcl->getLocation(),
2206               SemaRef.getLangOpts().CPlusPlus20
2207                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2208                   : diag::ext_constexpr_union_ctor_no_init);
2209         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2210           return false;
2211         }
2212       }
2213     } else if (!Constructor->isDependentContext() &&
2214                !Constructor->isDelegatingConstructor()) {
2215       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2216 
2217       // Skip detailed checking if we have enough initializers, and we would
2218       // allow at most one initializer per member.
2219       bool AnyAnonStructUnionMembers = false;
2220       unsigned Fields = 0;
2221       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2222            E = RD->field_end(); I != E; ++I, ++Fields) {
2223         if (I->isAnonymousStructOrUnion()) {
2224           AnyAnonStructUnionMembers = true;
2225           break;
2226         }
2227       }
2228       // DR1460:
2229       // - if the class is a union-like class, but is not a union, for each of
2230       //   its anonymous union members having variant members, exactly one of
2231       //   them shall be initialized;
2232       if (AnyAnonStructUnionMembers ||
2233           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2234         // Check initialization of non-static data members. Base classes are
2235         // always initialized so do not need to be checked. Dependent bases
2236         // might not have initializers in the member initializer list.
2237         llvm::SmallSet<Decl*, 16> Inits;
2238         for (const auto *I: Constructor->inits()) {
2239           if (FieldDecl *FD = I->getMember())
2240             Inits.insert(FD);
2241           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2242             Inits.insert(ID->chain_begin(), ID->chain_end());
2243         }
2244 
2245         bool Diagnosed = false;
2246         for (auto *I : RD->fields())
2247           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2248                                              Kind))
2249             return false;
2250       }
2251     }
2252   } else {
2253     if (ReturnStmts.empty()) {
2254       // C++1y doesn't require constexpr functions to contain a 'return'
2255       // statement. We still do, unless the return type might be void, because
2256       // otherwise if there's no return statement, the function cannot
2257       // be used in a core constant expression.
2258       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2259                 (Dcl->getReturnType()->isVoidType() ||
2260                  Dcl->getReturnType()->isDependentType());
2261       switch (Kind) {
2262       case Sema::CheckConstexprKind::Diagnose:
2263         SemaRef.Diag(Dcl->getLocation(),
2264                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2265                         : diag::err_constexpr_body_no_return)
2266             << Dcl->isConsteval();
2267         if (!OK)
2268           return false;
2269         break;
2270 
2271       case Sema::CheckConstexprKind::CheckValid:
2272         // The formal requirements don't include this rule in C++14, even
2273         // though the "must be able to produce a constant expression" rules
2274         // still imply it in some cases.
2275         if (!SemaRef.getLangOpts().CPlusPlus14)
2276           return false;
2277         break;
2278       }
2279     } else if (ReturnStmts.size() > 1) {
2280       switch (Kind) {
2281       case Sema::CheckConstexprKind::Diagnose:
2282         SemaRef.Diag(
2283             ReturnStmts.back(),
2284             SemaRef.getLangOpts().CPlusPlus14
2285                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2286                 : diag::ext_constexpr_body_multiple_return);
2287         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2288           SemaRef.Diag(ReturnStmts[I],
2289                        diag::note_constexpr_body_previous_return);
2290         break;
2291 
2292       case Sema::CheckConstexprKind::CheckValid:
2293         if (!SemaRef.getLangOpts().CPlusPlus14)
2294           return false;
2295         break;
2296       }
2297     }
2298   }
2299 
2300   // C++11 [dcl.constexpr]p5:
2301   //   if no function argument values exist such that the function invocation
2302   //   substitution would produce a constant expression, the program is
2303   //   ill-formed; no diagnostic required.
2304   // C++11 [dcl.constexpr]p3:
2305   //   - every constructor call and implicit conversion used in initializing the
2306   //     return value shall be one of those allowed in a constant expression.
2307   // C++11 [dcl.constexpr]p4:
2308   //   - every constructor involved in initializing non-static data members and
2309   //     base class sub-objects shall be a constexpr constructor.
2310   //
2311   // Note that this rule is distinct from the "requirements for a constexpr
2312   // function", so is not checked in CheckValid mode.
2313   SmallVector<PartialDiagnosticAt, 8> Diags;
2314   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2315       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2316     SemaRef.Diag(Dcl->getLocation(),
2317                  diag::ext_constexpr_function_never_constant_expr)
2318         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2319     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2320       SemaRef.Diag(Diags[I].first, Diags[I].second);
2321     // Don't return false here: we allow this for compatibility in
2322     // system headers.
2323   }
2324 
2325   return true;
2326 }
2327 
2328 /// Get the class that is directly named by the current context. This is the
2329 /// class for which an unqualified-id in this scope could name a constructor
2330 /// or destructor.
2331 ///
2332 /// If the scope specifier denotes a class, this will be that class.
2333 /// If the scope specifier is empty, this will be the class whose
2334 /// member-specification we are currently within. Otherwise, there
2335 /// is no such class.
2336 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2337   assert(getLangOpts().CPlusPlus && "No class names in C!");
2338 
2339   if (SS && SS->isInvalid())
2340     return nullptr;
2341 
2342   if (SS && SS->isNotEmpty()) {
2343     DeclContext *DC = computeDeclContext(*SS, true);
2344     return dyn_cast_or_null<CXXRecordDecl>(DC);
2345   }
2346 
2347   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2348 }
2349 
2350 /// isCurrentClassName - Determine whether the identifier II is the
2351 /// name of the class type currently being defined. In the case of
2352 /// nested classes, this will only return true if II is the name of
2353 /// the innermost class.
2354 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2355                               const CXXScopeSpec *SS) {
2356   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2357   return CurDecl && &II == CurDecl->getIdentifier();
2358 }
2359 
2360 /// Determine whether the identifier II is a typo for the name of
2361 /// the class type currently being defined. If so, update it to the identifier
2362 /// that should have been used.
2363 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2364   assert(getLangOpts().CPlusPlus && "No class names in C!");
2365 
2366   if (!getLangOpts().SpellChecking)
2367     return false;
2368 
2369   CXXRecordDecl *CurDecl;
2370   if (SS && SS->isSet() && !SS->isInvalid()) {
2371     DeclContext *DC = computeDeclContext(*SS, true);
2372     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2373   } else
2374     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2375 
2376   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2377       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2378           < II->getLength()) {
2379     II = CurDecl->getIdentifier();
2380     return true;
2381   }
2382 
2383   return false;
2384 }
2385 
2386 /// Determine whether the given class is a base class of the given
2387 /// class, including looking at dependent bases.
2388 static bool findCircularInheritance(const CXXRecordDecl *Class,
2389                                     const CXXRecordDecl *Current) {
2390   SmallVector<const CXXRecordDecl*, 8> Queue;
2391 
2392   Class = Class->getCanonicalDecl();
2393   while (true) {
2394     for (const auto &I : Current->bases()) {
2395       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2396       if (!Base)
2397         continue;
2398 
2399       Base = Base->getDefinition();
2400       if (!Base)
2401         continue;
2402 
2403       if (Base->getCanonicalDecl() == Class)
2404         return true;
2405 
2406       Queue.push_back(Base);
2407     }
2408 
2409     if (Queue.empty())
2410       return false;
2411 
2412     Current = Queue.pop_back_val();
2413   }
2414 
2415   return false;
2416 }
2417 
2418 /// Check the validity of a C++ base class specifier.
2419 ///
2420 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2421 /// and returns NULL otherwise.
2422 CXXBaseSpecifier *
2423 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2424                          SourceRange SpecifierRange,
2425                          bool Virtual, AccessSpecifier Access,
2426                          TypeSourceInfo *TInfo,
2427                          SourceLocation EllipsisLoc) {
2428   QualType BaseType = TInfo->getType();
2429   if (BaseType->containsErrors()) {
2430     // Already emitted a diagnostic when parsing the error type.
2431     return nullptr;
2432   }
2433   // C++ [class.union]p1:
2434   //   A union shall not have base classes.
2435   if (Class->isUnion()) {
2436     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2437       << SpecifierRange;
2438     return nullptr;
2439   }
2440 
2441   if (EllipsisLoc.isValid() &&
2442       !TInfo->getType()->containsUnexpandedParameterPack()) {
2443     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2444       << TInfo->getTypeLoc().getSourceRange();
2445     EllipsisLoc = SourceLocation();
2446   }
2447 
2448   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2449 
2450   if (BaseType->isDependentType()) {
2451     // Make sure that we don't have circular inheritance among our dependent
2452     // bases. For non-dependent bases, the check for completeness below handles
2453     // this.
2454     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2455       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2456           ((BaseDecl = BaseDecl->getDefinition()) &&
2457            findCircularInheritance(Class, BaseDecl))) {
2458         Diag(BaseLoc, diag::err_circular_inheritance)
2459           << BaseType << Context.getTypeDeclType(Class);
2460 
2461         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2462           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2463             << BaseType;
2464 
2465         return nullptr;
2466       }
2467     }
2468 
2469     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2470                                           Class->getTagKind() == TTK_Class,
2471                                           Access, TInfo, EllipsisLoc);
2472   }
2473 
2474   // Base specifiers must be record types.
2475   if (!BaseType->isRecordType()) {
2476     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2477     return nullptr;
2478   }
2479 
2480   // C++ [class.union]p1:
2481   //   A union shall not be used as a base class.
2482   if (BaseType->isUnionType()) {
2483     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2484     return nullptr;
2485   }
2486 
2487   // For the MS ABI, propagate DLL attributes to base class templates.
2488   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2489     if (Attr *ClassAttr = getDLLAttr(Class)) {
2490       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2491               BaseType->getAsCXXRecordDecl())) {
2492         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2493                                             BaseLoc);
2494       }
2495     }
2496   }
2497 
2498   // C++ [class.derived]p2:
2499   //   The class-name in a base-specifier shall not be an incompletely
2500   //   defined class.
2501   if (RequireCompleteType(BaseLoc, BaseType,
2502                           diag::err_incomplete_base_class, SpecifierRange)) {
2503     Class->setInvalidDecl();
2504     return nullptr;
2505   }
2506 
2507   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2508   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2509   assert(BaseDecl && "Record type has no declaration");
2510   BaseDecl = BaseDecl->getDefinition();
2511   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2512   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2513   assert(CXXBaseDecl && "Base type is not a C++ type");
2514 
2515   // Microsoft docs say:
2516   // "If a base-class has a code_seg attribute, derived classes must have the
2517   // same attribute."
2518   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2519   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2520   if ((DerivedCSA || BaseCSA) &&
2521       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2522     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2523     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2524       << CXXBaseDecl;
2525     return nullptr;
2526   }
2527 
2528   // A class which contains a flexible array member is not suitable for use as a
2529   // base class:
2530   //   - If the layout determines that a base comes before another base,
2531   //     the flexible array member would index into the subsequent base.
2532   //   - If the layout determines that base comes before the derived class,
2533   //     the flexible array member would index into the derived class.
2534   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2535     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2536       << CXXBaseDecl->getDeclName();
2537     return nullptr;
2538   }
2539 
2540   // C++ [class]p3:
2541   //   If a class is marked final and it appears as a base-type-specifier in
2542   //   base-clause, the program is ill-formed.
2543   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2544     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2545       << CXXBaseDecl->getDeclName()
2546       << FA->isSpelledAsSealed();
2547     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2548         << CXXBaseDecl->getDeclName() << FA->getRange();
2549     return nullptr;
2550   }
2551 
2552   if (BaseDecl->isInvalidDecl())
2553     Class->setInvalidDecl();
2554 
2555   // Create the base specifier.
2556   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2557                                         Class->getTagKind() == TTK_Class,
2558                                         Access, TInfo, EllipsisLoc);
2559 }
2560 
2561 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2562 /// one entry in the base class list of a class specifier, for
2563 /// example:
2564 ///    class foo : public bar, virtual private baz {
2565 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2566 BaseResult
2567 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2568                          ParsedAttributes &Attributes,
2569                          bool Virtual, AccessSpecifier Access,
2570                          ParsedType basetype, SourceLocation BaseLoc,
2571                          SourceLocation EllipsisLoc) {
2572   if (!classdecl)
2573     return true;
2574 
2575   AdjustDeclIfTemplate(classdecl);
2576   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2577   if (!Class)
2578     return true;
2579 
2580   // We haven't yet attached the base specifiers.
2581   Class->setIsParsingBaseSpecifiers();
2582 
2583   // We do not support any C++11 attributes on base-specifiers yet.
2584   // Diagnose any attributes we see.
2585   for (const ParsedAttr &AL : Attributes) {
2586     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2587       continue;
2588     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2589                           ? (unsigned)diag::warn_unknown_attribute_ignored
2590                           : (unsigned)diag::err_base_specifier_attribute)
2591         << AL;
2592   }
2593 
2594   TypeSourceInfo *TInfo = nullptr;
2595   GetTypeFromParser(basetype, &TInfo);
2596 
2597   if (EllipsisLoc.isInvalid() &&
2598       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2599                                       UPPC_BaseType))
2600     return true;
2601 
2602   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2603                                                       Virtual, Access, TInfo,
2604                                                       EllipsisLoc))
2605     return BaseSpec;
2606   else
2607     Class->setInvalidDecl();
2608 
2609   return true;
2610 }
2611 
2612 /// Use small set to collect indirect bases.  As this is only used
2613 /// locally, there's no need to abstract the small size parameter.
2614 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2615 
2616 /// Recursively add the bases of Type.  Don't add Type itself.
2617 static void
2618 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2619                   const QualType &Type)
2620 {
2621   // Even though the incoming type is a base, it might not be
2622   // a class -- it could be a template parm, for instance.
2623   if (auto Rec = Type->getAs<RecordType>()) {
2624     auto Decl = Rec->getAsCXXRecordDecl();
2625 
2626     // Iterate over its bases.
2627     for (const auto &BaseSpec : Decl->bases()) {
2628       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2629         .getUnqualifiedType();
2630       if (Set.insert(Base).second)
2631         // If we've not already seen it, recurse.
2632         NoteIndirectBases(Context, Set, Base);
2633     }
2634   }
2635 }
2636 
2637 /// Performs the actual work of attaching the given base class
2638 /// specifiers to a C++ class.
2639 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2640                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2641  if (Bases.empty())
2642     return false;
2643 
2644   // Used to keep track of which base types we have already seen, so
2645   // that we can properly diagnose redundant direct base types. Note
2646   // that the key is always the unqualified canonical type of the base
2647   // class.
2648   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2649 
2650   // Used to track indirect bases so we can see if a direct base is
2651   // ambiguous.
2652   IndirectBaseSet IndirectBaseTypes;
2653 
2654   // Copy non-redundant base specifiers into permanent storage.
2655   unsigned NumGoodBases = 0;
2656   bool Invalid = false;
2657   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2658     QualType NewBaseType
2659       = Context.getCanonicalType(Bases[idx]->getType());
2660     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2661 
2662     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2663     if (KnownBase) {
2664       // C++ [class.mi]p3:
2665       //   A class shall not be specified as a direct base class of a
2666       //   derived class more than once.
2667       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2668           << KnownBase->getType() << Bases[idx]->getSourceRange();
2669 
2670       // Delete the duplicate base class specifier; we're going to
2671       // overwrite its pointer later.
2672       Context.Deallocate(Bases[idx]);
2673 
2674       Invalid = true;
2675     } else {
2676       // Okay, add this new base class.
2677       KnownBase = Bases[idx];
2678       Bases[NumGoodBases++] = Bases[idx];
2679 
2680       // Note this base's direct & indirect bases, if there could be ambiguity.
2681       if (Bases.size() > 1)
2682         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2683 
2684       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2685         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2686         if (Class->isInterface() &&
2687               (!RD->isInterfaceLike() ||
2688                KnownBase->getAccessSpecifier() != AS_public)) {
2689           // The Microsoft extension __interface does not permit bases that
2690           // are not themselves public interfaces.
2691           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2692               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2693               << RD->getSourceRange();
2694           Invalid = true;
2695         }
2696         if (RD->hasAttr<WeakAttr>())
2697           Class->addAttr(WeakAttr::CreateImplicit(Context));
2698       }
2699     }
2700   }
2701 
2702   // Attach the remaining base class specifiers to the derived class.
2703   Class->setBases(Bases.data(), NumGoodBases);
2704 
2705   // Check that the only base classes that are duplicate are virtual.
2706   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2707     // Check whether this direct base is inaccessible due to ambiguity.
2708     QualType BaseType = Bases[idx]->getType();
2709 
2710     // Skip all dependent types in templates being used as base specifiers.
2711     // Checks below assume that the base specifier is a CXXRecord.
2712     if (BaseType->isDependentType())
2713       continue;
2714 
2715     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2716       .getUnqualifiedType();
2717 
2718     if (IndirectBaseTypes.count(CanonicalBase)) {
2719       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2720                          /*DetectVirtual=*/true);
2721       bool found
2722         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2723       assert(found);
2724       (void)found;
2725 
2726       if (Paths.isAmbiguous(CanonicalBase))
2727         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2728             << BaseType << getAmbiguousPathsDisplayString(Paths)
2729             << Bases[idx]->getSourceRange();
2730       else
2731         assert(Bases[idx]->isVirtual());
2732     }
2733 
2734     // Delete the base class specifier, since its data has been copied
2735     // into the CXXRecordDecl.
2736     Context.Deallocate(Bases[idx]);
2737   }
2738 
2739   return Invalid;
2740 }
2741 
2742 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2743 /// class, after checking whether there are any duplicate base
2744 /// classes.
2745 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2746                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2747   if (!ClassDecl || Bases.empty())
2748     return;
2749 
2750   AdjustDeclIfTemplate(ClassDecl);
2751   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2752 }
2753 
2754 /// Determine whether the type \p Derived is a C++ class that is
2755 /// derived from the type \p Base.
2756 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2757   if (!getLangOpts().CPlusPlus)
2758     return false;
2759 
2760   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2761   if (!DerivedRD)
2762     return false;
2763 
2764   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2765   if (!BaseRD)
2766     return false;
2767 
2768   // If either the base or the derived type is invalid, don't try to
2769   // check whether one is derived from the other.
2770   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2771     return false;
2772 
2773   // FIXME: In a modules build, do we need the entire path to be visible for us
2774   // to be able to use the inheritance relationship?
2775   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2776     return false;
2777 
2778   return DerivedRD->isDerivedFrom(BaseRD);
2779 }
2780 
2781 /// Determine whether the type \p Derived is a C++ class that is
2782 /// derived from the type \p Base.
2783 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2784                          CXXBasePaths &Paths) {
2785   if (!getLangOpts().CPlusPlus)
2786     return false;
2787 
2788   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2789   if (!DerivedRD)
2790     return false;
2791 
2792   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2793   if (!BaseRD)
2794     return false;
2795 
2796   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2797     return false;
2798 
2799   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2800 }
2801 
2802 static void BuildBasePathArray(const CXXBasePath &Path,
2803                                CXXCastPath &BasePathArray) {
2804   // We first go backward and check if we have a virtual base.
2805   // FIXME: It would be better if CXXBasePath had the base specifier for
2806   // the nearest virtual base.
2807   unsigned Start = 0;
2808   for (unsigned I = Path.size(); I != 0; --I) {
2809     if (Path[I - 1].Base->isVirtual()) {
2810       Start = I - 1;
2811       break;
2812     }
2813   }
2814 
2815   // Now add all bases.
2816   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2817     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2818 }
2819 
2820 
2821 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2822                               CXXCastPath &BasePathArray) {
2823   assert(BasePathArray.empty() && "Base path array must be empty!");
2824   assert(Paths.isRecordingPaths() && "Must record paths!");
2825   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2826 }
2827 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2828 /// conversion (where Derived and Base are class types) is
2829 /// well-formed, meaning that the conversion is unambiguous (and
2830 /// that all of the base classes are accessible). Returns true
2831 /// and emits a diagnostic if the code is ill-formed, returns false
2832 /// otherwise. Loc is the location where this routine should point to
2833 /// if there is an error, and Range is the source range to highlight
2834 /// if there is an error.
2835 ///
2836 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2837 /// diagnostic for the respective type of error will be suppressed, but the
2838 /// check for ill-formed code will still be performed.
2839 bool
2840 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2841                                    unsigned InaccessibleBaseID,
2842                                    unsigned AmbiguousBaseConvID,
2843                                    SourceLocation Loc, SourceRange Range,
2844                                    DeclarationName Name,
2845                                    CXXCastPath *BasePath,
2846                                    bool IgnoreAccess) {
2847   // First, determine whether the path from Derived to Base is
2848   // ambiguous. This is slightly more expensive than checking whether
2849   // the Derived to Base conversion exists, because here we need to
2850   // explore multiple paths to determine if there is an ambiguity.
2851   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2852                      /*DetectVirtual=*/false);
2853   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2854   if (!DerivationOkay)
2855     return true;
2856 
2857   const CXXBasePath *Path = nullptr;
2858   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2859     Path = &Paths.front();
2860 
2861   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2862   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2863   // user to access such bases.
2864   if (!Path && getLangOpts().MSVCCompat) {
2865     for (const CXXBasePath &PossiblePath : Paths) {
2866       if (PossiblePath.size() == 1) {
2867         Path = &PossiblePath;
2868         if (AmbiguousBaseConvID)
2869           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2870               << Base << Derived << Range;
2871         break;
2872       }
2873     }
2874   }
2875 
2876   if (Path) {
2877     if (!IgnoreAccess) {
2878       // Check that the base class can be accessed.
2879       switch (
2880           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2881       case AR_inaccessible:
2882         return true;
2883       case AR_accessible:
2884       case AR_dependent:
2885       case AR_delayed:
2886         break;
2887       }
2888     }
2889 
2890     // Build a base path if necessary.
2891     if (BasePath)
2892       ::BuildBasePathArray(*Path, *BasePath);
2893     return false;
2894   }
2895 
2896   if (AmbiguousBaseConvID) {
2897     // We know that the derived-to-base conversion is ambiguous, and
2898     // we're going to produce a diagnostic. Perform the derived-to-base
2899     // search just one more time to compute all of the possible paths so
2900     // that we can print them out. This is more expensive than any of
2901     // the previous derived-to-base checks we've done, but at this point
2902     // performance isn't as much of an issue.
2903     Paths.clear();
2904     Paths.setRecordingPaths(true);
2905     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2906     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2907     (void)StillOkay;
2908 
2909     // Build up a textual representation of the ambiguous paths, e.g.,
2910     // D -> B -> A, that will be used to illustrate the ambiguous
2911     // conversions in the diagnostic. We only print one of the paths
2912     // to each base class subobject.
2913     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2914 
2915     Diag(Loc, AmbiguousBaseConvID)
2916     << Derived << Base << PathDisplayStr << Range << Name;
2917   }
2918   return true;
2919 }
2920 
2921 bool
2922 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2923                                    SourceLocation Loc, SourceRange Range,
2924                                    CXXCastPath *BasePath,
2925                                    bool IgnoreAccess) {
2926   return CheckDerivedToBaseConversion(
2927       Derived, Base, diag::err_upcast_to_inaccessible_base,
2928       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2929       BasePath, IgnoreAccess);
2930 }
2931 
2932 
2933 /// Builds a string representing ambiguous paths from a
2934 /// specific derived class to different subobjects of the same base
2935 /// class.
2936 ///
2937 /// This function builds a string that can be used in error messages
2938 /// to show the different paths that one can take through the
2939 /// inheritance hierarchy to go from the derived class to different
2940 /// subobjects of a base class. The result looks something like this:
2941 /// @code
2942 /// struct D -> struct B -> struct A
2943 /// struct D -> struct C -> struct A
2944 /// @endcode
2945 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2946   std::string PathDisplayStr;
2947   std::set<unsigned> DisplayedPaths;
2948   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2949        Path != Paths.end(); ++Path) {
2950     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2951       // We haven't displayed a path to this particular base
2952       // class subobject yet.
2953       PathDisplayStr += "\n    ";
2954       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2955       for (CXXBasePath::const_iterator Element = Path->begin();
2956            Element != Path->end(); ++Element)
2957         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2958     }
2959   }
2960 
2961   return PathDisplayStr;
2962 }
2963 
2964 //===----------------------------------------------------------------------===//
2965 // C++ class member Handling
2966 //===----------------------------------------------------------------------===//
2967 
2968 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2969 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2970                                 SourceLocation ColonLoc,
2971                                 const ParsedAttributesView &Attrs) {
2972   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2973   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2974                                                   ASLoc, ColonLoc);
2975   CurContext->addHiddenDecl(ASDecl);
2976   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2977 }
2978 
2979 /// CheckOverrideControl - Check C++11 override control semantics.
2980 void Sema::CheckOverrideControl(NamedDecl *D) {
2981   if (D->isInvalidDecl())
2982     return;
2983 
2984   // We only care about "override" and "final" declarations.
2985   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2986     return;
2987 
2988   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2989 
2990   // We can't check dependent instance methods.
2991   if (MD && MD->isInstance() &&
2992       (MD->getParent()->hasAnyDependentBases() ||
2993        MD->getType()->isDependentType()))
2994     return;
2995 
2996   if (MD && !MD->isVirtual()) {
2997     // If we have a non-virtual method, check if if hides a virtual method.
2998     // (In that case, it's most likely the method has the wrong type.)
2999     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3000     FindHiddenVirtualMethods(MD, OverloadedMethods);
3001 
3002     if (!OverloadedMethods.empty()) {
3003       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3004         Diag(OA->getLocation(),
3005              diag::override_keyword_hides_virtual_member_function)
3006           << "override" << (OverloadedMethods.size() > 1);
3007       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3008         Diag(FA->getLocation(),
3009              diag::override_keyword_hides_virtual_member_function)
3010           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3011           << (OverloadedMethods.size() > 1);
3012       }
3013       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3014       MD->setInvalidDecl();
3015       return;
3016     }
3017     // Fall through into the general case diagnostic.
3018     // FIXME: We might want to attempt typo correction here.
3019   }
3020 
3021   if (!MD || !MD->isVirtual()) {
3022     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3023       Diag(OA->getLocation(),
3024            diag::override_keyword_only_allowed_on_virtual_member_functions)
3025         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3026       D->dropAttr<OverrideAttr>();
3027     }
3028     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3029       Diag(FA->getLocation(),
3030            diag::override_keyword_only_allowed_on_virtual_member_functions)
3031         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3032         << FixItHint::CreateRemoval(FA->getLocation());
3033       D->dropAttr<FinalAttr>();
3034     }
3035     return;
3036   }
3037 
3038   // C++11 [class.virtual]p5:
3039   //   If a function is marked with the virt-specifier override and
3040   //   does not override a member function of a base class, the program is
3041   //   ill-formed.
3042   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3043   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3044     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3045       << MD->getDeclName();
3046 }
3047 
3048 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
3049   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3050     return;
3051   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3052   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3053     return;
3054 
3055   SourceLocation Loc = MD->getLocation();
3056   SourceLocation SpellingLoc = Loc;
3057   if (getSourceManager().isMacroArgExpansion(Loc))
3058     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3059   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3060   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3061       return;
3062 
3063   if (MD->size_overridden_methods() > 0) {
3064     unsigned DiagID = isa<CXXDestructorDecl>(MD)
3065                           ? diag::warn_destructor_marked_not_override_overriding
3066                           : diag::warn_function_marked_not_override_overriding;
3067     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3068     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3069     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3070   }
3071 }
3072 
3073 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3074 /// function overrides a virtual member function marked 'final', according to
3075 /// C++11 [class.virtual]p4.
3076 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3077                                                   const CXXMethodDecl *Old) {
3078   FinalAttr *FA = Old->getAttr<FinalAttr>();
3079   if (!FA)
3080     return false;
3081 
3082   Diag(New->getLocation(), diag::err_final_function_overridden)
3083     << New->getDeclName()
3084     << FA->isSpelledAsSealed();
3085   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3086   return true;
3087 }
3088 
3089 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3090   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3091   // FIXME: Destruction of ObjC lifetime types has side-effects.
3092   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3093     return !RD->isCompleteDefinition() ||
3094            !RD->hasTrivialDefaultConstructor() ||
3095            !RD->hasTrivialDestructor();
3096   return false;
3097 }
3098 
3099 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3100   ParsedAttributesView::const_iterator Itr =
3101       llvm::find_if(list, [](const ParsedAttr &AL) {
3102         return AL.isDeclspecPropertyAttribute();
3103       });
3104   if (Itr != list.end())
3105     return &*Itr;
3106   return nullptr;
3107 }
3108 
3109 // Check if there is a field shadowing.
3110 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3111                                       DeclarationName FieldName,
3112                                       const CXXRecordDecl *RD,
3113                                       bool DeclIsField) {
3114   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3115     return;
3116 
3117   // To record a shadowed field in a base
3118   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3119   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3120                            CXXBasePath &Path) {
3121     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3122     // Record an ambiguous path directly
3123     if (Bases.find(Base) != Bases.end())
3124       return true;
3125     for (const auto Field : Base->lookup(FieldName)) {
3126       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3127           Field->getAccess() != AS_private) {
3128         assert(Field->getAccess() != AS_none);
3129         assert(Bases.find(Base) == Bases.end());
3130         Bases[Base] = Field;
3131         return true;
3132       }
3133     }
3134     return false;
3135   };
3136 
3137   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3138                      /*DetectVirtual=*/true);
3139   if (!RD->lookupInBases(FieldShadowed, Paths))
3140     return;
3141 
3142   for (const auto &P : Paths) {
3143     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3144     auto It = Bases.find(Base);
3145     // Skip duplicated bases
3146     if (It == Bases.end())
3147       continue;
3148     auto BaseField = It->second;
3149     assert(BaseField->getAccess() != AS_private);
3150     if (AS_none !=
3151         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3152       Diag(Loc, diag::warn_shadow_field)
3153         << FieldName << RD << Base << DeclIsField;
3154       Diag(BaseField->getLocation(), diag::note_shadow_field);
3155       Bases.erase(It);
3156     }
3157   }
3158 }
3159 
3160 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3161 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3162 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3163 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3164 /// present (but parsing it has been deferred).
3165 NamedDecl *
3166 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3167                                MultiTemplateParamsArg TemplateParameterLists,
3168                                Expr *BW, const VirtSpecifiers &VS,
3169                                InClassInitStyle InitStyle) {
3170   const DeclSpec &DS = D.getDeclSpec();
3171   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3172   DeclarationName Name = NameInfo.getName();
3173   SourceLocation Loc = NameInfo.getLoc();
3174 
3175   // For anonymous bitfields, the location should point to the type.
3176   if (Loc.isInvalid())
3177     Loc = D.getBeginLoc();
3178 
3179   Expr *BitWidth = static_cast<Expr*>(BW);
3180 
3181   assert(isa<CXXRecordDecl>(CurContext));
3182   assert(!DS.isFriendSpecified());
3183 
3184   bool isFunc = D.isDeclarationOfFunction();
3185   const ParsedAttr *MSPropertyAttr =
3186       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3187 
3188   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3189     // The Microsoft extension __interface only permits public member functions
3190     // and prohibits constructors, destructors, operators, non-public member
3191     // functions, static methods and data members.
3192     unsigned InvalidDecl;
3193     bool ShowDeclName = true;
3194     if (!isFunc &&
3195         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3196       InvalidDecl = 0;
3197     else if (!isFunc)
3198       InvalidDecl = 1;
3199     else if (AS != AS_public)
3200       InvalidDecl = 2;
3201     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3202       InvalidDecl = 3;
3203     else switch (Name.getNameKind()) {
3204       case DeclarationName::CXXConstructorName:
3205         InvalidDecl = 4;
3206         ShowDeclName = false;
3207         break;
3208 
3209       case DeclarationName::CXXDestructorName:
3210         InvalidDecl = 5;
3211         ShowDeclName = false;
3212         break;
3213 
3214       case DeclarationName::CXXOperatorName:
3215       case DeclarationName::CXXConversionFunctionName:
3216         InvalidDecl = 6;
3217         break;
3218 
3219       default:
3220         InvalidDecl = 0;
3221         break;
3222     }
3223 
3224     if (InvalidDecl) {
3225       if (ShowDeclName)
3226         Diag(Loc, diag::err_invalid_member_in_interface)
3227           << (InvalidDecl-1) << Name;
3228       else
3229         Diag(Loc, diag::err_invalid_member_in_interface)
3230           << (InvalidDecl-1) << "";
3231       return nullptr;
3232     }
3233   }
3234 
3235   // C++ 9.2p6: A member shall not be declared to have automatic storage
3236   // duration (auto, register) or with the extern storage-class-specifier.
3237   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3238   // data members and cannot be applied to names declared const or static,
3239   // and cannot be applied to reference members.
3240   switch (DS.getStorageClassSpec()) {
3241   case DeclSpec::SCS_unspecified:
3242   case DeclSpec::SCS_typedef:
3243   case DeclSpec::SCS_static:
3244     break;
3245   case DeclSpec::SCS_mutable:
3246     if (isFunc) {
3247       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3248 
3249       // FIXME: It would be nicer if the keyword was ignored only for this
3250       // declarator. Otherwise we could get follow-up errors.
3251       D.getMutableDeclSpec().ClearStorageClassSpecs();
3252     }
3253     break;
3254   default:
3255     Diag(DS.getStorageClassSpecLoc(),
3256          diag::err_storageclass_invalid_for_member);
3257     D.getMutableDeclSpec().ClearStorageClassSpecs();
3258     break;
3259   }
3260 
3261   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3262                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3263                       !isFunc);
3264 
3265   if (DS.hasConstexprSpecifier() && isInstField) {
3266     SemaDiagnosticBuilder B =
3267         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3268     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3269     if (InitStyle == ICIS_NoInit) {
3270       B << 0 << 0;
3271       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3272         B << FixItHint::CreateRemoval(ConstexprLoc);
3273       else {
3274         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3275         D.getMutableDeclSpec().ClearConstexprSpec();
3276         const char *PrevSpec;
3277         unsigned DiagID;
3278         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3279             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3280         (void)Failed;
3281         assert(!Failed && "Making a constexpr member const shouldn't fail");
3282       }
3283     } else {
3284       B << 1;
3285       const char *PrevSpec;
3286       unsigned DiagID;
3287       if (D.getMutableDeclSpec().SetStorageClassSpec(
3288           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3289           Context.getPrintingPolicy())) {
3290         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3291                "This is the only DeclSpec that should fail to be applied");
3292         B << 1;
3293       } else {
3294         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3295         isInstField = false;
3296       }
3297     }
3298   }
3299 
3300   NamedDecl *Member;
3301   if (isInstField) {
3302     CXXScopeSpec &SS = D.getCXXScopeSpec();
3303 
3304     // Data members must have identifiers for names.
3305     if (!Name.isIdentifier()) {
3306       Diag(Loc, diag::err_bad_variable_name)
3307         << Name;
3308       return nullptr;
3309     }
3310 
3311     IdentifierInfo *II = Name.getAsIdentifierInfo();
3312 
3313     // Member field could not be with "template" keyword.
3314     // So TemplateParameterLists should be empty in this case.
3315     if (TemplateParameterLists.size()) {
3316       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3317       if (TemplateParams->size()) {
3318         // There is no such thing as a member field template.
3319         Diag(D.getIdentifierLoc(), diag::err_template_member)
3320             << II
3321             << SourceRange(TemplateParams->getTemplateLoc(),
3322                 TemplateParams->getRAngleLoc());
3323       } else {
3324         // There is an extraneous 'template<>' for this member.
3325         Diag(TemplateParams->getTemplateLoc(),
3326             diag::err_template_member_noparams)
3327             << II
3328             << SourceRange(TemplateParams->getTemplateLoc(),
3329                 TemplateParams->getRAngleLoc());
3330       }
3331       return nullptr;
3332     }
3333 
3334     if (SS.isSet() && !SS.isInvalid()) {
3335       // The user provided a superfluous scope specifier inside a class
3336       // definition:
3337       //
3338       // class X {
3339       //   int X::member;
3340       // };
3341       if (DeclContext *DC = computeDeclContext(SS, false))
3342         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3343                                      D.getName().getKind() ==
3344                                          UnqualifiedIdKind::IK_TemplateId);
3345       else
3346         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3347           << Name << SS.getRange();
3348 
3349       SS.clear();
3350     }
3351 
3352     if (MSPropertyAttr) {
3353       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3354                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3355       if (!Member)
3356         return nullptr;
3357       isInstField = false;
3358     } else {
3359       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3360                                 BitWidth, InitStyle, AS);
3361       if (!Member)
3362         return nullptr;
3363     }
3364 
3365     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3366   } else {
3367     Member = HandleDeclarator(S, D, TemplateParameterLists);
3368     if (!Member)
3369       return nullptr;
3370 
3371     // Non-instance-fields can't have a bitfield.
3372     if (BitWidth) {
3373       if (Member->isInvalidDecl()) {
3374         // don't emit another diagnostic.
3375       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3376         // C++ 9.6p3: A bit-field shall not be a static member.
3377         // "static member 'A' cannot be a bit-field"
3378         Diag(Loc, diag::err_static_not_bitfield)
3379           << Name << BitWidth->getSourceRange();
3380       } else if (isa<TypedefDecl>(Member)) {
3381         // "typedef member 'x' cannot be a bit-field"
3382         Diag(Loc, diag::err_typedef_not_bitfield)
3383           << Name << BitWidth->getSourceRange();
3384       } else {
3385         // A function typedef ("typedef int f(); f a;").
3386         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3387         Diag(Loc, diag::err_not_integral_type_bitfield)
3388           << Name << cast<ValueDecl>(Member)->getType()
3389           << BitWidth->getSourceRange();
3390       }
3391 
3392       BitWidth = nullptr;
3393       Member->setInvalidDecl();
3394     }
3395 
3396     NamedDecl *NonTemplateMember = Member;
3397     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3398       NonTemplateMember = FunTmpl->getTemplatedDecl();
3399     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3400       NonTemplateMember = VarTmpl->getTemplatedDecl();
3401 
3402     Member->setAccess(AS);
3403 
3404     // If we have declared a member function template or static data member
3405     // template, set the access of the templated declaration as well.
3406     if (NonTemplateMember != Member)
3407       NonTemplateMember->setAccess(AS);
3408 
3409     // C++ [temp.deduct.guide]p3:
3410     //   A deduction guide [...] for a member class template [shall be
3411     //   declared] with the same access [as the template].
3412     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3413       auto *TD = DG->getDeducedTemplate();
3414       // Access specifiers are only meaningful if both the template and the
3415       // deduction guide are from the same scope.
3416       if (AS != TD->getAccess() &&
3417           TD->getDeclContext()->getRedeclContext()->Equals(
3418               DG->getDeclContext()->getRedeclContext())) {
3419         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3420         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3421             << TD->getAccess();
3422         const AccessSpecDecl *LastAccessSpec = nullptr;
3423         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3424           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3425             LastAccessSpec = AccessSpec;
3426         }
3427         assert(LastAccessSpec && "differing access with no access specifier");
3428         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3429             << AS;
3430       }
3431     }
3432   }
3433 
3434   if (VS.isOverrideSpecified())
3435     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3436                                          AttributeCommonInfo::AS_Keyword));
3437   if (VS.isFinalSpecified())
3438     Member->addAttr(FinalAttr::Create(
3439         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3440         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3441 
3442   if (VS.getLastLocation().isValid()) {
3443     // Update the end location of a method that has a virt-specifiers.
3444     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3445       MD->setRangeEnd(VS.getLastLocation());
3446   }
3447 
3448   CheckOverrideControl(Member);
3449 
3450   assert((Name || isInstField) && "No identifier for non-field ?");
3451 
3452   if (isInstField) {
3453     FieldDecl *FD = cast<FieldDecl>(Member);
3454     FieldCollector->Add(FD);
3455 
3456     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3457       // Remember all explicit private FieldDecls that have a name, no side
3458       // effects and are not part of a dependent type declaration.
3459       if (!FD->isImplicit() && FD->getDeclName() &&
3460           FD->getAccess() == AS_private &&
3461           !FD->hasAttr<UnusedAttr>() &&
3462           !FD->getParent()->isDependentContext() &&
3463           !InitializationHasSideEffects(*FD))
3464         UnusedPrivateFields.insert(FD);
3465     }
3466   }
3467 
3468   return Member;
3469 }
3470 
3471 namespace {
3472   class UninitializedFieldVisitor
3473       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3474     Sema &S;
3475     // List of Decls to generate a warning on.  Also remove Decls that become
3476     // initialized.
3477     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3478     // List of base classes of the record.  Classes are removed after their
3479     // initializers.
3480     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3481     // Vector of decls to be removed from the Decl set prior to visiting the
3482     // nodes.  These Decls may have been initialized in the prior initializer.
3483     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3484     // If non-null, add a note to the warning pointing back to the constructor.
3485     const CXXConstructorDecl *Constructor;
3486     // Variables to hold state when processing an initializer list.  When
3487     // InitList is true, special case initialization of FieldDecls matching
3488     // InitListFieldDecl.
3489     bool InitList;
3490     FieldDecl *InitListFieldDecl;
3491     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3492 
3493   public:
3494     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3495     UninitializedFieldVisitor(Sema &S,
3496                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3497                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3498       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3499         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3500 
3501     // Returns true if the use of ME is not an uninitialized use.
3502     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3503                                          bool CheckReferenceOnly) {
3504       llvm::SmallVector<FieldDecl*, 4> Fields;
3505       bool ReferenceField = false;
3506       while (ME) {
3507         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3508         if (!FD)
3509           return false;
3510         Fields.push_back(FD);
3511         if (FD->getType()->isReferenceType())
3512           ReferenceField = true;
3513         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3514       }
3515 
3516       // Binding a reference to an uninitialized field is not an
3517       // uninitialized use.
3518       if (CheckReferenceOnly && !ReferenceField)
3519         return true;
3520 
3521       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3522       // Discard the first field since it is the field decl that is being
3523       // initialized.
3524       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3525         UsedFieldIndex.push_back((*I)->getFieldIndex());
3526       }
3527 
3528       for (auto UsedIter = UsedFieldIndex.begin(),
3529                 UsedEnd = UsedFieldIndex.end(),
3530                 OrigIter = InitFieldIndex.begin(),
3531                 OrigEnd = InitFieldIndex.end();
3532            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3533         if (*UsedIter < *OrigIter)
3534           return true;
3535         if (*UsedIter > *OrigIter)
3536           break;
3537       }
3538 
3539       return false;
3540     }
3541 
3542     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3543                           bool AddressOf) {
3544       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3545         return;
3546 
3547       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3548       // or union.
3549       MemberExpr *FieldME = ME;
3550 
3551       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3552 
3553       Expr *Base = ME;
3554       while (MemberExpr *SubME =
3555                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3556 
3557         if (isa<VarDecl>(SubME->getMemberDecl()))
3558           return;
3559 
3560         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3561           if (!FD->isAnonymousStructOrUnion())
3562             FieldME = SubME;
3563 
3564         if (!FieldME->getType().isPODType(S.Context))
3565           AllPODFields = false;
3566 
3567         Base = SubME->getBase();
3568       }
3569 
3570       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3571         return;
3572 
3573       if (AddressOf && AllPODFields)
3574         return;
3575 
3576       ValueDecl* FoundVD = FieldME->getMemberDecl();
3577 
3578       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3579         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3580           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3581         }
3582 
3583         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3584           QualType T = BaseCast->getType();
3585           if (T->isPointerType() &&
3586               BaseClasses.count(T->getPointeeType())) {
3587             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3588                 << T->getPointeeType() << FoundVD;
3589           }
3590         }
3591       }
3592 
3593       if (!Decls.count(FoundVD))
3594         return;
3595 
3596       const bool IsReference = FoundVD->getType()->isReferenceType();
3597 
3598       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3599         // Special checking for initializer lists.
3600         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3601           return;
3602         }
3603       } else {
3604         // Prevent double warnings on use of unbounded references.
3605         if (CheckReferenceOnly && !IsReference)
3606           return;
3607       }
3608 
3609       unsigned diag = IsReference
3610           ? diag::warn_reference_field_is_uninit
3611           : diag::warn_field_is_uninit;
3612       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3613       if (Constructor)
3614         S.Diag(Constructor->getLocation(),
3615                diag::note_uninit_in_this_constructor)
3616           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3617 
3618     }
3619 
3620     void HandleValue(Expr *E, bool AddressOf) {
3621       E = E->IgnoreParens();
3622 
3623       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3624         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3625                          AddressOf /*AddressOf*/);
3626         return;
3627       }
3628 
3629       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3630         Visit(CO->getCond());
3631         HandleValue(CO->getTrueExpr(), AddressOf);
3632         HandleValue(CO->getFalseExpr(), AddressOf);
3633         return;
3634       }
3635 
3636       if (BinaryConditionalOperator *BCO =
3637               dyn_cast<BinaryConditionalOperator>(E)) {
3638         Visit(BCO->getCond());
3639         HandleValue(BCO->getFalseExpr(), AddressOf);
3640         return;
3641       }
3642 
3643       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3644         HandleValue(OVE->getSourceExpr(), AddressOf);
3645         return;
3646       }
3647 
3648       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3649         switch (BO->getOpcode()) {
3650         default:
3651           break;
3652         case(BO_PtrMemD):
3653         case(BO_PtrMemI):
3654           HandleValue(BO->getLHS(), AddressOf);
3655           Visit(BO->getRHS());
3656           return;
3657         case(BO_Comma):
3658           Visit(BO->getLHS());
3659           HandleValue(BO->getRHS(), AddressOf);
3660           return;
3661         }
3662       }
3663 
3664       Visit(E);
3665     }
3666 
3667     void CheckInitListExpr(InitListExpr *ILE) {
3668       InitFieldIndex.push_back(0);
3669       for (auto Child : ILE->children()) {
3670         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3671           CheckInitListExpr(SubList);
3672         } else {
3673           Visit(Child);
3674         }
3675         ++InitFieldIndex.back();
3676       }
3677       InitFieldIndex.pop_back();
3678     }
3679 
3680     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3681                           FieldDecl *Field, const Type *BaseClass) {
3682       // Remove Decls that may have been initialized in the previous
3683       // initializer.
3684       for (ValueDecl* VD : DeclsToRemove)
3685         Decls.erase(VD);
3686       DeclsToRemove.clear();
3687 
3688       Constructor = FieldConstructor;
3689       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3690 
3691       if (ILE && Field) {
3692         InitList = true;
3693         InitListFieldDecl = Field;
3694         InitFieldIndex.clear();
3695         CheckInitListExpr(ILE);
3696       } else {
3697         InitList = false;
3698         Visit(E);
3699       }
3700 
3701       if (Field)
3702         Decls.erase(Field);
3703       if (BaseClass)
3704         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3705     }
3706 
3707     void VisitMemberExpr(MemberExpr *ME) {
3708       // All uses of unbounded reference fields will warn.
3709       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3710     }
3711 
3712     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3713       if (E->getCastKind() == CK_LValueToRValue) {
3714         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3715         return;
3716       }
3717 
3718       Inherited::VisitImplicitCastExpr(E);
3719     }
3720 
3721     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3722       if (E->getConstructor()->isCopyConstructor()) {
3723         Expr *ArgExpr = E->getArg(0);
3724         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3725           if (ILE->getNumInits() == 1)
3726             ArgExpr = ILE->getInit(0);
3727         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3728           if (ICE->getCastKind() == CK_NoOp)
3729             ArgExpr = ICE->getSubExpr();
3730         HandleValue(ArgExpr, false /*AddressOf*/);
3731         return;
3732       }
3733       Inherited::VisitCXXConstructExpr(E);
3734     }
3735 
3736     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3737       Expr *Callee = E->getCallee();
3738       if (isa<MemberExpr>(Callee)) {
3739         HandleValue(Callee, false /*AddressOf*/);
3740         for (auto Arg : E->arguments())
3741           Visit(Arg);
3742         return;
3743       }
3744 
3745       Inherited::VisitCXXMemberCallExpr(E);
3746     }
3747 
3748     void VisitCallExpr(CallExpr *E) {
3749       // Treat std::move as a use.
3750       if (E->isCallToStdMove()) {
3751         HandleValue(E->getArg(0), /*AddressOf=*/false);
3752         return;
3753       }
3754 
3755       Inherited::VisitCallExpr(E);
3756     }
3757 
3758     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3759       Expr *Callee = E->getCallee();
3760 
3761       if (isa<UnresolvedLookupExpr>(Callee))
3762         return Inherited::VisitCXXOperatorCallExpr(E);
3763 
3764       Visit(Callee);
3765       for (auto Arg : E->arguments())
3766         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3767     }
3768 
3769     void VisitBinaryOperator(BinaryOperator *E) {
3770       // If a field assignment is detected, remove the field from the
3771       // uninitiailized field set.
3772       if (E->getOpcode() == BO_Assign)
3773         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3774           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3775             if (!FD->getType()->isReferenceType())
3776               DeclsToRemove.push_back(FD);
3777 
3778       if (E->isCompoundAssignmentOp()) {
3779         HandleValue(E->getLHS(), false /*AddressOf*/);
3780         Visit(E->getRHS());
3781         return;
3782       }
3783 
3784       Inherited::VisitBinaryOperator(E);
3785     }
3786 
3787     void VisitUnaryOperator(UnaryOperator *E) {
3788       if (E->isIncrementDecrementOp()) {
3789         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3790         return;
3791       }
3792       if (E->getOpcode() == UO_AddrOf) {
3793         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3794           HandleValue(ME->getBase(), true /*AddressOf*/);
3795           return;
3796         }
3797       }
3798 
3799       Inherited::VisitUnaryOperator(E);
3800     }
3801   };
3802 
3803   // Diagnose value-uses of fields to initialize themselves, e.g.
3804   //   foo(foo)
3805   // where foo is not also a parameter to the constructor.
3806   // Also diagnose across field uninitialized use such as
3807   //   x(y), y(x)
3808   // TODO: implement -Wuninitialized and fold this into that framework.
3809   static void DiagnoseUninitializedFields(
3810       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3811 
3812     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3813                                            Constructor->getLocation())) {
3814       return;
3815     }
3816 
3817     if (Constructor->isInvalidDecl())
3818       return;
3819 
3820     const CXXRecordDecl *RD = Constructor->getParent();
3821 
3822     if (RD->isDependentContext())
3823       return;
3824 
3825     // Holds fields that are uninitialized.
3826     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3827 
3828     // At the beginning, all fields are uninitialized.
3829     for (auto *I : RD->decls()) {
3830       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3831         UninitializedFields.insert(FD);
3832       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3833         UninitializedFields.insert(IFD->getAnonField());
3834       }
3835     }
3836 
3837     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3838     for (auto I : RD->bases())
3839       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3840 
3841     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3842       return;
3843 
3844     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3845                                                    UninitializedFields,
3846                                                    UninitializedBaseClasses);
3847 
3848     for (const auto *FieldInit : Constructor->inits()) {
3849       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3850         break;
3851 
3852       Expr *InitExpr = FieldInit->getInit();
3853       if (!InitExpr)
3854         continue;
3855 
3856       if (CXXDefaultInitExpr *Default =
3857               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3858         InitExpr = Default->getExpr();
3859         if (!InitExpr)
3860           continue;
3861         // In class initializers will point to the constructor.
3862         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3863                                               FieldInit->getAnyMember(),
3864                                               FieldInit->getBaseClass());
3865       } else {
3866         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3867                                               FieldInit->getAnyMember(),
3868                                               FieldInit->getBaseClass());
3869       }
3870     }
3871   }
3872 } // namespace
3873 
3874 /// Enter a new C++ default initializer scope. After calling this, the
3875 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3876 /// parsing or instantiating the initializer failed.
3877 void Sema::ActOnStartCXXInClassMemberInitializer() {
3878   // Create a synthetic function scope to represent the call to the constructor
3879   // that notionally surrounds a use of this initializer.
3880   PushFunctionScope();
3881 }
3882 
3883 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3884   if (!D.isFunctionDeclarator())
3885     return;
3886   auto &FTI = D.getFunctionTypeInfo();
3887   if (!FTI.Params)
3888     return;
3889   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3890                                                           FTI.NumParams)) {
3891     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3892     if (ParamDecl->getDeclName())
3893       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3894   }
3895 }
3896 
3897 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3898   if (ConstraintExpr.isInvalid())
3899     return ExprError();
3900   return CorrectDelayedTyposInExpr(ConstraintExpr);
3901 }
3902 
3903 /// This is invoked after parsing an in-class initializer for a
3904 /// non-static C++ class member, and after instantiating an in-class initializer
3905 /// in a class template. Such actions are deferred until the class is complete.
3906 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3907                                                   SourceLocation InitLoc,
3908                                                   Expr *InitExpr) {
3909   // Pop the notional constructor scope we created earlier.
3910   PopFunctionScopeInfo(nullptr, D);
3911 
3912   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3913   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3914          "must set init style when field is created");
3915 
3916   if (!InitExpr) {
3917     D->setInvalidDecl();
3918     if (FD)
3919       FD->removeInClassInitializer();
3920     return;
3921   }
3922 
3923   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3924     FD->setInvalidDecl();
3925     FD->removeInClassInitializer();
3926     return;
3927   }
3928 
3929   ExprResult Init = InitExpr;
3930   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3931     InitializedEntity Entity =
3932         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3933     InitializationKind Kind =
3934         FD->getInClassInitStyle() == ICIS_ListInit
3935             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3936                                                    InitExpr->getBeginLoc(),
3937                                                    InitExpr->getEndLoc())
3938             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3939     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3940     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3941     if (Init.isInvalid()) {
3942       FD->setInvalidDecl();
3943       return;
3944     }
3945   }
3946 
3947   // C++11 [class.base.init]p7:
3948   //   The initialization of each base and member constitutes a
3949   //   full-expression.
3950   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3951   if (Init.isInvalid()) {
3952     FD->setInvalidDecl();
3953     return;
3954   }
3955 
3956   InitExpr = Init.get();
3957 
3958   FD->setInClassInitializer(InitExpr);
3959 }
3960 
3961 /// Find the direct and/or virtual base specifiers that
3962 /// correspond to the given base type, for use in base initialization
3963 /// within a constructor.
3964 static bool FindBaseInitializer(Sema &SemaRef,
3965                                 CXXRecordDecl *ClassDecl,
3966                                 QualType BaseType,
3967                                 const CXXBaseSpecifier *&DirectBaseSpec,
3968                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3969   // First, check for a direct base class.
3970   DirectBaseSpec = nullptr;
3971   for (const auto &Base : ClassDecl->bases()) {
3972     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3973       // We found a direct base of this type. That's what we're
3974       // initializing.
3975       DirectBaseSpec = &Base;
3976       break;
3977     }
3978   }
3979 
3980   // Check for a virtual base class.
3981   // FIXME: We might be able to short-circuit this if we know in advance that
3982   // there are no virtual bases.
3983   VirtualBaseSpec = nullptr;
3984   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3985     // We haven't found a base yet; search the class hierarchy for a
3986     // virtual base class.
3987     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3988                        /*DetectVirtual=*/false);
3989     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3990                               SemaRef.Context.getTypeDeclType(ClassDecl),
3991                               BaseType, Paths)) {
3992       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3993            Path != Paths.end(); ++Path) {
3994         if (Path->back().Base->isVirtual()) {
3995           VirtualBaseSpec = Path->back().Base;
3996           break;
3997         }
3998       }
3999     }
4000   }
4001 
4002   return DirectBaseSpec || VirtualBaseSpec;
4003 }
4004 
4005 /// Handle a C++ member initializer using braced-init-list syntax.
4006 MemInitResult
4007 Sema::ActOnMemInitializer(Decl *ConstructorD,
4008                           Scope *S,
4009                           CXXScopeSpec &SS,
4010                           IdentifierInfo *MemberOrBase,
4011                           ParsedType TemplateTypeTy,
4012                           const DeclSpec &DS,
4013                           SourceLocation IdLoc,
4014                           Expr *InitList,
4015                           SourceLocation EllipsisLoc) {
4016   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4017                              DS, IdLoc, InitList,
4018                              EllipsisLoc);
4019 }
4020 
4021 /// Handle a C++ member initializer using parentheses syntax.
4022 MemInitResult
4023 Sema::ActOnMemInitializer(Decl *ConstructorD,
4024                           Scope *S,
4025                           CXXScopeSpec &SS,
4026                           IdentifierInfo *MemberOrBase,
4027                           ParsedType TemplateTypeTy,
4028                           const DeclSpec &DS,
4029                           SourceLocation IdLoc,
4030                           SourceLocation LParenLoc,
4031                           ArrayRef<Expr *> Args,
4032                           SourceLocation RParenLoc,
4033                           SourceLocation EllipsisLoc) {
4034   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4035   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4036                              DS, IdLoc, List, EllipsisLoc);
4037 }
4038 
4039 namespace {
4040 
4041 // Callback to only accept typo corrections that can be a valid C++ member
4042 // intializer: either a non-static field member or a base class.
4043 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4044 public:
4045   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4046       : ClassDecl(ClassDecl) {}
4047 
4048   bool ValidateCandidate(const TypoCorrection &candidate) override {
4049     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4050       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4051         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4052       return isa<TypeDecl>(ND);
4053     }
4054     return false;
4055   }
4056 
4057   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4058     return std::make_unique<MemInitializerValidatorCCC>(*this);
4059   }
4060 
4061 private:
4062   CXXRecordDecl *ClassDecl;
4063 };
4064 
4065 }
4066 
4067 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4068                                              CXXScopeSpec &SS,
4069                                              ParsedType TemplateTypeTy,
4070                                              IdentifierInfo *MemberOrBase) {
4071   if (SS.getScopeRep() || TemplateTypeTy)
4072     return nullptr;
4073   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4074   if (Result.empty())
4075     return nullptr;
4076   ValueDecl *Member;
4077   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4078       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4079     return Member;
4080   return nullptr;
4081 }
4082 
4083 /// Handle a C++ member initializer.
4084 MemInitResult
4085 Sema::BuildMemInitializer(Decl *ConstructorD,
4086                           Scope *S,
4087                           CXXScopeSpec &SS,
4088                           IdentifierInfo *MemberOrBase,
4089                           ParsedType TemplateTypeTy,
4090                           const DeclSpec &DS,
4091                           SourceLocation IdLoc,
4092                           Expr *Init,
4093                           SourceLocation EllipsisLoc) {
4094   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4095   if (!Res.isUsable())
4096     return true;
4097   Init = Res.get();
4098 
4099   if (!ConstructorD)
4100     return true;
4101 
4102   AdjustDeclIfTemplate(ConstructorD);
4103 
4104   CXXConstructorDecl *Constructor
4105     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4106   if (!Constructor) {
4107     // The user wrote a constructor initializer on a function that is
4108     // not a C++ constructor. Ignore the error for now, because we may
4109     // have more member initializers coming; we'll diagnose it just
4110     // once in ActOnMemInitializers.
4111     return true;
4112   }
4113 
4114   CXXRecordDecl *ClassDecl = Constructor->getParent();
4115 
4116   // C++ [class.base.init]p2:
4117   //   Names in a mem-initializer-id are looked up in the scope of the
4118   //   constructor's class and, if not found in that scope, are looked
4119   //   up in the scope containing the constructor's definition.
4120   //   [Note: if the constructor's class contains a member with the
4121   //   same name as a direct or virtual base class of the class, a
4122   //   mem-initializer-id naming the member or base class and composed
4123   //   of a single identifier refers to the class member. A
4124   //   mem-initializer-id for the hidden base class may be specified
4125   //   using a qualified name. ]
4126 
4127   // Look for a member, first.
4128   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4129           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4130     if (EllipsisLoc.isValid())
4131       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4132           << MemberOrBase
4133           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4134 
4135     return BuildMemberInitializer(Member, Init, IdLoc);
4136   }
4137   // It didn't name a member, so see if it names a class.
4138   QualType BaseType;
4139   TypeSourceInfo *TInfo = nullptr;
4140 
4141   if (TemplateTypeTy) {
4142     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4143     if (BaseType.isNull())
4144       return true;
4145   } else if (DS.getTypeSpecType() == TST_decltype) {
4146     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4147   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4148     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4149     return true;
4150   } else {
4151     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4152     LookupParsedName(R, S, &SS);
4153 
4154     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4155     if (!TyD) {
4156       if (R.isAmbiguous()) return true;
4157 
4158       // We don't want access-control diagnostics here.
4159       R.suppressDiagnostics();
4160 
4161       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4162         bool NotUnknownSpecialization = false;
4163         DeclContext *DC = computeDeclContext(SS, false);
4164         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4165           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4166 
4167         if (!NotUnknownSpecialization) {
4168           // When the scope specifier can refer to a member of an unknown
4169           // specialization, we take it as a type name.
4170           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4171                                        SS.getWithLocInContext(Context),
4172                                        *MemberOrBase, IdLoc);
4173           if (BaseType.isNull())
4174             return true;
4175 
4176           TInfo = Context.CreateTypeSourceInfo(BaseType);
4177           DependentNameTypeLoc TL =
4178               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4179           if (!TL.isNull()) {
4180             TL.setNameLoc(IdLoc);
4181             TL.setElaboratedKeywordLoc(SourceLocation());
4182             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4183           }
4184 
4185           R.clear();
4186           R.setLookupName(MemberOrBase);
4187         }
4188       }
4189 
4190       // If no results were found, try to correct typos.
4191       TypoCorrection Corr;
4192       MemInitializerValidatorCCC CCC(ClassDecl);
4193       if (R.empty() && BaseType.isNull() &&
4194           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4195                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4196         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4197           // We have found a non-static data member with a similar
4198           // name to what was typed; complain and initialize that
4199           // member.
4200           diagnoseTypo(Corr,
4201                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4202                          << MemberOrBase << true);
4203           return BuildMemberInitializer(Member, Init, IdLoc);
4204         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4205           const CXXBaseSpecifier *DirectBaseSpec;
4206           const CXXBaseSpecifier *VirtualBaseSpec;
4207           if (FindBaseInitializer(*this, ClassDecl,
4208                                   Context.getTypeDeclType(Type),
4209                                   DirectBaseSpec, VirtualBaseSpec)) {
4210             // We have found a direct or virtual base class with a
4211             // similar name to what was typed; complain and initialize
4212             // that base class.
4213             diagnoseTypo(Corr,
4214                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4215                            << MemberOrBase << false,
4216                          PDiag() /*Suppress note, we provide our own.*/);
4217 
4218             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4219                                                               : VirtualBaseSpec;
4220             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4221                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4222 
4223             TyD = Type;
4224           }
4225         }
4226       }
4227 
4228       if (!TyD && BaseType.isNull()) {
4229         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4230           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4231         return true;
4232       }
4233     }
4234 
4235     if (BaseType.isNull()) {
4236       BaseType = Context.getTypeDeclType(TyD);
4237       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4238       if (SS.isSet()) {
4239         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4240                                              BaseType);
4241         TInfo = Context.CreateTypeSourceInfo(BaseType);
4242         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4243         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4244         TL.setElaboratedKeywordLoc(SourceLocation());
4245         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4246       }
4247     }
4248   }
4249 
4250   if (!TInfo)
4251     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4252 
4253   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4254 }
4255 
4256 MemInitResult
4257 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4258                              SourceLocation IdLoc) {
4259   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4260   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4261   assert((DirectMember || IndirectMember) &&
4262          "Member must be a FieldDecl or IndirectFieldDecl");
4263 
4264   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4265     return true;
4266 
4267   if (Member->isInvalidDecl())
4268     return true;
4269 
4270   MultiExprArg Args;
4271   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4272     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4273   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4274     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4275   } else {
4276     // Template instantiation doesn't reconstruct ParenListExprs for us.
4277     Args = Init;
4278   }
4279 
4280   SourceRange InitRange = Init->getSourceRange();
4281 
4282   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4283     // Can't check initialization for a member of dependent type or when
4284     // any of the arguments are type-dependent expressions.
4285     DiscardCleanupsInEvaluationContext();
4286   } else {
4287     bool InitList = false;
4288     if (isa<InitListExpr>(Init)) {
4289       InitList = true;
4290       Args = Init;
4291     }
4292 
4293     // Initialize the member.
4294     InitializedEntity MemberEntity =
4295       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4296                    : InitializedEntity::InitializeMember(IndirectMember,
4297                                                          nullptr);
4298     InitializationKind Kind =
4299         InitList ? InitializationKind::CreateDirectList(
4300                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4301                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4302                                                     InitRange.getEnd());
4303 
4304     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4305     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4306                                             nullptr);
4307     if (MemberInit.isInvalid())
4308       return true;
4309 
4310     // C++11 [class.base.init]p7:
4311     //   The initialization of each base and member constitutes a
4312     //   full-expression.
4313     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4314                                      /*DiscardedValue*/ false);
4315     if (MemberInit.isInvalid())
4316       return true;
4317 
4318     Init = MemberInit.get();
4319   }
4320 
4321   if (DirectMember) {
4322     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4323                                             InitRange.getBegin(), Init,
4324                                             InitRange.getEnd());
4325   } else {
4326     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4327                                             InitRange.getBegin(), Init,
4328                                             InitRange.getEnd());
4329   }
4330 }
4331 
4332 MemInitResult
4333 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4334                                  CXXRecordDecl *ClassDecl) {
4335   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4336   if (!LangOpts.CPlusPlus11)
4337     return Diag(NameLoc, diag::err_delegating_ctor)
4338       << TInfo->getTypeLoc().getLocalSourceRange();
4339   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4340 
4341   bool InitList = true;
4342   MultiExprArg Args = Init;
4343   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4344     InitList = false;
4345     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4346   }
4347 
4348   SourceRange InitRange = Init->getSourceRange();
4349   // Initialize the object.
4350   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4351                                      QualType(ClassDecl->getTypeForDecl(), 0));
4352   InitializationKind Kind =
4353       InitList ? InitializationKind::CreateDirectList(
4354                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4355                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4356                                                   InitRange.getEnd());
4357   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4358   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4359                                               Args, nullptr);
4360   if (DelegationInit.isInvalid())
4361     return true;
4362 
4363   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4364          "Delegating constructor with no target?");
4365 
4366   // C++11 [class.base.init]p7:
4367   //   The initialization of each base and member constitutes a
4368   //   full-expression.
4369   DelegationInit = ActOnFinishFullExpr(
4370       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4371   if (DelegationInit.isInvalid())
4372     return true;
4373 
4374   // If we are in a dependent context, template instantiation will
4375   // perform this type-checking again. Just save the arguments that we
4376   // received in a ParenListExpr.
4377   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4378   // of the information that we have about the base
4379   // initializer. However, deconstructing the ASTs is a dicey process,
4380   // and this approach is far more likely to get the corner cases right.
4381   if (CurContext->isDependentContext())
4382     DelegationInit = Init;
4383 
4384   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4385                                           DelegationInit.getAs<Expr>(),
4386                                           InitRange.getEnd());
4387 }
4388 
4389 MemInitResult
4390 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4391                            Expr *Init, CXXRecordDecl *ClassDecl,
4392                            SourceLocation EllipsisLoc) {
4393   SourceLocation BaseLoc
4394     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4395 
4396   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4397     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4398              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4399 
4400   // C++ [class.base.init]p2:
4401   //   [...] Unless the mem-initializer-id names a nonstatic data
4402   //   member of the constructor's class or a direct or virtual base
4403   //   of that class, the mem-initializer is ill-formed. A
4404   //   mem-initializer-list can initialize a base class using any
4405   //   name that denotes that base class type.
4406   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4407 
4408   SourceRange InitRange = Init->getSourceRange();
4409   if (EllipsisLoc.isValid()) {
4410     // This is a pack expansion.
4411     if (!BaseType->containsUnexpandedParameterPack())  {
4412       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4413         << SourceRange(BaseLoc, InitRange.getEnd());
4414 
4415       EllipsisLoc = SourceLocation();
4416     }
4417   } else {
4418     // Check for any unexpanded parameter packs.
4419     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4420       return true;
4421 
4422     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4423       return true;
4424   }
4425 
4426   // Check for direct and virtual base classes.
4427   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4428   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4429   if (!Dependent) {
4430     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4431                                        BaseType))
4432       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4433 
4434     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4435                         VirtualBaseSpec);
4436 
4437     // C++ [base.class.init]p2:
4438     // Unless the mem-initializer-id names a nonstatic data member of the
4439     // constructor's class or a direct or virtual base of that class, the
4440     // mem-initializer is ill-formed.
4441     if (!DirectBaseSpec && !VirtualBaseSpec) {
4442       // If the class has any dependent bases, then it's possible that
4443       // one of those types will resolve to the same type as
4444       // BaseType. Therefore, just treat this as a dependent base
4445       // class initialization.  FIXME: Should we try to check the
4446       // initialization anyway? It seems odd.
4447       if (ClassDecl->hasAnyDependentBases())
4448         Dependent = true;
4449       else
4450         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4451           << BaseType << Context.getTypeDeclType(ClassDecl)
4452           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4453     }
4454   }
4455 
4456   if (Dependent) {
4457     DiscardCleanupsInEvaluationContext();
4458 
4459     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4460                                             /*IsVirtual=*/false,
4461                                             InitRange.getBegin(), Init,
4462                                             InitRange.getEnd(), EllipsisLoc);
4463   }
4464 
4465   // C++ [base.class.init]p2:
4466   //   If a mem-initializer-id is ambiguous because it designates both
4467   //   a direct non-virtual base class and an inherited virtual base
4468   //   class, the mem-initializer is ill-formed.
4469   if (DirectBaseSpec && VirtualBaseSpec)
4470     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4471       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4472 
4473   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4474   if (!BaseSpec)
4475     BaseSpec = VirtualBaseSpec;
4476 
4477   // Initialize the base.
4478   bool InitList = true;
4479   MultiExprArg Args = Init;
4480   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4481     InitList = false;
4482     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4483   }
4484 
4485   InitializedEntity BaseEntity =
4486     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4487   InitializationKind Kind =
4488       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4489                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4490                                                   InitRange.getEnd());
4491   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4492   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4493   if (BaseInit.isInvalid())
4494     return true;
4495 
4496   // C++11 [class.base.init]p7:
4497   //   The initialization of each base and member constitutes a
4498   //   full-expression.
4499   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4500                                  /*DiscardedValue*/ false);
4501   if (BaseInit.isInvalid())
4502     return true;
4503 
4504   // If we are in a dependent context, template instantiation will
4505   // perform this type-checking again. Just save the arguments that we
4506   // received in a ParenListExpr.
4507   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4508   // of the information that we have about the base
4509   // initializer. However, deconstructing the ASTs is a dicey process,
4510   // and this approach is far more likely to get the corner cases right.
4511   if (CurContext->isDependentContext())
4512     BaseInit = Init;
4513 
4514   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4515                                           BaseSpec->isVirtual(),
4516                                           InitRange.getBegin(),
4517                                           BaseInit.getAs<Expr>(),
4518                                           InitRange.getEnd(), EllipsisLoc);
4519 }
4520 
4521 // Create a static_cast\<T&&>(expr).
4522 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4523   if (T.isNull()) T = E->getType();
4524   QualType TargetType = SemaRef.BuildReferenceType(
4525       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4526   SourceLocation ExprLoc = E->getBeginLoc();
4527   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4528       TargetType, ExprLoc);
4529 
4530   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4531                                    SourceRange(ExprLoc, ExprLoc),
4532                                    E->getSourceRange()).get();
4533 }
4534 
4535 /// ImplicitInitializerKind - How an implicit base or member initializer should
4536 /// initialize its base or member.
4537 enum ImplicitInitializerKind {
4538   IIK_Default,
4539   IIK_Copy,
4540   IIK_Move,
4541   IIK_Inherit
4542 };
4543 
4544 static bool
4545 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4546                              ImplicitInitializerKind ImplicitInitKind,
4547                              CXXBaseSpecifier *BaseSpec,
4548                              bool IsInheritedVirtualBase,
4549                              CXXCtorInitializer *&CXXBaseInit) {
4550   InitializedEntity InitEntity
4551     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4552                                         IsInheritedVirtualBase);
4553 
4554   ExprResult BaseInit;
4555 
4556   switch (ImplicitInitKind) {
4557   case IIK_Inherit:
4558   case IIK_Default: {
4559     InitializationKind InitKind
4560       = InitializationKind::CreateDefault(Constructor->getLocation());
4561     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4562     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4563     break;
4564   }
4565 
4566   case IIK_Move:
4567   case IIK_Copy: {
4568     bool Moving = ImplicitInitKind == IIK_Move;
4569     ParmVarDecl *Param = Constructor->getParamDecl(0);
4570     QualType ParamType = Param->getType().getNonReferenceType();
4571 
4572     Expr *CopyCtorArg =
4573       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4574                           SourceLocation(), Param, false,
4575                           Constructor->getLocation(), ParamType,
4576                           VK_LValue, nullptr);
4577 
4578     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4579 
4580     // Cast to the base class to avoid ambiguities.
4581     QualType ArgTy =
4582       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4583                                        ParamType.getQualifiers());
4584 
4585     if (Moving) {
4586       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4587     }
4588 
4589     CXXCastPath BasePath;
4590     BasePath.push_back(BaseSpec);
4591     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4592                                             CK_UncheckedDerivedToBase,
4593                                             Moving ? VK_XValue : VK_LValue,
4594                                             &BasePath).get();
4595 
4596     InitializationKind InitKind
4597       = InitializationKind::CreateDirect(Constructor->getLocation(),
4598                                          SourceLocation(), SourceLocation());
4599     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4600     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4601     break;
4602   }
4603   }
4604 
4605   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4606   if (BaseInit.isInvalid())
4607     return true;
4608 
4609   CXXBaseInit =
4610     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4611                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4612                                                         SourceLocation()),
4613                                              BaseSpec->isVirtual(),
4614                                              SourceLocation(),
4615                                              BaseInit.getAs<Expr>(),
4616                                              SourceLocation(),
4617                                              SourceLocation());
4618 
4619   return false;
4620 }
4621 
4622 static bool RefersToRValueRef(Expr *MemRef) {
4623   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4624   return Referenced->getType()->isRValueReferenceType();
4625 }
4626 
4627 static bool
4628 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4629                                ImplicitInitializerKind ImplicitInitKind,
4630                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4631                                CXXCtorInitializer *&CXXMemberInit) {
4632   if (Field->isInvalidDecl())
4633     return true;
4634 
4635   SourceLocation Loc = Constructor->getLocation();
4636 
4637   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4638     bool Moving = ImplicitInitKind == IIK_Move;
4639     ParmVarDecl *Param = Constructor->getParamDecl(0);
4640     QualType ParamType = Param->getType().getNonReferenceType();
4641 
4642     // Suppress copying zero-width bitfields.
4643     if (Field->isZeroLengthBitField(SemaRef.Context))
4644       return false;
4645 
4646     Expr *MemberExprBase =
4647       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4648                           SourceLocation(), Param, false,
4649                           Loc, ParamType, VK_LValue, nullptr);
4650 
4651     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4652 
4653     if (Moving) {
4654       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4655     }
4656 
4657     // Build a reference to this field within the parameter.
4658     CXXScopeSpec SS;
4659     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4660                               Sema::LookupMemberName);
4661     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4662                                   : cast<ValueDecl>(Field), AS_public);
4663     MemberLookup.resolveKind();
4664     ExprResult CtorArg
4665       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4666                                          ParamType, Loc,
4667                                          /*IsArrow=*/false,
4668                                          SS,
4669                                          /*TemplateKWLoc=*/SourceLocation(),
4670                                          /*FirstQualifierInScope=*/nullptr,
4671                                          MemberLookup,
4672                                          /*TemplateArgs=*/nullptr,
4673                                          /*S*/nullptr);
4674     if (CtorArg.isInvalid())
4675       return true;
4676 
4677     // C++11 [class.copy]p15:
4678     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4679     //     with static_cast<T&&>(x.m);
4680     if (RefersToRValueRef(CtorArg.get())) {
4681       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4682     }
4683 
4684     InitializedEntity Entity =
4685         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4686                                                        /*Implicit*/ true)
4687                  : InitializedEntity::InitializeMember(Field, nullptr,
4688                                                        /*Implicit*/ true);
4689 
4690     // Direct-initialize to use the copy constructor.
4691     InitializationKind InitKind =
4692       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4693 
4694     Expr *CtorArgE = CtorArg.getAs<Expr>();
4695     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4696     ExprResult MemberInit =
4697         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4698     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4699     if (MemberInit.isInvalid())
4700       return true;
4701 
4702     if (Indirect)
4703       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4704           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4705     else
4706       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4707           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4708     return false;
4709   }
4710 
4711   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4712          "Unhandled implicit init kind!");
4713 
4714   QualType FieldBaseElementType =
4715     SemaRef.Context.getBaseElementType(Field->getType());
4716 
4717   if (FieldBaseElementType->isRecordType()) {
4718     InitializedEntity InitEntity =
4719         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4720                                                        /*Implicit*/ true)
4721                  : InitializedEntity::InitializeMember(Field, nullptr,
4722                                                        /*Implicit*/ true);
4723     InitializationKind InitKind =
4724       InitializationKind::CreateDefault(Loc);
4725 
4726     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4727     ExprResult MemberInit =
4728       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4729 
4730     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4731     if (MemberInit.isInvalid())
4732       return true;
4733 
4734     if (Indirect)
4735       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4736                                                                Indirect, Loc,
4737                                                                Loc,
4738                                                                MemberInit.get(),
4739                                                                Loc);
4740     else
4741       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4742                                                                Field, Loc, Loc,
4743                                                                MemberInit.get(),
4744                                                                Loc);
4745     return false;
4746   }
4747 
4748   if (!Field->getParent()->isUnion()) {
4749     if (FieldBaseElementType->isReferenceType()) {
4750       SemaRef.Diag(Constructor->getLocation(),
4751                    diag::err_uninitialized_member_in_ctor)
4752       << (int)Constructor->isImplicit()
4753       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4754       << 0 << Field->getDeclName();
4755       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4756       return true;
4757     }
4758 
4759     if (FieldBaseElementType.isConstQualified()) {
4760       SemaRef.Diag(Constructor->getLocation(),
4761                    diag::err_uninitialized_member_in_ctor)
4762       << (int)Constructor->isImplicit()
4763       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4764       << 1 << Field->getDeclName();
4765       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4766       return true;
4767     }
4768   }
4769 
4770   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4771     // ARC and Weak:
4772     //   Default-initialize Objective-C pointers to NULL.
4773     CXXMemberInit
4774       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4775                                                  Loc, Loc,
4776                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4777                                                  Loc);
4778     return false;
4779   }
4780 
4781   // Nothing to initialize.
4782   CXXMemberInit = nullptr;
4783   return false;
4784 }
4785 
4786 namespace {
4787 struct BaseAndFieldInfo {
4788   Sema &S;
4789   CXXConstructorDecl *Ctor;
4790   bool AnyErrorsInInits;
4791   ImplicitInitializerKind IIK;
4792   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4793   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4794   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4795 
4796   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4797     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4798     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4799     if (Ctor->getInheritedConstructor())
4800       IIK = IIK_Inherit;
4801     else if (Generated && Ctor->isCopyConstructor())
4802       IIK = IIK_Copy;
4803     else if (Generated && Ctor->isMoveConstructor())
4804       IIK = IIK_Move;
4805     else
4806       IIK = IIK_Default;
4807   }
4808 
4809   bool isImplicitCopyOrMove() const {
4810     switch (IIK) {
4811     case IIK_Copy:
4812     case IIK_Move:
4813       return true;
4814 
4815     case IIK_Default:
4816     case IIK_Inherit:
4817       return false;
4818     }
4819 
4820     llvm_unreachable("Invalid ImplicitInitializerKind!");
4821   }
4822 
4823   bool addFieldInitializer(CXXCtorInitializer *Init) {
4824     AllToInit.push_back(Init);
4825 
4826     // Check whether this initializer makes the field "used".
4827     if (Init->getInit()->HasSideEffects(S.Context))
4828       S.UnusedPrivateFields.remove(Init->getAnyMember());
4829 
4830     return false;
4831   }
4832 
4833   bool isInactiveUnionMember(FieldDecl *Field) {
4834     RecordDecl *Record = Field->getParent();
4835     if (!Record->isUnion())
4836       return false;
4837 
4838     if (FieldDecl *Active =
4839             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4840       return Active != Field->getCanonicalDecl();
4841 
4842     // In an implicit copy or move constructor, ignore any in-class initializer.
4843     if (isImplicitCopyOrMove())
4844       return true;
4845 
4846     // If there's no explicit initialization, the field is active only if it
4847     // has an in-class initializer...
4848     if (Field->hasInClassInitializer())
4849       return false;
4850     // ... or it's an anonymous struct or union whose class has an in-class
4851     // initializer.
4852     if (!Field->isAnonymousStructOrUnion())
4853       return true;
4854     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4855     return !FieldRD->hasInClassInitializer();
4856   }
4857 
4858   /// Determine whether the given field is, or is within, a union member
4859   /// that is inactive (because there was an initializer given for a different
4860   /// member of the union, or because the union was not initialized at all).
4861   bool isWithinInactiveUnionMember(FieldDecl *Field,
4862                                    IndirectFieldDecl *Indirect) {
4863     if (!Indirect)
4864       return isInactiveUnionMember(Field);
4865 
4866     for (auto *C : Indirect->chain()) {
4867       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4868       if (Field && isInactiveUnionMember(Field))
4869         return true;
4870     }
4871     return false;
4872   }
4873 };
4874 }
4875 
4876 /// Determine whether the given type is an incomplete or zero-lenfgth
4877 /// array type.
4878 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4879   if (T->isIncompleteArrayType())
4880     return true;
4881 
4882   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4883     if (!ArrayT->getSize())
4884       return true;
4885 
4886     T = ArrayT->getElementType();
4887   }
4888 
4889   return false;
4890 }
4891 
4892 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4893                                     FieldDecl *Field,
4894                                     IndirectFieldDecl *Indirect = nullptr) {
4895   if (Field->isInvalidDecl())
4896     return false;
4897 
4898   // Overwhelmingly common case: we have a direct initializer for this field.
4899   if (CXXCtorInitializer *Init =
4900           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4901     return Info.addFieldInitializer(Init);
4902 
4903   // C++11 [class.base.init]p8:
4904   //   if the entity is a non-static data member that has a
4905   //   brace-or-equal-initializer and either
4906   //   -- the constructor's class is a union and no other variant member of that
4907   //      union is designated by a mem-initializer-id or
4908   //   -- the constructor's class is not a union, and, if the entity is a member
4909   //      of an anonymous union, no other member of that union is designated by
4910   //      a mem-initializer-id,
4911   //   the entity is initialized as specified in [dcl.init].
4912   //
4913   // We also apply the same rules to handle anonymous structs within anonymous
4914   // unions.
4915   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4916     return false;
4917 
4918   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4919     ExprResult DIE =
4920         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4921     if (DIE.isInvalid())
4922       return true;
4923 
4924     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4925     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4926 
4927     CXXCtorInitializer *Init;
4928     if (Indirect)
4929       Init = new (SemaRef.Context)
4930           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4931                              SourceLocation(), DIE.get(), SourceLocation());
4932     else
4933       Init = new (SemaRef.Context)
4934           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4935                              SourceLocation(), DIE.get(), SourceLocation());
4936     return Info.addFieldInitializer(Init);
4937   }
4938 
4939   // Don't initialize incomplete or zero-length arrays.
4940   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4941     return false;
4942 
4943   // Don't try to build an implicit initializer if there were semantic
4944   // errors in any of the initializers (and therefore we might be
4945   // missing some that the user actually wrote).
4946   if (Info.AnyErrorsInInits)
4947     return false;
4948 
4949   CXXCtorInitializer *Init = nullptr;
4950   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4951                                      Indirect, Init))
4952     return true;
4953 
4954   if (!Init)
4955     return false;
4956 
4957   return Info.addFieldInitializer(Init);
4958 }
4959 
4960 bool
4961 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4962                                CXXCtorInitializer *Initializer) {
4963   assert(Initializer->isDelegatingInitializer());
4964   Constructor->setNumCtorInitializers(1);
4965   CXXCtorInitializer **initializer =
4966     new (Context) CXXCtorInitializer*[1];
4967   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4968   Constructor->setCtorInitializers(initializer);
4969 
4970   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4971     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4972     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4973   }
4974 
4975   DelegatingCtorDecls.push_back(Constructor);
4976 
4977   DiagnoseUninitializedFields(*this, Constructor);
4978 
4979   return false;
4980 }
4981 
4982 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4983                                ArrayRef<CXXCtorInitializer *> Initializers) {
4984   if (Constructor->isDependentContext()) {
4985     // Just store the initializers as written, they will be checked during
4986     // instantiation.
4987     if (!Initializers.empty()) {
4988       Constructor->setNumCtorInitializers(Initializers.size());
4989       CXXCtorInitializer **baseOrMemberInitializers =
4990         new (Context) CXXCtorInitializer*[Initializers.size()];
4991       memcpy(baseOrMemberInitializers, Initializers.data(),
4992              Initializers.size() * sizeof(CXXCtorInitializer*));
4993       Constructor->setCtorInitializers(baseOrMemberInitializers);
4994     }
4995 
4996     // Let template instantiation know whether we had errors.
4997     if (AnyErrors)
4998       Constructor->setInvalidDecl();
4999 
5000     return false;
5001   }
5002 
5003   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5004 
5005   // We need to build the initializer AST according to order of construction
5006   // and not what user specified in the Initializers list.
5007   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5008   if (!ClassDecl)
5009     return true;
5010 
5011   bool HadError = false;
5012 
5013   for (unsigned i = 0; i < Initializers.size(); i++) {
5014     CXXCtorInitializer *Member = Initializers[i];
5015 
5016     if (Member->isBaseInitializer())
5017       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5018     else {
5019       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5020 
5021       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5022         for (auto *C : F->chain()) {
5023           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5024           if (FD && FD->getParent()->isUnion())
5025             Info.ActiveUnionMember.insert(std::make_pair(
5026                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5027         }
5028       } else if (FieldDecl *FD = Member->getMember()) {
5029         if (FD->getParent()->isUnion())
5030           Info.ActiveUnionMember.insert(std::make_pair(
5031               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5032       }
5033     }
5034   }
5035 
5036   // Keep track of the direct virtual bases.
5037   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5038   for (auto &I : ClassDecl->bases()) {
5039     if (I.isVirtual())
5040       DirectVBases.insert(&I);
5041   }
5042 
5043   // Push virtual bases before others.
5044   for (auto &VBase : ClassDecl->vbases()) {
5045     if (CXXCtorInitializer *Value
5046         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5047       // [class.base.init]p7, per DR257:
5048       //   A mem-initializer where the mem-initializer-id names a virtual base
5049       //   class is ignored during execution of a constructor of any class that
5050       //   is not the most derived class.
5051       if (ClassDecl->isAbstract()) {
5052         // FIXME: Provide a fixit to remove the base specifier. This requires
5053         // tracking the location of the associated comma for a base specifier.
5054         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5055           << VBase.getType() << ClassDecl;
5056         DiagnoseAbstractType(ClassDecl);
5057       }
5058 
5059       Info.AllToInit.push_back(Value);
5060     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5061       // [class.base.init]p8, per DR257:
5062       //   If a given [...] base class is not named by a mem-initializer-id
5063       //   [...] and the entity is not a virtual base class of an abstract
5064       //   class, then [...] the entity is default-initialized.
5065       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5066       CXXCtorInitializer *CXXBaseInit;
5067       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5068                                        &VBase, IsInheritedVirtualBase,
5069                                        CXXBaseInit)) {
5070         HadError = true;
5071         continue;
5072       }
5073 
5074       Info.AllToInit.push_back(CXXBaseInit);
5075     }
5076   }
5077 
5078   // Non-virtual bases.
5079   for (auto &Base : ClassDecl->bases()) {
5080     // Virtuals are in the virtual base list and already constructed.
5081     if (Base.isVirtual())
5082       continue;
5083 
5084     if (CXXCtorInitializer *Value
5085           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5086       Info.AllToInit.push_back(Value);
5087     } else if (!AnyErrors) {
5088       CXXCtorInitializer *CXXBaseInit;
5089       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5090                                        &Base, /*IsInheritedVirtualBase=*/false,
5091                                        CXXBaseInit)) {
5092         HadError = true;
5093         continue;
5094       }
5095 
5096       Info.AllToInit.push_back(CXXBaseInit);
5097     }
5098   }
5099 
5100   // Fields.
5101   for (auto *Mem : ClassDecl->decls()) {
5102     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5103       // C++ [class.bit]p2:
5104       //   A declaration for a bit-field that omits the identifier declares an
5105       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5106       //   initialized.
5107       if (F->isUnnamedBitfield())
5108         continue;
5109 
5110       // If we're not generating the implicit copy/move constructor, then we'll
5111       // handle anonymous struct/union fields based on their individual
5112       // indirect fields.
5113       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5114         continue;
5115 
5116       if (CollectFieldInitializer(*this, Info, F))
5117         HadError = true;
5118       continue;
5119     }
5120 
5121     // Beyond this point, we only consider default initialization.
5122     if (Info.isImplicitCopyOrMove())
5123       continue;
5124 
5125     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5126       if (F->getType()->isIncompleteArrayType()) {
5127         assert(ClassDecl->hasFlexibleArrayMember() &&
5128                "Incomplete array type is not valid");
5129         continue;
5130       }
5131 
5132       // Initialize each field of an anonymous struct individually.
5133       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5134         HadError = true;
5135 
5136       continue;
5137     }
5138   }
5139 
5140   unsigned NumInitializers = Info.AllToInit.size();
5141   if (NumInitializers > 0) {
5142     Constructor->setNumCtorInitializers(NumInitializers);
5143     CXXCtorInitializer **baseOrMemberInitializers =
5144       new (Context) CXXCtorInitializer*[NumInitializers];
5145     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5146            NumInitializers * sizeof(CXXCtorInitializer*));
5147     Constructor->setCtorInitializers(baseOrMemberInitializers);
5148 
5149     // Constructors implicitly reference the base and member
5150     // destructors.
5151     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5152                                            Constructor->getParent());
5153   }
5154 
5155   return HadError;
5156 }
5157 
5158 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5159   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5160     const RecordDecl *RD = RT->getDecl();
5161     if (RD->isAnonymousStructOrUnion()) {
5162       for (auto *Field : RD->fields())
5163         PopulateKeysForFields(Field, IdealInits);
5164       return;
5165     }
5166   }
5167   IdealInits.push_back(Field->getCanonicalDecl());
5168 }
5169 
5170 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5171   return Context.getCanonicalType(BaseType).getTypePtr();
5172 }
5173 
5174 static const void *GetKeyForMember(ASTContext &Context,
5175                                    CXXCtorInitializer *Member) {
5176   if (!Member->isAnyMemberInitializer())
5177     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5178 
5179   return Member->getAnyMember()->getCanonicalDecl();
5180 }
5181 
5182 static void DiagnoseBaseOrMemInitializerOrder(
5183     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5184     ArrayRef<CXXCtorInitializer *> Inits) {
5185   if (Constructor->getDeclContext()->isDependentContext())
5186     return;
5187 
5188   // Don't check initializers order unless the warning is enabled at the
5189   // location of at least one initializer.
5190   bool ShouldCheckOrder = false;
5191   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5192     CXXCtorInitializer *Init = Inits[InitIndex];
5193     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5194                                  Init->getSourceLocation())) {
5195       ShouldCheckOrder = true;
5196       break;
5197     }
5198   }
5199   if (!ShouldCheckOrder)
5200     return;
5201 
5202   // Build the list of bases and members in the order that they'll
5203   // actually be initialized.  The explicit initializers should be in
5204   // this same order but may be missing things.
5205   SmallVector<const void*, 32> IdealInitKeys;
5206 
5207   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5208 
5209   // 1. Virtual bases.
5210   for (const auto &VBase : ClassDecl->vbases())
5211     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5212 
5213   // 2. Non-virtual bases.
5214   for (const auto &Base : ClassDecl->bases()) {
5215     if (Base.isVirtual())
5216       continue;
5217     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5218   }
5219 
5220   // 3. Direct fields.
5221   for (auto *Field : ClassDecl->fields()) {
5222     if (Field->isUnnamedBitfield())
5223       continue;
5224 
5225     PopulateKeysForFields(Field, IdealInitKeys);
5226   }
5227 
5228   unsigned NumIdealInits = IdealInitKeys.size();
5229   unsigned IdealIndex = 0;
5230 
5231   CXXCtorInitializer *PrevInit = nullptr;
5232   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5233     CXXCtorInitializer *Init = Inits[InitIndex];
5234     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5235 
5236     // Scan forward to try to find this initializer in the idealized
5237     // initializers list.
5238     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5239       if (InitKey == IdealInitKeys[IdealIndex])
5240         break;
5241 
5242     // If we didn't find this initializer, it must be because we
5243     // scanned past it on a previous iteration.  That can only
5244     // happen if we're out of order;  emit a warning.
5245     if (IdealIndex == NumIdealInits && PrevInit) {
5246       Sema::SemaDiagnosticBuilder D =
5247         SemaRef.Diag(PrevInit->getSourceLocation(),
5248                      diag::warn_initializer_out_of_order);
5249 
5250       if (PrevInit->isAnyMemberInitializer())
5251         D << 0 << PrevInit->getAnyMember()->getDeclName();
5252       else
5253         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5254 
5255       if (Init->isAnyMemberInitializer())
5256         D << 0 << Init->getAnyMember()->getDeclName();
5257       else
5258         D << 1 << Init->getTypeSourceInfo()->getType();
5259 
5260       // Move back to the initializer's location in the ideal list.
5261       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5262         if (InitKey == IdealInitKeys[IdealIndex])
5263           break;
5264 
5265       assert(IdealIndex < NumIdealInits &&
5266              "initializer not found in initializer list");
5267     }
5268 
5269     PrevInit = Init;
5270   }
5271 }
5272 
5273 namespace {
5274 bool CheckRedundantInit(Sema &S,
5275                         CXXCtorInitializer *Init,
5276                         CXXCtorInitializer *&PrevInit) {
5277   if (!PrevInit) {
5278     PrevInit = Init;
5279     return false;
5280   }
5281 
5282   if (FieldDecl *Field = Init->getAnyMember())
5283     S.Diag(Init->getSourceLocation(),
5284            diag::err_multiple_mem_initialization)
5285       << Field->getDeclName()
5286       << Init->getSourceRange();
5287   else {
5288     const Type *BaseClass = Init->getBaseClass();
5289     assert(BaseClass && "neither field nor base");
5290     S.Diag(Init->getSourceLocation(),
5291            diag::err_multiple_base_initialization)
5292       << QualType(BaseClass, 0)
5293       << Init->getSourceRange();
5294   }
5295   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5296     << 0 << PrevInit->getSourceRange();
5297 
5298   return true;
5299 }
5300 
5301 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5302 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5303 
5304 bool CheckRedundantUnionInit(Sema &S,
5305                              CXXCtorInitializer *Init,
5306                              RedundantUnionMap &Unions) {
5307   FieldDecl *Field = Init->getAnyMember();
5308   RecordDecl *Parent = Field->getParent();
5309   NamedDecl *Child = Field;
5310 
5311   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5312     if (Parent->isUnion()) {
5313       UnionEntry &En = Unions[Parent];
5314       if (En.first && En.first != Child) {
5315         S.Diag(Init->getSourceLocation(),
5316                diag::err_multiple_mem_union_initialization)
5317           << Field->getDeclName()
5318           << Init->getSourceRange();
5319         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5320           << 0 << En.second->getSourceRange();
5321         return true;
5322       }
5323       if (!En.first) {
5324         En.first = Child;
5325         En.second = Init;
5326       }
5327       if (!Parent->isAnonymousStructOrUnion())
5328         return false;
5329     }
5330 
5331     Child = Parent;
5332     Parent = cast<RecordDecl>(Parent->getDeclContext());
5333   }
5334 
5335   return false;
5336 }
5337 }
5338 
5339 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5340 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5341                                 SourceLocation ColonLoc,
5342                                 ArrayRef<CXXCtorInitializer*> MemInits,
5343                                 bool AnyErrors) {
5344   if (!ConstructorDecl)
5345     return;
5346 
5347   AdjustDeclIfTemplate(ConstructorDecl);
5348 
5349   CXXConstructorDecl *Constructor
5350     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5351 
5352   if (!Constructor) {
5353     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5354     return;
5355   }
5356 
5357   // Mapping for the duplicate initializers check.
5358   // For member initializers, this is keyed with a FieldDecl*.
5359   // For base initializers, this is keyed with a Type*.
5360   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5361 
5362   // Mapping for the inconsistent anonymous-union initializers check.
5363   RedundantUnionMap MemberUnions;
5364 
5365   bool HadError = false;
5366   for (unsigned i = 0; i < MemInits.size(); i++) {
5367     CXXCtorInitializer *Init = MemInits[i];
5368 
5369     // Set the source order index.
5370     Init->setSourceOrder(i);
5371 
5372     if (Init->isAnyMemberInitializer()) {
5373       const void *Key = GetKeyForMember(Context, Init);
5374       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5375           CheckRedundantUnionInit(*this, Init, MemberUnions))
5376         HadError = true;
5377     } else if (Init->isBaseInitializer()) {
5378       const void *Key = GetKeyForMember(Context, Init);
5379       if (CheckRedundantInit(*this, Init, Members[Key]))
5380         HadError = true;
5381     } else {
5382       assert(Init->isDelegatingInitializer());
5383       // This must be the only initializer
5384       if (MemInits.size() != 1) {
5385         Diag(Init->getSourceLocation(),
5386              diag::err_delegating_initializer_alone)
5387           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5388         // We will treat this as being the only initializer.
5389       }
5390       SetDelegatingInitializer(Constructor, MemInits[i]);
5391       // Return immediately as the initializer is set.
5392       return;
5393     }
5394   }
5395 
5396   if (HadError)
5397     return;
5398 
5399   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5400 
5401   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5402 
5403   DiagnoseUninitializedFields(*this, Constructor);
5404 }
5405 
5406 void
5407 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5408                                              CXXRecordDecl *ClassDecl) {
5409   // Ignore dependent contexts. Also ignore unions, since their members never
5410   // have destructors implicitly called.
5411   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5412     return;
5413 
5414   // FIXME: all the access-control diagnostics are positioned on the
5415   // field/base declaration.  That's probably good; that said, the
5416   // user might reasonably want to know why the destructor is being
5417   // emitted, and we currently don't say.
5418 
5419   // Non-static data members.
5420   for (auto *Field : ClassDecl->fields()) {
5421     if (Field->isInvalidDecl())
5422       continue;
5423 
5424     // Don't destroy incomplete or zero-length arrays.
5425     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5426       continue;
5427 
5428     QualType FieldType = Context.getBaseElementType(Field->getType());
5429 
5430     const RecordType* RT = FieldType->getAs<RecordType>();
5431     if (!RT)
5432       continue;
5433 
5434     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5435     if (FieldClassDecl->isInvalidDecl())
5436       continue;
5437     if (FieldClassDecl->hasIrrelevantDestructor())
5438       continue;
5439     // The destructor for an implicit anonymous union member is never invoked.
5440     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5441       continue;
5442 
5443     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5444     assert(Dtor && "No dtor found for FieldClassDecl!");
5445     CheckDestructorAccess(Field->getLocation(), Dtor,
5446                           PDiag(diag::err_access_dtor_field)
5447                             << Field->getDeclName()
5448                             << FieldType);
5449 
5450     MarkFunctionReferenced(Location, Dtor);
5451     DiagnoseUseOfDecl(Dtor, Location);
5452   }
5453 
5454   // We only potentially invoke the destructors of potentially constructed
5455   // subobjects.
5456   bool VisitVirtualBases = !ClassDecl->isAbstract();
5457 
5458   // If the destructor exists and has already been marked used in the MS ABI,
5459   // then virtual base destructors have already been checked and marked used.
5460   // Skip checking them again to avoid duplicate diagnostics.
5461   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5462     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5463     if (Dtor && Dtor->isUsed())
5464       VisitVirtualBases = false;
5465   }
5466 
5467   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5468 
5469   // Bases.
5470   for (const auto &Base : ClassDecl->bases()) {
5471     // Bases are always records in a well-formed non-dependent class.
5472     const RecordType *RT = Base.getType()->getAs<RecordType>();
5473 
5474     // Remember direct virtual bases.
5475     if (Base.isVirtual()) {
5476       if (!VisitVirtualBases)
5477         continue;
5478       DirectVirtualBases.insert(RT);
5479     }
5480 
5481     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5482     // If our base class is invalid, we probably can't get its dtor anyway.
5483     if (BaseClassDecl->isInvalidDecl())
5484       continue;
5485     if (BaseClassDecl->hasIrrelevantDestructor())
5486       continue;
5487 
5488     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5489     assert(Dtor && "No dtor found for BaseClassDecl!");
5490 
5491     // FIXME: caret should be on the start of the class name
5492     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5493                           PDiag(diag::err_access_dtor_base)
5494                               << Base.getType() << Base.getSourceRange(),
5495                           Context.getTypeDeclType(ClassDecl));
5496 
5497     MarkFunctionReferenced(Location, Dtor);
5498     DiagnoseUseOfDecl(Dtor, Location);
5499   }
5500 
5501   if (VisitVirtualBases)
5502     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5503                                          &DirectVirtualBases);
5504 }
5505 
5506 void Sema::MarkVirtualBaseDestructorsReferenced(
5507     SourceLocation Location, CXXRecordDecl *ClassDecl,
5508     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5509   // Virtual bases.
5510   for (const auto &VBase : ClassDecl->vbases()) {
5511     // Bases are always records in a well-formed non-dependent class.
5512     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5513 
5514     // Ignore already visited direct virtual bases.
5515     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5516       continue;
5517 
5518     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5519     // If our base class is invalid, we probably can't get its dtor anyway.
5520     if (BaseClassDecl->isInvalidDecl())
5521       continue;
5522     if (BaseClassDecl->hasIrrelevantDestructor())
5523       continue;
5524 
5525     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5526     assert(Dtor && "No dtor found for BaseClassDecl!");
5527     if (CheckDestructorAccess(
5528             ClassDecl->getLocation(), Dtor,
5529             PDiag(diag::err_access_dtor_vbase)
5530                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5531             Context.getTypeDeclType(ClassDecl)) ==
5532         AR_accessible) {
5533       CheckDerivedToBaseConversion(
5534           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5535           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5536           SourceRange(), DeclarationName(), nullptr);
5537     }
5538 
5539     MarkFunctionReferenced(Location, Dtor);
5540     DiagnoseUseOfDecl(Dtor, Location);
5541   }
5542 }
5543 
5544 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5545   if (!CDtorDecl)
5546     return;
5547 
5548   if (CXXConstructorDecl *Constructor
5549       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5550     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5551     DiagnoseUninitializedFields(*this, Constructor);
5552   }
5553 }
5554 
5555 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5556   if (!getLangOpts().CPlusPlus)
5557     return false;
5558 
5559   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5560   if (!RD)
5561     return false;
5562 
5563   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5564   // class template specialization here, but doing so breaks a lot of code.
5565 
5566   // We can't answer whether something is abstract until it has a
5567   // definition. If it's currently being defined, we'll walk back
5568   // over all the declarations when we have a full definition.
5569   const CXXRecordDecl *Def = RD->getDefinition();
5570   if (!Def || Def->isBeingDefined())
5571     return false;
5572 
5573   return RD->isAbstract();
5574 }
5575 
5576 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5577                                   TypeDiagnoser &Diagnoser) {
5578   if (!isAbstractType(Loc, T))
5579     return false;
5580 
5581   T = Context.getBaseElementType(T);
5582   Diagnoser.diagnose(*this, Loc, T);
5583   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5584   return true;
5585 }
5586 
5587 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5588   // Check if we've already emitted the list of pure virtual functions
5589   // for this class.
5590   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5591     return;
5592 
5593   // If the diagnostic is suppressed, don't emit the notes. We're only
5594   // going to emit them once, so try to attach them to a diagnostic we're
5595   // actually going to show.
5596   if (Diags.isLastDiagnosticIgnored())
5597     return;
5598 
5599   CXXFinalOverriderMap FinalOverriders;
5600   RD->getFinalOverriders(FinalOverriders);
5601 
5602   // Keep a set of seen pure methods so we won't diagnose the same method
5603   // more than once.
5604   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5605 
5606   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5607                                    MEnd = FinalOverriders.end();
5608        M != MEnd;
5609        ++M) {
5610     for (OverridingMethods::iterator SO = M->second.begin(),
5611                                   SOEnd = M->second.end();
5612          SO != SOEnd; ++SO) {
5613       // C++ [class.abstract]p4:
5614       //   A class is abstract if it contains or inherits at least one
5615       //   pure virtual function for which the final overrider is pure
5616       //   virtual.
5617 
5618       //
5619       if (SO->second.size() != 1)
5620         continue;
5621 
5622       if (!SO->second.front().Method->isPure())
5623         continue;
5624 
5625       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5626         continue;
5627 
5628       Diag(SO->second.front().Method->getLocation(),
5629            diag::note_pure_virtual_function)
5630         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5631     }
5632   }
5633 
5634   if (!PureVirtualClassDiagSet)
5635     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5636   PureVirtualClassDiagSet->insert(RD);
5637 }
5638 
5639 namespace {
5640 struct AbstractUsageInfo {
5641   Sema &S;
5642   CXXRecordDecl *Record;
5643   CanQualType AbstractType;
5644   bool Invalid;
5645 
5646   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5647     : S(S), Record(Record),
5648       AbstractType(S.Context.getCanonicalType(
5649                    S.Context.getTypeDeclType(Record))),
5650       Invalid(false) {}
5651 
5652   void DiagnoseAbstractType() {
5653     if (Invalid) return;
5654     S.DiagnoseAbstractType(Record);
5655     Invalid = true;
5656   }
5657 
5658   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5659 };
5660 
5661 struct CheckAbstractUsage {
5662   AbstractUsageInfo &Info;
5663   const NamedDecl *Ctx;
5664 
5665   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5666     : Info(Info), Ctx(Ctx) {}
5667 
5668   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5669     switch (TL.getTypeLocClass()) {
5670 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5671 #define TYPELOC(CLASS, PARENT) \
5672     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5673 #include "clang/AST/TypeLocNodes.def"
5674     }
5675   }
5676 
5677   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5678     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5679     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5680       if (!TL.getParam(I))
5681         continue;
5682 
5683       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5684       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5685     }
5686   }
5687 
5688   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5689     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5690   }
5691 
5692   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5693     // Visit the type parameters from a permissive context.
5694     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5695       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5696       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5697         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5698           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5699       // TODO: other template argument types?
5700     }
5701   }
5702 
5703   // Visit pointee types from a permissive context.
5704 #define CheckPolymorphic(Type) \
5705   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5706     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5707   }
5708   CheckPolymorphic(PointerTypeLoc)
5709   CheckPolymorphic(ReferenceTypeLoc)
5710   CheckPolymorphic(MemberPointerTypeLoc)
5711   CheckPolymorphic(BlockPointerTypeLoc)
5712   CheckPolymorphic(AtomicTypeLoc)
5713 
5714   /// Handle all the types we haven't given a more specific
5715   /// implementation for above.
5716   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5717     // Every other kind of type that we haven't called out already
5718     // that has an inner type is either (1) sugar or (2) contains that
5719     // inner type in some way as a subobject.
5720     if (TypeLoc Next = TL.getNextTypeLoc())
5721       return Visit(Next, Sel);
5722 
5723     // If there's no inner type and we're in a permissive context,
5724     // don't diagnose.
5725     if (Sel == Sema::AbstractNone) return;
5726 
5727     // Check whether the type matches the abstract type.
5728     QualType T = TL.getType();
5729     if (T->isArrayType()) {
5730       Sel = Sema::AbstractArrayType;
5731       T = Info.S.Context.getBaseElementType(T);
5732     }
5733     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5734     if (CT != Info.AbstractType) return;
5735 
5736     // It matched; do some magic.
5737     if (Sel == Sema::AbstractArrayType) {
5738       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5739         << T << TL.getSourceRange();
5740     } else {
5741       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5742         << Sel << T << TL.getSourceRange();
5743     }
5744     Info.DiagnoseAbstractType();
5745   }
5746 };
5747 
5748 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5749                                   Sema::AbstractDiagSelID Sel) {
5750   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5751 }
5752 
5753 }
5754 
5755 /// Check for invalid uses of an abstract type in a method declaration.
5756 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5757                                     CXXMethodDecl *MD) {
5758   // No need to do the check on definitions, which require that
5759   // the return/param types be complete.
5760   if (MD->doesThisDeclarationHaveABody())
5761     return;
5762 
5763   // For safety's sake, just ignore it if we don't have type source
5764   // information.  This should never happen for non-implicit methods,
5765   // but...
5766   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5767     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5768 }
5769 
5770 /// Check for invalid uses of an abstract type within a class definition.
5771 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5772                                     CXXRecordDecl *RD) {
5773   for (auto *D : RD->decls()) {
5774     if (D->isImplicit()) continue;
5775 
5776     // Methods and method templates.
5777     if (isa<CXXMethodDecl>(D)) {
5778       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5779     } else if (isa<FunctionTemplateDecl>(D)) {
5780       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5781       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5782 
5783     // Fields and static variables.
5784     } else if (isa<FieldDecl>(D)) {
5785       FieldDecl *FD = cast<FieldDecl>(D);
5786       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5787         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5788     } else if (isa<VarDecl>(D)) {
5789       VarDecl *VD = cast<VarDecl>(D);
5790       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5791         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5792 
5793     // Nested classes and class templates.
5794     } else if (isa<CXXRecordDecl>(D)) {
5795       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5796     } else if (isa<ClassTemplateDecl>(D)) {
5797       CheckAbstractClassUsage(Info,
5798                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5799     }
5800   }
5801 }
5802 
5803 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5804   Attr *ClassAttr = getDLLAttr(Class);
5805   if (!ClassAttr)
5806     return;
5807 
5808   assert(ClassAttr->getKind() == attr::DLLExport);
5809 
5810   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5811 
5812   if (TSK == TSK_ExplicitInstantiationDeclaration)
5813     // Don't go any further if this is just an explicit instantiation
5814     // declaration.
5815     return;
5816 
5817   // Add a context note to explain how we got to any diagnostics produced below.
5818   struct MarkingClassDllexported {
5819     Sema &S;
5820     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5821                             SourceLocation AttrLoc)
5822         : S(S) {
5823       Sema::CodeSynthesisContext Ctx;
5824       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5825       Ctx.PointOfInstantiation = AttrLoc;
5826       Ctx.Entity = Class;
5827       S.pushCodeSynthesisContext(Ctx);
5828     }
5829     ~MarkingClassDllexported() {
5830       S.popCodeSynthesisContext();
5831     }
5832   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5833 
5834   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5835     S.MarkVTableUsed(Class->getLocation(), Class, true);
5836 
5837   for (Decl *Member : Class->decls()) {
5838     // Defined static variables that are members of an exported base
5839     // class must be marked export too.
5840     auto *VD = dyn_cast<VarDecl>(Member);
5841     if (VD && Member->getAttr<DLLExportAttr>() &&
5842         VD->getStorageClass() == SC_Static &&
5843         TSK == TSK_ImplicitInstantiation)
5844       S.MarkVariableReferenced(VD->getLocation(), VD);
5845 
5846     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5847     if (!MD)
5848       continue;
5849 
5850     if (Member->getAttr<DLLExportAttr>()) {
5851       if (MD->isUserProvided()) {
5852         // Instantiate non-default class member functions ...
5853 
5854         // .. except for certain kinds of template specializations.
5855         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5856           continue;
5857 
5858         S.MarkFunctionReferenced(Class->getLocation(), MD);
5859 
5860         // The function will be passed to the consumer when its definition is
5861         // encountered.
5862       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5863                  MD->isCopyAssignmentOperator() ||
5864                  MD->isMoveAssignmentOperator()) {
5865         // Synthesize and instantiate non-trivial implicit methods, explicitly
5866         // defaulted methods, and the copy and move assignment operators. The
5867         // latter are exported even if they are trivial, because the address of
5868         // an operator can be taken and should compare equal across libraries.
5869         S.MarkFunctionReferenced(Class->getLocation(), MD);
5870 
5871         // There is no later point when we will see the definition of this
5872         // function, so pass it to the consumer now.
5873         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5874       }
5875     }
5876   }
5877 }
5878 
5879 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5880                                                         CXXRecordDecl *Class) {
5881   // Only the MS ABI has default constructor closures, so we don't need to do
5882   // this semantic checking anywhere else.
5883   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5884     return;
5885 
5886   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5887   for (Decl *Member : Class->decls()) {
5888     // Look for exported default constructors.
5889     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5890     if (!CD || !CD->isDefaultConstructor())
5891       continue;
5892     auto *Attr = CD->getAttr<DLLExportAttr>();
5893     if (!Attr)
5894       continue;
5895 
5896     // If the class is non-dependent, mark the default arguments as ODR-used so
5897     // that we can properly codegen the constructor closure.
5898     if (!Class->isDependentContext()) {
5899       for (ParmVarDecl *PD : CD->parameters()) {
5900         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5901         S.DiscardCleanupsInEvaluationContext();
5902       }
5903     }
5904 
5905     if (LastExportedDefaultCtor) {
5906       S.Diag(LastExportedDefaultCtor->getLocation(),
5907              diag::err_attribute_dll_ambiguous_default_ctor)
5908           << Class;
5909       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5910           << CD->getDeclName();
5911       return;
5912     }
5913     LastExportedDefaultCtor = CD;
5914   }
5915 }
5916 
5917 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5918                                                        CXXRecordDecl *Class) {
5919   bool ErrorReported = false;
5920   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5921                                                      ClassTemplateDecl *TD) {
5922     if (ErrorReported)
5923       return;
5924     S.Diag(TD->getLocation(),
5925            diag::err_cuda_device_builtin_surftex_cls_template)
5926         << /*surface*/ 0 << TD;
5927     ErrorReported = true;
5928   };
5929 
5930   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5931   if (!TD) {
5932     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5933     if (!SD) {
5934       S.Diag(Class->getLocation(),
5935              diag::err_cuda_device_builtin_surftex_ref_decl)
5936           << /*surface*/ 0 << Class;
5937       S.Diag(Class->getLocation(),
5938              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5939           << Class;
5940       return;
5941     }
5942     TD = SD->getSpecializedTemplate();
5943   }
5944 
5945   TemplateParameterList *Params = TD->getTemplateParameters();
5946   unsigned N = Params->size();
5947 
5948   if (N != 2) {
5949     reportIllegalClassTemplate(S, TD);
5950     S.Diag(TD->getLocation(),
5951            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5952         << TD << 2;
5953   }
5954   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5955     reportIllegalClassTemplate(S, TD);
5956     S.Diag(TD->getLocation(),
5957            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5958         << TD << /*1st*/ 0 << /*type*/ 0;
5959   }
5960   if (N > 1) {
5961     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5962     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5963       reportIllegalClassTemplate(S, TD);
5964       S.Diag(TD->getLocation(),
5965              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5966           << TD << /*2nd*/ 1 << /*integer*/ 1;
5967     }
5968   }
5969 }
5970 
5971 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5972                                                        CXXRecordDecl *Class) {
5973   bool ErrorReported = false;
5974   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5975                                                      ClassTemplateDecl *TD) {
5976     if (ErrorReported)
5977       return;
5978     S.Diag(TD->getLocation(),
5979            diag::err_cuda_device_builtin_surftex_cls_template)
5980         << /*texture*/ 1 << TD;
5981     ErrorReported = true;
5982   };
5983 
5984   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5985   if (!TD) {
5986     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5987     if (!SD) {
5988       S.Diag(Class->getLocation(),
5989              diag::err_cuda_device_builtin_surftex_ref_decl)
5990           << /*texture*/ 1 << Class;
5991       S.Diag(Class->getLocation(),
5992              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5993           << Class;
5994       return;
5995     }
5996     TD = SD->getSpecializedTemplate();
5997   }
5998 
5999   TemplateParameterList *Params = TD->getTemplateParameters();
6000   unsigned N = Params->size();
6001 
6002   if (N != 3) {
6003     reportIllegalClassTemplate(S, TD);
6004     S.Diag(TD->getLocation(),
6005            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6006         << TD << 3;
6007   }
6008   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6009     reportIllegalClassTemplate(S, TD);
6010     S.Diag(TD->getLocation(),
6011            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6012         << TD << /*1st*/ 0 << /*type*/ 0;
6013   }
6014   if (N > 1) {
6015     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6016     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6017       reportIllegalClassTemplate(S, TD);
6018       S.Diag(TD->getLocation(),
6019              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6020           << TD << /*2nd*/ 1 << /*integer*/ 1;
6021     }
6022   }
6023   if (N > 2) {
6024     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6025     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6026       reportIllegalClassTemplate(S, TD);
6027       S.Diag(TD->getLocation(),
6028              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6029           << TD << /*3rd*/ 2 << /*integer*/ 1;
6030     }
6031   }
6032 }
6033 
6034 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6035   // Mark any compiler-generated routines with the implicit code_seg attribute.
6036   for (auto *Method : Class->methods()) {
6037     if (Method->isUserProvided())
6038       continue;
6039     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6040       Method->addAttr(A);
6041   }
6042 }
6043 
6044 /// Check class-level dllimport/dllexport attribute.
6045 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6046   Attr *ClassAttr = getDLLAttr(Class);
6047 
6048   // MSVC inherits DLL attributes to partial class template specializations.
6049   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6050     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6051       if (Attr *TemplateAttr =
6052               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6053         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6054         A->setInherited(true);
6055         ClassAttr = A;
6056       }
6057     }
6058   }
6059 
6060   if (!ClassAttr)
6061     return;
6062 
6063   if (!Class->isExternallyVisible()) {
6064     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6065         << Class << ClassAttr;
6066     return;
6067   }
6068 
6069   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6070       !ClassAttr->isInherited()) {
6071     // Diagnose dll attributes on members of class with dll attribute.
6072     for (Decl *Member : Class->decls()) {
6073       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6074         continue;
6075       InheritableAttr *MemberAttr = getDLLAttr(Member);
6076       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6077         continue;
6078 
6079       Diag(MemberAttr->getLocation(),
6080              diag::err_attribute_dll_member_of_dll_class)
6081           << MemberAttr << ClassAttr;
6082       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6083       Member->setInvalidDecl();
6084     }
6085   }
6086 
6087   if (Class->getDescribedClassTemplate())
6088     // Don't inherit dll attribute until the template is instantiated.
6089     return;
6090 
6091   // The class is either imported or exported.
6092   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6093 
6094   // Check if this was a dllimport attribute propagated from a derived class to
6095   // a base class template specialization. We don't apply these attributes to
6096   // static data members.
6097   const bool PropagatedImport =
6098       !ClassExported &&
6099       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6100 
6101   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6102 
6103   // Ignore explicit dllexport on explicit class template instantiation
6104   // declarations, except in MinGW mode.
6105   if (ClassExported && !ClassAttr->isInherited() &&
6106       TSK == TSK_ExplicitInstantiationDeclaration &&
6107       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6108     Class->dropAttr<DLLExportAttr>();
6109     return;
6110   }
6111 
6112   // Force declaration of implicit members so they can inherit the attribute.
6113   ForceDeclarationOfImplicitMembers(Class);
6114 
6115   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6116   // seem to be true in practice?
6117 
6118   for (Decl *Member : Class->decls()) {
6119     VarDecl *VD = dyn_cast<VarDecl>(Member);
6120     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6121 
6122     // Only methods and static fields inherit the attributes.
6123     if (!VD && !MD)
6124       continue;
6125 
6126     if (MD) {
6127       // Don't process deleted methods.
6128       if (MD->isDeleted())
6129         continue;
6130 
6131       if (MD->isInlined()) {
6132         // MinGW does not import or export inline methods. But do it for
6133         // template instantiations.
6134         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6135             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6136             TSK != TSK_ExplicitInstantiationDeclaration &&
6137             TSK != TSK_ExplicitInstantiationDefinition)
6138           continue;
6139 
6140         // MSVC versions before 2015 don't export the move assignment operators
6141         // and move constructor, so don't attempt to import/export them if
6142         // we have a definition.
6143         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6144         if ((MD->isMoveAssignmentOperator() ||
6145              (Ctor && Ctor->isMoveConstructor())) &&
6146             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6147           continue;
6148 
6149         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6150         // operator is exported anyway.
6151         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6152             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6153           continue;
6154       }
6155     }
6156 
6157     // Don't apply dllimport attributes to static data members of class template
6158     // instantiations when the attribute is propagated from a derived class.
6159     if (VD && PropagatedImport)
6160       continue;
6161 
6162     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6163       continue;
6164 
6165     if (!getDLLAttr(Member)) {
6166       InheritableAttr *NewAttr = nullptr;
6167 
6168       // Do not export/import inline function when -fno-dllexport-inlines is
6169       // passed. But add attribute for later local static var check.
6170       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6171           TSK != TSK_ExplicitInstantiationDeclaration &&
6172           TSK != TSK_ExplicitInstantiationDefinition) {
6173         if (ClassExported) {
6174           NewAttr = ::new (getASTContext())
6175               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6176         } else {
6177           NewAttr = ::new (getASTContext())
6178               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6179         }
6180       } else {
6181         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6182       }
6183 
6184       NewAttr->setInherited(true);
6185       Member->addAttr(NewAttr);
6186 
6187       if (MD) {
6188         // Propagate DLLAttr to friend re-declarations of MD that have already
6189         // been constructed.
6190         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6191              FD = FD->getPreviousDecl()) {
6192           if (FD->getFriendObjectKind() == Decl::FOK_None)
6193             continue;
6194           assert(!getDLLAttr(FD) &&
6195                  "friend re-decl should not already have a DLLAttr");
6196           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6197           NewAttr->setInherited(true);
6198           FD->addAttr(NewAttr);
6199         }
6200       }
6201     }
6202   }
6203 
6204   if (ClassExported)
6205     DelayedDllExportClasses.push_back(Class);
6206 }
6207 
6208 /// Perform propagation of DLL attributes from a derived class to a
6209 /// templated base class for MS compatibility.
6210 void Sema::propagateDLLAttrToBaseClassTemplate(
6211     CXXRecordDecl *Class, Attr *ClassAttr,
6212     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6213   if (getDLLAttr(
6214           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6215     // If the base class template has a DLL attribute, don't try to change it.
6216     return;
6217   }
6218 
6219   auto TSK = BaseTemplateSpec->getSpecializationKind();
6220   if (!getDLLAttr(BaseTemplateSpec) &&
6221       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6222        TSK == TSK_ImplicitInstantiation)) {
6223     // The template hasn't been instantiated yet (or it has, but only as an
6224     // explicit instantiation declaration or implicit instantiation, which means
6225     // we haven't codegenned any members yet), so propagate the attribute.
6226     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6227     NewAttr->setInherited(true);
6228     BaseTemplateSpec->addAttr(NewAttr);
6229 
6230     // If this was an import, mark that we propagated it from a derived class to
6231     // a base class template specialization.
6232     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6233       ImportAttr->setPropagatedToBaseTemplate();
6234 
6235     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6236     // needs to be run again to work see the new attribute. Otherwise this will
6237     // get run whenever the template is instantiated.
6238     if (TSK != TSK_Undeclared)
6239       checkClassLevelDLLAttribute(BaseTemplateSpec);
6240 
6241     return;
6242   }
6243 
6244   if (getDLLAttr(BaseTemplateSpec)) {
6245     // The template has already been specialized or instantiated with an
6246     // attribute, explicitly or through propagation. We should not try to change
6247     // it.
6248     return;
6249   }
6250 
6251   // The template was previously instantiated or explicitly specialized without
6252   // a dll attribute, It's too late for us to add an attribute, so warn that
6253   // this is unsupported.
6254   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6255       << BaseTemplateSpec->isExplicitSpecialization();
6256   Diag(ClassAttr->getLocation(), diag::note_attribute);
6257   if (BaseTemplateSpec->isExplicitSpecialization()) {
6258     Diag(BaseTemplateSpec->getLocation(),
6259            diag::note_template_class_explicit_specialization_was_here)
6260         << BaseTemplateSpec;
6261   } else {
6262     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6263            diag::note_template_class_instantiation_was_here)
6264         << BaseTemplateSpec;
6265   }
6266 }
6267 
6268 /// Determine the kind of defaulting that would be done for a given function.
6269 ///
6270 /// If the function is both a default constructor and a copy / move constructor
6271 /// (due to having a default argument for the first parameter), this picks
6272 /// CXXDefaultConstructor.
6273 ///
6274 /// FIXME: Check that case is properly handled by all callers.
6275 Sema::DefaultedFunctionKind
6276 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6277   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6278     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6279       if (Ctor->isDefaultConstructor())
6280         return Sema::CXXDefaultConstructor;
6281 
6282       if (Ctor->isCopyConstructor())
6283         return Sema::CXXCopyConstructor;
6284 
6285       if (Ctor->isMoveConstructor())
6286         return Sema::CXXMoveConstructor;
6287     }
6288 
6289     if (MD->isCopyAssignmentOperator())
6290       return Sema::CXXCopyAssignment;
6291 
6292     if (MD->isMoveAssignmentOperator())
6293       return Sema::CXXMoveAssignment;
6294 
6295     if (isa<CXXDestructorDecl>(FD))
6296       return Sema::CXXDestructor;
6297   }
6298 
6299   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6300   case OO_EqualEqual:
6301     return DefaultedComparisonKind::Equal;
6302 
6303   case OO_ExclaimEqual:
6304     return DefaultedComparisonKind::NotEqual;
6305 
6306   case OO_Spaceship:
6307     // No point allowing this if <=> doesn't exist in the current language mode.
6308     if (!getLangOpts().CPlusPlus20)
6309       break;
6310     return DefaultedComparisonKind::ThreeWay;
6311 
6312   case OO_Less:
6313   case OO_LessEqual:
6314   case OO_Greater:
6315   case OO_GreaterEqual:
6316     // No point allowing this if <=> doesn't exist in the current language mode.
6317     if (!getLangOpts().CPlusPlus20)
6318       break;
6319     return DefaultedComparisonKind::Relational;
6320 
6321   default:
6322     break;
6323   }
6324 
6325   // Not defaultable.
6326   return DefaultedFunctionKind();
6327 }
6328 
6329 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6330                                     SourceLocation DefaultLoc) {
6331   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6332   if (DFK.isComparison())
6333     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6334 
6335   switch (DFK.asSpecialMember()) {
6336   case Sema::CXXDefaultConstructor:
6337     S.DefineImplicitDefaultConstructor(DefaultLoc,
6338                                        cast<CXXConstructorDecl>(FD));
6339     break;
6340   case Sema::CXXCopyConstructor:
6341     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6342     break;
6343   case Sema::CXXCopyAssignment:
6344     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6345     break;
6346   case Sema::CXXDestructor:
6347     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6348     break;
6349   case Sema::CXXMoveConstructor:
6350     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6351     break;
6352   case Sema::CXXMoveAssignment:
6353     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6354     break;
6355   case Sema::CXXInvalid:
6356     llvm_unreachable("Invalid special member.");
6357   }
6358 }
6359 
6360 /// Determine whether a type is permitted to be passed or returned in
6361 /// registers, per C++ [class.temporary]p3.
6362 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6363                                TargetInfo::CallingConvKind CCK) {
6364   if (D->isDependentType() || D->isInvalidDecl())
6365     return false;
6366 
6367   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6368   // The PS4 platform ABI follows the behavior of Clang 3.2.
6369   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6370     return !D->hasNonTrivialDestructorForCall() &&
6371            !D->hasNonTrivialCopyConstructorForCall();
6372 
6373   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6374     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6375     bool DtorIsTrivialForCall = false;
6376 
6377     // If a class has at least one non-deleted, trivial copy constructor, it
6378     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6379     //
6380     // Note: This permits classes with non-trivial copy or move ctors to be
6381     // passed in registers, so long as they *also* have a trivial copy ctor,
6382     // which is non-conforming.
6383     if (D->needsImplicitCopyConstructor()) {
6384       if (!D->defaultedCopyConstructorIsDeleted()) {
6385         if (D->hasTrivialCopyConstructor())
6386           CopyCtorIsTrivial = true;
6387         if (D->hasTrivialCopyConstructorForCall())
6388           CopyCtorIsTrivialForCall = true;
6389       }
6390     } else {
6391       for (const CXXConstructorDecl *CD : D->ctors()) {
6392         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6393           if (CD->isTrivial())
6394             CopyCtorIsTrivial = true;
6395           if (CD->isTrivialForCall())
6396             CopyCtorIsTrivialForCall = true;
6397         }
6398       }
6399     }
6400 
6401     if (D->needsImplicitDestructor()) {
6402       if (!D->defaultedDestructorIsDeleted() &&
6403           D->hasTrivialDestructorForCall())
6404         DtorIsTrivialForCall = true;
6405     } else if (const auto *DD = D->getDestructor()) {
6406       if (!DD->isDeleted() && DD->isTrivialForCall())
6407         DtorIsTrivialForCall = true;
6408     }
6409 
6410     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6411     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6412       return true;
6413 
6414     // If a class has a destructor, we'd really like to pass it indirectly
6415     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6416     // impossible for small types, which it will pass in a single register or
6417     // stack slot. Most objects with dtors are large-ish, so handle that early.
6418     // We can't call out all large objects as being indirect because there are
6419     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6420     // how we pass large POD types.
6421 
6422     // Note: This permits small classes with nontrivial destructors to be
6423     // passed in registers, which is non-conforming.
6424     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6425     uint64_t TypeSize = isAArch64 ? 128 : 64;
6426 
6427     if (CopyCtorIsTrivial &&
6428         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6429       return true;
6430     return false;
6431   }
6432 
6433   // Per C++ [class.temporary]p3, the relevant condition is:
6434   //   each copy constructor, move constructor, and destructor of X is
6435   //   either trivial or deleted, and X has at least one non-deleted copy
6436   //   or move constructor
6437   bool HasNonDeletedCopyOrMove = false;
6438 
6439   if (D->needsImplicitCopyConstructor() &&
6440       !D->defaultedCopyConstructorIsDeleted()) {
6441     if (!D->hasTrivialCopyConstructorForCall())
6442       return false;
6443     HasNonDeletedCopyOrMove = true;
6444   }
6445 
6446   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6447       !D->defaultedMoveConstructorIsDeleted()) {
6448     if (!D->hasTrivialMoveConstructorForCall())
6449       return false;
6450     HasNonDeletedCopyOrMove = true;
6451   }
6452 
6453   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6454       !D->hasTrivialDestructorForCall())
6455     return false;
6456 
6457   for (const CXXMethodDecl *MD : D->methods()) {
6458     if (MD->isDeleted())
6459       continue;
6460 
6461     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6462     if (CD && CD->isCopyOrMoveConstructor())
6463       HasNonDeletedCopyOrMove = true;
6464     else if (!isa<CXXDestructorDecl>(MD))
6465       continue;
6466 
6467     if (!MD->isTrivialForCall())
6468       return false;
6469   }
6470 
6471   return HasNonDeletedCopyOrMove;
6472 }
6473 
6474 /// Report an error regarding overriding, along with any relevant
6475 /// overridden methods.
6476 ///
6477 /// \param DiagID the primary error to report.
6478 /// \param MD the overriding method.
6479 static bool
6480 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6481                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6482   bool IssuedDiagnostic = false;
6483   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6484     if (Report(O)) {
6485       if (!IssuedDiagnostic) {
6486         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6487         IssuedDiagnostic = true;
6488       }
6489       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6490     }
6491   }
6492   return IssuedDiagnostic;
6493 }
6494 
6495 /// Perform semantic checks on a class definition that has been
6496 /// completing, introducing implicitly-declared members, checking for
6497 /// abstract types, etc.
6498 ///
6499 /// \param S The scope in which the class was parsed. Null if we didn't just
6500 ///        parse a class definition.
6501 /// \param Record The completed class.
6502 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6503   if (!Record)
6504     return;
6505 
6506   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6507     AbstractUsageInfo Info(*this, Record);
6508     CheckAbstractClassUsage(Info, Record);
6509   }
6510 
6511   // If this is not an aggregate type and has no user-declared constructor,
6512   // complain about any non-static data members of reference or const scalar
6513   // type, since they will never get initializers.
6514   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6515       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6516       !Record->isLambda()) {
6517     bool Complained = false;
6518     for (const auto *F : Record->fields()) {
6519       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6520         continue;
6521 
6522       if (F->getType()->isReferenceType() ||
6523           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6524         if (!Complained) {
6525           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6526             << Record->getTagKind() << Record;
6527           Complained = true;
6528         }
6529 
6530         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6531           << F->getType()->isReferenceType()
6532           << F->getDeclName();
6533       }
6534     }
6535   }
6536 
6537   if (Record->getIdentifier()) {
6538     // C++ [class.mem]p13:
6539     //   If T is the name of a class, then each of the following shall have a
6540     //   name different from T:
6541     //     - every member of every anonymous union that is a member of class T.
6542     //
6543     // C++ [class.mem]p14:
6544     //   In addition, if class T has a user-declared constructor (12.1), every
6545     //   non-static data member of class T shall have a name different from T.
6546     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6547     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6548          ++I) {
6549       NamedDecl *D = (*I)->getUnderlyingDecl();
6550       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6551            Record->hasUserDeclaredConstructor()) ||
6552           isa<IndirectFieldDecl>(D)) {
6553         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6554           << D->getDeclName();
6555         break;
6556       }
6557     }
6558   }
6559 
6560   // Warn if the class has virtual methods but non-virtual public destructor.
6561   if (Record->isPolymorphic() && !Record->isDependentType()) {
6562     CXXDestructorDecl *dtor = Record->getDestructor();
6563     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6564         !Record->hasAttr<FinalAttr>())
6565       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6566            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6567   }
6568 
6569   if (Record->isAbstract()) {
6570     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6571       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6572         << FA->isSpelledAsSealed();
6573       DiagnoseAbstractType(Record);
6574     }
6575   }
6576 
6577   // Warn if the class has a final destructor but is not itself marked final.
6578   if (!Record->hasAttr<FinalAttr>()) {
6579     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6580       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6581         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6582             << FA->isSpelledAsSealed()
6583             << FixItHint::CreateInsertion(
6584                    getLocForEndOfToken(Record->getLocation()),
6585                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6586         Diag(Record->getLocation(),
6587              diag::note_final_dtor_non_final_class_silence)
6588             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6589       }
6590     }
6591   }
6592 
6593   // See if trivial_abi has to be dropped.
6594   if (Record->hasAttr<TrivialABIAttr>())
6595     checkIllFormedTrivialABIStruct(*Record);
6596 
6597   // Set HasTrivialSpecialMemberForCall if the record has attribute
6598   // "trivial_abi".
6599   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6600 
6601   if (HasTrivialABI)
6602     Record->setHasTrivialSpecialMemberForCall();
6603 
6604   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6605   // We check these last because they can depend on the properties of the
6606   // primary comparison functions (==, <=>).
6607   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6608 
6609   // Perform checks that can't be done until we know all the properties of a
6610   // member function (whether it's defaulted, deleted, virtual, overriding,
6611   // ...).
6612   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6613     // A static function cannot override anything.
6614     if (MD->getStorageClass() == SC_Static) {
6615       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6616                           [](const CXXMethodDecl *) { return true; }))
6617         return;
6618     }
6619 
6620     // A deleted function cannot override a non-deleted function and vice
6621     // versa.
6622     if (ReportOverrides(*this,
6623                         MD->isDeleted() ? diag::err_deleted_override
6624                                         : diag::err_non_deleted_override,
6625                         MD, [&](const CXXMethodDecl *V) {
6626                           return MD->isDeleted() != V->isDeleted();
6627                         })) {
6628       if (MD->isDefaulted() && MD->isDeleted())
6629         // Explain why this defaulted function was deleted.
6630         DiagnoseDeletedDefaultedFunction(MD);
6631       return;
6632     }
6633 
6634     // A consteval function cannot override a non-consteval function and vice
6635     // versa.
6636     if (ReportOverrides(*this,
6637                         MD->isConsteval() ? diag::err_consteval_override
6638                                           : diag::err_non_consteval_override,
6639                         MD, [&](const CXXMethodDecl *V) {
6640                           return MD->isConsteval() != V->isConsteval();
6641                         })) {
6642       if (MD->isDefaulted() && MD->isDeleted())
6643         // Explain why this defaulted function was deleted.
6644         DiagnoseDeletedDefaultedFunction(MD);
6645       return;
6646     }
6647   };
6648 
6649   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6650     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6651       return false;
6652 
6653     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6654     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6655         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6656       DefaultedSecondaryComparisons.push_back(FD);
6657       return true;
6658     }
6659 
6660     CheckExplicitlyDefaultedFunction(S, FD);
6661     return false;
6662   };
6663 
6664   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6665     // Check whether the explicitly-defaulted members are valid.
6666     bool Incomplete = CheckForDefaultedFunction(M);
6667 
6668     // Skip the rest of the checks for a member of a dependent class.
6669     if (Record->isDependentType())
6670       return;
6671 
6672     // For an explicitly defaulted or deleted special member, we defer
6673     // determining triviality until the class is complete. That time is now!
6674     CXXSpecialMember CSM = getSpecialMember(M);
6675     if (!M->isImplicit() && !M->isUserProvided()) {
6676       if (CSM != CXXInvalid) {
6677         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6678         // Inform the class that we've finished declaring this member.
6679         Record->finishedDefaultedOrDeletedMember(M);
6680         M->setTrivialForCall(
6681             HasTrivialABI ||
6682             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6683         Record->setTrivialForCallFlags(M);
6684       }
6685     }
6686 
6687     // Set triviality for the purpose of calls if this is a user-provided
6688     // copy/move constructor or destructor.
6689     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6690          CSM == CXXDestructor) && M->isUserProvided()) {
6691       M->setTrivialForCall(HasTrivialABI);
6692       Record->setTrivialForCallFlags(M);
6693     }
6694 
6695     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6696         M->hasAttr<DLLExportAttr>()) {
6697       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6698           M->isTrivial() &&
6699           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6700            CSM == CXXDestructor))
6701         M->dropAttr<DLLExportAttr>();
6702 
6703       if (M->hasAttr<DLLExportAttr>()) {
6704         // Define after any fields with in-class initializers have been parsed.
6705         DelayedDllExportMemberFunctions.push_back(M);
6706       }
6707     }
6708 
6709     // Define defaulted constexpr virtual functions that override a base class
6710     // function right away.
6711     // FIXME: We can defer doing this until the vtable is marked as used.
6712     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6713       DefineDefaultedFunction(*this, M, M->getLocation());
6714 
6715     if (!Incomplete)
6716       CheckCompletedMemberFunction(M);
6717   };
6718 
6719   // Check the destructor before any other member function. We need to
6720   // determine whether it's trivial in order to determine whether the claas
6721   // type is a literal type, which is a prerequisite for determining whether
6722   // other special member functions are valid and whether they're implicitly
6723   // 'constexpr'.
6724   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6725     CompleteMemberFunction(Dtor);
6726 
6727   bool HasMethodWithOverrideControl = false,
6728        HasOverridingMethodWithoutOverrideControl = false;
6729   for (auto *D : Record->decls()) {
6730     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6731       // FIXME: We could do this check for dependent types with non-dependent
6732       // bases.
6733       if (!Record->isDependentType()) {
6734         // See if a method overloads virtual methods in a base
6735         // class without overriding any.
6736         if (!M->isStatic())
6737           DiagnoseHiddenVirtualMethods(M);
6738         if (M->hasAttr<OverrideAttr>())
6739           HasMethodWithOverrideControl = true;
6740         else if (M->size_overridden_methods() > 0)
6741           HasOverridingMethodWithoutOverrideControl = true;
6742       }
6743 
6744       if (!isa<CXXDestructorDecl>(M))
6745         CompleteMemberFunction(M);
6746     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6747       CheckForDefaultedFunction(
6748           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6749     }
6750   }
6751 
6752   if (HasMethodWithOverrideControl &&
6753       HasOverridingMethodWithoutOverrideControl) {
6754     // At least one method has the 'override' control declared.
6755     // Diagnose all other overridden methods which do not have 'override'
6756     // specified on them.
6757     for (auto *M : Record->methods())
6758       DiagnoseAbsenceOfOverrideControl(M);
6759   }
6760 
6761   // Check the defaulted secondary comparisons after any other member functions.
6762   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6763     CheckExplicitlyDefaultedFunction(S, FD);
6764 
6765     // If this is a member function, we deferred checking it until now.
6766     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6767       CheckCompletedMemberFunction(MD);
6768   }
6769 
6770   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6771   // whether this class uses any C++ features that are implemented
6772   // completely differently in MSVC, and if so, emit a diagnostic.
6773   // That diagnostic defaults to an error, but we allow projects to
6774   // map it down to a warning (or ignore it).  It's a fairly common
6775   // practice among users of the ms_struct pragma to mass-annotate
6776   // headers, sweeping up a bunch of types that the project doesn't
6777   // really rely on MSVC-compatible layout for.  We must therefore
6778   // support "ms_struct except for C++ stuff" as a secondary ABI.
6779   // Don't emit this diagnostic if the feature was enabled as a
6780   // language option (as opposed to via a pragma or attribute), as
6781   // the option -mms-bitfields otherwise essentially makes it impossible
6782   // to build C++ code, unless this diagnostic is turned off.
6783   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6784       (Record->isPolymorphic() || Record->getNumBases())) {
6785     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6786   }
6787 
6788   checkClassLevelDLLAttribute(Record);
6789   checkClassLevelCodeSegAttribute(Record);
6790 
6791   bool ClangABICompat4 =
6792       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6793   TargetInfo::CallingConvKind CCK =
6794       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6795   bool CanPass = canPassInRegisters(*this, Record, CCK);
6796 
6797   // Do not change ArgPassingRestrictions if it has already been set to
6798   // APK_CanNeverPassInRegs.
6799   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6800     Record->setArgPassingRestrictions(CanPass
6801                                           ? RecordDecl::APK_CanPassInRegs
6802                                           : RecordDecl::APK_CannotPassInRegs);
6803 
6804   // If canPassInRegisters returns true despite the record having a non-trivial
6805   // destructor, the record is destructed in the callee. This happens only when
6806   // the record or one of its subobjects has a field annotated with trivial_abi
6807   // or a field qualified with ObjC __strong/__weak.
6808   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6809     Record->setParamDestroyedInCallee(true);
6810   else if (Record->hasNonTrivialDestructor())
6811     Record->setParamDestroyedInCallee(CanPass);
6812 
6813   if (getLangOpts().ForceEmitVTables) {
6814     // If we want to emit all the vtables, we need to mark it as used.  This
6815     // is especially required for cases like vtable assumption loads.
6816     MarkVTableUsed(Record->getInnerLocStart(), Record);
6817   }
6818 
6819   if (getLangOpts().CUDA) {
6820     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6821       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6822     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6823       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6824   }
6825 }
6826 
6827 /// Look up the special member function that would be called by a special
6828 /// member function for a subobject of class type.
6829 ///
6830 /// \param Class The class type of the subobject.
6831 /// \param CSM The kind of special member function.
6832 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6833 /// \param ConstRHS True if this is a copy operation with a const object
6834 ///        on its RHS, that is, if the argument to the outer special member
6835 ///        function is 'const' and this is not a field marked 'mutable'.
6836 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6837     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6838     unsigned FieldQuals, bool ConstRHS) {
6839   unsigned LHSQuals = 0;
6840   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6841     LHSQuals = FieldQuals;
6842 
6843   unsigned RHSQuals = FieldQuals;
6844   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6845     RHSQuals = 0;
6846   else if (ConstRHS)
6847     RHSQuals |= Qualifiers::Const;
6848 
6849   return S.LookupSpecialMember(Class, CSM,
6850                                RHSQuals & Qualifiers::Const,
6851                                RHSQuals & Qualifiers::Volatile,
6852                                false,
6853                                LHSQuals & Qualifiers::Const,
6854                                LHSQuals & Qualifiers::Volatile);
6855 }
6856 
6857 class Sema::InheritedConstructorInfo {
6858   Sema &S;
6859   SourceLocation UseLoc;
6860 
6861   /// A mapping from the base classes through which the constructor was
6862   /// inherited to the using shadow declaration in that base class (or a null
6863   /// pointer if the constructor was declared in that base class).
6864   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6865       InheritedFromBases;
6866 
6867 public:
6868   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6869                            ConstructorUsingShadowDecl *Shadow)
6870       : S(S), UseLoc(UseLoc) {
6871     bool DiagnosedMultipleConstructedBases = false;
6872     CXXRecordDecl *ConstructedBase = nullptr;
6873     UsingDecl *ConstructedBaseUsing = nullptr;
6874 
6875     // Find the set of such base class subobjects and check that there's a
6876     // unique constructed subobject.
6877     for (auto *D : Shadow->redecls()) {
6878       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6879       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6880       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6881 
6882       InheritedFromBases.insert(
6883           std::make_pair(DNominatedBase->getCanonicalDecl(),
6884                          DShadow->getNominatedBaseClassShadowDecl()));
6885       if (DShadow->constructsVirtualBase())
6886         InheritedFromBases.insert(
6887             std::make_pair(DConstructedBase->getCanonicalDecl(),
6888                            DShadow->getConstructedBaseClassShadowDecl()));
6889       else
6890         assert(DNominatedBase == DConstructedBase);
6891 
6892       // [class.inhctor.init]p2:
6893       //   If the constructor was inherited from multiple base class subobjects
6894       //   of type B, the program is ill-formed.
6895       if (!ConstructedBase) {
6896         ConstructedBase = DConstructedBase;
6897         ConstructedBaseUsing = D->getUsingDecl();
6898       } else if (ConstructedBase != DConstructedBase &&
6899                  !Shadow->isInvalidDecl()) {
6900         if (!DiagnosedMultipleConstructedBases) {
6901           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6902               << Shadow->getTargetDecl();
6903           S.Diag(ConstructedBaseUsing->getLocation(),
6904                diag::note_ambiguous_inherited_constructor_using)
6905               << ConstructedBase;
6906           DiagnosedMultipleConstructedBases = true;
6907         }
6908         S.Diag(D->getUsingDecl()->getLocation(),
6909                diag::note_ambiguous_inherited_constructor_using)
6910             << DConstructedBase;
6911       }
6912     }
6913 
6914     if (DiagnosedMultipleConstructedBases)
6915       Shadow->setInvalidDecl();
6916   }
6917 
6918   /// Find the constructor to use for inherited construction of a base class,
6919   /// and whether that base class constructor inherits the constructor from a
6920   /// virtual base class (in which case it won't actually invoke it).
6921   std::pair<CXXConstructorDecl *, bool>
6922   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6923     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6924     if (It == InheritedFromBases.end())
6925       return std::make_pair(nullptr, false);
6926 
6927     // This is an intermediary class.
6928     if (It->second)
6929       return std::make_pair(
6930           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6931           It->second->constructsVirtualBase());
6932 
6933     // This is the base class from which the constructor was inherited.
6934     return std::make_pair(Ctor, false);
6935   }
6936 };
6937 
6938 /// Is the special member function which would be selected to perform the
6939 /// specified operation on the specified class type a constexpr constructor?
6940 static bool
6941 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6942                          Sema::CXXSpecialMember CSM, unsigned Quals,
6943                          bool ConstRHS,
6944                          CXXConstructorDecl *InheritedCtor = nullptr,
6945                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6946   // If we're inheriting a constructor, see if we need to call it for this base
6947   // class.
6948   if (InheritedCtor) {
6949     assert(CSM == Sema::CXXDefaultConstructor);
6950     auto BaseCtor =
6951         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6952     if (BaseCtor)
6953       return BaseCtor->isConstexpr();
6954   }
6955 
6956   if (CSM == Sema::CXXDefaultConstructor)
6957     return ClassDecl->hasConstexprDefaultConstructor();
6958   if (CSM == Sema::CXXDestructor)
6959     return ClassDecl->hasConstexprDestructor();
6960 
6961   Sema::SpecialMemberOverloadResult SMOR =
6962       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6963   if (!SMOR.getMethod())
6964     // A constructor we wouldn't select can't be "involved in initializing"
6965     // anything.
6966     return true;
6967   return SMOR.getMethod()->isConstexpr();
6968 }
6969 
6970 /// Determine whether the specified special member function would be constexpr
6971 /// if it were implicitly defined.
6972 static bool defaultedSpecialMemberIsConstexpr(
6973     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6974     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6975     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6976   if (!S.getLangOpts().CPlusPlus11)
6977     return false;
6978 
6979   // C++11 [dcl.constexpr]p4:
6980   // In the definition of a constexpr constructor [...]
6981   bool Ctor = true;
6982   switch (CSM) {
6983   case Sema::CXXDefaultConstructor:
6984     if (Inherited)
6985       break;
6986     // Since default constructor lookup is essentially trivial (and cannot
6987     // involve, for instance, template instantiation), we compute whether a
6988     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6989     //
6990     // This is important for performance; we need to know whether the default
6991     // constructor is constexpr to determine whether the type is a literal type.
6992     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6993 
6994   case Sema::CXXCopyConstructor:
6995   case Sema::CXXMoveConstructor:
6996     // For copy or move constructors, we need to perform overload resolution.
6997     break;
6998 
6999   case Sema::CXXCopyAssignment:
7000   case Sema::CXXMoveAssignment:
7001     if (!S.getLangOpts().CPlusPlus14)
7002       return false;
7003     // In C++1y, we need to perform overload resolution.
7004     Ctor = false;
7005     break;
7006 
7007   case Sema::CXXDestructor:
7008     return ClassDecl->defaultedDestructorIsConstexpr();
7009 
7010   case Sema::CXXInvalid:
7011     return false;
7012   }
7013 
7014   //   -- if the class is a non-empty union, or for each non-empty anonymous
7015   //      union member of a non-union class, exactly one non-static data member
7016   //      shall be initialized; [DR1359]
7017   //
7018   // If we squint, this is guaranteed, since exactly one non-static data member
7019   // will be initialized (if the constructor isn't deleted), we just don't know
7020   // which one.
7021   if (Ctor && ClassDecl->isUnion())
7022     return CSM == Sema::CXXDefaultConstructor
7023                ? ClassDecl->hasInClassInitializer() ||
7024                      !ClassDecl->hasVariantMembers()
7025                : true;
7026 
7027   //   -- the class shall not have any virtual base classes;
7028   if (Ctor && ClassDecl->getNumVBases())
7029     return false;
7030 
7031   // C++1y [class.copy]p26:
7032   //   -- [the class] is a literal type, and
7033   if (!Ctor && !ClassDecl->isLiteral())
7034     return false;
7035 
7036   //   -- every constructor involved in initializing [...] base class
7037   //      sub-objects shall be a constexpr constructor;
7038   //   -- the assignment operator selected to copy/move each direct base
7039   //      class is a constexpr function, and
7040   for (const auto &B : ClassDecl->bases()) {
7041     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7042     if (!BaseType) continue;
7043 
7044     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7045     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7046                                   InheritedCtor, Inherited))
7047       return false;
7048   }
7049 
7050   //   -- every constructor involved in initializing non-static data members
7051   //      [...] shall be a constexpr constructor;
7052   //   -- every non-static data member and base class sub-object shall be
7053   //      initialized
7054   //   -- for each non-static data member of X that is of class type (or array
7055   //      thereof), the assignment operator selected to copy/move that member is
7056   //      a constexpr function
7057   for (const auto *F : ClassDecl->fields()) {
7058     if (F->isInvalidDecl())
7059       continue;
7060     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7061       continue;
7062     QualType BaseType = S.Context.getBaseElementType(F->getType());
7063     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7064       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7065       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7066                                     BaseType.getCVRQualifiers(),
7067                                     ConstArg && !F->isMutable()))
7068         return false;
7069     } else if (CSM == Sema::CXXDefaultConstructor) {
7070       return false;
7071     }
7072   }
7073 
7074   // All OK, it's constexpr!
7075   return true;
7076 }
7077 
7078 namespace {
7079 /// RAII object to register a defaulted function as having its exception
7080 /// specification computed.
7081 struct ComputingExceptionSpec {
7082   Sema &S;
7083 
7084   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7085       : S(S) {
7086     Sema::CodeSynthesisContext Ctx;
7087     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7088     Ctx.PointOfInstantiation = Loc;
7089     Ctx.Entity = FD;
7090     S.pushCodeSynthesisContext(Ctx);
7091   }
7092   ~ComputingExceptionSpec() {
7093     S.popCodeSynthesisContext();
7094   }
7095 };
7096 }
7097 
7098 static Sema::ImplicitExceptionSpecification
7099 ComputeDefaultedSpecialMemberExceptionSpec(
7100     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7101     Sema::InheritedConstructorInfo *ICI);
7102 
7103 static Sema::ImplicitExceptionSpecification
7104 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7105                                         FunctionDecl *FD,
7106                                         Sema::DefaultedComparisonKind DCK);
7107 
7108 static Sema::ImplicitExceptionSpecification
7109 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7110   auto DFK = S.getDefaultedFunctionKind(FD);
7111   if (DFK.isSpecialMember())
7112     return ComputeDefaultedSpecialMemberExceptionSpec(
7113         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7114   if (DFK.isComparison())
7115     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7116                                                    DFK.asComparison());
7117 
7118   auto *CD = cast<CXXConstructorDecl>(FD);
7119   assert(CD->getInheritedConstructor() &&
7120          "only defaulted functions and inherited constructors have implicit "
7121          "exception specs");
7122   Sema::InheritedConstructorInfo ICI(
7123       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7124   return ComputeDefaultedSpecialMemberExceptionSpec(
7125       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7126 }
7127 
7128 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7129                                                             CXXMethodDecl *MD) {
7130   FunctionProtoType::ExtProtoInfo EPI;
7131 
7132   // Build an exception specification pointing back at this member.
7133   EPI.ExceptionSpec.Type = EST_Unevaluated;
7134   EPI.ExceptionSpec.SourceDecl = MD;
7135 
7136   // Set the calling convention to the default for C++ instance methods.
7137   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7138       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7139                                             /*IsCXXMethod=*/true));
7140   return EPI;
7141 }
7142 
7143 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7144   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7145   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7146     return;
7147 
7148   // Evaluate the exception specification.
7149   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7150   auto ESI = IES.getExceptionSpec();
7151 
7152   // Update the type of the special member to use it.
7153   UpdateExceptionSpec(FD, ESI);
7154 }
7155 
7156 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7157   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7158 
7159   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7160   if (!DefKind) {
7161     assert(FD->getDeclContext()->isDependentContext());
7162     return;
7163   }
7164 
7165   if (DefKind.isSpecialMember()
7166           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7167                                                   DefKind.asSpecialMember())
7168           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7169     FD->setInvalidDecl();
7170 }
7171 
7172 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7173                                                  CXXSpecialMember CSM) {
7174   CXXRecordDecl *RD = MD->getParent();
7175 
7176   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7177          "not an explicitly-defaulted special member");
7178 
7179   // Defer all checking for special members of a dependent type.
7180   if (RD->isDependentType())
7181     return false;
7182 
7183   // Whether this was the first-declared instance of the constructor.
7184   // This affects whether we implicitly add an exception spec and constexpr.
7185   bool First = MD == MD->getCanonicalDecl();
7186 
7187   bool HadError = false;
7188 
7189   // C++11 [dcl.fct.def.default]p1:
7190   //   A function that is explicitly defaulted shall
7191   //     -- be a special member function [...] (checked elsewhere),
7192   //     -- have the same type (except for ref-qualifiers, and except that a
7193   //        copy operation can take a non-const reference) as an implicit
7194   //        declaration, and
7195   //     -- not have default arguments.
7196   // C++2a changes the second bullet to instead delete the function if it's
7197   // defaulted on its first declaration, unless it's "an assignment operator,
7198   // and its return type differs or its parameter type is not a reference".
7199   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7200   bool ShouldDeleteForTypeMismatch = false;
7201   unsigned ExpectedParams = 1;
7202   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7203     ExpectedParams = 0;
7204   if (MD->getNumParams() != ExpectedParams) {
7205     // This checks for default arguments: a copy or move constructor with a
7206     // default argument is classified as a default constructor, and assignment
7207     // operations and destructors can't have default arguments.
7208     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7209       << CSM << MD->getSourceRange();
7210     HadError = true;
7211   } else if (MD->isVariadic()) {
7212     if (DeleteOnTypeMismatch)
7213       ShouldDeleteForTypeMismatch = true;
7214     else {
7215       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7216         << CSM << MD->getSourceRange();
7217       HadError = true;
7218     }
7219   }
7220 
7221   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7222 
7223   bool CanHaveConstParam = false;
7224   if (CSM == CXXCopyConstructor)
7225     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7226   else if (CSM == CXXCopyAssignment)
7227     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7228 
7229   QualType ReturnType = Context.VoidTy;
7230   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7231     // Check for return type matching.
7232     ReturnType = Type->getReturnType();
7233 
7234     QualType DeclType = Context.getTypeDeclType(RD);
7235     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7236     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7237 
7238     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7239       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7240         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7241       HadError = true;
7242     }
7243 
7244     // A defaulted special member cannot have cv-qualifiers.
7245     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7246       if (DeleteOnTypeMismatch)
7247         ShouldDeleteForTypeMismatch = true;
7248       else {
7249         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7250           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7251         HadError = true;
7252       }
7253     }
7254   }
7255 
7256   // Check for parameter type matching.
7257   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7258   bool HasConstParam = false;
7259   if (ExpectedParams && ArgType->isReferenceType()) {
7260     // Argument must be reference to possibly-const T.
7261     QualType ReferentType = ArgType->getPointeeType();
7262     HasConstParam = ReferentType.isConstQualified();
7263 
7264     if (ReferentType.isVolatileQualified()) {
7265       if (DeleteOnTypeMismatch)
7266         ShouldDeleteForTypeMismatch = true;
7267       else {
7268         Diag(MD->getLocation(),
7269              diag::err_defaulted_special_member_volatile_param) << CSM;
7270         HadError = true;
7271       }
7272     }
7273 
7274     if (HasConstParam && !CanHaveConstParam) {
7275       if (DeleteOnTypeMismatch)
7276         ShouldDeleteForTypeMismatch = true;
7277       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7278         Diag(MD->getLocation(),
7279              diag::err_defaulted_special_member_copy_const_param)
7280           << (CSM == CXXCopyAssignment);
7281         // FIXME: Explain why this special member can't be const.
7282         HadError = true;
7283       } else {
7284         Diag(MD->getLocation(),
7285              diag::err_defaulted_special_member_move_const_param)
7286           << (CSM == CXXMoveAssignment);
7287         HadError = true;
7288       }
7289     }
7290   } else if (ExpectedParams) {
7291     // A copy assignment operator can take its argument by value, but a
7292     // defaulted one cannot.
7293     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7294     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7295     HadError = true;
7296   }
7297 
7298   // C++11 [dcl.fct.def.default]p2:
7299   //   An explicitly-defaulted function may be declared constexpr only if it
7300   //   would have been implicitly declared as constexpr,
7301   // Do not apply this rule to members of class templates, since core issue 1358
7302   // makes such functions always instantiate to constexpr functions. For
7303   // functions which cannot be constexpr (for non-constructors in C++11 and for
7304   // destructors in C++14 and C++17), this is checked elsewhere.
7305   //
7306   // FIXME: This should not apply if the member is deleted.
7307   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7308                                                      HasConstParam);
7309   if ((getLangOpts().CPlusPlus20 ||
7310        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7311                                   : isa<CXXConstructorDecl>(MD))) &&
7312       MD->isConstexpr() && !Constexpr &&
7313       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7314     Diag(MD->getBeginLoc(), MD->isConsteval()
7315                                 ? diag::err_incorrect_defaulted_consteval
7316                                 : diag::err_incorrect_defaulted_constexpr)
7317         << CSM;
7318     // FIXME: Explain why the special member can't be constexpr.
7319     HadError = true;
7320   }
7321 
7322   if (First) {
7323     // C++2a [dcl.fct.def.default]p3:
7324     //   If a function is explicitly defaulted on its first declaration, it is
7325     //   implicitly considered to be constexpr if the implicit declaration
7326     //   would be.
7327     MD->setConstexprKind(
7328         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7329                   : CSK_unspecified);
7330 
7331     if (!Type->hasExceptionSpec()) {
7332       // C++2a [except.spec]p3:
7333       //   If a declaration of a function does not have a noexcept-specifier
7334       //   [and] is defaulted on its first declaration, [...] the exception
7335       //   specification is as specified below
7336       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7337       EPI.ExceptionSpec.Type = EST_Unevaluated;
7338       EPI.ExceptionSpec.SourceDecl = MD;
7339       MD->setType(Context.getFunctionType(ReturnType,
7340                                           llvm::makeArrayRef(&ArgType,
7341                                                              ExpectedParams),
7342                                           EPI));
7343     }
7344   }
7345 
7346   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7347     if (First) {
7348       SetDeclDeleted(MD, MD->getLocation());
7349       if (!inTemplateInstantiation() && !HadError) {
7350         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7351         if (ShouldDeleteForTypeMismatch) {
7352           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7353         } else {
7354           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7355         }
7356       }
7357       if (ShouldDeleteForTypeMismatch && !HadError) {
7358         Diag(MD->getLocation(),
7359              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7360       }
7361     } else {
7362       // C++11 [dcl.fct.def.default]p4:
7363       //   [For a] user-provided explicitly-defaulted function [...] if such a
7364       //   function is implicitly defined as deleted, the program is ill-formed.
7365       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7366       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7367       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7368       HadError = true;
7369     }
7370   }
7371 
7372   return HadError;
7373 }
7374 
7375 namespace {
7376 /// Helper class for building and checking a defaulted comparison.
7377 ///
7378 /// Defaulted functions are built in two phases:
7379 ///
7380 ///  * First, the set of operations that the function will perform are
7381 ///    identified, and some of them are checked. If any of the checked
7382 ///    operations is invalid in certain ways, the comparison function is
7383 ///    defined as deleted and no body is built.
7384 ///  * Then, if the function is not defined as deleted, the body is built.
7385 ///
7386 /// This is accomplished by performing two visitation steps over the eventual
7387 /// body of the function.
7388 template<typename Derived, typename ResultList, typename Result,
7389          typename Subobject>
7390 class DefaultedComparisonVisitor {
7391 public:
7392   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7393 
7394   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7395                              DefaultedComparisonKind DCK)
7396       : S(S), RD(RD), FD(FD), DCK(DCK) {
7397     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7398       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7399       // UnresolvedSet to avoid this copy.
7400       Fns.assign(Info->getUnqualifiedLookups().begin(),
7401                  Info->getUnqualifiedLookups().end());
7402     }
7403   }
7404 
7405   ResultList visit() {
7406     // The type of an lvalue naming a parameter of this function.
7407     QualType ParamLvalType =
7408         FD->getParamDecl(0)->getType().getNonReferenceType();
7409 
7410     ResultList Results;
7411 
7412     switch (DCK) {
7413     case DefaultedComparisonKind::None:
7414       llvm_unreachable("not a defaulted comparison");
7415 
7416     case DefaultedComparisonKind::Equal:
7417     case DefaultedComparisonKind::ThreeWay:
7418       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7419       return Results;
7420 
7421     case DefaultedComparisonKind::NotEqual:
7422     case DefaultedComparisonKind::Relational:
7423       Results.add(getDerived().visitExpandedSubobject(
7424           ParamLvalType, getDerived().getCompleteObject()));
7425       return Results;
7426     }
7427     llvm_unreachable("");
7428   }
7429 
7430 protected:
7431   Derived &getDerived() { return static_cast<Derived&>(*this); }
7432 
7433   /// Visit the expanded list of subobjects of the given type, as specified in
7434   /// C++2a [class.compare.default].
7435   ///
7436   /// \return \c true if the ResultList object said we're done, \c false if not.
7437   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7438                        Qualifiers Quals) {
7439     // C++2a [class.compare.default]p4:
7440     //   The direct base class subobjects of C
7441     for (CXXBaseSpecifier &Base : Record->bases())
7442       if (Results.add(getDerived().visitSubobject(
7443               S.Context.getQualifiedType(Base.getType(), Quals),
7444               getDerived().getBase(&Base))))
7445         return true;
7446 
7447     //   followed by the non-static data members of C
7448     for (FieldDecl *Field : Record->fields()) {
7449       // Recursively expand anonymous structs.
7450       if (Field->isAnonymousStructOrUnion()) {
7451         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7452                             Quals))
7453           return true;
7454         continue;
7455       }
7456 
7457       // Figure out the type of an lvalue denoting this field.
7458       Qualifiers FieldQuals = Quals;
7459       if (Field->isMutable())
7460         FieldQuals.removeConst();
7461       QualType FieldType =
7462           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7463 
7464       if (Results.add(getDerived().visitSubobject(
7465               FieldType, getDerived().getField(Field))))
7466         return true;
7467     }
7468 
7469     //   form a list of subobjects.
7470     return false;
7471   }
7472 
7473   Result visitSubobject(QualType Type, Subobject Subobj) {
7474     //   In that list, any subobject of array type is recursively expanded
7475     const ArrayType *AT = S.Context.getAsArrayType(Type);
7476     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7477       return getDerived().visitSubobjectArray(CAT->getElementType(),
7478                                               CAT->getSize(), Subobj);
7479     return getDerived().visitExpandedSubobject(Type, Subobj);
7480   }
7481 
7482   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7483                              Subobject Subobj) {
7484     return getDerived().visitSubobject(Type, Subobj);
7485   }
7486 
7487 protected:
7488   Sema &S;
7489   CXXRecordDecl *RD;
7490   FunctionDecl *FD;
7491   DefaultedComparisonKind DCK;
7492   UnresolvedSet<16> Fns;
7493 };
7494 
7495 /// Information about a defaulted comparison, as determined by
7496 /// DefaultedComparisonAnalyzer.
7497 struct DefaultedComparisonInfo {
7498   bool Deleted = false;
7499   bool Constexpr = true;
7500   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7501 
7502   static DefaultedComparisonInfo deleted() {
7503     DefaultedComparisonInfo Deleted;
7504     Deleted.Deleted = true;
7505     return Deleted;
7506   }
7507 
7508   bool add(const DefaultedComparisonInfo &R) {
7509     Deleted |= R.Deleted;
7510     Constexpr &= R.Constexpr;
7511     Category = commonComparisonType(Category, R.Category);
7512     return Deleted;
7513   }
7514 };
7515 
7516 /// An element in the expanded list of subobjects of a defaulted comparison, as
7517 /// specified in C++2a [class.compare.default]p4.
7518 struct DefaultedComparisonSubobject {
7519   enum { CompleteObject, Member, Base } Kind;
7520   NamedDecl *Decl;
7521   SourceLocation Loc;
7522 };
7523 
7524 /// A visitor over the notional body of a defaulted comparison that determines
7525 /// whether that body would be deleted or constexpr.
7526 class DefaultedComparisonAnalyzer
7527     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7528                                         DefaultedComparisonInfo,
7529                                         DefaultedComparisonInfo,
7530                                         DefaultedComparisonSubobject> {
7531 public:
7532   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7533 
7534 private:
7535   DiagnosticKind Diagnose;
7536 
7537 public:
7538   using Base = DefaultedComparisonVisitor;
7539   using Result = DefaultedComparisonInfo;
7540   using Subobject = DefaultedComparisonSubobject;
7541 
7542   friend Base;
7543 
7544   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7545                               DefaultedComparisonKind DCK,
7546                               DiagnosticKind Diagnose = NoDiagnostics)
7547       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7548 
7549   Result visit() {
7550     if ((DCK == DefaultedComparisonKind::Equal ||
7551          DCK == DefaultedComparisonKind::ThreeWay) &&
7552         RD->hasVariantMembers()) {
7553       // C++2a [class.compare.default]p2 [P2002R0]:
7554       //   A defaulted comparison operator function for class C is defined as
7555       //   deleted if [...] C has variant members.
7556       if (Diagnose == ExplainDeleted) {
7557         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7558           << FD << RD->isUnion() << RD;
7559       }
7560       return Result::deleted();
7561     }
7562 
7563     return Base::visit();
7564   }
7565 
7566 private:
7567   Subobject getCompleteObject() {
7568     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7569   }
7570 
7571   Subobject getBase(CXXBaseSpecifier *Base) {
7572     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7573                      Base->getBaseTypeLoc()};
7574   }
7575 
7576   Subobject getField(FieldDecl *Field) {
7577     return Subobject{Subobject::Member, Field, Field->getLocation()};
7578   }
7579 
7580   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7581     // C++2a [class.compare.default]p2 [P2002R0]:
7582     //   A defaulted <=> or == operator function for class C is defined as
7583     //   deleted if any non-static data member of C is of reference type
7584     if (Type->isReferenceType()) {
7585       if (Diagnose == ExplainDeleted) {
7586         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7587             << FD << RD;
7588       }
7589       return Result::deleted();
7590     }
7591 
7592     // [...] Let xi be an lvalue denoting the ith element [...]
7593     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7594     Expr *Args[] = {&Xi, &Xi};
7595 
7596     // All operators start by trying to apply that same operator recursively.
7597     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7598     assert(OO != OO_None && "not an overloaded operator!");
7599     return visitBinaryOperator(OO, Args, Subobj);
7600   }
7601 
7602   Result
7603   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7604                       Subobject Subobj,
7605                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7606     // Note that there is no need to consider rewritten candidates here if
7607     // we've already found there is no viable 'operator<=>' candidate (and are
7608     // considering synthesizing a '<=>' from '==' and '<').
7609     OverloadCandidateSet CandidateSet(
7610         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7611         OverloadCandidateSet::OperatorRewriteInfo(
7612             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7613 
7614     /// C++2a [class.compare.default]p1 [P2002R0]:
7615     ///   [...] the defaulted function itself is never a candidate for overload
7616     ///   resolution [...]
7617     CandidateSet.exclude(FD);
7618 
7619     if (Args[0]->getType()->isOverloadableType())
7620       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7621     else {
7622       // FIXME: We determine whether this is a valid expression by checking to
7623       // see if there's a viable builtin operator candidate for it. That isn't
7624       // really what the rules ask us to do, but should give the right results.
7625       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7626     }
7627 
7628     Result R;
7629 
7630     OverloadCandidateSet::iterator Best;
7631     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7632     case OR_Success: {
7633       // C++2a [class.compare.secondary]p2 [P2002R0]:
7634       //   The operator function [...] is defined as deleted if [...] the
7635       //   candidate selected by overload resolution is not a rewritten
7636       //   candidate.
7637       if ((DCK == DefaultedComparisonKind::NotEqual ||
7638            DCK == DefaultedComparisonKind::Relational) &&
7639           !Best->RewriteKind) {
7640         if (Diagnose == ExplainDeleted) {
7641           S.Diag(Best->Function->getLocation(),
7642                  diag::note_defaulted_comparison_not_rewritten_callee)
7643               << FD;
7644         }
7645         return Result::deleted();
7646       }
7647 
7648       // Throughout C++2a [class.compare]: if overload resolution does not
7649       // result in a usable function, the candidate function is defined as
7650       // deleted. This requires that we selected an accessible function.
7651       //
7652       // Note that this only considers the access of the function when named
7653       // within the type of the subobject, and not the access path for any
7654       // derived-to-base conversion.
7655       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7656       if (ArgClass && Best->FoundDecl.getDecl() &&
7657           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7658         QualType ObjectType = Subobj.Kind == Subobject::Member
7659                                   ? Args[0]->getType()
7660                                   : S.Context.getRecordType(RD);
7661         if (!S.isMemberAccessibleForDeletion(
7662                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7663                 Diagnose == ExplainDeleted
7664                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7665                           << FD << Subobj.Kind << Subobj.Decl
7666                     : S.PDiag()))
7667           return Result::deleted();
7668       }
7669 
7670       // C++2a [class.compare.default]p3 [P2002R0]:
7671       //   A defaulted comparison function is constexpr-compatible if [...]
7672       //   no overlod resolution performed [...] results in a non-constexpr
7673       //   function.
7674       if (FunctionDecl *BestFD = Best->Function) {
7675         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7676         // If it's not constexpr, explain why not.
7677         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7678           if (Subobj.Kind != Subobject::CompleteObject)
7679             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7680               << Subobj.Kind << Subobj.Decl;
7681           S.Diag(BestFD->getLocation(),
7682                  diag::note_defaulted_comparison_not_constexpr_here);
7683           // Bail out after explaining; we don't want any more notes.
7684           return Result::deleted();
7685         }
7686         R.Constexpr &= BestFD->isConstexpr();
7687       }
7688 
7689       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7690         if (auto *BestFD = Best->Function) {
7691           // If any callee has an undeduced return type, deduce it now.
7692           // FIXME: It's not clear how a failure here should be handled. For
7693           // now, we produce an eager diagnostic, because that is forward
7694           // compatible with most (all?) other reasonable options.
7695           if (BestFD->getReturnType()->isUndeducedType() &&
7696               S.DeduceReturnType(BestFD, FD->getLocation(),
7697                                  /*Diagnose=*/false)) {
7698             // Don't produce a duplicate error when asked to explain why the
7699             // comparison is deleted: we diagnosed that when initially checking
7700             // the defaulted operator.
7701             if (Diagnose == NoDiagnostics) {
7702               S.Diag(
7703                   FD->getLocation(),
7704                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7705                   << Subobj.Kind << Subobj.Decl;
7706               S.Diag(
7707                   Subobj.Loc,
7708                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7709                   << Subobj.Kind << Subobj.Decl;
7710               S.Diag(BestFD->getLocation(),
7711                      diag::note_defaulted_comparison_cannot_deduce_callee)
7712                   << Subobj.Kind << Subobj.Decl;
7713             }
7714             return Result::deleted();
7715           }
7716           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7717               BestFD->getCallResultType())) {
7718             R.Category = Info->Kind;
7719           } else {
7720             if (Diagnose == ExplainDeleted) {
7721               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7722                   << Subobj.Kind << Subobj.Decl
7723                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7724               S.Diag(BestFD->getLocation(),
7725                      diag::note_defaulted_comparison_cannot_deduce_callee)
7726                   << Subobj.Kind << Subobj.Decl;
7727             }
7728             return Result::deleted();
7729           }
7730         } else {
7731           Optional<ComparisonCategoryType> Cat =
7732               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7733           assert(Cat && "no category for builtin comparison?");
7734           R.Category = *Cat;
7735         }
7736       }
7737 
7738       // Note that we might be rewriting to a different operator. That call is
7739       // not considered until we come to actually build the comparison function.
7740       break;
7741     }
7742 
7743     case OR_Ambiguous:
7744       if (Diagnose == ExplainDeleted) {
7745         unsigned Kind = 0;
7746         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7747           Kind = OO == OO_EqualEqual ? 1 : 2;
7748         CandidateSet.NoteCandidates(
7749             PartialDiagnosticAt(
7750                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7751                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7752             S, OCD_AmbiguousCandidates, Args);
7753       }
7754       R = Result::deleted();
7755       break;
7756 
7757     case OR_Deleted:
7758       if (Diagnose == ExplainDeleted) {
7759         if ((DCK == DefaultedComparisonKind::NotEqual ||
7760              DCK == DefaultedComparisonKind::Relational) &&
7761             !Best->RewriteKind) {
7762           S.Diag(Best->Function->getLocation(),
7763                  diag::note_defaulted_comparison_not_rewritten_callee)
7764               << FD;
7765         } else {
7766           S.Diag(Subobj.Loc,
7767                  diag::note_defaulted_comparison_calls_deleted)
7768               << FD << Subobj.Kind << Subobj.Decl;
7769           S.NoteDeletedFunction(Best->Function);
7770         }
7771       }
7772       R = Result::deleted();
7773       break;
7774 
7775     case OR_No_Viable_Function:
7776       // If there's no usable candidate, we're done unless we can rewrite a
7777       // '<=>' in terms of '==' and '<'.
7778       if (OO == OO_Spaceship &&
7779           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7780         // For any kind of comparison category return type, we need a usable
7781         // '==' and a usable '<'.
7782         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7783                                        &CandidateSet)))
7784           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7785         break;
7786       }
7787 
7788       if (Diagnose == ExplainDeleted) {
7789         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7790             << FD << Subobj.Kind << Subobj.Decl;
7791 
7792         // For a three-way comparison, list both the candidates for the
7793         // original operator and the candidates for the synthesized operator.
7794         if (SpaceshipCandidates) {
7795           SpaceshipCandidates->NoteCandidates(
7796               S, Args,
7797               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7798                                                       Args, FD->getLocation()));
7799           S.Diag(Subobj.Loc,
7800                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7801               << (OO == OO_EqualEqual ? 0 : 1);
7802         }
7803 
7804         CandidateSet.NoteCandidates(
7805             S, Args,
7806             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7807                                             FD->getLocation()));
7808       }
7809       R = Result::deleted();
7810       break;
7811     }
7812 
7813     return R;
7814   }
7815 };
7816 
7817 /// A list of statements.
7818 struct StmtListResult {
7819   bool IsInvalid = false;
7820   llvm::SmallVector<Stmt*, 16> Stmts;
7821 
7822   bool add(const StmtResult &S) {
7823     IsInvalid |= S.isInvalid();
7824     if (IsInvalid)
7825       return true;
7826     Stmts.push_back(S.get());
7827     return false;
7828   }
7829 };
7830 
7831 /// A visitor over the notional body of a defaulted comparison that synthesizes
7832 /// the actual body.
7833 class DefaultedComparisonSynthesizer
7834     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7835                                         StmtListResult, StmtResult,
7836                                         std::pair<ExprResult, ExprResult>> {
7837   SourceLocation Loc;
7838   unsigned ArrayDepth = 0;
7839 
7840 public:
7841   using Base = DefaultedComparisonVisitor;
7842   using ExprPair = std::pair<ExprResult, ExprResult>;
7843 
7844   friend Base;
7845 
7846   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7847                                  DefaultedComparisonKind DCK,
7848                                  SourceLocation BodyLoc)
7849       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7850 
7851   /// Build a suitable function body for this defaulted comparison operator.
7852   StmtResult build() {
7853     Sema::CompoundScopeRAII CompoundScope(S);
7854 
7855     StmtListResult Stmts = visit();
7856     if (Stmts.IsInvalid)
7857       return StmtError();
7858 
7859     ExprResult RetVal;
7860     switch (DCK) {
7861     case DefaultedComparisonKind::None:
7862       llvm_unreachable("not a defaulted comparison");
7863 
7864     case DefaultedComparisonKind::Equal: {
7865       // C++2a [class.eq]p3:
7866       //   [...] compar[e] the corresponding elements [...] until the first
7867       //   index i where xi == yi yields [...] false. If no such index exists,
7868       //   V is true. Otherwise, V is false.
7869       //
7870       // Join the comparisons with '&&'s and return the result. Use a right
7871       // fold (traversing the conditions right-to-left), because that
7872       // short-circuits more naturally.
7873       auto OldStmts = std::move(Stmts.Stmts);
7874       Stmts.Stmts.clear();
7875       ExprResult CmpSoFar;
7876       // Finish a particular comparison chain.
7877       auto FinishCmp = [&] {
7878         if (Expr *Prior = CmpSoFar.get()) {
7879           // Convert the last expression to 'return ...;'
7880           if (RetVal.isUnset() && Stmts.Stmts.empty())
7881             RetVal = CmpSoFar;
7882           // Convert any prior comparison to 'if (!(...)) return false;'
7883           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7884             return true;
7885           CmpSoFar = ExprResult();
7886         }
7887         return false;
7888       };
7889       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7890         Expr *E = dyn_cast<Expr>(EAsStmt);
7891         if (!E) {
7892           // Found an array comparison.
7893           if (FinishCmp() || Stmts.add(EAsStmt))
7894             return StmtError();
7895           continue;
7896         }
7897 
7898         if (CmpSoFar.isUnset()) {
7899           CmpSoFar = E;
7900           continue;
7901         }
7902         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7903         if (CmpSoFar.isInvalid())
7904           return StmtError();
7905       }
7906       if (FinishCmp())
7907         return StmtError();
7908       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7909       //   If no such index exists, V is true.
7910       if (RetVal.isUnset())
7911         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7912       break;
7913     }
7914 
7915     case DefaultedComparisonKind::ThreeWay: {
7916       // Per C++2a [class.spaceship]p3, as a fallback add:
7917       // return static_cast<R>(std::strong_ordering::equal);
7918       QualType StrongOrdering = S.CheckComparisonCategoryType(
7919           ComparisonCategoryType::StrongOrdering, Loc,
7920           Sema::ComparisonCategoryUsage::DefaultedOperator);
7921       if (StrongOrdering.isNull())
7922         return StmtError();
7923       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7924                              .getValueInfo(ComparisonCategoryResult::Equal)
7925                              ->VD;
7926       RetVal = getDecl(EqualVD);
7927       if (RetVal.isInvalid())
7928         return StmtError();
7929       RetVal = buildStaticCastToR(RetVal.get());
7930       break;
7931     }
7932 
7933     case DefaultedComparisonKind::NotEqual:
7934     case DefaultedComparisonKind::Relational:
7935       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7936       break;
7937     }
7938 
7939     // Build the final return statement.
7940     if (RetVal.isInvalid())
7941       return StmtError();
7942     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7943     if (ReturnStmt.isInvalid())
7944       return StmtError();
7945     Stmts.Stmts.push_back(ReturnStmt.get());
7946 
7947     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7948   }
7949 
7950 private:
7951   ExprResult getDecl(ValueDecl *VD) {
7952     return S.BuildDeclarationNameExpr(
7953         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7954   }
7955 
7956   ExprResult getParam(unsigned I) {
7957     ParmVarDecl *PD = FD->getParamDecl(I);
7958     return getDecl(PD);
7959   }
7960 
7961   ExprPair getCompleteObject() {
7962     unsigned Param = 0;
7963     ExprResult LHS;
7964     if (isa<CXXMethodDecl>(FD)) {
7965       // LHS is '*this'.
7966       LHS = S.ActOnCXXThis(Loc);
7967       if (!LHS.isInvalid())
7968         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7969     } else {
7970       LHS = getParam(Param++);
7971     }
7972     ExprResult RHS = getParam(Param++);
7973     assert(Param == FD->getNumParams());
7974     return {LHS, RHS};
7975   }
7976 
7977   ExprPair getBase(CXXBaseSpecifier *Base) {
7978     ExprPair Obj = getCompleteObject();
7979     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7980       return {ExprError(), ExprError()};
7981     CXXCastPath Path = {Base};
7982     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7983                                 CK_DerivedToBase, VK_LValue, &Path),
7984             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7985                                 CK_DerivedToBase, VK_LValue, &Path)};
7986   }
7987 
7988   ExprPair getField(FieldDecl *Field) {
7989     ExprPair Obj = getCompleteObject();
7990     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7991       return {ExprError(), ExprError()};
7992 
7993     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
7994     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
7995     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
7996                                       CXXScopeSpec(), Field, Found, NameInfo),
7997             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
7998                                       CXXScopeSpec(), Field, Found, NameInfo)};
7999   }
8000 
8001   // FIXME: When expanding a subobject, register a note in the code synthesis
8002   // stack to say which subobject we're comparing.
8003 
8004   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8005     if (Cond.isInvalid())
8006       return StmtError();
8007 
8008     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8009     if (NotCond.isInvalid())
8010       return StmtError();
8011 
8012     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8013     assert(!False.isInvalid() && "should never fail");
8014     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8015     if (ReturnFalse.isInvalid())
8016       return StmtError();
8017 
8018     return S.ActOnIfStmt(Loc, false, nullptr,
8019                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8020                                           Sema::ConditionKind::Boolean),
8021                          ReturnFalse.get(), SourceLocation(), nullptr);
8022   }
8023 
8024   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8025                                  ExprPair Subobj) {
8026     QualType SizeType = S.Context.getSizeType();
8027     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8028 
8029     // Build 'size_t i$n = 0'.
8030     IdentifierInfo *IterationVarName = nullptr;
8031     {
8032       SmallString<8> Str;
8033       llvm::raw_svector_ostream OS(Str);
8034       OS << "i" << ArrayDepth;
8035       IterationVarName = &S.Context.Idents.get(OS.str());
8036     }
8037     VarDecl *IterationVar = VarDecl::Create(
8038         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8039         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8040     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8041     IterationVar->setInit(
8042         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8043     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8044 
8045     auto IterRef = [&] {
8046       ExprResult Ref = S.BuildDeclarationNameExpr(
8047           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8048           IterationVar);
8049       assert(!Ref.isInvalid() && "can't reference our own variable?");
8050       return Ref.get();
8051     };
8052 
8053     // Build 'i$n != Size'.
8054     ExprResult Cond = S.CreateBuiltinBinOp(
8055         Loc, BO_NE, IterRef(),
8056         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8057     assert(!Cond.isInvalid() && "should never fail");
8058 
8059     // Build '++i$n'.
8060     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8061     assert(!Inc.isInvalid() && "should never fail");
8062 
8063     // Build 'a[i$n]' and 'b[i$n]'.
8064     auto Index = [&](ExprResult E) {
8065       if (E.isInvalid())
8066         return ExprError();
8067       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8068     };
8069     Subobj.first = Index(Subobj.first);
8070     Subobj.second = Index(Subobj.second);
8071 
8072     // Compare the array elements.
8073     ++ArrayDepth;
8074     StmtResult Substmt = visitSubobject(Type, Subobj);
8075     --ArrayDepth;
8076 
8077     if (Substmt.isInvalid())
8078       return StmtError();
8079 
8080     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8081     // For outer levels or for an 'operator<=>' we already have a suitable
8082     // statement that returns as necessary.
8083     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8084       assert(DCK == DefaultedComparisonKind::Equal &&
8085              "should have non-expression statement");
8086       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8087       if (Substmt.isInvalid())
8088         return StmtError();
8089     }
8090 
8091     // Build 'for (...) ...'
8092     return S.ActOnForStmt(Loc, Loc, Init,
8093                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8094                                            Sema::ConditionKind::Boolean),
8095                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8096                           Substmt.get());
8097   }
8098 
8099   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8100     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8101       return StmtError();
8102 
8103     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8104     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8105     ExprResult Op;
8106     if (Type->isOverloadableType())
8107       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8108                                    Obj.second.get(), /*PerformADL=*/true,
8109                                    /*AllowRewrittenCandidates=*/true, FD);
8110     else
8111       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8112     if (Op.isInvalid())
8113       return StmtError();
8114 
8115     switch (DCK) {
8116     case DefaultedComparisonKind::None:
8117       llvm_unreachable("not a defaulted comparison");
8118 
8119     case DefaultedComparisonKind::Equal:
8120       // Per C++2a [class.eq]p2, each comparison is individually contextually
8121       // converted to bool.
8122       Op = S.PerformContextuallyConvertToBool(Op.get());
8123       if (Op.isInvalid())
8124         return StmtError();
8125       return Op.get();
8126 
8127     case DefaultedComparisonKind::ThreeWay: {
8128       // Per C++2a [class.spaceship]p3, form:
8129       //   if (R cmp = static_cast<R>(op); cmp != 0)
8130       //     return cmp;
8131       QualType R = FD->getReturnType();
8132       Op = buildStaticCastToR(Op.get());
8133       if (Op.isInvalid())
8134         return StmtError();
8135 
8136       // R cmp = ...;
8137       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8138       VarDecl *VD =
8139           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8140                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8141       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8142       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8143 
8144       // cmp != 0
8145       ExprResult VDRef = getDecl(VD);
8146       if (VDRef.isInvalid())
8147         return StmtError();
8148       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8149       Expr *Zero =
8150           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8151       ExprResult Comp;
8152       if (VDRef.get()->getType()->isOverloadableType())
8153         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8154                                        true, FD);
8155       else
8156         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8157       if (Comp.isInvalid())
8158         return StmtError();
8159       Sema::ConditionResult Cond = S.ActOnCondition(
8160           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8161       if (Cond.isInvalid())
8162         return StmtError();
8163 
8164       // return cmp;
8165       VDRef = getDecl(VD);
8166       if (VDRef.isInvalid())
8167         return StmtError();
8168       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8169       if (ReturnStmt.isInvalid())
8170         return StmtError();
8171 
8172       // if (...)
8173       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond,
8174                            ReturnStmt.get(), /*ElseLoc=*/SourceLocation(),
8175                            /*Else=*/nullptr);
8176     }
8177 
8178     case DefaultedComparisonKind::NotEqual:
8179     case DefaultedComparisonKind::Relational:
8180       // C++2a [class.compare.secondary]p2:
8181       //   Otherwise, the operator function yields x @ y.
8182       return Op.get();
8183     }
8184     llvm_unreachable("");
8185   }
8186 
8187   /// Build "static_cast<R>(E)".
8188   ExprResult buildStaticCastToR(Expr *E) {
8189     QualType R = FD->getReturnType();
8190     assert(!R->isUndeducedType() && "type should have been deduced already");
8191 
8192     // Don't bother forming a no-op cast in the common case.
8193     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8194       return E;
8195     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8196                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8197                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8198   }
8199 };
8200 }
8201 
8202 /// Perform the unqualified lookups that might be needed to form a defaulted
8203 /// comparison function for the given operator.
8204 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8205                                                   UnresolvedSetImpl &Operators,
8206                                                   OverloadedOperatorKind Op) {
8207   auto Lookup = [&](OverloadedOperatorKind OO) {
8208     Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators);
8209   };
8210 
8211   // Every defaulted operator looks up itself.
8212   Lookup(Op);
8213   // ... and the rewritten form of itself, if any.
8214   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8215     Lookup(ExtraOp);
8216 
8217   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8218   // synthesize a three-way comparison from '<' and '=='. In a dependent
8219   // context, we also need to look up '==' in case we implicitly declare a
8220   // defaulted 'operator=='.
8221   if (Op == OO_Spaceship) {
8222     Lookup(OO_ExclaimEqual);
8223     Lookup(OO_Less);
8224     Lookup(OO_EqualEqual);
8225   }
8226 }
8227 
8228 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8229                                               DefaultedComparisonKind DCK) {
8230   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8231 
8232   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8233   assert(RD && "defaulted comparison is not defaulted in a class");
8234 
8235   // Perform any unqualified lookups we're going to need to default this
8236   // function.
8237   if (S) {
8238     UnresolvedSet<32> Operators;
8239     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8240                                           FD->getOverloadedOperator());
8241     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8242         Context, Operators.pairs()));
8243   }
8244 
8245   // C++2a [class.compare.default]p1:
8246   //   A defaulted comparison operator function for some class C shall be a
8247   //   non-template function declared in the member-specification of C that is
8248   //    -- a non-static const member of C having one parameter of type
8249   //       const C&, or
8250   //    -- a friend of C having two parameters of type const C& or two
8251   //       parameters of type C.
8252   QualType ExpectedParmType1 = Context.getRecordType(RD);
8253   QualType ExpectedParmType2 =
8254       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8255   if (isa<CXXMethodDecl>(FD))
8256     ExpectedParmType1 = ExpectedParmType2;
8257   for (const ParmVarDecl *Param : FD->parameters()) {
8258     if (!Param->getType()->isDependentType() &&
8259         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8260         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8261       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8262       // corresponding defaulted 'operator<=>' already.
8263       if (!FD->isImplicit()) {
8264         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8265             << (int)DCK << Param->getType() << ExpectedParmType1
8266             << !isa<CXXMethodDecl>(FD)
8267             << ExpectedParmType2 << Param->getSourceRange();
8268       }
8269       return true;
8270     }
8271   }
8272   if (FD->getNumParams() == 2 &&
8273       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8274                            FD->getParamDecl(1)->getType())) {
8275     if (!FD->isImplicit()) {
8276       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8277           << (int)DCK
8278           << FD->getParamDecl(0)->getType()
8279           << FD->getParamDecl(0)->getSourceRange()
8280           << FD->getParamDecl(1)->getType()
8281           << FD->getParamDecl(1)->getSourceRange();
8282     }
8283     return true;
8284   }
8285 
8286   // ... non-static const member ...
8287   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8288     assert(!MD->isStatic() && "comparison function cannot be a static member");
8289     if (!MD->isConst()) {
8290       SourceLocation InsertLoc;
8291       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8292         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8293       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8294       // corresponding defaulted 'operator<=>' already.
8295       if (!MD->isImplicit()) {
8296         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8297           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8298       }
8299 
8300       // Add the 'const' to the type to recover.
8301       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8302       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8303       EPI.TypeQuals.addConst();
8304       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8305                                           FPT->getParamTypes(), EPI));
8306     }
8307   } else {
8308     // A non-member function declared in a class must be a friend.
8309     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8310   }
8311 
8312   // C++2a [class.eq]p1, [class.rel]p1:
8313   //   A [defaulted comparison other than <=>] shall have a declared return
8314   //   type bool.
8315   if (DCK != DefaultedComparisonKind::ThreeWay &&
8316       !FD->getDeclaredReturnType()->isDependentType() &&
8317       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8318     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8319         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8320         << FD->getReturnTypeSourceRange();
8321     return true;
8322   }
8323   // C++2a [class.spaceship]p2 [P2002R0]:
8324   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8325   //   R shall not contain a placeholder type.
8326   if (DCK == DefaultedComparisonKind::ThreeWay &&
8327       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8328       !Context.hasSameType(FD->getDeclaredReturnType(),
8329                            Context.getAutoDeductType())) {
8330     Diag(FD->getLocation(),
8331          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8332         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8333         << FD->getReturnTypeSourceRange();
8334     return true;
8335   }
8336 
8337   // For a defaulted function in a dependent class, defer all remaining checks
8338   // until instantiation.
8339   if (RD->isDependentType())
8340     return false;
8341 
8342   // Determine whether the function should be defined as deleted.
8343   DefaultedComparisonInfo Info =
8344       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8345 
8346   bool First = FD == FD->getCanonicalDecl();
8347 
8348   // If we want to delete the function, then do so; there's nothing else to
8349   // check in that case.
8350   if (Info.Deleted) {
8351     if (!First) {
8352       // C++11 [dcl.fct.def.default]p4:
8353       //   [For a] user-provided explicitly-defaulted function [...] if such a
8354       //   function is implicitly defined as deleted, the program is ill-formed.
8355       //
8356       // This is really just a consequence of the general rule that you can
8357       // only delete a function on its first declaration.
8358       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8359           << FD->isImplicit() << (int)DCK;
8360       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8361                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8362           .visit();
8363       return true;
8364     }
8365 
8366     SetDeclDeleted(FD, FD->getLocation());
8367     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8368       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8369           << (int)DCK;
8370       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8371                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8372           .visit();
8373     }
8374     return false;
8375   }
8376 
8377   // C++2a [class.spaceship]p2:
8378   //   The return type is deduced as the common comparison type of R0, R1, ...
8379   if (DCK == DefaultedComparisonKind::ThreeWay &&
8380       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8381     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8382     if (RetLoc.isInvalid())
8383       RetLoc = FD->getBeginLoc();
8384     // FIXME: Should we really care whether we have the complete type and the
8385     // 'enumerator' constants here? A forward declaration seems sufficient.
8386     QualType Cat = CheckComparisonCategoryType(
8387         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8388     if (Cat.isNull())
8389       return true;
8390     Context.adjustDeducedFunctionResultType(
8391         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8392   }
8393 
8394   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8395   //   An explicitly-defaulted function that is not defined as deleted may be
8396   //   declared constexpr or consteval only if it is constexpr-compatible.
8397   // C++2a [class.compare.default]p3 [P2002R0]:
8398   //   A defaulted comparison function is constexpr-compatible if it satisfies
8399   //   the requirements for a constexpr function [...]
8400   // The only relevant requirements are that the parameter and return types are
8401   // literal types. The remaining conditions are checked by the analyzer.
8402   if (FD->isConstexpr()) {
8403     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8404         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8405         !Info.Constexpr) {
8406       Diag(FD->getBeginLoc(),
8407            diag::err_incorrect_defaulted_comparison_constexpr)
8408           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8409       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8410                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8411           .visit();
8412     }
8413   }
8414 
8415   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8416   //   If a constexpr-compatible function is explicitly defaulted on its first
8417   //   declaration, it is implicitly considered to be constexpr.
8418   // FIXME: Only applying this to the first declaration seems problematic, as
8419   // simple reorderings can affect the meaning of the program.
8420   if (First && !FD->isConstexpr() && Info.Constexpr)
8421     FD->setConstexprKind(CSK_constexpr);
8422 
8423   // C++2a [except.spec]p3:
8424   //   If a declaration of a function does not have a noexcept-specifier
8425   //   [and] is defaulted on its first declaration, [...] the exception
8426   //   specification is as specified below
8427   if (FD->getExceptionSpecType() == EST_None) {
8428     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8429     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8430     EPI.ExceptionSpec.Type = EST_Unevaluated;
8431     EPI.ExceptionSpec.SourceDecl = FD;
8432     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8433                                         FPT->getParamTypes(), EPI));
8434   }
8435 
8436   return false;
8437 }
8438 
8439 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8440                                              FunctionDecl *Spaceship) {
8441   Sema::CodeSynthesisContext Ctx;
8442   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8443   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8444   Ctx.Entity = Spaceship;
8445   pushCodeSynthesisContext(Ctx);
8446 
8447   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8448     EqualEqual->setImplicit();
8449 
8450   popCodeSynthesisContext();
8451 }
8452 
8453 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8454                                      DefaultedComparisonKind DCK) {
8455   assert(FD->isDefaulted() && !FD->isDeleted() &&
8456          !FD->doesThisDeclarationHaveABody());
8457   if (FD->willHaveBody() || FD->isInvalidDecl())
8458     return;
8459 
8460   SynthesizedFunctionScope Scope(*this, FD);
8461 
8462   // Add a context note for diagnostics produced after this point.
8463   Scope.addContextNote(UseLoc);
8464 
8465   {
8466     // Build and set up the function body.
8467     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8468     SourceLocation BodyLoc =
8469         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8470     StmtResult Body =
8471         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8472     if (Body.isInvalid()) {
8473       FD->setInvalidDecl();
8474       return;
8475     }
8476     FD->setBody(Body.get());
8477     FD->markUsed(Context);
8478   }
8479 
8480   // The exception specification is needed because we are defining the
8481   // function. Note that this will reuse the body we just built.
8482   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8483 
8484   if (ASTMutationListener *L = getASTMutationListener())
8485     L->CompletedImplicitDefinition(FD);
8486 }
8487 
8488 static Sema::ImplicitExceptionSpecification
8489 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8490                                         FunctionDecl *FD,
8491                                         Sema::DefaultedComparisonKind DCK) {
8492   ComputingExceptionSpec CES(S, FD, Loc);
8493   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8494 
8495   if (FD->isInvalidDecl())
8496     return ExceptSpec;
8497 
8498   // The common case is that we just defined the comparison function. In that
8499   // case, just look at whether the body can throw.
8500   if (FD->hasBody()) {
8501     ExceptSpec.CalledStmt(FD->getBody());
8502   } else {
8503     // Otherwise, build a body so we can check it. This should ideally only
8504     // happen when we're not actually marking the function referenced. (This is
8505     // only really important for efficiency: we don't want to build and throw
8506     // away bodies for comparison functions more than we strictly need to.)
8507 
8508     // Pretend to synthesize the function body in an unevaluated context.
8509     // Note that we can't actually just go ahead and define the function here:
8510     // we are not permitted to mark its callees as referenced.
8511     Sema::SynthesizedFunctionScope Scope(S, FD);
8512     EnterExpressionEvaluationContext Context(
8513         S, Sema::ExpressionEvaluationContext::Unevaluated);
8514 
8515     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8516     SourceLocation BodyLoc =
8517         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8518     StmtResult Body =
8519         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8520     if (!Body.isInvalid())
8521       ExceptSpec.CalledStmt(Body.get());
8522 
8523     // FIXME: Can we hold onto this body and just transform it to potentially
8524     // evaluated when we're asked to define the function rather than rebuilding
8525     // it? Either that, or we should only build the bits of the body that we
8526     // need (the expressions, not the statements).
8527   }
8528 
8529   return ExceptSpec;
8530 }
8531 
8532 void Sema::CheckDelayedMemberExceptionSpecs() {
8533   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8534   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8535 
8536   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8537   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8538 
8539   // Perform any deferred checking of exception specifications for virtual
8540   // destructors.
8541   for (auto &Check : Overriding)
8542     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8543 
8544   // Perform any deferred checking of exception specifications for befriended
8545   // special members.
8546   for (auto &Check : Equivalent)
8547     CheckEquivalentExceptionSpec(Check.second, Check.first);
8548 }
8549 
8550 namespace {
8551 /// CRTP base class for visiting operations performed by a special member
8552 /// function (or inherited constructor).
8553 template<typename Derived>
8554 struct SpecialMemberVisitor {
8555   Sema &S;
8556   CXXMethodDecl *MD;
8557   Sema::CXXSpecialMember CSM;
8558   Sema::InheritedConstructorInfo *ICI;
8559 
8560   // Properties of the special member, computed for convenience.
8561   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8562 
8563   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8564                        Sema::InheritedConstructorInfo *ICI)
8565       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8566     switch (CSM) {
8567     case Sema::CXXDefaultConstructor:
8568     case Sema::CXXCopyConstructor:
8569     case Sema::CXXMoveConstructor:
8570       IsConstructor = true;
8571       break;
8572     case Sema::CXXCopyAssignment:
8573     case Sema::CXXMoveAssignment:
8574       IsAssignment = true;
8575       break;
8576     case Sema::CXXDestructor:
8577       break;
8578     case Sema::CXXInvalid:
8579       llvm_unreachable("invalid special member kind");
8580     }
8581 
8582     if (MD->getNumParams()) {
8583       if (const ReferenceType *RT =
8584               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8585         ConstArg = RT->getPointeeType().isConstQualified();
8586     }
8587   }
8588 
8589   Derived &getDerived() { return static_cast<Derived&>(*this); }
8590 
8591   /// Is this a "move" special member?
8592   bool isMove() const {
8593     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8594   }
8595 
8596   /// Look up the corresponding special member in the given class.
8597   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8598                                              unsigned Quals, bool IsMutable) {
8599     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8600                                        ConstArg && !IsMutable);
8601   }
8602 
8603   /// Look up the constructor for the specified base class to see if it's
8604   /// overridden due to this being an inherited constructor.
8605   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8606     if (!ICI)
8607       return {};
8608     assert(CSM == Sema::CXXDefaultConstructor);
8609     auto *BaseCtor =
8610       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8611     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8612       return MD;
8613     return {};
8614   }
8615 
8616   /// A base or member subobject.
8617   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8618 
8619   /// Get the location to use for a subobject in diagnostics.
8620   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8621     // FIXME: For an indirect virtual base, the direct base leading to
8622     // the indirect virtual base would be a more useful choice.
8623     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8624       return B->getBaseTypeLoc();
8625     else
8626       return Subobj.get<FieldDecl*>()->getLocation();
8627   }
8628 
8629   enum BasesToVisit {
8630     /// Visit all non-virtual (direct) bases.
8631     VisitNonVirtualBases,
8632     /// Visit all direct bases, virtual or not.
8633     VisitDirectBases,
8634     /// Visit all non-virtual bases, and all virtual bases if the class
8635     /// is not abstract.
8636     VisitPotentiallyConstructedBases,
8637     /// Visit all direct or virtual bases.
8638     VisitAllBases
8639   };
8640 
8641   // Visit the bases and members of the class.
8642   bool visit(BasesToVisit Bases) {
8643     CXXRecordDecl *RD = MD->getParent();
8644 
8645     if (Bases == VisitPotentiallyConstructedBases)
8646       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8647 
8648     for (auto &B : RD->bases())
8649       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8650           getDerived().visitBase(&B))
8651         return true;
8652 
8653     if (Bases == VisitAllBases)
8654       for (auto &B : RD->vbases())
8655         if (getDerived().visitBase(&B))
8656           return true;
8657 
8658     for (auto *F : RD->fields())
8659       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8660           getDerived().visitField(F))
8661         return true;
8662 
8663     return false;
8664   }
8665 };
8666 }
8667 
8668 namespace {
8669 struct SpecialMemberDeletionInfo
8670     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8671   bool Diagnose;
8672 
8673   SourceLocation Loc;
8674 
8675   bool AllFieldsAreConst;
8676 
8677   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8678                             Sema::CXXSpecialMember CSM,
8679                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8680       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8681         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8682 
8683   bool inUnion() const { return MD->getParent()->isUnion(); }
8684 
8685   Sema::CXXSpecialMember getEffectiveCSM() {
8686     return ICI ? Sema::CXXInvalid : CSM;
8687   }
8688 
8689   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8690 
8691   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8692   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8693 
8694   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8695   bool shouldDeleteForField(FieldDecl *FD);
8696   bool shouldDeleteForAllConstMembers();
8697 
8698   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8699                                      unsigned Quals);
8700   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8701                                     Sema::SpecialMemberOverloadResult SMOR,
8702                                     bool IsDtorCallInCtor);
8703 
8704   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8705 };
8706 }
8707 
8708 /// Is the given special member inaccessible when used on the given
8709 /// sub-object.
8710 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8711                                              CXXMethodDecl *target) {
8712   /// If we're operating on a base class, the object type is the
8713   /// type of this special member.
8714   QualType objectTy;
8715   AccessSpecifier access = target->getAccess();
8716   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8717     objectTy = S.Context.getTypeDeclType(MD->getParent());
8718     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8719 
8720   // If we're operating on a field, the object type is the type of the field.
8721   } else {
8722     objectTy = S.Context.getTypeDeclType(target->getParent());
8723   }
8724 
8725   return S.isMemberAccessibleForDeletion(
8726       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8727 }
8728 
8729 /// Check whether we should delete a special member due to the implicit
8730 /// definition containing a call to a special member of a subobject.
8731 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8732     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8733     bool IsDtorCallInCtor) {
8734   CXXMethodDecl *Decl = SMOR.getMethod();
8735   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8736 
8737   int DiagKind = -1;
8738 
8739   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8740     DiagKind = !Decl ? 0 : 1;
8741   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8742     DiagKind = 2;
8743   else if (!isAccessible(Subobj, Decl))
8744     DiagKind = 3;
8745   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8746            !Decl->isTrivial()) {
8747     // A member of a union must have a trivial corresponding special member.
8748     // As a weird special case, a destructor call from a union's constructor
8749     // must be accessible and non-deleted, but need not be trivial. Such a
8750     // destructor is never actually called, but is semantically checked as
8751     // if it were.
8752     DiagKind = 4;
8753   }
8754 
8755   if (DiagKind == -1)
8756     return false;
8757 
8758   if (Diagnose) {
8759     if (Field) {
8760       S.Diag(Field->getLocation(),
8761              diag::note_deleted_special_member_class_subobject)
8762         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8763         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8764     } else {
8765       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8766       S.Diag(Base->getBeginLoc(),
8767              diag::note_deleted_special_member_class_subobject)
8768           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8769           << Base->getType() << DiagKind << IsDtorCallInCtor
8770           << /*IsObjCPtr*/false;
8771     }
8772 
8773     if (DiagKind == 1)
8774       S.NoteDeletedFunction(Decl);
8775     // FIXME: Explain inaccessibility if DiagKind == 3.
8776   }
8777 
8778   return true;
8779 }
8780 
8781 /// Check whether we should delete a special member function due to having a
8782 /// direct or virtual base class or non-static data member of class type M.
8783 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8784     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8785   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8786   bool IsMutable = Field && Field->isMutable();
8787 
8788   // C++11 [class.ctor]p5:
8789   // -- any direct or virtual base class, or non-static data member with no
8790   //    brace-or-equal-initializer, has class type M (or array thereof) and
8791   //    either M has no default constructor or overload resolution as applied
8792   //    to M's default constructor results in an ambiguity or in a function
8793   //    that is deleted or inaccessible
8794   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8795   // -- a direct or virtual base class B that cannot be copied/moved because
8796   //    overload resolution, as applied to B's corresponding special member,
8797   //    results in an ambiguity or a function that is deleted or inaccessible
8798   //    from the defaulted special member
8799   // C++11 [class.dtor]p5:
8800   // -- any direct or virtual base class [...] has a type with a destructor
8801   //    that is deleted or inaccessible
8802   if (!(CSM == Sema::CXXDefaultConstructor &&
8803         Field && Field->hasInClassInitializer()) &&
8804       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8805                                    false))
8806     return true;
8807 
8808   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8809   // -- any direct or virtual base class or non-static data member has a
8810   //    type with a destructor that is deleted or inaccessible
8811   if (IsConstructor) {
8812     Sema::SpecialMemberOverloadResult SMOR =
8813         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8814                               false, false, false, false, false);
8815     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8816       return true;
8817   }
8818 
8819   return false;
8820 }
8821 
8822 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8823     FieldDecl *FD, QualType FieldType) {
8824   // The defaulted special functions are defined as deleted if this is a variant
8825   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8826   // type under ARC.
8827   if (!FieldType.hasNonTrivialObjCLifetime())
8828     return false;
8829 
8830   // Don't make the defaulted default constructor defined as deleted if the
8831   // member has an in-class initializer.
8832   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8833     return false;
8834 
8835   if (Diagnose) {
8836     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8837     S.Diag(FD->getLocation(),
8838            diag::note_deleted_special_member_class_subobject)
8839         << getEffectiveCSM() << ParentClass << /*IsField*/true
8840         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8841   }
8842 
8843   return true;
8844 }
8845 
8846 /// Check whether we should delete a special member function due to the class
8847 /// having a particular direct or virtual base class.
8848 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8849   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8850   // If program is correct, BaseClass cannot be null, but if it is, the error
8851   // must be reported elsewhere.
8852   if (!BaseClass)
8853     return false;
8854   // If we have an inheriting constructor, check whether we're calling an
8855   // inherited constructor instead of a default constructor.
8856   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8857   if (auto *BaseCtor = SMOR.getMethod()) {
8858     // Note that we do not check access along this path; other than that,
8859     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8860     // FIXME: Check that the base has a usable destructor! Sink this into
8861     // shouldDeleteForClassSubobject.
8862     if (BaseCtor->isDeleted() && Diagnose) {
8863       S.Diag(Base->getBeginLoc(),
8864              diag::note_deleted_special_member_class_subobject)
8865           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8866           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8867           << /*IsObjCPtr*/false;
8868       S.NoteDeletedFunction(BaseCtor);
8869     }
8870     return BaseCtor->isDeleted();
8871   }
8872   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8873 }
8874 
8875 /// Check whether we should delete a special member function due to the class
8876 /// having a particular non-static data member.
8877 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8878   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8879   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8880 
8881   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8882     return true;
8883 
8884   if (CSM == Sema::CXXDefaultConstructor) {
8885     // For a default constructor, all references must be initialized in-class
8886     // and, if a union, it must have a non-const member.
8887     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8888       if (Diagnose)
8889         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8890           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8891       return true;
8892     }
8893     // C++11 [class.ctor]p5: any non-variant non-static data member of
8894     // const-qualified type (or array thereof) with no
8895     // brace-or-equal-initializer does not have a user-provided default
8896     // constructor.
8897     if (!inUnion() && FieldType.isConstQualified() &&
8898         !FD->hasInClassInitializer() &&
8899         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8900       if (Diagnose)
8901         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8902           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8903       return true;
8904     }
8905 
8906     if (inUnion() && !FieldType.isConstQualified())
8907       AllFieldsAreConst = false;
8908   } else if (CSM == Sema::CXXCopyConstructor) {
8909     // For a copy constructor, data members must not be of rvalue reference
8910     // type.
8911     if (FieldType->isRValueReferenceType()) {
8912       if (Diagnose)
8913         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8914           << MD->getParent() << FD << FieldType;
8915       return true;
8916     }
8917   } else if (IsAssignment) {
8918     // For an assignment operator, data members must not be of reference type.
8919     if (FieldType->isReferenceType()) {
8920       if (Diagnose)
8921         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8922           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8923       return true;
8924     }
8925     if (!FieldRecord && FieldType.isConstQualified()) {
8926       // C++11 [class.copy]p23:
8927       // -- a non-static data member of const non-class type (or array thereof)
8928       if (Diagnose)
8929         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8930           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8931       return true;
8932     }
8933   }
8934 
8935   if (FieldRecord) {
8936     // Some additional restrictions exist on the variant members.
8937     if (!inUnion() && FieldRecord->isUnion() &&
8938         FieldRecord->isAnonymousStructOrUnion()) {
8939       bool AllVariantFieldsAreConst = true;
8940 
8941       // FIXME: Handle anonymous unions declared within anonymous unions.
8942       for (auto *UI : FieldRecord->fields()) {
8943         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8944 
8945         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8946           return true;
8947 
8948         if (!UnionFieldType.isConstQualified())
8949           AllVariantFieldsAreConst = false;
8950 
8951         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8952         if (UnionFieldRecord &&
8953             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8954                                           UnionFieldType.getCVRQualifiers()))
8955           return true;
8956       }
8957 
8958       // At least one member in each anonymous union must be non-const
8959       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8960           !FieldRecord->field_empty()) {
8961         if (Diagnose)
8962           S.Diag(FieldRecord->getLocation(),
8963                  diag::note_deleted_default_ctor_all_const)
8964             << !!ICI << MD->getParent() << /*anonymous union*/1;
8965         return true;
8966       }
8967 
8968       // Don't check the implicit member of the anonymous union type.
8969       // This is technically non-conformant, but sanity demands it.
8970       return false;
8971     }
8972 
8973     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8974                                       FieldType.getCVRQualifiers()))
8975       return true;
8976   }
8977 
8978   return false;
8979 }
8980 
8981 /// C++11 [class.ctor] p5:
8982 ///   A defaulted default constructor for a class X is defined as deleted if
8983 /// X is a union and all of its variant members are of const-qualified type.
8984 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8985   // This is a silly definition, because it gives an empty union a deleted
8986   // default constructor. Don't do that.
8987   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8988     bool AnyFields = false;
8989     for (auto *F : MD->getParent()->fields())
8990       if ((AnyFields = !F->isUnnamedBitfield()))
8991         break;
8992     if (!AnyFields)
8993       return false;
8994     if (Diagnose)
8995       S.Diag(MD->getParent()->getLocation(),
8996              diag::note_deleted_default_ctor_all_const)
8997         << !!ICI << MD->getParent() << /*not anonymous union*/0;
8998     return true;
8999   }
9000   return false;
9001 }
9002 
9003 /// Determine whether a defaulted special member function should be defined as
9004 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9005 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9006 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9007                                      InheritedConstructorInfo *ICI,
9008                                      bool Diagnose) {
9009   if (MD->isInvalidDecl())
9010     return false;
9011   CXXRecordDecl *RD = MD->getParent();
9012   assert(!RD->isDependentType() && "do deletion after instantiation");
9013   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9014     return false;
9015 
9016   // C++11 [expr.lambda.prim]p19:
9017   //   The closure type associated with a lambda-expression has a
9018   //   deleted (8.4.3) default constructor and a deleted copy
9019   //   assignment operator.
9020   // C++2a adds back these operators if the lambda has no lambda-capture.
9021   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9022       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9023     if (Diagnose)
9024       Diag(RD->getLocation(), diag::note_lambda_decl);
9025     return true;
9026   }
9027 
9028   // For an anonymous struct or union, the copy and assignment special members
9029   // will never be used, so skip the check. For an anonymous union declared at
9030   // namespace scope, the constructor and destructor are used.
9031   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9032       RD->isAnonymousStructOrUnion())
9033     return false;
9034 
9035   // C++11 [class.copy]p7, p18:
9036   //   If the class definition declares a move constructor or move assignment
9037   //   operator, an implicitly declared copy constructor or copy assignment
9038   //   operator is defined as deleted.
9039   if (MD->isImplicit() &&
9040       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9041     CXXMethodDecl *UserDeclaredMove = nullptr;
9042 
9043     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9044     // deletion of the corresponding copy operation, not both copy operations.
9045     // MSVC 2015 has adopted the standards conforming behavior.
9046     bool DeletesOnlyMatchingCopy =
9047         getLangOpts().MSVCCompat &&
9048         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9049 
9050     if (RD->hasUserDeclaredMoveConstructor() &&
9051         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9052       if (!Diagnose) return true;
9053 
9054       // Find any user-declared move constructor.
9055       for (auto *I : RD->ctors()) {
9056         if (I->isMoveConstructor()) {
9057           UserDeclaredMove = I;
9058           break;
9059         }
9060       }
9061       assert(UserDeclaredMove);
9062     } else if (RD->hasUserDeclaredMoveAssignment() &&
9063                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9064       if (!Diagnose) return true;
9065 
9066       // Find any user-declared move assignment operator.
9067       for (auto *I : RD->methods()) {
9068         if (I->isMoveAssignmentOperator()) {
9069           UserDeclaredMove = I;
9070           break;
9071         }
9072       }
9073       assert(UserDeclaredMove);
9074     }
9075 
9076     if (UserDeclaredMove) {
9077       Diag(UserDeclaredMove->getLocation(),
9078            diag::note_deleted_copy_user_declared_move)
9079         << (CSM == CXXCopyAssignment) << RD
9080         << UserDeclaredMove->isMoveAssignmentOperator();
9081       return true;
9082     }
9083   }
9084 
9085   // Do access control from the special member function
9086   ContextRAII MethodContext(*this, MD);
9087 
9088   // C++11 [class.dtor]p5:
9089   // -- for a virtual destructor, lookup of the non-array deallocation function
9090   //    results in an ambiguity or in a function that is deleted or inaccessible
9091   if (CSM == CXXDestructor && MD->isVirtual()) {
9092     FunctionDecl *OperatorDelete = nullptr;
9093     DeclarationName Name =
9094       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9095     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9096                                  OperatorDelete, /*Diagnose*/false)) {
9097       if (Diagnose)
9098         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9099       return true;
9100     }
9101   }
9102 
9103   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9104 
9105   // Per DR1611, do not consider virtual bases of constructors of abstract
9106   // classes, since we are not going to construct them.
9107   // Per DR1658, do not consider virtual bases of destructors of abstract
9108   // classes either.
9109   // Per DR2180, for assignment operators we only assign (and thus only
9110   // consider) direct bases.
9111   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9112                                  : SMI.VisitPotentiallyConstructedBases))
9113     return true;
9114 
9115   if (SMI.shouldDeleteForAllConstMembers())
9116     return true;
9117 
9118   if (getLangOpts().CUDA) {
9119     // We should delete the special member in CUDA mode if target inference
9120     // failed.
9121     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9122     // is treated as certain special member, which may not reflect what special
9123     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9124     // expects CSM to match MD, therefore recalculate CSM.
9125     assert(ICI || CSM == getSpecialMember(MD));
9126     auto RealCSM = CSM;
9127     if (ICI)
9128       RealCSM = getSpecialMember(MD);
9129 
9130     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9131                                                    SMI.ConstArg, Diagnose);
9132   }
9133 
9134   return false;
9135 }
9136 
9137 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9138   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9139   assert(DFK && "not a defaultable function");
9140   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9141 
9142   if (DFK.isSpecialMember()) {
9143     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9144                               nullptr, /*Diagnose=*/true);
9145   } else {
9146     DefaultedComparisonAnalyzer(
9147         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9148         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9149         .visit();
9150   }
9151 }
9152 
9153 /// Perform lookup for a special member of the specified kind, and determine
9154 /// whether it is trivial. If the triviality can be determined without the
9155 /// lookup, skip it. This is intended for use when determining whether a
9156 /// special member of a containing object is trivial, and thus does not ever
9157 /// perform overload resolution for default constructors.
9158 ///
9159 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9160 /// member that was most likely to be intended to be trivial, if any.
9161 ///
9162 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9163 /// determine whether the special member is trivial.
9164 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9165                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9166                                      bool ConstRHS,
9167                                      Sema::TrivialABIHandling TAH,
9168                                      CXXMethodDecl **Selected) {
9169   if (Selected)
9170     *Selected = nullptr;
9171 
9172   switch (CSM) {
9173   case Sema::CXXInvalid:
9174     llvm_unreachable("not a special member");
9175 
9176   case Sema::CXXDefaultConstructor:
9177     // C++11 [class.ctor]p5:
9178     //   A default constructor is trivial if:
9179     //    - all the [direct subobjects] have trivial default constructors
9180     //
9181     // Note, no overload resolution is performed in this case.
9182     if (RD->hasTrivialDefaultConstructor())
9183       return true;
9184 
9185     if (Selected) {
9186       // If there's a default constructor which could have been trivial, dig it
9187       // out. Otherwise, if there's any user-provided default constructor, point
9188       // to that as an example of why there's not a trivial one.
9189       CXXConstructorDecl *DefCtor = nullptr;
9190       if (RD->needsImplicitDefaultConstructor())
9191         S.DeclareImplicitDefaultConstructor(RD);
9192       for (auto *CI : RD->ctors()) {
9193         if (!CI->isDefaultConstructor())
9194           continue;
9195         DefCtor = CI;
9196         if (!DefCtor->isUserProvided())
9197           break;
9198       }
9199 
9200       *Selected = DefCtor;
9201     }
9202 
9203     return false;
9204 
9205   case Sema::CXXDestructor:
9206     // C++11 [class.dtor]p5:
9207     //   A destructor is trivial if:
9208     //    - all the direct [subobjects] have trivial destructors
9209     if (RD->hasTrivialDestructor() ||
9210         (TAH == Sema::TAH_ConsiderTrivialABI &&
9211          RD->hasTrivialDestructorForCall()))
9212       return true;
9213 
9214     if (Selected) {
9215       if (RD->needsImplicitDestructor())
9216         S.DeclareImplicitDestructor(RD);
9217       *Selected = RD->getDestructor();
9218     }
9219 
9220     return false;
9221 
9222   case Sema::CXXCopyConstructor:
9223     // C++11 [class.copy]p12:
9224     //   A copy constructor is trivial if:
9225     //    - the constructor selected to copy each direct [subobject] is trivial
9226     if (RD->hasTrivialCopyConstructor() ||
9227         (TAH == Sema::TAH_ConsiderTrivialABI &&
9228          RD->hasTrivialCopyConstructorForCall())) {
9229       if (Quals == Qualifiers::Const)
9230         // We must either select the trivial copy constructor or reach an
9231         // ambiguity; no need to actually perform overload resolution.
9232         return true;
9233     } else if (!Selected) {
9234       return false;
9235     }
9236     // In C++98, we are not supposed to perform overload resolution here, but we
9237     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9238     // cases like B as having a non-trivial copy constructor:
9239     //   struct A { template<typename T> A(T&); };
9240     //   struct B { mutable A a; };
9241     goto NeedOverloadResolution;
9242 
9243   case Sema::CXXCopyAssignment:
9244     // C++11 [class.copy]p25:
9245     //   A copy assignment operator is trivial if:
9246     //    - the assignment operator selected to copy each direct [subobject] is
9247     //      trivial
9248     if (RD->hasTrivialCopyAssignment()) {
9249       if (Quals == Qualifiers::Const)
9250         return true;
9251     } else if (!Selected) {
9252       return false;
9253     }
9254     // In C++98, we are not supposed to perform overload resolution here, but we
9255     // treat that as a language defect.
9256     goto NeedOverloadResolution;
9257 
9258   case Sema::CXXMoveConstructor:
9259   case Sema::CXXMoveAssignment:
9260   NeedOverloadResolution:
9261     Sema::SpecialMemberOverloadResult SMOR =
9262         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9263 
9264     // The standard doesn't describe how to behave if the lookup is ambiguous.
9265     // We treat it as not making the member non-trivial, just like the standard
9266     // mandates for the default constructor. This should rarely matter, because
9267     // the member will also be deleted.
9268     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9269       return true;
9270 
9271     if (!SMOR.getMethod()) {
9272       assert(SMOR.getKind() ==
9273              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9274       return false;
9275     }
9276 
9277     // We deliberately don't check if we found a deleted special member. We're
9278     // not supposed to!
9279     if (Selected)
9280       *Selected = SMOR.getMethod();
9281 
9282     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9283         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9284       return SMOR.getMethod()->isTrivialForCall();
9285     return SMOR.getMethod()->isTrivial();
9286   }
9287 
9288   llvm_unreachable("unknown special method kind");
9289 }
9290 
9291 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9292   for (auto *CI : RD->ctors())
9293     if (!CI->isImplicit())
9294       return CI;
9295 
9296   // Look for constructor templates.
9297   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9298   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9299     if (CXXConstructorDecl *CD =
9300           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9301       return CD;
9302   }
9303 
9304   return nullptr;
9305 }
9306 
9307 /// The kind of subobject we are checking for triviality. The values of this
9308 /// enumeration are used in diagnostics.
9309 enum TrivialSubobjectKind {
9310   /// The subobject is a base class.
9311   TSK_BaseClass,
9312   /// The subobject is a non-static data member.
9313   TSK_Field,
9314   /// The object is actually the complete object.
9315   TSK_CompleteObject
9316 };
9317 
9318 /// Check whether the special member selected for a given type would be trivial.
9319 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9320                                       QualType SubType, bool ConstRHS,
9321                                       Sema::CXXSpecialMember CSM,
9322                                       TrivialSubobjectKind Kind,
9323                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9324   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9325   if (!SubRD)
9326     return true;
9327 
9328   CXXMethodDecl *Selected;
9329   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9330                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9331     return true;
9332 
9333   if (Diagnose) {
9334     if (ConstRHS)
9335       SubType.addConst();
9336 
9337     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9338       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9339         << Kind << SubType.getUnqualifiedType();
9340       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9341         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9342     } else if (!Selected)
9343       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9344         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9345     else if (Selected->isUserProvided()) {
9346       if (Kind == TSK_CompleteObject)
9347         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9348           << Kind << SubType.getUnqualifiedType() << CSM;
9349       else {
9350         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9351           << Kind << SubType.getUnqualifiedType() << CSM;
9352         S.Diag(Selected->getLocation(), diag::note_declared_at);
9353       }
9354     } else {
9355       if (Kind != TSK_CompleteObject)
9356         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9357           << Kind << SubType.getUnqualifiedType() << CSM;
9358 
9359       // Explain why the defaulted or deleted special member isn't trivial.
9360       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9361                                Diagnose);
9362     }
9363   }
9364 
9365   return false;
9366 }
9367 
9368 /// Check whether the members of a class type allow a special member to be
9369 /// trivial.
9370 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9371                                      Sema::CXXSpecialMember CSM,
9372                                      bool ConstArg,
9373                                      Sema::TrivialABIHandling TAH,
9374                                      bool Diagnose) {
9375   for (const auto *FI : RD->fields()) {
9376     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9377       continue;
9378 
9379     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9380 
9381     // Pretend anonymous struct or union members are members of this class.
9382     if (FI->isAnonymousStructOrUnion()) {
9383       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9384                                     CSM, ConstArg, TAH, Diagnose))
9385         return false;
9386       continue;
9387     }
9388 
9389     // C++11 [class.ctor]p5:
9390     //   A default constructor is trivial if [...]
9391     //    -- no non-static data member of its class has a
9392     //       brace-or-equal-initializer
9393     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9394       if (Diagnose)
9395         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9396       return false;
9397     }
9398 
9399     // Objective C ARC 4.3.5:
9400     //   [...] nontrivally ownership-qualified types are [...] not trivially
9401     //   default constructible, copy constructible, move constructible, copy
9402     //   assignable, move assignable, or destructible [...]
9403     if (FieldType.hasNonTrivialObjCLifetime()) {
9404       if (Diagnose)
9405         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9406           << RD << FieldType.getObjCLifetime();
9407       return false;
9408     }
9409 
9410     bool ConstRHS = ConstArg && !FI->isMutable();
9411     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9412                                    CSM, TSK_Field, TAH, Diagnose))
9413       return false;
9414   }
9415 
9416   return true;
9417 }
9418 
9419 /// Diagnose why the specified class does not have a trivial special member of
9420 /// the given kind.
9421 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9422   QualType Ty = Context.getRecordType(RD);
9423 
9424   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9425   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9426                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9427                             /*Diagnose*/true);
9428 }
9429 
9430 /// Determine whether a defaulted or deleted special member function is trivial,
9431 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9432 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9433 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9434                                   TrivialABIHandling TAH, bool Diagnose) {
9435   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9436 
9437   CXXRecordDecl *RD = MD->getParent();
9438 
9439   bool ConstArg = false;
9440 
9441   // C++11 [class.copy]p12, p25: [DR1593]
9442   //   A [special member] is trivial if [...] its parameter-type-list is
9443   //   equivalent to the parameter-type-list of an implicit declaration [...]
9444   switch (CSM) {
9445   case CXXDefaultConstructor:
9446   case CXXDestructor:
9447     // Trivial default constructors and destructors cannot have parameters.
9448     break;
9449 
9450   case CXXCopyConstructor:
9451   case CXXCopyAssignment: {
9452     // Trivial copy operations always have const, non-volatile parameter types.
9453     ConstArg = true;
9454     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9455     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9456     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9457       if (Diagnose)
9458         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9459           << Param0->getSourceRange() << Param0->getType()
9460           << Context.getLValueReferenceType(
9461                Context.getRecordType(RD).withConst());
9462       return false;
9463     }
9464     break;
9465   }
9466 
9467   case CXXMoveConstructor:
9468   case CXXMoveAssignment: {
9469     // Trivial move operations always have non-cv-qualified parameters.
9470     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9471     const RValueReferenceType *RT =
9472       Param0->getType()->getAs<RValueReferenceType>();
9473     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9474       if (Diagnose)
9475         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9476           << Param0->getSourceRange() << Param0->getType()
9477           << Context.getRValueReferenceType(Context.getRecordType(RD));
9478       return false;
9479     }
9480     break;
9481   }
9482 
9483   case CXXInvalid:
9484     llvm_unreachable("not a special member");
9485   }
9486 
9487   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9488     if (Diagnose)
9489       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9490            diag::note_nontrivial_default_arg)
9491         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9492     return false;
9493   }
9494   if (MD->isVariadic()) {
9495     if (Diagnose)
9496       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9497     return false;
9498   }
9499 
9500   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9501   //   A copy/move [constructor or assignment operator] is trivial if
9502   //    -- the [member] selected to copy/move each direct base class subobject
9503   //       is trivial
9504   //
9505   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9506   //   A [default constructor or destructor] is trivial if
9507   //    -- all the direct base classes have trivial [default constructors or
9508   //       destructors]
9509   for (const auto &BI : RD->bases())
9510     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9511                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9512       return false;
9513 
9514   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9515   //   A copy/move [constructor or assignment operator] for a class X is
9516   //   trivial if
9517   //    -- for each non-static data member of X that is of class type (or array
9518   //       thereof), the constructor selected to copy/move that member is
9519   //       trivial
9520   //
9521   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9522   //   A [default constructor or destructor] is trivial if
9523   //    -- for all of the non-static data members of its class that are of class
9524   //       type (or array thereof), each such class has a trivial [default
9525   //       constructor or destructor]
9526   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9527     return false;
9528 
9529   // C++11 [class.dtor]p5:
9530   //   A destructor is trivial if [...]
9531   //    -- the destructor is not virtual
9532   if (CSM == CXXDestructor && MD->isVirtual()) {
9533     if (Diagnose)
9534       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9535     return false;
9536   }
9537 
9538   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9539   //   A [special member] for class X is trivial if [...]
9540   //    -- class X has no virtual functions and no virtual base classes
9541   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9542     if (!Diagnose)
9543       return false;
9544 
9545     if (RD->getNumVBases()) {
9546       // Check for virtual bases. We already know that the corresponding
9547       // member in all bases is trivial, so vbases must all be direct.
9548       CXXBaseSpecifier &BS = *RD->vbases_begin();
9549       assert(BS.isVirtual());
9550       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9551       return false;
9552     }
9553 
9554     // Must have a virtual method.
9555     for (const auto *MI : RD->methods()) {
9556       if (MI->isVirtual()) {
9557         SourceLocation MLoc = MI->getBeginLoc();
9558         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9559         return false;
9560       }
9561     }
9562 
9563     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9564   }
9565 
9566   // Looks like it's trivial!
9567   return true;
9568 }
9569 
9570 namespace {
9571 struct FindHiddenVirtualMethod {
9572   Sema *S;
9573   CXXMethodDecl *Method;
9574   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9575   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9576 
9577 private:
9578   /// Check whether any most overridden method from MD in Methods
9579   static bool CheckMostOverridenMethods(
9580       const CXXMethodDecl *MD,
9581       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9582     if (MD->size_overridden_methods() == 0)
9583       return Methods.count(MD->getCanonicalDecl());
9584     for (const CXXMethodDecl *O : MD->overridden_methods())
9585       if (CheckMostOverridenMethods(O, Methods))
9586         return true;
9587     return false;
9588   }
9589 
9590 public:
9591   /// Member lookup function that determines whether a given C++
9592   /// method overloads virtual methods in a base class without overriding any,
9593   /// to be used with CXXRecordDecl::lookupInBases().
9594   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9595     RecordDecl *BaseRecord =
9596         Specifier->getType()->castAs<RecordType>()->getDecl();
9597 
9598     DeclarationName Name = Method->getDeclName();
9599     assert(Name.getNameKind() == DeclarationName::Identifier);
9600 
9601     bool foundSameNameMethod = false;
9602     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9603     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9604          Path.Decls = Path.Decls.slice(1)) {
9605       NamedDecl *D = Path.Decls.front();
9606       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9607         MD = MD->getCanonicalDecl();
9608         foundSameNameMethod = true;
9609         // Interested only in hidden virtual methods.
9610         if (!MD->isVirtual())
9611           continue;
9612         // If the method we are checking overrides a method from its base
9613         // don't warn about the other overloaded methods. Clang deviates from
9614         // GCC by only diagnosing overloads of inherited virtual functions that
9615         // do not override any other virtual functions in the base. GCC's
9616         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9617         // function from a base class. These cases may be better served by a
9618         // warning (not specific to virtual functions) on call sites when the
9619         // call would select a different function from the base class, were it
9620         // visible.
9621         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9622         if (!S->IsOverload(Method, MD, false))
9623           return true;
9624         // Collect the overload only if its hidden.
9625         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9626           overloadedMethods.push_back(MD);
9627       }
9628     }
9629 
9630     if (foundSameNameMethod)
9631       OverloadedMethods.append(overloadedMethods.begin(),
9632                                overloadedMethods.end());
9633     return foundSameNameMethod;
9634   }
9635 };
9636 } // end anonymous namespace
9637 
9638 /// Add the most overriden methods from MD to Methods
9639 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9640                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9641   if (MD->size_overridden_methods() == 0)
9642     Methods.insert(MD->getCanonicalDecl());
9643   else
9644     for (const CXXMethodDecl *O : MD->overridden_methods())
9645       AddMostOverridenMethods(O, Methods);
9646 }
9647 
9648 /// Check if a method overloads virtual methods in a base class without
9649 /// overriding any.
9650 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9651                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9652   if (!MD->getDeclName().isIdentifier())
9653     return;
9654 
9655   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9656                      /*bool RecordPaths=*/false,
9657                      /*bool DetectVirtual=*/false);
9658   FindHiddenVirtualMethod FHVM;
9659   FHVM.Method = MD;
9660   FHVM.S = this;
9661 
9662   // Keep the base methods that were overridden or introduced in the subclass
9663   // by 'using' in a set. A base method not in this set is hidden.
9664   CXXRecordDecl *DC = MD->getParent();
9665   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9666   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9667     NamedDecl *ND = *I;
9668     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9669       ND = shad->getTargetDecl();
9670     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9671       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9672   }
9673 
9674   if (DC->lookupInBases(FHVM, Paths))
9675     OverloadedMethods = FHVM.OverloadedMethods;
9676 }
9677 
9678 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9679                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9680   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9681     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9682     PartialDiagnostic PD = PDiag(
9683          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9684     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9685     Diag(overloadedMD->getLocation(), PD);
9686   }
9687 }
9688 
9689 /// Diagnose methods which overload virtual methods in a base class
9690 /// without overriding any.
9691 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9692   if (MD->isInvalidDecl())
9693     return;
9694 
9695   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9696     return;
9697 
9698   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9699   FindHiddenVirtualMethods(MD, OverloadedMethods);
9700   if (!OverloadedMethods.empty()) {
9701     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9702       << MD << (OverloadedMethods.size() > 1);
9703 
9704     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9705   }
9706 }
9707 
9708 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9709   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9710     // No diagnostics if this is a template instantiation.
9711     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9712       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9713            diag::ext_cannot_use_trivial_abi) << &RD;
9714       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9715            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9716     }
9717     RD.dropAttr<TrivialABIAttr>();
9718   };
9719 
9720   // Ill-formed if the copy and move constructors are deleted.
9721   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9722     if (RD.needsImplicitCopyConstructor() &&
9723         !RD.defaultedCopyConstructorIsDeleted())
9724       return true;
9725     if (RD.needsImplicitMoveConstructor() &&
9726         !RD.defaultedMoveConstructorIsDeleted())
9727       return true;
9728     for (const CXXConstructorDecl *CD : RD.ctors())
9729       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9730         return true;
9731     return false;
9732   };
9733 
9734   if (!HasNonDeletedCopyOrMoveConstructor()) {
9735     PrintDiagAndRemoveAttr(0);
9736     return;
9737   }
9738 
9739   // Ill-formed if the struct has virtual functions.
9740   if (RD.isPolymorphic()) {
9741     PrintDiagAndRemoveAttr(1);
9742     return;
9743   }
9744 
9745   for (const auto &B : RD.bases()) {
9746     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9747     // virtual base.
9748     if (!B.getType()->isDependentType() &&
9749         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9750       PrintDiagAndRemoveAttr(2);
9751       return;
9752     }
9753 
9754     if (B.isVirtual()) {
9755       PrintDiagAndRemoveAttr(3);
9756       return;
9757     }
9758   }
9759 
9760   for (const auto *FD : RD.fields()) {
9761     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9762     // non-trivial for the purpose of calls.
9763     QualType FT = FD->getType();
9764     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9765       PrintDiagAndRemoveAttr(4);
9766       return;
9767     }
9768 
9769     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9770       if (!RT->isDependentType() &&
9771           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9772         PrintDiagAndRemoveAttr(5);
9773         return;
9774       }
9775   }
9776 }
9777 
9778 void Sema::ActOnFinishCXXMemberSpecification(
9779     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9780     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9781   if (!TagDecl)
9782     return;
9783 
9784   AdjustDeclIfTemplate(TagDecl);
9785 
9786   for (const ParsedAttr &AL : AttrList) {
9787     if (AL.getKind() != ParsedAttr::AT_Visibility)
9788       continue;
9789     AL.setInvalid();
9790     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9791   }
9792 
9793   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9794               // strict aliasing violation!
9795               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9796               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9797 
9798   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9799 }
9800 
9801 /// Find the equality comparison functions that should be implicitly declared
9802 /// in a given class definition, per C++2a [class.compare.default]p3.
9803 static void findImplicitlyDeclaredEqualityComparisons(
9804     ASTContext &Ctx, CXXRecordDecl *RD,
9805     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9806   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9807   if (!RD->lookup(EqEq).empty())
9808     // Member operator== explicitly declared: no implicit operator==s.
9809     return;
9810 
9811   // Traverse friends looking for an '==' or a '<=>'.
9812   for (FriendDecl *Friend : RD->friends()) {
9813     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9814     if (!FD) continue;
9815 
9816     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9817       // Friend operator== explicitly declared: no implicit operator==s.
9818       Spaceships.clear();
9819       return;
9820     }
9821 
9822     if (FD->getOverloadedOperator() == OO_Spaceship &&
9823         FD->isExplicitlyDefaulted())
9824       Spaceships.push_back(FD);
9825   }
9826 
9827   // Look for members named 'operator<=>'.
9828   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9829   for (NamedDecl *ND : RD->lookup(Cmp)) {
9830     // Note that we could find a non-function here (either a function template
9831     // or a using-declaration). Neither case results in an implicit
9832     // 'operator=='.
9833     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9834       if (FD->isExplicitlyDefaulted())
9835         Spaceships.push_back(FD);
9836   }
9837 }
9838 
9839 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9840 /// special functions, such as the default constructor, copy
9841 /// constructor, or destructor, to the given C++ class (C++
9842 /// [special]p1).  This routine can only be executed just before the
9843 /// definition of the class is complete.
9844 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9845   // Don't add implicit special members to templated classes.
9846   // FIXME: This means unqualified lookups for 'operator=' within a class
9847   // template don't work properly.
9848   if (!ClassDecl->isDependentType()) {
9849     if (ClassDecl->needsImplicitDefaultConstructor()) {
9850       ++getASTContext().NumImplicitDefaultConstructors;
9851 
9852       if (ClassDecl->hasInheritedConstructor())
9853         DeclareImplicitDefaultConstructor(ClassDecl);
9854     }
9855 
9856     if (ClassDecl->needsImplicitCopyConstructor()) {
9857       ++getASTContext().NumImplicitCopyConstructors;
9858 
9859       // If the properties or semantics of the copy constructor couldn't be
9860       // determined while the class was being declared, force a declaration
9861       // of it now.
9862       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9863           ClassDecl->hasInheritedConstructor())
9864         DeclareImplicitCopyConstructor(ClassDecl);
9865       // For the MS ABI we need to know whether the copy ctor is deleted. A
9866       // prerequisite for deleting the implicit copy ctor is that the class has
9867       // a move ctor or move assignment that is either user-declared or whose
9868       // semantics are inherited from a subobject. FIXME: We should provide a
9869       // more direct way for CodeGen to ask whether the constructor was deleted.
9870       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9871                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9872                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9873                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9874                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9875         DeclareImplicitCopyConstructor(ClassDecl);
9876     }
9877 
9878     if (getLangOpts().CPlusPlus11 &&
9879         ClassDecl->needsImplicitMoveConstructor()) {
9880       ++getASTContext().NumImplicitMoveConstructors;
9881 
9882       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9883           ClassDecl->hasInheritedConstructor())
9884         DeclareImplicitMoveConstructor(ClassDecl);
9885     }
9886 
9887     if (ClassDecl->needsImplicitCopyAssignment()) {
9888       ++getASTContext().NumImplicitCopyAssignmentOperators;
9889 
9890       // If we have a dynamic class, then the copy assignment operator may be
9891       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9892       // it shows up in the right place in the vtable and that we diagnose
9893       // problems with the implicit exception specification.
9894       if (ClassDecl->isDynamicClass() ||
9895           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9896           ClassDecl->hasInheritedAssignment())
9897         DeclareImplicitCopyAssignment(ClassDecl);
9898     }
9899 
9900     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9901       ++getASTContext().NumImplicitMoveAssignmentOperators;
9902 
9903       // Likewise for the move assignment operator.
9904       if (ClassDecl->isDynamicClass() ||
9905           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9906           ClassDecl->hasInheritedAssignment())
9907         DeclareImplicitMoveAssignment(ClassDecl);
9908     }
9909 
9910     if (ClassDecl->needsImplicitDestructor()) {
9911       ++getASTContext().NumImplicitDestructors;
9912 
9913       // If we have a dynamic class, then the destructor may be virtual, so we
9914       // have to declare the destructor immediately. This ensures that, e.g., it
9915       // shows up in the right place in the vtable and that we diagnose problems
9916       // with the implicit exception specification.
9917       if (ClassDecl->isDynamicClass() ||
9918           ClassDecl->needsOverloadResolutionForDestructor())
9919         DeclareImplicitDestructor(ClassDecl);
9920     }
9921   }
9922 
9923   // C++2a [class.compare.default]p3:
9924   //   If the member-specification does not explicitly declare any member or
9925   //   friend named operator==, an == operator function is declared implicitly
9926   //   for each defaulted three-way comparison operator function defined in
9927   //   the member-specification
9928   // FIXME: Consider doing this lazily.
9929   // We do this during the initial parse for a class template, not during
9930   // instantiation, so that we can handle unqualified lookups for 'operator=='
9931   // when parsing the template.
9932   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9933     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9934     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9935                                               DefaultedSpaceships);
9936     for (auto *FD : DefaultedSpaceships)
9937       DeclareImplicitEqualityComparison(ClassDecl, FD);
9938   }
9939 }
9940 
9941 unsigned
9942 Sema::ActOnReenterTemplateScope(Decl *D,
9943                                 llvm::function_ref<Scope *()> EnterScope) {
9944   if (!D)
9945     return 0;
9946   AdjustDeclIfTemplate(D);
9947 
9948   // In order to get name lookup right, reenter template scopes in order from
9949   // outermost to innermost.
9950   SmallVector<TemplateParameterList *, 4> ParameterLists;
9951   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9952 
9953   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9954     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9955       ParameterLists.push_back(DD->getTemplateParameterList(i));
9956 
9957     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9958       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9959         ParameterLists.push_back(FTD->getTemplateParameters());
9960     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9961       LookupDC = VD->getDeclContext();
9962 
9963       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9964         ParameterLists.push_back(VTD->getTemplateParameters());
9965       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9966         ParameterLists.push_back(PSD->getTemplateParameters());
9967     }
9968   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9969     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9970       ParameterLists.push_back(TD->getTemplateParameterList(i));
9971 
9972     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9973       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9974         ParameterLists.push_back(CTD->getTemplateParameters());
9975       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9976         ParameterLists.push_back(PSD->getTemplateParameters());
9977     }
9978   }
9979   // FIXME: Alias declarations and concepts.
9980 
9981   unsigned Count = 0;
9982   Scope *InnermostTemplateScope = nullptr;
9983   for (TemplateParameterList *Params : ParameterLists) {
9984     // Ignore explicit specializations; they don't contribute to the template
9985     // depth.
9986     if (Params->size() == 0)
9987       continue;
9988 
9989     InnermostTemplateScope = EnterScope();
9990     for (NamedDecl *Param : *Params) {
9991       if (Param->getDeclName()) {
9992         InnermostTemplateScope->AddDecl(Param);
9993         IdResolver.AddDecl(Param);
9994       }
9995     }
9996     ++Count;
9997   }
9998 
9999   // Associate the new template scopes with the corresponding entities.
10000   if (InnermostTemplateScope) {
10001     assert(LookupDC && "no enclosing DeclContext for template lookup");
10002     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10003   }
10004 
10005   return Count;
10006 }
10007 
10008 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10009   if (!RecordD) return;
10010   AdjustDeclIfTemplate(RecordD);
10011   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10012   PushDeclContext(S, Record);
10013 }
10014 
10015 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10016   if (!RecordD) return;
10017   PopDeclContext();
10018 }
10019 
10020 /// This is used to implement the constant expression evaluation part of the
10021 /// attribute enable_if extension. There is nothing in standard C++ which would
10022 /// require reentering parameters.
10023 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10024   if (!Param)
10025     return;
10026 
10027   S->AddDecl(Param);
10028   if (Param->getDeclName())
10029     IdResolver.AddDecl(Param);
10030 }
10031 
10032 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10033 /// parsing a top-level (non-nested) C++ class, and we are now
10034 /// parsing those parts of the given Method declaration that could
10035 /// not be parsed earlier (C++ [class.mem]p2), such as default
10036 /// arguments. This action should enter the scope of the given
10037 /// Method declaration as if we had just parsed the qualified method
10038 /// name. However, it should not bring the parameters into scope;
10039 /// that will be performed by ActOnDelayedCXXMethodParameter.
10040 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10041 }
10042 
10043 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10044 /// C++ method declaration. We're (re-)introducing the given
10045 /// function parameter into scope for use in parsing later parts of
10046 /// the method declaration. For example, we could see an
10047 /// ActOnParamDefaultArgument event for this parameter.
10048 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10049   if (!ParamD)
10050     return;
10051 
10052   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10053 
10054   S->AddDecl(Param);
10055   if (Param->getDeclName())
10056     IdResolver.AddDecl(Param);
10057 }
10058 
10059 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10060 /// processing the delayed method declaration for Method. The method
10061 /// declaration is now considered finished. There may be a separate
10062 /// ActOnStartOfFunctionDef action later (not necessarily
10063 /// immediately!) for this method, if it was also defined inside the
10064 /// class body.
10065 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10066   if (!MethodD)
10067     return;
10068 
10069   AdjustDeclIfTemplate(MethodD);
10070 
10071   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10072 
10073   // Now that we have our default arguments, check the constructor
10074   // again. It could produce additional diagnostics or affect whether
10075   // the class has implicitly-declared destructors, among other
10076   // things.
10077   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10078     CheckConstructor(Constructor);
10079 
10080   // Check the default arguments, which we may have added.
10081   if (!Method->isInvalidDecl())
10082     CheckCXXDefaultArguments(Method);
10083 }
10084 
10085 // Emit the given diagnostic for each non-address-space qualifier.
10086 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10087 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10088   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10089   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10090     bool DiagOccured = false;
10091     FTI.MethodQualifiers->forEachQualifier(
10092         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10093                                    SourceLocation SL) {
10094           // This diagnostic should be emitted on any qualifier except an addr
10095           // space qualifier. However, forEachQualifier currently doesn't visit
10096           // addr space qualifiers, so there's no way to write this condition
10097           // right now; we just diagnose on everything.
10098           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10099           DiagOccured = true;
10100         });
10101     if (DiagOccured)
10102       D.setInvalidType();
10103   }
10104 }
10105 
10106 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10107 /// the well-formedness of the constructor declarator @p D with type @p
10108 /// R. If there are any errors in the declarator, this routine will
10109 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10110 /// will be updated to reflect a well-formed type for the constructor and
10111 /// returned.
10112 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10113                                           StorageClass &SC) {
10114   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10115 
10116   // C++ [class.ctor]p3:
10117   //   A constructor shall not be virtual (10.3) or static (9.4). A
10118   //   constructor can be invoked for a const, volatile or const
10119   //   volatile object. A constructor shall not be declared const,
10120   //   volatile, or const volatile (9.3.2).
10121   if (isVirtual) {
10122     if (!D.isInvalidType())
10123       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10124         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10125         << SourceRange(D.getIdentifierLoc());
10126     D.setInvalidType();
10127   }
10128   if (SC == SC_Static) {
10129     if (!D.isInvalidType())
10130       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10131         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10132         << SourceRange(D.getIdentifierLoc());
10133     D.setInvalidType();
10134     SC = SC_None;
10135   }
10136 
10137   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10138     diagnoseIgnoredQualifiers(
10139         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10140         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10141         D.getDeclSpec().getRestrictSpecLoc(),
10142         D.getDeclSpec().getAtomicSpecLoc());
10143     D.setInvalidType();
10144   }
10145 
10146   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10147 
10148   // C++0x [class.ctor]p4:
10149   //   A constructor shall not be declared with a ref-qualifier.
10150   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10151   if (FTI.hasRefQualifier()) {
10152     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10153       << FTI.RefQualifierIsLValueRef
10154       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10155     D.setInvalidType();
10156   }
10157 
10158   // Rebuild the function type "R" without any type qualifiers (in
10159   // case any of the errors above fired) and with "void" as the
10160   // return type, since constructors don't have return types.
10161   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10162   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10163     return R;
10164 
10165   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10166   EPI.TypeQuals = Qualifiers();
10167   EPI.RefQualifier = RQ_None;
10168 
10169   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10170 }
10171 
10172 /// CheckConstructor - Checks a fully-formed constructor for
10173 /// well-formedness, issuing any diagnostics required. Returns true if
10174 /// the constructor declarator is invalid.
10175 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10176   CXXRecordDecl *ClassDecl
10177     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10178   if (!ClassDecl)
10179     return Constructor->setInvalidDecl();
10180 
10181   // C++ [class.copy]p3:
10182   //   A declaration of a constructor for a class X is ill-formed if
10183   //   its first parameter is of type (optionally cv-qualified) X and
10184   //   either there are no other parameters or else all other
10185   //   parameters have default arguments.
10186   if (!Constructor->isInvalidDecl() &&
10187       Constructor->hasOneParamOrDefaultArgs() &&
10188       Constructor->getTemplateSpecializationKind() !=
10189           TSK_ImplicitInstantiation) {
10190     QualType ParamType = Constructor->getParamDecl(0)->getType();
10191     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10192     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10193       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10194       const char *ConstRef
10195         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10196                                                         : " const &";
10197       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10198         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10199 
10200       // FIXME: Rather that making the constructor invalid, we should endeavor
10201       // to fix the type.
10202       Constructor->setInvalidDecl();
10203     }
10204   }
10205 }
10206 
10207 /// CheckDestructor - Checks a fully-formed destructor definition for
10208 /// well-formedness, issuing any diagnostics required.  Returns true
10209 /// on error.
10210 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10211   CXXRecordDecl *RD = Destructor->getParent();
10212 
10213   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10214     SourceLocation Loc;
10215 
10216     if (!Destructor->isImplicit())
10217       Loc = Destructor->getLocation();
10218     else
10219       Loc = RD->getLocation();
10220 
10221     // If we have a virtual destructor, look up the deallocation function
10222     if (FunctionDecl *OperatorDelete =
10223             FindDeallocationFunctionForDestructor(Loc, RD)) {
10224       Expr *ThisArg = nullptr;
10225 
10226       // If the notional 'delete this' expression requires a non-trivial
10227       // conversion from 'this' to the type of a destroying operator delete's
10228       // first parameter, perform that conversion now.
10229       if (OperatorDelete->isDestroyingOperatorDelete()) {
10230         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10231         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10232           // C++ [class.dtor]p13:
10233           //   ... as if for the expression 'delete this' appearing in a
10234           //   non-virtual destructor of the destructor's class.
10235           ContextRAII SwitchContext(*this, Destructor);
10236           ExprResult This =
10237               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10238           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10239           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10240           if (This.isInvalid()) {
10241             // FIXME: Register this as a context note so that it comes out
10242             // in the right order.
10243             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10244             return true;
10245           }
10246           ThisArg = This.get();
10247         }
10248       }
10249 
10250       DiagnoseUseOfDecl(OperatorDelete, Loc);
10251       MarkFunctionReferenced(Loc, OperatorDelete);
10252       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10253     }
10254   }
10255 
10256   return false;
10257 }
10258 
10259 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10260 /// the well-formednes of the destructor declarator @p D with type @p
10261 /// R. If there are any errors in the declarator, this routine will
10262 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10263 /// will be updated to reflect a well-formed type for the destructor and
10264 /// returned.
10265 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10266                                          StorageClass& SC) {
10267   // C++ [class.dtor]p1:
10268   //   [...] A typedef-name that names a class is a class-name
10269   //   (7.1.3); however, a typedef-name that names a class shall not
10270   //   be used as the identifier in the declarator for a destructor
10271   //   declaration.
10272   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10273   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10274     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10275       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10276   else if (const TemplateSpecializationType *TST =
10277              DeclaratorType->getAs<TemplateSpecializationType>())
10278     if (TST->isTypeAlias())
10279       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10280         << DeclaratorType << 1;
10281 
10282   // C++ [class.dtor]p2:
10283   //   A destructor is used to destroy objects of its class type. A
10284   //   destructor takes no parameters, and no return type can be
10285   //   specified for it (not even void). The address of a destructor
10286   //   shall not be taken. A destructor shall not be static. A
10287   //   destructor can be invoked for a const, volatile or const
10288   //   volatile object. A destructor shall not be declared const,
10289   //   volatile or const volatile (9.3.2).
10290   if (SC == SC_Static) {
10291     if (!D.isInvalidType())
10292       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10293         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10294         << SourceRange(D.getIdentifierLoc())
10295         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10296 
10297     SC = SC_None;
10298   }
10299   if (!D.isInvalidType()) {
10300     // Destructors don't have return types, but the parser will
10301     // happily parse something like:
10302     //
10303     //   class X {
10304     //     float ~X();
10305     //   };
10306     //
10307     // The return type will be eliminated later.
10308     if (D.getDeclSpec().hasTypeSpecifier())
10309       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10310         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10311         << SourceRange(D.getIdentifierLoc());
10312     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10313       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10314                                 SourceLocation(),
10315                                 D.getDeclSpec().getConstSpecLoc(),
10316                                 D.getDeclSpec().getVolatileSpecLoc(),
10317                                 D.getDeclSpec().getRestrictSpecLoc(),
10318                                 D.getDeclSpec().getAtomicSpecLoc());
10319       D.setInvalidType();
10320     }
10321   }
10322 
10323   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10324 
10325   // C++0x [class.dtor]p2:
10326   //   A destructor shall not be declared with a ref-qualifier.
10327   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10328   if (FTI.hasRefQualifier()) {
10329     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10330       << FTI.RefQualifierIsLValueRef
10331       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10332     D.setInvalidType();
10333   }
10334 
10335   // Make sure we don't have any parameters.
10336   if (FTIHasNonVoidParameters(FTI)) {
10337     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10338 
10339     // Delete the parameters.
10340     FTI.freeParams();
10341     D.setInvalidType();
10342   }
10343 
10344   // Make sure the destructor isn't variadic.
10345   if (FTI.isVariadic) {
10346     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10347     D.setInvalidType();
10348   }
10349 
10350   // Rebuild the function type "R" without any type qualifiers or
10351   // parameters (in case any of the errors above fired) and with
10352   // "void" as the return type, since destructors don't have return
10353   // types.
10354   if (!D.isInvalidType())
10355     return R;
10356 
10357   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10358   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10359   EPI.Variadic = false;
10360   EPI.TypeQuals = Qualifiers();
10361   EPI.RefQualifier = RQ_None;
10362   return Context.getFunctionType(Context.VoidTy, None, EPI);
10363 }
10364 
10365 static void extendLeft(SourceRange &R, SourceRange Before) {
10366   if (Before.isInvalid())
10367     return;
10368   R.setBegin(Before.getBegin());
10369   if (R.getEnd().isInvalid())
10370     R.setEnd(Before.getEnd());
10371 }
10372 
10373 static void extendRight(SourceRange &R, SourceRange After) {
10374   if (After.isInvalid())
10375     return;
10376   if (R.getBegin().isInvalid())
10377     R.setBegin(After.getBegin());
10378   R.setEnd(After.getEnd());
10379 }
10380 
10381 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10382 /// well-formednes of the conversion function declarator @p D with
10383 /// type @p R. If there are any errors in the declarator, this routine
10384 /// will emit diagnostics and return true. Otherwise, it will return
10385 /// false. Either way, the type @p R will be updated to reflect a
10386 /// well-formed type for the conversion operator.
10387 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10388                                      StorageClass& SC) {
10389   // C++ [class.conv.fct]p1:
10390   //   Neither parameter types nor return type can be specified. The
10391   //   type of a conversion function (8.3.5) is "function taking no
10392   //   parameter returning conversion-type-id."
10393   if (SC == SC_Static) {
10394     if (!D.isInvalidType())
10395       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10396         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10397         << D.getName().getSourceRange();
10398     D.setInvalidType();
10399     SC = SC_None;
10400   }
10401 
10402   TypeSourceInfo *ConvTSI = nullptr;
10403   QualType ConvType =
10404       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10405 
10406   const DeclSpec &DS = D.getDeclSpec();
10407   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10408     // Conversion functions don't have return types, but the parser will
10409     // happily parse something like:
10410     //
10411     //   class X {
10412     //     float operator bool();
10413     //   };
10414     //
10415     // The return type will be changed later anyway.
10416     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10417       << SourceRange(DS.getTypeSpecTypeLoc())
10418       << SourceRange(D.getIdentifierLoc());
10419     D.setInvalidType();
10420   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10421     // It's also plausible that the user writes type qualifiers in the wrong
10422     // place, such as:
10423     //   struct S { const operator int(); };
10424     // FIXME: we could provide a fixit to move the qualifiers onto the
10425     // conversion type.
10426     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10427         << SourceRange(D.getIdentifierLoc()) << 0;
10428     D.setInvalidType();
10429   }
10430 
10431   const auto *Proto = R->castAs<FunctionProtoType>();
10432 
10433   // Make sure we don't have any parameters.
10434   if (Proto->getNumParams() > 0) {
10435     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10436 
10437     // Delete the parameters.
10438     D.getFunctionTypeInfo().freeParams();
10439     D.setInvalidType();
10440   } else if (Proto->isVariadic()) {
10441     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10442     D.setInvalidType();
10443   }
10444 
10445   // Diagnose "&operator bool()" and other such nonsense.  This
10446   // is actually a gcc extension which we don't support.
10447   if (Proto->getReturnType() != ConvType) {
10448     bool NeedsTypedef = false;
10449     SourceRange Before, After;
10450 
10451     // Walk the chunks and extract information on them for our diagnostic.
10452     bool PastFunctionChunk = false;
10453     for (auto &Chunk : D.type_objects()) {
10454       switch (Chunk.Kind) {
10455       case DeclaratorChunk::Function:
10456         if (!PastFunctionChunk) {
10457           if (Chunk.Fun.HasTrailingReturnType) {
10458             TypeSourceInfo *TRT = nullptr;
10459             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10460             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10461           }
10462           PastFunctionChunk = true;
10463           break;
10464         }
10465         LLVM_FALLTHROUGH;
10466       case DeclaratorChunk::Array:
10467         NeedsTypedef = true;
10468         extendRight(After, Chunk.getSourceRange());
10469         break;
10470 
10471       case DeclaratorChunk::Pointer:
10472       case DeclaratorChunk::BlockPointer:
10473       case DeclaratorChunk::Reference:
10474       case DeclaratorChunk::MemberPointer:
10475       case DeclaratorChunk::Pipe:
10476         extendLeft(Before, Chunk.getSourceRange());
10477         break;
10478 
10479       case DeclaratorChunk::Paren:
10480         extendLeft(Before, Chunk.Loc);
10481         extendRight(After, Chunk.EndLoc);
10482         break;
10483       }
10484     }
10485 
10486     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10487                          After.isValid()  ? After.getBegin() :
10488                                             D.getIdentifierLoc();
10489     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10490     DB << Before << After;
10491 
10492     if (!NeedsTypedef) {
10493       DB << /*don't need a typedef*/0;
10494 
10495       // If we can provide a correct fix-it hint, do so.
10496       if (After.isInvalid() && ConvTSI) {
10497         SourceLocation InsertLoc =
10498             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10499         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10500            << FixItHint::CreateInsertionFromRange(
10501                   InsertLoc, CharSourceRange::getTokenRange(Before))
10502            << FixItHint::CreateRemoval(Before);
10503       }
10504     } else if (!Proto->getReturnType()->isDependentType()) {
10505       DB << /*typedef*/1 << Proto->getReturnType();
10506     } else if (getLangOpts().CPlusPlus11) {
10507       DB << /*alias template*/2 << Proto->getReturnType();
10508     } else {
10509       DB << /*might not be fixable*/3;
10510     }
10511 
10512     // Recover by incorporating the other type chunks into the result type.
10513     // Note, this does *not* change the name of the function. This is compatible
10514     // with the GCC extension:
10515     //   struct S { &operator int(); } s;
10516     //   int &r = s.operator int(); // ok in GCC
10517     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10518     ConvType = Proto->getReturnType();
10519   }
10520 
10521   // C++ [class.conv.fct]p4:
10522   //   The conversion-type-id shall not represent a function type nor
10523   //   an array type.
10524   if (ConvType->isArrayType()) {
10525     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10526     ConvType = Context.getPointerType(ConvType);
10527     D.setInvalidType();
10528   } else if (ConvType->isFunctionType()) {
10529     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10530     ConvType = Context.getPointerType(ConvType);
10531     D.setInvalidType();
10532   }
10533 
10534   // Rebuild the function type "R" without any parameters (in case any
10535   // of the errors above fired) and with the conversion type as the
10536   // return type.
10537   if (D.isInvalidType())
10538     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10539 
10540   // C++0x explicit conversion operators.
10541   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10542     Diag(DS.getExplicitSpecLoc(),
10543          getLangOpts().CPlusPlus11
10544              ? diag::warn_cxx98_compat_explicit_conversion_functions
10545              : diag::ext_explicit_conversion_functions)
10546         << SourceRange(DS.getExplicitSpecRange());
10547 }
10548 
10549 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10550 /// the declaration of the given C++ conversion function. This routine
10551 /// is responsible for recording the conversion function in the C++
10552 /// class, if possible.
10553 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10554   assert(Conversion && "Expected to receive a conversion function declaration");
10555 
10556   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10557 
10558   // Make sure we aren't redeclaring the conversion function.
10559   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10560   // C++ [class.conv.fct]p1:
10561   //   [...] A conversion function is never used to convert a
10562   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10563   //   same object type (or a reference to it), to a (possibly
10564   //   cv-qualified) base class of that type (or a reference to it),
10565   //   or to (possibly cv-qualified) void.
10566   QualType ClassType
10567     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10568   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10569     ConvType = ConvTypeRef->getPointeeType();
10570   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10571       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10572     /* Suppress diagnostics for instantiations. */;
10573   else if (Conversion->size_overridden_methods() != 0)
10574     /* Suppress diagnostics for overriding virtual function in a base class. */;
10575   else if (ConvType->isRecordType()) {
10576     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10577     if (ConvType == ClassType)
10578       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10579         << ClassType;
10580     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10581       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10582         <<  ClassType << ConvType;
10583   } else if (ConvType->isVoidType()) {
10584     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10585       << ClassType << ConvType;
10586   }
10587 
10588   if (FunctionTemplateDecl *ConversionTemplate
10589                                 = Conversion->getDescribedFunctionTemplate())
10590     return ConversionTemplate;
10591 
10592   return Conversion;
10593 }
10594 
10595 namespace {
10596 /// Utility class to accumulate and print a diagnostic listing the invalid
10597 /// specifier(s) on a declaration.
10598 struct BadSpecifierDiagnoser {
10599   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10600       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10601   ~BadSpecifierDiagnoser() {
10602     Diagnostic << Specifiers;
10603   }
10604 
10605   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10606     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10607   }
10608   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10609     return check(SpecLoc,
10610                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10611   }
10612   void check(SourceLocation SpecLoc, const char *Spec) {
10613     if (SpecLoc.isInvalid()) return;
10614     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10615     if (!Specifiers.empty()) Specifiers += " ";
10616     Specifiers += Spec;
10617   }
10618 
10619   Sema &S;
10620   Sema::SemaDiagnosticBuilder Diagnostic;
10621   std::string Specifiers;
10622 };
10623 }
10624 
10625 /// Check the validity of a declarator that we parsed for a deduction-guide.
10626 /// These aren't actually declarators in the grammar, so we need to check that
10627 /// the user didn't specify any pieces that are not part of the deduction-guide
10628 /// grammar.
10629 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10630                                          StorageClass &SC) {
10631   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10632   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10633   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10634 
10635   // C++ [temp.deduct.guide]p3:
10636   //   A deduction-gide shall be declared in the same scope as the
10637   //   corresponding class template.
10638   if (!CurContext->getRedeclContext()->Equals(
10639           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10640     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10641       << GuidedTemplateDecl;
10642     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10643   }
10644 
10645   auto &DS = D.getMutableDeclSpec();
10646   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10647   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10648       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10649       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10650     BadSpecifierDiagnoser Diagnoser(
10651         *this, D.getIdentifierLoc(),
10652         diag::err_deduction_guide_invalid_specifier);
10653 
10654     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10655     DS.ClearStorageClassSpecs();
10656     SC = SC_None;
10657 
10658     // 'explicit' is permitted.
10659     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10660     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10661     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10662     DS.ClearConstexprSpec();
10663 
10664     Diagnoser.check(DS.getConstSpecLoc(), "const");
10665     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10666     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10667     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10668     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10669     DS.ClearTypeQualifiers();
10670 
10671     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10672     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10673     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10674     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10675     DS.ClearTypeSpecType();
10676   }
10677 
10678   if (D.isInvalidType())
10679     return;
10680 
10681   // Check the declarator is simple enough.
10682   bool FoundFunction = false;
10683   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10684     if (Chunk.Kind == DeclaratorChunk::Paren)
10685       continue;
10686     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10687       Diag(D.getDeclSpec().getBeginLoc(),
10688            diag::err_deduction_guide_with_complex_decl)
10689           << D.getSourceRange();
10690       break;
10691     }
10692     if (!Chunk.Fun.hasTrailingReturnType()) {
10693       Diag(D.getName().getBeginLoc(),
10694            diag::err_deduction_guide_no_trailing_return_type);
10695       break;
10696     }
10697 
10698     // Check that the return type is written as a specialization of
10699     // the template specified as the deduction-guide's name.
10700     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10701     TypeSourceInfo *TSI = nullptr;
10702     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10703     assert(TSI && "deduction guide has valid type but invalid return type?");
10704     bool AcceptableReturnType = false;
10705     bool MightInstantiateToSpecialization = false;
10706     if (auto RetTST =
10707             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10708       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10709       bool TemplateMatches =
10710           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10711       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10712         AcceptableReturnType = true;
10713       else {
10714         // This could still instantiate to the right type, unless we know it
10715         // names the wrong class template.
10716         auto *TD = SpecifiedName.getAsTemplateDecl();
10717         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10718                                              !TemplateMatches);
10719       }
10720     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10721       MightInstantiateToSpecialization = true;
10722     }
10723 
10724     if (!AcceptableReturnType) {
10725       Diag(TSI->getTypeLoc().getBeginLoc(),
10726            diag::err_deduction_guide_bad_trailing_return_type)
10727           << GuidedTemplate << TSI->getType()
10728           << MightInstantiateToSpecialization
10729           << TSI->getTypeLoc().getSourceRange();
10730     }
10731 
10732     // Keep going to check that we don't have any inner declarator pieces (we
10733     // could still have a function returning a pointer to a function).
10734     FoundFunction = true;
10735   }
10736 
10737   if (D.isFunctionDefinition())
10738     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10739 }
10740 
10741 //===----------------------------------------------------------------------===//
10742 // Namespace Handling
10743 //===----------------------------------------------------------------------===//
10744 
10745 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10746 /// reopened.
10747 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10748                                             SourceLocation Loc,
10749                                             IdentifierInfo *II, bool *IsInline,
10750                                             NamespaceDecl *PrevNS) {
10751   assert(*IsInline != PrevNS->isInline());
10752 
10753   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10754   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10755   // inline namespaces, with the intention of bringing names into namespace std.
10756   //
10757   // We support this just well enough to get that case working; this is not
10758   // sufficient to support reopening namespaces as inline in general.
10759   if (*IsInline && II && II->getName().startswith("__atomic") &&
10760       S.getSourceManager().isInSystemHeader(Loc)) {
10761     // Mark all prior declarations of the namespace as inline.
10762     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10763          NS = NS->getPreviousDecl())
10764       NS->setInline(*IsInline);
10765     // Patch up the lookup table for the containing namespace. This isn't really
10766     // correct, but it's good enough for this particular case.
10767     for (auto *I : PrevNS->decls())
10768       if (auto *ND = dyn_cast<NamedDecl>(I))
10769         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10770     return;
10771   }
10772 
10773   if (PrevNS->isInline())
10774     // The user probably just forgot the 'inline', so suggest that it
10775     // be added back.
10776     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10777       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10778   else
10779     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10780 
10781   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10782   *IsInline = PrevNS->isInline();
10783 }
10784 
10785 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10786 /// definition.
10787 Decl *Sema::ActOnStartNamespaceDef(
10788     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10789     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10790     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10791   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10792   // For anonymous namespace, take the location of the left brace.
10793   SourceLocation Loc = II ? IdentLoc : LBrace;
10794   bool IsInline = InlineLoc.isValid();
10795   bool IsInvalid = false;
10796   bool IsStd = false;
10797   bool AddToKnown = false;
10798   Scope *DeclRegionScope = NamespcScope->getParent();
10799 
10800   NamespaceDecl *PrevNS = nullptr;
10801   if (II) {
10802     // C++ [namespace.def]p2:
10803     //   The identifier in an original-namespace-definition shall not
10804     //   have been previously defined in the declarative region in
10805     //   which the original-namespace-definition appears. The
10806     //   identifier in an original-namespace-definition is the name of
10807     //   the namespace. Subsequently in that declarative region, it is
10808     //   treated as an original-namespace-name.
10809     //
10810     // Since namespace names are unique in their scope, and we don't
10811     // look through using directives, just look for any ordinary names
10812     // as if by qualified name lookup.
10813     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10814                    ForExternalRedeclaration);
10815     LookupQualifiedName(R, CurContext->getRedeclContext());
10816     NamedDecl *PrevDecl =
10817         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10818     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10819 
10820     if (PrevNS) {
10821       // This is an extended namespace definition.
10822       if (IsInline != PrevNS->isInline())
10823         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10824                                         &IsInline, PrevNS);
10825     } else if (PrevDecl) {
10826       // This is an invalid name redefinition.
10827       Diag(Loc, diag::err_redefinition_different_kind)
10828         << II;
10829       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10830       IsInvalid = true;
10831       // Continue on to push Namespc as current DeclContext and return it.
10832     } else if (II->isStr("std") &&
10833                CurContext->getRedeclContext()->isTranslationUnit()) {
10834       // This is the first "real" definition of the namespace "std", so update
10835       // our cache of the "std" namespace to point at this definition.
10836       PrevNS = getStdNamespace();
10837       IsStd = true;
10838       AddToKnown = !IsInline;
10839     } else {
10840       // We've seen this namespace for the first time.
10841       AddToKnown = !IsInline;
10842     }
10843   } else {
10844     // Anonymous namespaces.
10845 
10846     // Determine whether the parent already has an anonymous namespace.
10847     DeclContext *Parent = CurContext->getRedeclContext();
10848     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10849       PrevNS = TU->getAnonymousNamespace();
10850     } else {
10851       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10852       PrevNS = ND->getAnonymousNamespace();
10853     }
10854 
10855     if (PrevNS && IsInline != PrevNS->isInline())
10856       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10857                                       &IsInline, PrevNS);
10858   }
10859 
10860   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10861                                                  StartLoc, Loc, II, PrevNS);
10862   if (IsInvalid)
10863     Namespc->setInvalidDecl();
10864 
10865   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10866   AddPragmaAttributes(DeclRegionScope, Namespc);
10867 
10868   // FIXME: Should we be merging attributes?
10869   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10870     PushNamespaceVisibilityAttr(Attr, Loc);
10871 
10872   if (IsStd)
10873     StdNamespace = Namespc;
10874   if (AddToKnown)
10875     KnownNamespaces[Namespc] = false;
10876 
10877   if (II) {
10878     PushOnScopeChains(Namespc, DeclRegionScope);
10879   } else {
10880     // Link the anonymous namespace into its parent.
10881     DeclContext *Parent = CurContext->getRedeclContext();
10882     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10883       TU->setAnonymousNamespace(Namespc);
10884     } else {
10885       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10886     }
10887 
10888     CurContext->addDecl(Namespc);
10889 
10890     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10891     //   behaves as if it were replaced by
10892     //     namespace unique { /* empty body */ }
10893     //     using namespace unique;
10894     //     namespace unique { namespace-body }
10895     //   where all occurrences of 'unique' in a translation unit are
10896     //   replaced by the same identifier and this identifier differs
10897     //   from all other identifiers in the entire program.
10898 
10899     // We just create the namespace with an empty name and then add an
10900     // implicit using declaration, just like the standard suggests.
10901     //
10902     // CodeGen enforces the "universally unique" aspect by giving all
10903     // declarations semantically contained within an anonymous
10904     // namespace internal linkage.
10905 
10906     if (!PrevNS) {
10907       UD = UsingDirectiveDecl::Create(Context, Parent,
10908                                       /* 'using' */ LBrace,
10909                                       /* 'namespace' */ SourceLocation(),
10910                                       /* qualifier */ NestedNameSpecifierLoc(),
10911                                       /* identifier */ SourceLocation(),
10912                                       Namespc,
10913                                       /* Ancestor */ Parent);
10914       UD->setImplicit();
10915       Parent->addDecl(UD);
10916     }
10917   }
10918 
10919   ActOnDocumentableDecl(Namespc);
10920 
10921   // Although we could have an invalid decl (i.e. the namespace name is a
10922   // redefinition), push it as current DeclContext and try to continue parsing.
10923   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10924   // for the namespace has the declarations that showed up in that particular
10925   // namespace definition.
10926   PushDeclContext(NamespcScope, Namespc);
10927   return Namespc;
10928 }
10929 
10930 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10931 /// is a namespace alias, returns the namespace it points to.
10932 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10933   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10934     return AD->getNamespace();
10935   return dyn_cast_or_null<NamespaceDecl>(D);
10936 }
10937 
10938 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10939 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10940 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10941   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10942   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10943   Namespc->setRBraceLoc(RBrace);
10944   PopDeclContext();
10945   if (Namespc->hasAttr<VisibilityAttr>())
10946     PopPragmaVisibility(true, RBrace);
10947   // If this namespace contains an export-declaration, export it now.
10948   if (DeferredExportedNamespaces.erase(Namespc))
10949     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10950 }
10951 
10952 CXXRecordDecl *Sema::getStdBadAlloc() const {
10953   return cast_or_null<CXXRecordDecl>(
10954                                   StdBadAlloc.get(Context.getExternalSource()));
10955 }
10956 
10957 EnumDecl *Sema::getStdAlignValT() const {
10958   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10959 }
10960 
10961 NamespaceDecl *Sema::getStdNamespace() const {
10962   return cast_or_null<NamespaceDecl>(
10963                                  StdNamespace.get(Context.getExternalSource()));
10964 }
10965 
10966 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10967   if (!StdExperimentalNamespaceCache) {
10968     if (auto Std = getStdNamespace()) {
10969       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10970                           SourceLocation(), LookupNamespaceName);
10971       if (!LookupQualifiedName(Result, Std) ||
10972           !(StdExperimentalNamespaceCache =
10973                 Result.getAsSingle<NamespaceDecl>()))
10974         Result.suppressDiagnostics();
10975     }
10976   }
10977   return StdExperimentalNamespaceCache;
10978 }
10979 
10980 namespace {
10981 
10982 enum UnsupportedSTLSelect {
10983   USS_InvalidMember,
10984   USS_MissingMember,
10985   USS_NonTrivial,
10986   USS_Other
10987 };
10988 
10989 struct InvalidSTLDiagnoser {
10990   Sema &S;
10991   SourceLocation Loc;
10992   QualType TyForDiags;
10993 
10994   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
10995                       const VarDecl *VD = nullptr) {
10996     {
10997       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
10998                << TyForDiags << ((int)Sel);
10999       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11000         assert(!Name.empty());
11001         D << Name;
11002       }
11003     }
11004     if (Sel == USS_InvalidMember) {
11005       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11006           << VD << VD->getSourceRange();
11007     }
11008     return QualType();
11009   }
11010 };
11011 } // namespace
11012 
11013 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11014                                            SourceLocation Loc,
11015                                            ComparisonCategoryUsage Usage) {
11016   assert(getLangOpts().CPlusPlus &&
11017          "Looking for comparison category type outside of C++.");
11018 
11019   // Use an elaborated type for diagnostics which has a name containing the
11020   // prepended 'std' namespace but not any inline namespace names.
11021   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11022     auto *NNS =
11023         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11024     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11025   };
11026 
11027   // Check if we've already successfully checked the comparison category type
11028   // before. If so, skip checking it again.
11029   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11030   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11031     // The only thing we need to check is that the type has a reachable
11032     // definition in the current context.
11033     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11034       return QualType();
11035 
11036     return Info->getType();
11037   }
11038 
11039   // If lookup failed
11040   if (!Info) {
11041     std::string NameForDiags = "std::";
11042     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11043     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11044         << NameForDiags << (int)Usage;
11045     return QualType();
11046   }
11047 
11048   assert(Info->Kind == Kind);
11049   assert(Info->Record);
11050 
11051   // Update the Record decl in case we encountered a forward declaration on our
11052   // first pass. FIXME: This is a bit of a hack.
11053   if (Info->Record->hasDefinition())
11054     Info->Record = Info->Record->getDefinition();
11055 
11056   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11057     return QualType();
11058 
11059   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11060 
11061   if (!Info->Record->isTriviallyCopyable())
11062     return UnsupportedSTLError(USS_NonTrivial);
11063 
11064   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11065     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11066     // Tolerate empty base classes.
11067     if (Base->isEmpty())
11068       continue;
11069     // Reject STL implementations which have at least one non-empty base.
11070     return UnsupportedSTLError();
11071   }
11072 
11073   // Check that the STL has implemented the types using a single integer field.
11074   // This expectation allows better codegen for builtin operators. We require:
11075   //   (1) The class has exactly one field.
11076   //   (2) The field is an integral or enumeration type.
11077   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11078   if (std::distance(FIt, FEnd) != 1 ||
11079       !FIt->getType()->isIntegralOrEnumerationType()) {
11080     return UnsupportedSTLError();
11081   }
11082 
11083   // Build each of the require values and store them in Info.
11084   for (ComparisonCategoryResult CCR :
11085        ComparisonCategories::getPossibleResultsForType(Kind)) {
11086     StringRef MemName = ComparisonCategories::getResultString(CCR);
11087     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11088 
11089     if (!ValInfo)
11090       return UnsupportedSTLError(USS_MissingMember, MemName);
11091 
11092     VarDecl *VD = ValInfo->VD;
11093     assert(VD && "should not be null!");
11094 
11095     // Attempt to diagnose reasons why the STL definition of this type
11096     // might be foobar, including it failing to be a constant expression.
11097     // TODO Handle more ways the lookup or result can be invalid.
11098     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11099         !VD->checkInitIsICE())
11100       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11101 
11102     // Attempt to evaluate the var decl as a constant expression and extract
11103     // the value of its first field as a ICE. If this fails, the STL
11104     // implementation is not supported.
11105     if (!ValInfo->hasValidIntValue())
11106       return UnsupportedSTLError();
11107 
11108     MarkVariableReferenced(Loc, VD);
11109   }
11110 
11111   // We've successfully built the required types and expressions. Update
11112   // the cache and return the newly cached value.
11113   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11114   return Info->getType();
11115 }
11116 
11117 /// Retrieve the special "std" namespace, which may require us to
11118 /// implicitly define the namespace.
11119 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11120   if (!StdNamespace) {
11121     // The "std" namespace has not yet been defined, so build one implicitly.
11122     StdNamespace = NamespaceDecl::Create(Context,
11123                                          Context.getTranslationUnitDecl(),
11124                                          /*Inline=*/false,
11125                                          SourceLocation(), SourceLocation(),
11126                                          &PP.getIdentifierTable().get("std"),
11127                                          /*PrevDecl=*/nullptr);
11128     getStdNamespace()->setImplicit(true);
11129   }
11130 
11131   return getStdNamespace();
11132 }
11133 
11134 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11135   assert(getLangOpts().CPlusPlus &&
11136          "Looking for std::initializer_list outside of C++.");
11137 
11138   // We're looking for implicit instantiations of
11139   // template <typename E> class std::initializer_list.
11140 
11141   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11142     return false;
11143 
11144   ClassTemplateDecl *Template = nullptr;
11145   const TemplateArgument *Arguments = nullptr;
11146 
11147   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11148 
11149     ClassTemplateSpecializationDecl *Specialization =
11150         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11151     if (!Specialization)
11152       return false;
11153 
11154     Template = Specialization->getSpecializedTemplate();
11155     Arguments = Specialization->getTemplateArgs().data();
11156   } else if (const TemplateSpecializationType *TST =
11157                  Ty->getAs<TemplateSpecializationType>()) {
11158     Template = dyn_cast_or_null<ClassTemplateDecl>(
11159         TST->getTemplateName().getAsTemplateDecl());
11160     Arguments = TST->getArgs();
11161   }
11162   if (!Template)
11163     return false;
11164 
11165   if (!StdInitializerList) {
11166     // Haven't recognized std::initializer_list yet, maybe this is it.
11167     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11168     if (TemplateClass->getIdentifier() !=
11169             &PP.getIdentifierTable().get("initializer_list") ||
11170         !getStdNamespace()->InEnclosingNamespaceSetOf(
11171             TemplateClass->getDeclContext()))
11172       return false;
11173     // This is a template called std::initializer_list, but is it the right
11174     // template?
11175     TemplateParameterList *Params = Template->getTemplateParameters();
11176     if (Params->getMinRequiredArguments() != 1)
11177       return false;
11178     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11179       return false;
11180 
11181     // It's the right template.
11182     StdInitializerList = Template;
11183   }
11184 
11185   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11186     return false;
11187 
11188   // This is an instance of std::initializer_list. Find the argument type.
11189   if (Element)
11190     *Element = Arguments[0].getAsType();
11191   return true;
11192 }
11193 
11194 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11195   NamespaceDecl *Std = S.getStdNamespace();
11196   if (!Std) {
11197     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11198     return nullptr;
11199   }
11200 
11201   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11202                       Loc, Sema::LookupOrdinaryName);
11203   if (!S.LookupQualifiedName(Result, Std)) {
11204     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11205     return nullptr;
11206   }
11207   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11208   if (!Template) {
11209     Result.suppressDiagnostics();
11210     // We found something weird. Complain about the first thing we found.
11211     NamedDecl *Found = *Result.begin();
11212     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11213     return nullptr;
11214   }
11215 
11216   // We found some template called std::initializer_list. Now verify that it's
11217   // correct.
11218   TemplateParameterList *Params = Template->getTemplateParameters();
11219   if (Params->getMinRequiredArguments() != 1 ||
11220       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11221     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11222     return nullptr;
11223   }
11224 
11225   return Template;
11226 }
11227 
11228 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11229   if (!StdInitializerList) {
11230     StdInitializerList = LookupStdInitializerList(*this, Loc);
11231     if (!StdInitializerList)
11232       return QualType();
11233   }
11234 
11235   TemplateArgumentListInfo Args(Loc, Loc);
11236   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11237                                        Context.getTrivialTypeSourceInfo(Element,
11238                                                                         Loc)));
11239   return Context.getCanonicalType(
11240       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11241 }
11242 
11243 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11244   // C++ [dcl.init.list]p2:
11245   //   A constructor is an initializer-list constructor if its first parameter
11246   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11247   //   std::initializer_list<E> for some type E, and either there are no other
11248   //   parameters or else all other parameters have default arguments.
11249   if (!Ctor->hasOneParamOrDefaultArgs())
11250     return false;
11251 
11252   QualType ArgType = Ctor->getParamDecl(0)->getType();
11253   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11254     ArgType = RT->getPointeeType().getUnqualifiedType();
11255 
11256   return isStdInitializerList(ArgType, nullptr);
11257 }
11258 
11259 /// Determine whether a using statement is in a context where it will be
11260 /// apply in all contexts.
11261 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11262   switch (CurContext->getDeclKind()) {
11263     case Decl::TranslationUnit:
11264       return true;
11265     case Decl::LinkageSpec:
11266       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11267     default:
11268       return false;
11269   }
11270 }
11271 
11272 namespace {
11273 
11274 // Callback to only accept typo corrections that are namespaces.
11275 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11276 public:
11277   bool ValidateCandidate(const TypoCorrection &candidate) override {
11278     if (NamedDecl *ND = candidate.getCorrectionDecl())
11279       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11280     return false;
11281   }
11282 
11283   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11284     return std::make_unique<NamespaceValidatorCCC>(*this);
11285   }
11286 };
11287 
11288 }
11289 
11290 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11291                                        CXXScopeSpec &SS,
11292                                        SourceLocation IdentLoc,
11293                                        IdentifierInfo *Ident) {
11294   R.clear();
11295   NamespaceValidatorCCC CCC{};
11296   if (TypoCorrection Corrected =
11297           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11298                         Sema::CTK_ErrorRecovery)) {
11299     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11300       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11301       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11302                               Ident->getName().equals(CorrectedStr);
11303       S.diagnoseTypo(Corrected,
11304                      S.PDiag(diag::err_using_directive_member_suggest)
11305                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11306                      S.PDiag(diag::note_namespace_defined_here));
11307     } else {
11308       S.diagnoseTypo(Corrected,
11309                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11310                      S.PDiag(diag::note_namespace_defined_here));
11311     }
11312     R.addDecl(Corrected.getFoundDecl());
11313     return true;
11314   }
11315   return false;
11316 }
11317 
11318 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11319                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11320                                 SourceLocation IdentLoc,
11321                                 IdentifierInfo *NamespcName,
11322                                 const ParsedAttributesView &AttrList) {
11323   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11324   assert(NamespcName && "Invalid NamespcName.");
11325   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11326 
11327   // This can only happen along a recovery path.
11328   while (S->isTemplateParamScope())
11329     S = S->getParent();
11330   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11331 
11332   UsingDirectiveDecl *UDir = nullptr;
11333   NestedNameSpecifier *Qualifier = nullptr;
11334   if (SS.isSet())
11335     Qualifier = SS.getScopeRep();
11336 
11337   // Lookup namespace name.
11338   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11339   LookupParsedName(R, S, &SS);
11340   if (R.isAmbiguous())
11341     return nullptr;
11342 
11343   if (R.empty()) {
11344     R.clear();
11345     // Allow "using namespace std;" or "using namespace ::std;" even if
11346     // "std" hasn't been defined yet, for GCC compatibility.
11347     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11348         NamespcName->isStr("std")) {
11349       Diag(IdentLoc, diag::ext_using_undefined_std);
11350       R.addDecl(getOrCreateStdNamespace());
11351       R.resolveKind();
11352     }
11353     // Otherwise, attempt typo correction.
11354     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11355   }
11356 
11357   if (!R.empty()) {
11358     NamedDecl *Named = R.getRepresentativeDecl();
11359     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11360     assert(NS && "expected namespace decl");
11361 
11362     // The use of a nested name specifier may trigger deprecation warnings.
11363     DiagnoseUseOfDecl(Named, IdentLoc);
11364 
11365     // C++ [namespace.udir]p1:
11366     //   A using-directive specifies that the names in the nominated
11367     //   namespace can be used in the scope in which the
11368     //   using-directive appears after the using-directive. During
11369     //   unqualified name lookup (3.4.1), the names appear as if they
11370     //   were declared in the nearest enclosing namespace which
11371     //   contains both the using-directive and the nominated
11372     //   namespace. [Note: in this context, "contains" means "contains
11373     //   directly or indirectly". ]
11374 
11375     // Find enclosing context containing both using-directive and
11376     // nominated namespace.
11377     DeclContext *CommonAncestor = NS;
11378     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11379       CommonAncestor = CommonAncestor->getParent();
11380 
11381     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11382                                       SS.getWithLocInContext(Context),
11383                                       IdentLoc, Named, CommonAncestor);
11384 
11385     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11386         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11387       Diag(IdentLoc, diag::warn_using_directive_in_header);
11388     }
11389 
11390     PushUsingDirective(S, UDir);
11391   } else {
11392     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11393   }
11394 
11395   if (UDir)
11396     ProcessDeclAttributeList(S, UDir, AttrList);
11397 
11398   return UDir;
11399 }
11400 
11401 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11402   // If the scope has an associated entity and the using directive is at
11403   // namespace or translation unit scope, add the UsingDirectiveDecl into
11404   // its lookup structure so qualified name lookup can find it.
11405   DeclContext *Ctx = S->getEntity();
11406   if (Ctx && !Ctx->isFunctionOrMethod())
11407     Ctx->addDecl(UDir);
11408   else
11409     // Otherwise, it is at block scope. The using-directives will affect lookup
11410     // only to the end of the scope.
11411     S->PushUsingDirective(UDir);
11412 }
11413 
11414 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11415                                   SourceLocation UsingLoc,
11416                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11417                                   UnqualifiedId &Name,
11418                                   SourceLocation EllipsisLoc,
11419                                   const ParsedAttributesView &AttrList) {
11420   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11421 
11422   if (SS.isEmpty()) {
11423     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11424     return nullptr;
11425   }
11426 
11427   switch (Name.getKind()) {
11428   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11429   case UnqualifiedIdKind::IK_Identifier:
11430   case UnqualifiedIdKind::IK_OperatorFunctionId:
11431   case UnqualifiedIdKind::IK_LiteralOperatorId:
11432   case UnqualifiedIdKind::IK_ConversionFunctionId:
11433     break;
11434 
11435   case UnqualifiedIdKind::IK_ConstructorName:
11436   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11437     // C++11 inheriting constructors.
11438     Diag(Name.getBeginLoc(),
11439          getLangOpts().CPlusPlus11
11440              ? diag::warn_cxx98_compat_using_decl_constructor
11441              : diag::err_using_decl_constructor)
11442         << SS.getRange();
11443 
11444     if (getLangOpts().CPlusPlus11) break;
11445 
11446     return nullptr;
11447 
11448   case UnqualifiedIdKind::IK_DestructorName:
11449     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11450     return nullptr;
11451 
11452   case UnqualifiedIdKind::IK_TemplateId:
11453     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11454         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11455     return nullptr;
11456 
11457   case UnqualifiedIdKind::IK_DeductionGuideName:
11458     llvm_unreachable("cannot parse qualified deduction guide name");
11459   }
11460 
11461   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11462   DeclarationName TargetName = TargetNameInfo.getName();
11463   if (!TargetName)
11464     return nullptr;
11465 
11466   // Warn about access declarations.
11467   if (UsingLoc.isInvalid()) {
11468     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11469                                  ? diag::err_access_decl
11470                                  : diag::warn_access_decl_deprecated)
11471         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11472   }
11473 
11474   if (EllipsisLoc.isInvalid()) {
11475     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11476         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11477       return nullptr;
11478   } else {
11479     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11480         !TargetNameInfo.containsUnexpandedParameterPack()) {
11481       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11482         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11483       EllipsisLoc = SourceLocation();
11484     }
11485   }
11486 
11487   NamedDecl *UD =
11488       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11489                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11490                             /*IsInstantiation*/false);
11491   if (UD)
11492     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11493 
11494   return UD;
11495 }
11496 
11497 /// Determine whether a using declaration considers the given
11498 /// declarations as "equivalent", e.g., if they are redeclarations of
11499 /// the same entity or are both typedefs of the same type.
11500 static bool
11501 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11502   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11503     return true;
11504 
11505   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11506     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11507       return Context.hasSameType(TD1->getUnderlyingType(),
11508                                  TD2->getUnderlyingType());
11509 
11510   return false;
11511 }
11512 
11513 
11514 /// Determines whether to create a using shadow decl for a particular
11515 /// decl, given the set of decls existing prior to this using lookup.
11516 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11517                                 const LookupResult &Previous,
11518                                 UsingShadowDecl *&PrevShadow) {
11519   // Diagnose finding a decl which is not from a base class of the
11520   // current class.  We do this now because there are cases where this
11521   // function will silently decide not to build a shadow decl, which
11522   // will pre-empt further diagnostics.
11523   //
11524   // We don't need to do this in C++11 because we do the check once on
11525   // the qualifier.
11526   //
11527   // FIXME: diagnose the following if we care enough:
11528   //   struct A { int foo; };
11529   //   struct B : A { using A::foo; };
11530   //   template <class T> struct C : A {};
11531   //   template <class T> struct D : C<T> { using B::foo; } // <---
11532   // This is invalid (during instantiation) in C++03 because B::foo
11533   // resolves to the using decl in B, which is not a base class of D<T>.
11534   // We can't diagnose it immediately because C<T> is an unknown
11535   // specialization.  The UsingShadowDecl in D<T> then points directly
11536   // to A::foo, which will look well-formed when we instantiate.
11537   // The right solution is to not collapse the shadow-decl chain.
11538   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11539     DeclContext *OrigDC = Orig->getDeclContext();
11540 
11541     // Handle enums and anonymous structs.
11542     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11543     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11544     while (OrigRec->isAnonymousStructOrUnion())
11545       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11546 
11547     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11548       if (OrigDC == CurContext) {
11549         Diag(Using->getLocation(),
11550              diag::err_using_decl_nested_name_specifier_is_current_class)
11551           << Using->getQualifierLoc().getSourceRange();
11552         Diag(Orig->getLocation(), diag::note_using_decl_target);
11553         Using->setInvalidDecl();
11554         return true;
11555       }
11556 
11557       Diag(Using->getQualifierLoc().getBeginLoc(),
11558            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11559         << Using->getQualifier()
11560         << cast<CXXRecordDecl>(CurContext)
11561         << Using->getQualifierLoc().getSourceRange();
11562       Diag(Orig->getLocation(), diag::note_using_decl_target);
11563       Using->setInvalidDecl();
11564       return true;
11565     }
11566   }
11567 
11568   if (Previous.empty()) return false;
11569 
11570   NamedDecl *Target = Orig;
11571   if (isa<UsingShadowDecl>(Target))
11572     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11573 
11574   // If the target happens to be one of the previous declarations, we
11575   // don't have a conflict.
11576   //
11577   // FIXME: but we might be increasing its access, in which case we
11578   // should redeclare it.
11579   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11580   bool FoundEquivalentDecl = false;
11581   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11582          I != E; ++I) {
11583     NamedDecl *D = (*I)->getUnderlyingDecl();
11584     // We can have UsingDecls in our Previous results because we use the same
11585     // LookupResult for checking whether the UsingDecl itself is a valid
11586     // redeclaration.
11587     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11588       continue;
11589 
11590     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11591       // C++ [class.mem]p19:
11592       //   If T is the name of a class, then [every named member other than
11593       //   a non-static data member] shall have a name different from T
11594       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11595           !isa<IndirectFieldDecl>(Target) &&
11596           !isa<UnresolvedUsingValueDecl>(Target) &&
11597           DiagnoseClassNameShadow(
11598               CurContext,
11599               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11600         return true;
11601     }
11602 
11603     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11604       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11605         PrevShadow = Shadow;
11606       FoundEquivalentDecl = true;
11607     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11608       // We don't conflict with an existing using shadow decl of an equivalent
11609       // declaration, but we're not a redeclaration of it.
11610       FoundEquivalentDecl = true;
11611     }
11612 
11613     if (isVisible(D))
11614       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11615   }
11616 
11617   if (FoundEquivalentDecl)
11618     return false;
11619 
11620   if (FunctionDecl *FD = Target->getAsFunction()) {
11621     NamedDecl *OldDecl = nullptr;
11622     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11623                           /*IsForUsingDecl*/ true)) {
11624     case Ovl_Overload:
11625       return false;
11626 
11627     case Ovl_NonFunction:
11628       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11629       break;
11630 
11631     // We found a decl with the exact signature.
11632     case Ovl_Match:
11633       // If we're in a record, we want to hide the target, so we
11634       // return true (without a diagnostic) to tell the caller not to
11635       // build a shadow decl.
11636       if (CurContext->isRecord())
11637         return true;
11638 
11639       // If we're not in a record, this is an error.
11640       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11641       break;
11642     }
11643 
11644     Diag(Target->getLocation(), diag::note_using_decl_target);
11645     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11646     Using->setInvalidDecl();
11647     return true;
11648   }
11649 
11650   // Target is not a function.
11651 
11652   if (isa<TagDecl>(Target)) {
11653     // No conflict between a tag and a non-tag.
11654     if (!Tag) return false;
11655 
11656     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11657     Diag(Target->getLocation(), diag::note_using_decl_target);
11658     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11659     Using->setInvalidDecl();
11660     return true;
11661   }
11662 
11663   // No conflict between a tag and a non-tag.
11664   if (!NonTag) return false;
11665 
11666   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11667   Diag(Target->getLocation(), diag::note_using_decl_target);
11668   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11669   Using->setInvalidDecl();
11670   return true;
11671 }
11672 
11673 /// Determine whether a direct base class is a virtual base class.
11674 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11675   if (!Derived->getNumVBases())
11676     return false;
11677   for (auto &B : Derived->bases())
11678     if (B.getType()->getAsCXXRecordDecl() == Base)
11679       return B.isVirtual();
11680   llvm_unreachable("not a direct base class");
11681 }
11682 
11683 /// Builds a shadow declaration corresponding to a 'using' declaration.
11684 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11685                                             UsingDecl *UD,
11686                                             NamedDecl *Orig,
11687                                             UsingShadowDecl *PrevDecl) {
11688   // If we resolved to another shadow declaration, just coalesce them.
11689   NamedDecl *Target = Orig;
11690   if (isa<UsingShadowDecl>(Target)) {
11691     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11692     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11693   }
11694 
11695   NamedDecl *NonTemplateTarget = Target;
11696   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11697     NonTemplateTarget = TargetTD->getTemplatedDecl();
11698 
11699   UsingShadowDecl *Shadow;
11700   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11701     bool IsVirtualBase =
11702         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11703                             UD->getQualifier()->getAsRecordDecl());
11704     Shadow = ConstructorUsingShadowDecl::Create(
11705         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11706   } else {
11707     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11708                                      Target);
11709   }
11710   UD->addShadowDecl(Shadow);
11711 
11712   Shadow->setAccess(UD->getAccess());
11713   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11714     Shadow->setInvalidDecl();
11715 
11716   Shadow->setPreviousDecl(PrevDecl);
11717 
11718   if (S)
11719     PushOnScopeChains(Shadow, S);
11720   else
11721     CurContext->addDecl(Shadow);
11722 
11723 
11724   return Shadow;
11725 }
11726 
11727 /// Hides a using shadow declaration.  This is required by the current
11728 /// using-decl implementation when a resolvable using declaration in a
11729 /// class is followed by a declaration which would hide or override
11730 /// one or more of the using decl's targets; for example:
11731 ///
11732 ///   struct Base { void foo(int); };
11733 ///   struct Derived : Base {
11734 ///     using Base::foo;
11735 ///     void foo(int);
11736 ///   };
11737 ///
11738 /// The governing language is C++03 [namespace.udecl]p12:
11739 ///
11740 ///   When a using-declaration brings names from a base class into a
11741 ///   derived class scope, member functions in the derived class
11742 ///   override and/or hide member functions with the same name and
11743 ///   parameter types in a base class (rather than conflicting).
11744 ///
11745 /// There are two ways to implement this:
11746 ///   (1) optimistically create shadow decls when they're not hidden
11747 ///       by existing declarations, or
11748 ///   (2) don't create any shadow decls (or at least don't make them
11749 ///       visible) until we've fully parsed/instantiated the class.
11750 /// The problem with (1) is that we might have to retroactively remove
11751 /// a shadow decl, which requires several O(n) operations because the
11752 /// decl structures are (very reasonably) not designed for removal.
11753 /// (2) avoids this but is very fiddly and phase-dependent.
11754 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11755   if (Shadow->getDeclName().getNameKind() ==
11756         DeclarationName::CXXConversionFunctionName)
11757     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11758 
11759   // Remove it from the DeclContext...
11760   Shadow->getDeclContext()->removeDecl(Shadow);
11761 
11762   // ...and the scope, if applicable...
11763   if (S) {
11764     S->RemoveDecl(Shadow);
11765     IdResolver.RemoveDecl(Shadow);
11766   }
11767 
11768   // ...and the using decl.
11769   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11770 
11771   // TODO: complain somehow if Shadow was used.  It shouldn't
11772   // be possible for this to happen, because...?
11773 }
11774 
11775 /// Find the base specifier for a base class with the given type.
11776 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11777                                                 QualType DesiredBase,
11778                                                 bool &AnyDependentBases) {
11779   // Check whether the named type is a direct base class.
11780   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11781     .getUnqualifiedType();
11782   for (auto &Base : Derived->bases()) {
11783     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11784     if (CanonicalDesiredBase == BaseType)
11785       return &Base;
11786     if (BaseType->isDependentType())
11787       AnyDependentBases = true;
11788   }
11789   return nullptr;
11790 }
11791 
11792 namespace {
11793 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11794 public:
11795   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11796                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11797       : HasTypenameKeyword(HasTypenameKeyword),
11798         IsInstantiation(IsInstantiation), OldNNS(NNS),
11799         RequireMemberOf(RequireMemberOf) {}
11800 
11801   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11802     NamedDecl *ND = Candidate.getCorrectionDecl();
11803 
11804     // Keywords are not valid here.
11805     if (!ND || isa<NamespaceDecl>(ND))
11806       return false;
11807 
11808     // Completely unqualified names are invalid for a 'using' declaration.
11809     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11810       return false;
11811 
11812     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11813     // reject.
11814 
11815     if (RequireMemberOf) {
11816       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11817       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11818         // No-one ever wants a using-declaration to name an injected-class-name
11819         // of a base class, unless they're declaring an inheriting constructor.
11820         ASTContext &Ctx = ND->getASTContext();
11821         if (!Ctx.getLangOpts().CPlusPlus11)
11822           return false;
11823         QualType FoundType = Ctx.getRecordType(FoundRecord);
11824 
11825         // Check that the injected-class-name is named as a member of its own
11826         // type; we don't want to suggest 'using Derived::Base;', since that
11827         // means something else.
11828         NestedNameSpecifier *Specifier =
11829             Candidate.WillReplaceSpecifier()
11830                 ? Candidate.getCorrectionSpecifier()
11831                 : OldNNS;
11832         if (!Specifier->getAsType() ||
11833             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11834           return false;
11835 
11836         // Check that this inheriting constructor declaration actually names a
11837         // direct base class of the current class.
11838         bool AnyDependentBases = false;
11839         if (!findDirectBaseWithType(RequireMemberOf,
11840                                     Ctx.getRecordType(FoundRecord),
11841                                     AnyDependentBases) &&
11842             !AnyDependentBases)
11843           return false;
11844       } else {
11845         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11846         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11847           return false;
11848 
11849         // FIXME: Check that the base class member is accessible?
11850       }
11851     } else {
11852       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11853       if (FoundRecord && FoundRecord->isInjectedClassName())
11854         return false;
11855     }
11856 
11857     if (isa<TypeDecl>(ND))
11858       return HasTypenameKeyword || !IsInstantiation;
11859 
11860     return !HasTypenameKeyword;
11861   }
11862 
11863   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11864     return std::make_unique<UsingValidatorCCC>(*this);
11865   }
11866 
11867 private:
11868   bool HasTypenameKeyword;
11869   bool IsInstantiation;
11870   NestedNameSpecifier *OldNNS;
11871   CXXRecordDecl *RequireMemberOf;
11872 };
11873 } // end anonymous namespace
11874 
11875 /// Builds a using declaration.
11876 ///
11877 /// \param IsInstantiation - Whether this call arises from an
11878 ///   instantiation of an unresolved using declaration.  We treat
11879 ///   the lookup differently for these declarations.
11880 NamedDecl *Sema::BuildUsingDeclaration(
11881     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11882     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11883     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11884     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11885   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11886   SourceLocation IdentLoc = NameInfo.getLoc();
11887   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11888 
11889   // FIXME: We ignore attributes for now.
11890 
11891   // For an inheriting constructor declaration, the name of the using
11892   // declaration is the name of a constructor in this class, not in the
11893   // base class.
11894   DeclarationNameInfo UsingName = NameInfo;
11895   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11896     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11897       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11898           Context.getCanonicalType(Context.getRecordType(RD))));
11899 
11900   // Do the redeclaration lookup in the current scope.
11901   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11902                         ForVisibleRedeclaration);
11903   Previous.setHideTags(false);
11904   if (S) {
11905     LookupName(Previous, S);
11906 
11907     // It is really dumb that we have to do this.
11908     LookupResult::Filter F = Previous.makeFilter();
11909     while (F.hasNext()) {
11910       NamedDecl *D = F.next();
11911       if (!isDeclInScope(D, CurContext, S))
11912         F.erase();
11913       // If we found a local extern declaration that's not ordinarily visible,
11914       // and this declaration is being added to a non-block scope, ignore it.
11915       // We're only checking for scope conflicts here, not also for violations
11916       // of the linkage rules.
11917       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11918                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11919         F.erase();
11920     }
11921     F.done();
11922   } else {
11923     assert(IsInstantiation && "no scope in non-instantiation");
11924     if (CurContext->isRecord())
11925       LookupQualifiedName(Previous, CurContext);
11926     else {
11927       // No redeclaration check is needed here; in non-member contexts we
11928       // diagnosed all possible conflicts with other using-declarations when
11929       // building the template:
11930       //
11931       // For a dependent non-type using declaration, the only valid case is
11932       // if we instantiate to a single enumerator. We check for conflicts
11933       // between shadow declarations we introduce, and we check in the template
11934       // definition for conflicts between a non-type using declaration and any
11935       // other declaration, which together covers all cases.
11936       //
11937       // A dependent typename using declaration will never successfully
11938       // instantiate, since it will always name a class member, so we reject
11939       // that in the template definition.
11940     }
11941   }
11942 
11943   // Check for invalid redeclarations.
11944   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11945                                   SS, IdentLoc, Previous))
11946     return nullptr;
11947 
11948   // Check for bad qualifiers.
11949   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11950                               IdentLoc))
11951     return nullptr;
11952 
11953   DeclContext *LookupContext = computeDeclContext(SS);
11954   NamedDecl *D;
11955   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11956   if (!LookupContext || EllipsisLoc.isValid()) {
11957     if (HasTypenameKeyword) {
11958       // FIXME: not all declaration name kinds are legal here
11959       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11960                                               UsingLoc, TypenameLoc,
11961                                               QualifierLoc,
11962                                               IdentLoc, NameInfo.getName(),
11963                                               EllipsisLoc);
11964     } else {
11965       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11966                                            QualifierLoc, NameInfo, EllipsisLoc);
11967     }
11968     D->setAccess(AS);
11969     CurContext->addDecl(D);
11970     return D;
11971   }
11972 
11973   auto Build = [&](bool Invalid) {
11974     UsingDecl *UD =
11975         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11976                           UsingName, HasTypenameKeyword);
11977     UD->setAccess(AS);
11978     CurContext->addDecl(UD);
11979     UD->setInvalidDecl(Invalid);
11980     return UD;
11981   };
11982   auto BuildInvalid = [&]{ return Build(true); };
11983   auto BuildValid = [&]{ return Build(false); };
11984 
11985   if (RequireCompleteDeclContext(SS, LookupContext))
11986     return BuildInvalid();
11987 
11988   // Look up the target name.
11989   LookupResult R(*this, NameInfo, LookupOrdinaryName);
11990 
11991   // Unlike most lookups, we don't always want to hide tag
11992   // declarations: tag names are visible through the using declaration
11993   // even if hidden by ordinary names, *except* in a dependent context
11994   // where it's important for the sanity of two-phase lookup.
11995   if (!IsInstantiation)
11996     R.setHideTags(false);
11997 
11998   // For the purposes of this lookup, we have a base object type
11999   // equal to that of the current context.
12000   if (CurContext->isRecord()) {
12001     R.setBaseObjectType(
12002                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12003   }
12004 
12005   LookupQualifiedName(R, LookupContext);
12006 
12007   // Try to correct typos if possible. If constructor name lookup finds no
12008   // results, that means the named class has no explicit constructors, and we
12009   // suppressed declaring implicit ones (probably because it's dependent or
12010   // invalid).
12011   if (R.empty() &&
12012       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12013     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12014     // it will believe that glibc provides a ::gets in cases where it does not,
12015     // and will try to pull it into namespace std with a using-declaration.
12016     // Just ignore the using-declaration in that case.
12017     auto *II = NameInfo.getName().getAsIdentifierInfo();
12018     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12019         CurContext->isStdNamespace() &&
12020         isa<TranslationUnitDecl>(LookupContext) &&
12021         getSourceManager().isInSystemHeader(UsingLoc))
12022       return nullptr;
12023     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12024                           dyn_cast<CXXRecordDecl>(CurContext));
12025     if (TypoCorrection Corrected =
12026             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12027                         CTK_ErrorRecovery)) {
12028       // We reject candidates where DroppedSpecifier == true, hence the
12029       // literal '0' below.
12030       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12031                                 << NameInfo.getName() << LookupContext << 0
12032                                 << SS.getRange());
12033 
12034       // If we picked a correction with no attached Decl we can't do anything
12035       // useful with it, bail out.
12036       NamedDecl *ND = Corrected.getCorrectionDecl();
12037       if (!ND)
12038         return BuildInvalid();
12039 
12040       // If we corrected to an inheriting constructor, handle it as one.
12041       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12042       if (RD && RD->isInjectedClassName()) {
12043         // The parent of the injected class name is the class itself.
12044         RD = cast<CXXRecordDecl>(RD->getParent());
12045 
12046         // Fix up the information we'll use to build the using declaration.
12047         if (Corrected.WillReplaceSpecifier()) {
12048           NestedNameSpecifierLocBuilder Builder;
12049           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12050                               QualifierLoc.getSourceRange());
12051           QualifierLoc = Builder.getWithLocInContext(Context);
12052         }
12053 
12054         // In this case, the name we introduce is the name of a derived class
12055         // constructor.
12056         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12057         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12058             Context.getCanonicalType(Context.getRecordType(CurClass))));
12059         UsingName.setNamedTypeInfo(nullptr);
12060         for (auto *Ctor : LookupConstructors(RD))
12061           R.addDecl(Ctor);
12062         R.resolveKind();
12063       } else {
12064         // FIXME: Pick up all the declarations if we found an overloaded
12065         // function.
12066         UsingName.setName(ND->getDeclName());
12067         R.addDecl(ND);
12068       }
12069     } else {
12070       Diag(IdentLoc, diag::err_no_member)
12071         << NameInfo.getName() << LookupContext << SS.getRange();
12072       return BuildInvalid();
12073     }
12074   }
12075 
12076   if (R.isAmbiguous())
12077     return BuildInvalid();
12078 
12079   if (HasTypenameKeyword) {
12080     // If we asked for a typename and got a non-type decl, error out.
12081     if (!R.getAsSingle<TypeDecl>()) {
12082       Diag(IdentLoc, diag::err_using_typename_non_type);
12083       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12084         Diag((*I)->getUnderlyingDecl()->getLocation(),
12085              diag::note_using_decl_target);
12086       return BuildInvalid();
12087     }
12088   } else {
12089     // If we asked for a non-typename and we got a type, error out,
12090     // but only if this is an instantiation of an unresolved using
12091     // decl.  Otherwise just silently find the type name.
12092     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12093       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12094       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12095       return BuildInvalid();
12096     }
12097   }
12098 
12099   // C++14 [namespace.udecl]p6:
12100   // A using-declaration shall not name a namespace.
12101   if (R.getAsSingle<NamespaceDecl>()) {
12102     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12103       << SS.getRange();
12104     return BuildInvalid();
12105   }
12106 
12107   // C++14 [namespace.udecl]p7:
12108   // A using-declaration shall not name a scoped enumerator.
12109   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12110     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12111       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12112         << SS.getRange();
12113       return BuildInvalid();
12114     }
12115   }
12116 
12117   UsingDecl *UD = BuildValid();
12118 
12119   // Some additional rules apply to inheriting constructors.
12120   if (UsingName.getName().getNameKind() ==
12121         DeclarationName::CXXConstructorName) {
12122     // Suppress access diagnostics; the access check is instead performed at the
12123     // point of use for an inheriting constructor.
12124     R.suppressDiagnostics();
12125     if (CheckInheritingConstructorUsingDecl(UD))
12126       return UD;
12127   }
12128 
12129   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12130     UsingShadowDecl *PrevDecl = nullptr;
12131     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12132       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12133   }
12134 
12135   return UD;
12136 }
12137 
12138 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12139                                     ArrayRef<NamedDecl *> Expansions) {
12140   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12141          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12142          isa<UsingPackDecl>(InstantiatedFrom));
12143 
12144   auto *UPD =
12145       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12146   UPD->setAccess(InstantiatedFrom->getAccess());
12147   CurContext->addDecl(UPD);
12148   return UPD;
12149 }
12150 
12151 /// Additional checks for a using declaration referring to a constructor name.
12152 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12153   assert(!UD->hasTypename() && "expecting a constructor name");
12154 
12155   const Type *SourceType = UD->getQualifier()->getAsType();
12156   assert(SourceType &&
12157          "Using decl naming constructor doesn't have type in scope spec.");
12158   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12159 
12160   // Check whether the named type is a direct base class.
12161   bool AnyDependentBases = false;
12162   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12163                                       AnyDependentBases);
12164   if (!Base && !AnyDependentBases) {
12165     Diag(UD->getUsingLoc(),
12166          diag::err_using_decl_constructor_not_in_direct_base)
12167       << UD->getNameInfo().getSourceRange()
12168       << QualType(SourceType, 0) << TargetClass;
12169     UD->setInvalidDecl();
12170     return true;
12171   }
12172 
12173   if (Base)
12174     Base->setInheritConstructors();
12175 
12176   return false;
12177 }
12178 
12179 /// Checks that the given using declaration is not an invalid
12180 /// redeclaration.  Note that this is checking only for the using decl
12181 /// itself, not for any ill-formedness among the UsingShadowDecls.
12182 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12183                                        bool HasTypenameKeyword,
12184                                        const CXXScopeSpec &SS,
12185                                        SourceLocation NameLoc,
12186                                        const LookupResult &Prev) {
12187   NestedNameSpecifier *Qual = SS.getScopeRep();
12188 
12189   // C++03 [namespace.udecl]p8:
12190   // C++0x [namespace.udecl]p10:
12191   //   A using-declaration is a declaration and can therefore be used
12192   //   repeatedly where (and only where) multiple declarations are
12193   //   allowed.
12194   //
12195   // That's in non-member contexts.
12196   if (!CurContext->getRedeclContext()->isRecord()) {
12197     // A dependent qualifier outside a class can only ever resolve to an
12198     // enumeration type. Therefore it conflicts with any other non-type
12199     // declaration in the same scope.
12200     // FIXME: How should we check for dependent type-type conflicts at block
12201     // scope?
12202     if (Qual->isDependent() && !HasTypenameKeyword) {
12203       for (auto *D : Prev) {
12204         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12205           bool OldCouldBeEnumerator =
12206               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12207           Diag(NameLoc,
12208                OldCouldBeEnumerator ? diag::err_redefinition
12209                                     : diag::err_redefinition_different_kind)
12210               << Prev.getLookupName();
12211           Diag(D->getLocation(), diag::note_previous_definition);
12212           return true;
12213         }
12214       }
12215     }
12216     return false;
12217   }
12218 
12219   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12220     NamedDecl *D = *I;
12221 
12222     bool DTypename;
12223     NestedNameSpecifier *DQual;
12224     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12225       DTypename = UD->hasTypename();
12226       DQual = UD->getQualifier();
12227     } else if (UnresolvedUsingValueDecl *UD
12228                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12229       DTypename = false;
12230       DQual = UD->getQualifier();
12231     } else if (UnresolvedUsingTypenameDecl *UD
12232                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12233       DTypename = true;
12234       DQual = UD->getQualifier();
12235     } else continue;
12236 
12237     // using decls differ if one says 'typename' and the other doesn't.
12238     // FIXME: non-dependent using decls?
12239     if (HasTypenameKeyword != DTypename) continue;
12240 
12241     // using decls differ if they name different scopes (but note that
12242     // template instantiation can cause this check to trigger when it
12243     // didn't before instantiation).
12244     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12245         Context.getCanonicalNestedNameSpecifier(DQual))
12246       continue;
12247 
12248     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12249     Diag(D->getLocation(), diag::note_using_decl) << 1;
12250     return true;
12251   }
12252 
12253   return false;
12254 }
12255 
12256 
12257 /// Checks that the given nested-name qualifier used in a using decl
12258 /// in the current context is appropriately related to the current
12259 /// scope.  If an error is found, diagnoses it and returns true.
12260 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12261                                    bool HasTypename,
12262                                    const CXXScopeSpec &SS,
12263                                    const DeclarationNameInfo &NameInfo,
12264                                    SourceLocation NameLoc) {
12265   DeclContext *NamedContext = computeDeclContext(SS);
12266 
12267   if (!CurContext->isRecord()) {
12268     // C++03 [namespace.udecl]p3:
12269     // C++0x [namespace.udecl]p8:
12270     //   A using-declaration for a class member shall be a member-declaration.
12271 
12272     // If we weren't able to compute a valid scope, it might validly be a
12273     // dependent class scope or a dependent enumeration unscoped scope. If
12274     // we have a 'typename' keyword, the scope must resolve to a class type.
12275     if ((HasTypename && !NamedContext) ||
12276         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12277       auto *RD = NamedContext
12278                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12279                      : nullptr;
12280       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12281         RD = nullptr;
12282 
12283       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12284         << SS.getRange();
12285 
12286       // If we have a complete, non-dependent source type, try to suggest a
12287       // way to get the same effect.
12288       if (!RD)
12289         return true;
12290 
12291       // Find what this using-declaration was referring to.
12292       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12293       R.setHideTags(false);
12294       R.suppressDiagnostics();
12295       LookupQualifiedName(R, RD);
12296 
12297       if (R.getAsSingle<TypeDecl>()) {
12298         if (getLangOpts().CPlusPlus11) {
12299           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12300           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12301             << 0 // alias declaration
12302             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12303                                           NameInfo.getName().getAsString() +
12304                                               " = ");
12305         } else {
12306           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12307           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12308           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12309             << 1 // typedef declaration
12310             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12311             << FixItHint::CreateInsertion(
12312                    InsertLoc, " " + NameInfo.getName().getAsString());
12313         }
12314       } else if (R.getAsSingle<VarDecl>()) {
12315         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12316         // repeating the type of the static data member here.
12317         FixItHint FixIt;
12318         if (getLangOpts().CPlusPlus11) {
12319           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12320           FixIt = FixItHint::CreateReplacement(
12321               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12322         }
12323 
12324         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12325           << 2 // reference declaration
12326           << FixIt;
12327       } else if (R.getAsSingle<EnumConstantDecl>()) {
12328         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12329         // repeating the type of the enumeration here, and we can't do so if
12330         // the type is anonymous.
12331         FixItHint FixIt;
12332         if (getLangOpts().CPlusPlus11) {
12333           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12334           FixIt = FixItHint::CreateReplacement(
12335               UsingLoc,
12336               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12337         }
12338 
12339         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12340           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12341           << FixIt;
12342       }
12343       return true;
12344     }
12345 
12346     // Otherwise, this might be valid.
12347     return false;
12348   }
12349 
12350   // The current scope is a record.
12351 
12352   // If the named context is dependent, we can't decide much.
12353   if (!NamedContext) {
12354     // FIXME: in C++0x, we can diagnose if we can prove that the
12355     // nested-name-specifier does not refer to a base class, which is
12356     // still possible in some cases.
12357 
12358     // Otherwise we have to conservatively report that things might be
12359     // okay.
12360     return false;
12361   }
12362 
12363   if (!NamedContext->isRecord()) {
12364     // Ideally this would point at the last name in the specifier,
12365     // but we don't have that level of source info.
12366     Diag(SS.getRange().getBegin(),
12367          diag::err_using_decl_nested_name_specifier_is_not_class)
12368       << SS.getScopeRep() << SS.getRange();
12369     return true;
12370   }
12371 
12372   if (!NamedContext->isDependentContext() &&
12373       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12374     return true;
12375 
12376   if (getLangOpts().CPlusPlus11) {
12377     // C++11 [namespace.udecl]p3:
12378     //   In a using-declaration used as a member-declaration, the
12379     //   nested-name-specifier shall name a base class of the class
12380     //   being defined.
12381 
12382     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12383                                  cast<CXXRecordDecl>(NamedContext))) {
12384       if (CurContext == NamedContext) {
12385         Diag(NameLoc,
12386              diag::err_using_decl_nested_name_specifier_is_current_class)
12387           << SS.getRange();
12388         return true;
12389       }
12390 
12391       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12392         Diag(SS.getRange().getBegin(),
12393              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12394           << SS.getScopeRep()
12395           << cast<CXXRecordDecl>(CurContext)
12396           << SS.getRange();
12397       }
12398       return true;
12399     }
12400 
12401     return false;
12402   }
12403 
12404   // C++03 [namespace.udecl]p4:
12405   //   A using-declaration used as a member-declaration shall refer
12406   //   to a member of a base class of the class being defined [etc.].
12407 
12408   // Salient point: SS doesn't have to name a base class as long as
12409   // lookup only finds members from base classes.  Therefore we can
12410   // diagnose here only if we can prove that that can't happen,
12411   // i.e. if the class hierarchies provably don't intersect.
12412 
12413   // TODO: it would be nice if "definitely valid" results were cached
12414   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12415   // need to be repeated.
12416 
12417   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12418   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12419     Bases.insert(Base);
12420     return true;
12421   };
12422 
12423   // Collect all bases. Return false if we find a dependent base.
12424   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12425     return false;
12426 
12427   // Returns true if the base is dependent or is one of the accumulated base
12428   // classes.
12429   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12430     return !Bases.count(Base);
12431   };
12432 
12433   // Return false if the class has a dependent base or if it or one
12434   // of its bases is present in the base set of the current context.
12435   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12436       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12437     return false;
12438 
12439   Diag(SS.getRange().getBegin(),
12440        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12441     << SS.getScopeRep()
12442     << cast<CXXRecordDecl>(CurContext)
12443     << SS.getRange();
12444 
12445   return true;
12446 }
12447 
12448 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12449                                   MultiTemplateParamsArg TemplateParamLists,
12450                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12451                                   const ParsedAttributesView &AttrList,
12452                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12453   // Skip up to the relevant declaration scope.
12454   while (S->isTemplateParamScope())
12455     S = S->getParent();
12456   assert((S->getFlags() & Scope::DeclScope) &&
12457          "got alias-declaration outside of declaration scope");
12458 
12459   if (Type.isInvalid())
12460     return nullptr;
12461 
12462   bool Invalid = false;
12463   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12464   TypeSourceInfo *TInfo = nullptr;
12465   GetTypeFromParser(Type.get(), &TInfo);
12466 
12467   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12468     return nullptr;
12469 
12470   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12471                                       UPPC_DeclarationType)) {
12472     Invalid = true;
12473     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12474                                              TInfo->getTypeLoc().getBeginLoc());
12475   }
12476 
12477   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12478                         TemplateParamLists.size()
12479                             ? forRedeclarationInCurContext()
12480                             : ForVisibleRedeclaration);
12481   LookupName(Previous, S);
12482 
12483   // Warn about shadowing the name of a template parameter.
12484   if (Previous.isSingleResult() &&
12485       Previous.getFoundDecl()->isTemplateParameter()) {
12486     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12487     Previous.clear();
12488   }
12489 
12490   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12491          "name in alias declaration must be an identifier");
12492   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12493                                                Name.StartLocation,
12494                                                Name.Identifier, TInfo);
12495 
12496   NewTD->setAccess(AS);
12497 
12498   if (Invalid)
12499     NewTD->setInvalidDecl();
12500 
12501   ProcessDeclAttributeList(S, NewTD, AttrList);
12502   AddPragmaAttributes(S, NewTD);
12503 
12504   CheckTypedefForVariablyModifiedType(S, NewTD);
12505   Invalid |= NewTD->isInvalidDecl();
12506 
12507   bool Redeclaration = false;
12508 
12509   NamedDecl *NewND;
12510   if (TemplateParamLists.size()) {
12511     TypeAliasTemplateDecl *OldDecl = nullptr;
12512     TemplateParameterList *OldTemplateParams = nullptr;
12513 
12514     if (TemplateParamLists.size() != 1) {
12515       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12516         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12517          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12518     }
12519     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12520 
12521     // Check that we can declare a template here.
12522     if (CheckTemplateDeclScope(S, TemplateParams))
12523       return nullptr;
12524 
12525     // Only consider previous declarations in the same scope.
12526     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12527                          /*ExplicitInstantiationOrSpecialization*/false);
12528     if (!Previous.empty()) {
12529       Redeclaration = true;
12530 
12531       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12532       if (!OldDecl && !Invalid) {
12533         Diag(UsingLoc, diag::err_redefinition_different_kind)
12534           << Name.Identifier;
12535 
12536         NamedDecl *OldD = Previous.getRepresentativeDecl();
12537         if (OldD->getLocation().isValid())
12538           Diag(OldD->getLocation(), diag::note_previous_definition);
12539 
12540         Invalid = true;
12541       }
12542 
12543       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12544         if (TemplateParameterListsAreEqual(TemplateParams,
12545                                            OldDecl->getTemplateParameters(),
12546                                            /*Complain=*/true,
12547                                            TPL_TemplateMatch))
12548           OldTemplateParams =
12549               OldDecl->getMostRecentDecl()->getTemplateParameters();
12550         else
12551           Invalid = true;
12552 
12553         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12554         if (!Invalid &&
12555             !Context.hasSameType(OldTD->getUnderlyingType(),
12556                                  NewTD->getUnderlyingType())) {
12557           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12558           // but we can't reasonably accept it.
12559           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12560             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12561           if (OldTD->getLocation().isValid())
12562             Diag(OldTD->getLocation(), diag::note_previous_definition);
12563           Invalid = true;
12564         }
12565       }
12566     }
12567 
12568     // Merge any previous default template arguments into our parameters,
12569     // and check the parameter list.
12570     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12571                                    TPC_TypeAliasTemplate))
12572       return nullptr;
12573 
12574     TypeAliasTemplateDecl *NewDecl =
12575       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12576                                     Name.Identifier, TemplateParams,
12577                                     NewTD);
12578     NewTD->setDescribedAliasTemplate(NewDecl);
12579 
12580     NewDecl->setAccess(AS);
12581 
12582     if (Invalid)
12583       NewDecl->setInvalidDecl();
12584     else if (OldDecl) {
12585       NewDecl->setPreviousDecl(OldDecl);
12586       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12587     }
12588 
12589     NewND = NewDecl;
12590   } else {
12591     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12592       setTagNameForLinkagePurposes(TD, NewTD);
12593       handleTagNumbering(TD, S);
12594     }
12595     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12596     NewND = NewTD;
12597   }
12598 
12599   PushOnScopeChains(NewND, S);
12600   ActOnDocumentableDecl(NewND);
12601   return NewND;
12602 }
12603 
12604 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12605                                    SourceLocation AliasLoc,
12606                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12607                                    SourceLocation IdentLoc,
12608                                    IdentifierInfo *Ident) {
12609 
12610   // Lookup the namespace name.
12611   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12612   LookupParsedName(R, S, &SS);
12613 
12614   if (R.isAmbiguous())
12615     return nullptr;
12616 
12617   if (R.empty()) {
12618     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12619       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12620       return nullptr;
12621     }
12622   }
12623   assert(!R.isAmbiguous() && !R.empty());
12624   NamedDecl *ND = R.getRepresentativeDecl();
12625 
12626   // Check if we have a previous declaration with the same name.
12627   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12628                      ForVisibleRedeclaration);
12629   LookupName(PrevR, S);
12630 
12631   // Check we're not shadowing a template parameter.
12632   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12633     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12634     PrevR.clear();
12635   }
12636 
12637   // Filter out any other lookup result from an enclosing scope.
12638   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12639                        /*AllowInlineNamespace*/false);
12640 
12641   // Find the previous declaration and check that we can redeclare it.
12642   NamespaceAliasDecl *Prev = nullptr;
12643   if (PrevR.isSingleResult()) {
12644     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12645     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12646       // We already have an alias with the same name that points to the same
12647       // namespace; check that it matches.
12648       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12649         Prev = AD;
12650       } else if (isVisible(PrevDecl)) {
12651         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12652           << Alias;
12653         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12654           << AD->getNamespace();
12655         return nullptr;
12656       }
12657     } else if (isVisible(PrevDecl)) {
12658       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12659                             ? diag::err_redefinition
12660                             : diag::err_redefinition_different_kind;
12661       Diag(AliasLoc, DiagID) << Alias;
12662       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12663       return nullptr;
12664     }
12665   }
12666 
12667   // The use of a nested name specifier may trigger deprecation warnings.
12668   DiagnoseUseOfDecl(ND, IdentLoc);
12669 
12670   NamespaceAliasDecl *AliasDecl =
12671     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12672                                Alias, SS.getWithLocInContext(Context),
12673                                IdentLoc, ND);
12674   if (Prev)
12675     AliasDecl->setPreviousDecl(Prev);
12676 
12677   PushOnScopeChains(AliasDecl, S);
12678   return AliasDecl;
12679 }
12680 
12681 namespace {
12682 struct SpecialMemberExceptionSpecInfo
12683     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12684   SourceLocation Loc;
12685   Sema::ImplicitExceptionSpecification ExceptSpec;
12686 
12687   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12688                                  Sema::CXXSpecialMember CSM,
12689                                  Sema::InheritedConstructorInfo *ICI,
12690                                  SourceLocation Loc)
12691       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12692 
12693   bool visitBase(CXXBaseSpecifier *Base);
12694   bool visitField(FieldDecl *FD);
12695 
12696   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12697                            unsigned Quals);
12698 
12699   void visitSubobjectCall(Subobject Subobj,
12700                           Sema::SpecialMemberOverloadResult SMOR);
12701 };
12702 }
12703 
12704 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12705   auto *RT = Base->getType()->getAs<RecordType>();
12706   if (!RT)
12707     return false;
12708 
12709   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12710   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12711   if (auto *BaseCtor = SMOR.getMethod()) {
12712     visitSubobjectCall(Base, BaseCtor);
12713     return false;
12714   }
12715 
12716   visitClassSubobject(BaseClass, Base, 0);
12717   return false;
12718 }
12719 
12720 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12721   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12722     Expr *E = FD->getInClassInitializer();
12723     if (!E)
12724       // FIXME: It's a little wasteful to build and throw away a
12725       // CXXDefaultInitExpr here.
12726       // FIXME: We should have a single context note pointing at Loc, and
12727       // this location should be MD->getLocation() instead, since that's
12728       // the location where we actually use the default init expression.
12729       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12730     if (E)
12731       ExceptSpec.CalledExpr(E);
12732   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12733                             ->getAs<RecordType>()) {
12734     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12735                         FD->getType().getCVRQualifiers());
12736   }
12737   return false;
12738 }
12739 
12740 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12741                                                          Subobject Subobj,
12742                                                          unsigned Quals) {
12743   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12744   bool IsMutable = Field && Field->isMutable();
12745   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12746 }
12747 
12748 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12749     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12750   // Note, if lookup fails, it doesn't matter what exception specification we
12751   // choose because the special member will be deleted.
12752   if (CXXMethodDecl *MD = SMOR.getMethod())
12753     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12754 }
12755 
12756 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12757   llvm::APSInt Result;
12758   ExprResult Converted = CheckConvertedConstantExpression(
12759       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12760   ExplicitSpec.setExpr(Converted.get());
12761   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12762     ExplicitSpec.setKind(Result.getBoolValue()
12763                              ? ExplicitSpecKind::ResolvedTrue
12764                              : ExplicitSpecKind::ResolvedFalse);
12765     return true;
12766   }
12767   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12768   return false;
12769 }
12770 
12771 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12772   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12773   if (!ExplicitExpr->isTypeDependent())
12774     tryResolveExplicitSpecifier(ES);
12775   return ES;
12776 }
12777 
12778 static Sema::ImplicitExceptionSpecification
12779 ComputeDefaultedSpecialMemberExceptionSpec(
12780     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12781     Sema::InheritedConstructorInfo *ICI) {
12782   ComputingExceptionSpec CES(S, MD, Loc);
12783 
12784   CXXRecordDecl *ClassDecl = MD->getParent();
12785 
12786   // C++ [except.spec]p14:
12787   //   An implicitly declared special member function (Clause 12) shall have an
12788   //   exception-specification. [...]
12789   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12790   if (ClassDecl->isInvalidDecl())
12791     return Info.ExceptSpec;
12792 
12793   // FIXME: If this diagnostic fires, we're probably missing a check for
12794   // attempting to resolve an exception specification before it's known
12795   // at a higher level.
12796   if (S.RequireCompleteType(MD->getLocation(),
12797                             S.Context.getRecordType(ClassDecl),
12798                             diag::err_exception_spec_incomplete_type))
12799     return Info.ExceptSpec;
12800 
12801   // C++1z [except.spec]p7:
12802   //   [Look for exceptions thrown by] a constructor selected [...] to
12803   //   initialize a potentially constructed subobject,
12804   // C++1z [except.spec]p8:
12805   //   The exception specification for an implicitly-declared destructor, or a
12806   //   destructor without a noexcept-specifier, is potentially-throwing if and
12807   //   only if any of the destructors for any of its potentially constructed
12808   //   subojects is potentially throwing.
12809   // FIXME: We respect the first rule but ignore the "potentially constructed"
12810   // in the second rule to resolve a core issue (no number yet) that would have
12811   // us reject:
12812   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12813   //   struct B : A {};
12814   //   struct C : B { void f(); };
12815   // ... due to giving B::~B() a non-throwing exception specification.
12816   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12817                                 : Info.VisitAllBases);
12818 
12819   return Info.ExceptSpec;
12820 }
12821 
12822 namespace {
12823 /// RAII object to register a special member as being currently declared.
12824 struct DeclaringSpecialMember {
12825   Sema &S;
12826   Sema::SpecialMemberDecl D;
12827   Sema::ContextRAII SavedContext;
12828   bool WasAlreadyBeingDeclared;
12829 
12830   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12831       : S(S), D(RD, CSM), SavedContext(S, RD) {
12832     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12833     if (WasAlreadyBeingDeclared)
12834       // This almost never happens, but if it does, ensure that our cache
12835       // doesn't contain a stale result.
12836       S.SpecialMemberCache.clear();
12837     else {
12838       // Register a note to be produced if we encounter an error while
12839       // declaring the special member.
12840       Sema::CodeSynthesisContext Ctx;
12841       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12842       // FIXME: We don't have a location to use here. Using the class's
12843       // location maintains the fiction that we declare all special members
12844       // with the class, but (1) it's not clear that lying about that helps our
12845       // users understand what's going on, and (2) there may be outer contexts
12846       // on the stack (some of which are relevant) and printing them exposes
12847       // our lies.
12848       Ctx.PointOfInstantiation = RD->getLocation();
12849       Ctx.Entity = RD;
12850       Ctx.SpecialMember = CSM;
12851       S.pushCodeSynthesisContext(Ctx);
12852     }
12853   }
12854   ~DeclaringSpecialMember() {
12855     if (!WasAlreadyBeingDeclared) {
12856       S.SpecialMembersBeingDeclared.erase(D);
12857       S.popCodeSynthesisContext();
12858     }
12859   }
12860 
12861   /// Are we already trying to declare this special member?
12862   bool isAlreadyBeingDeclared() const {
12863     return WasAlreadyBeingDeclared;
12864   }
12865 };
12866 }
12867 
12868 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12869   // Look up any existing declarations, but don't trigger declaration of all
12870   // implicit special members with this name.
12871   DeclarationName Name = FD->getDeclName();
12872   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12873                  ForExternalRedeclaration);
12874   for (auto *D : FD->getParent()->lookup(Name))
12875     if (auto *Acceptable = R.getAcceptableDecl(D))
12876       R.addDecl(Acceptable);
12877   R.resolveKind();
12878   R.suppressDiagnostics();
12879 
12880   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12881 }
12882 
12883 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12884                                           QualType ResultTy,
12885                                           ArrayRef<QualType> Args) {
12886   // Build an exception specification pointing back at this constructor.
12887   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12888 
12889   LangAS AS = getDefaultCXXMethodAddrSpace();
12890   if (AS != LangAS::Default) {
12891     EPI.TypeQuals.addAddressSpace(AS);
12892   }
12893 
12894   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12895   SpecialMem->setType(QT);
12896 }
12897 
12898 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12899                                                      CXXRecordDecl *ClassDecl) {
12900   // C++ [class.ctor]p5:
12901   //   A default constructor for a class X is a constructor of class X
12902   //   that can be called without an argument. If there is no
12903   //   user-declared constructor for class X, a default constructor is
12904   //   implicitly declared. An implicitly-declared default constructor
12905   //   is an inline public member of its class.
12906   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12907          "Should not build implicit default constructor!");
12908 
12909   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12910   if (DSM.isAlreadyBeingDeclared())
12911     return nullptr;
12912 
12913   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12914                                                      CXXDefaultConstructor,
12915                                                      false);
12916 
12917   // Create the actual constructor declaration.
12918   CanQualType ClassType
12919     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12920   SourceLocation ClassLoc = ClassDecl->getLocation();
12921   DeclarationName Name
12922     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12923   DeclarationNameInfo NameInfo(Name, ClassLoc);
12924   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12925       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12926       /*TInfo=*/nullptr, ExplicitSpecifier(),
12927       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12928       Constexpr ? CSK_constexpr : CSK_unspecified);
12929   DefaultCon->setAccess(AS_public);
12930   DefaultCon->setDefaulted();
12931 
12932   if (getLangOpts().CUDA) {
12933     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12934                                             DefaultCon,
12935                                             /* ConstRHS */ false,
12936                                             /* Diagnose */ false);
12937   }
12938 
12939   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12940 
12941   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12942   // constructors is easy to compute.
12943   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12944 
12945   // Note that we have declared this constructor.
12946   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12947 
12948   Scope *S = getScopeForContext(ClassDecl);
12949   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12950 
12951   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12952     SetDeclDeleted(DefaultCon, ClassLoc);
12953 
12954   if (S)
12955     PushOnScopeChains(DefaultCon, S, false);
12956   ClassDecl->addDecl(DefaultCon);
12957 
12958   return DefaultCon;
12959 }
12960 
12961 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12962                                             CXXConstructorDecl *Constructor) {
12963   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12964           !Constructor->doesThisDeclarationHaveABody() &&
12965           !Constructor->isDeleted()) &&
12966     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12967   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12968     return;
12969 
12970   CXXRecordDecl *ClassDecl = Constructor->getParent();
12971   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12972 
12973   SynthesizedFunctionScope Scope(*this, Constructor);
12974 
12975   // The exception specification is needed because we are defining the
12976   // function.
12977   ResolveExceptionSpec(CurrentLocation,
12978                        Constructor->getType()->castAs<FunctionProtoType>());
12979   MarkVTableUsed(CurrentLocation, ClassDecl);
12980 
12981   // Add a context note for diagnostics produced after this point.
12982   Scope.addContextNote(CurrentLocation);
12983 
12984   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12985     Constructor->setInvalidDecl();
12986     return;
12987   }
12988 
12989   SourceLocation Loc = Constructor->getEndLoc().isValid()
12990                            ? Constructor->getEndLoc()
12991                            : Constructor->getLocation();
12992   Constructor->setBody(new (Context) CompoundStmt(Loc));
12993   Constructor->markUsed(Context);
12994 
12995   if (ASTMutationListener *L = getASTMutationListener()) {
12996     L->CompletedImplicitDefinition(Constructor);
12997   }
12998 
12999   DiagnoseUninitializedFields(*this, Constructor);
13000 }
13001 
13002 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13003   // Perform any delayed checks on exception specifications.
13004   CheckDelayedMemberExceptionSpecs();
13005 }
13006 
13007 /// Find or create the fake constructor we synthesize to model constructing an
13008 /// object of a derived class via a constructor of a base class.
13009 CXXConstructorDecl *
13010 Sema::findInheritingConstructor(SourceLocation Loc,
13011                                 CXXConstructorDecl *BaseCtor,
13012                                 ConstructorUsingShadowDecl *Shadow) {
13013   CXXRecordDecl *Derived = Shadow->getParent();
13014   SourceLocation UsingLoc = Shadow->getLocation();
13015 
13016   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13017   // For now we use the name of the base class constructor as a member of the
13018   // derived class to indicate a (fake) inherited constructor name.
13019   DeclarationName Name = BaseCtor->getDeclName();
13020 
13021   // Check to see if we already have a fake constructor for this inherited
13022   // constructor call.
13023   for (NamedDecl *Ctor : Derived->lookup(Name))
13024     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13025                                ->getInheritedConstructor()
13026                                .getConstructor(),
13027                            BaseCtor))
13028       return cast<CXXConstructorDecl>(Ctor);
13029 
13030   DeclarationNameInfo NameInfo(Name, UsingLoc);
13031   TypeSourceInfo *TInfo =
13032       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13033   FunctionProtoTypeLoc ProtoLoc =
13034       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13035 
13036   // Check the inherited constructor is valid and find the list of base classes
13037   // from which it was inherited.
13038   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13039 
13040   bool Constexpr =
13041       BaseCtor->isConstexpr() &&
13042       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13043                                         false, BaseCtor, &ICI);
13044 
13045   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13046       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13047       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13048       /*isImplicitlyDeclared=*/true,
13049       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13050       InheritedConstructor(Shadow, BaseCtor),
13051       BaseCtor->getTrailingRequiresClause());
13052   if (Shadow->isInvalidDecl())
13053     DerivedCtor->setInvalidDecl();
13054 
13055   // Build an unevaluated exception specification for this fake constructor.
13056   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13057   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13058   EPI.ExceptionSpec.Type = EST_Unevaluated;
13059   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13060   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13061                                                FPT->getParamTypes(), EPI));
13062 
13063   // Build the parameter declarations.
13064   SmallVector<ParmVarDecl *, 16> ParamDecls;
13065   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13066     TypeSourceInfo *TInfo =
13067         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13068     ParmVarDecl *PD = ParmVarDecl::Create(
13069         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13070         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13071     PD->setScopeInfo(0, I);
13072     PD->setImplicit();
13073     // Ensure attributes are propagated onto parameters (this matters for
13074     // format, pass_object_size, ...).
13075     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13076     ParamDecls.push_back(PD);
13077     ProtoLoc.setParam(I, PD);
13078   }
13079 
13080   // Set up the new constructor.
13081   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13082   DerivedCtor->setAccess(BaseCtor->getAccess());
13083   DerivedCtor->setParams(ParamDecls);
13084   Derived->addDecl(DerivedCtor);
13085 
13086   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13087     SetDeclDeleted(DerivedCtor, UsingLoc);
13088 
13089   return DerivedCtor;
13090 }
13091 
13092 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13093   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13094                                Ctor->getInheritedConstructor().getShadowDecl());
13095   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13096                             /*Diagnose*/true);
13097 }
13098 
13099 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13100                                        CXXConstructorDecl *Constructor) {
13101   CXXRecordDecl *ClassDecl = Constructor->getParent();
13102   assert(Constructor->getInheritedConstructor() &&
13103          !Constructor->doesThisDeclarationHaveABody() &&
13104          !Constructor->isDeleted());
13105   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13106     return;
13107 
13108   // Initializations are performed "as if by a defaulted default constructor",
13109   // so enter the appropriate scope.
13110   SynthesizedFunctionScope Scope(*this, Constructor);
13111 
13112   // The exception specification is needed because we are defining the
13113   // function.
13114   ResolveExceptionSpec(CurrentLocation,
13115                        Constructor->getType()->castAs<FunctionProtoType>());
13116   MarkVTableUsed(CurrentLocation, ClassDecl);
13117 
13118   // Add a context note for diagnostics produced after this point.
13119   Scope.addContextNote(CurrentLocation);
13120 
13121   ConstructorUsingShadowDecl *Shadow =
13122       Constructor->getInheritedConstructor().getShadowDecl();
13123   CXXConstructorDecl *InheritedCtor =
13124       Constructor->getInheritedConstructor().getConstructor();
13125 
13126   // [class.inhctor.init]p1:
13127   //   initialization proceeds as if a defaulted default constructor is used to
13128   //   initialize the D object and each base class subobject from which the
13129   //   constructor was inherited
13130 
13131   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13132   CXXRecordDecl *RD = Shadow->getParent();
13133   SourceLocation InitLoc = Shadow->getLocation();
13134 
13135   // Build explicit initializers for all base classes from which the
13136   // constructor was inherited.
13137   SmallVector<CXXCtorInitializer*, 8> Inits;
13138   for (bool VBase : {false, true}) {
13139     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13140       if (B.isVirtual() != VBase)
13141         continue;
13142 
13143       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13144       if (!BaseRD)
13145         continue;
13146 
13147       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13148       if (!BaseCtor.first)
13149         continue;
13150 
13151       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13152       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13153           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13154 
13155       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13156       Inits.push_back(new (Context) CXXCtorInitializer(
13157           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13158           SourceLocation()));
13159     }
13160   }
13161 
13162   // We now proceed as if for a defaulted default constructor, with the relevant
13163   // initializers replaced.
13164 
13165   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13166     Constructor->setInvalidDecl();
13167     return;
13168   }
13169 
13170   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13171   Constructor->markUsed(Context);
13172 
13173   if (ASTMutationListener *L = getASTMutationListener()) {
13174     L->CompletedImplicitDefinition(Constructor);
13175   }
13176 
13177   DiagnoseUninitializedFields(*this, Constructor);
13178 }
13179 
13180 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13181   // C++ [class.dtor]p2:
13182   //   If a class has no user-declared destructor, a destructor is
13183   //   declared implicitly. An implicitly-declared destructor is an
13184   //   inline public member of its class.
13185   assert(ClassDecl->needsImplicitDestructor());
13186 
13187   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13188   if (DSM.isAlreadyBeingDeclared())
13189     return nullptr;
13190 
13191   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13192                                                      CXXDestructor,
13193                                                      false);
13194 
13195   // Create the actual destructor declaration.
13196   CanQualType ClassType
13197     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13198   SourceLocation ClassLoc = ClassDecl->getLocation();
13199   DeclarationName Name
13200     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13201   DeclarationNameInfo NameInfo(Name, ClassLoc);
13202   CXXDestructorDecl *Destructor =
13203       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13204                                 QualType(), nullptr, /*isInline=*/true,
13205                                 /*isImplicitlyDeclared=*/true,
13206                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13207   Destructor->setAccess(AS_public);
13208   Destructor->setDefaulted();
13209 
13210   if (getLangOpts().CUDA) {
13211     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13212                                             Destructor,
13213                                             /* ConstRHS */ false,
13214                                             /* Diagnose */ false);
13215   }
13216 
13217   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13218 
13219   // We don't need to use SpecialMemberIsTrivial here; triviality for
13220   // destructors is easy to compute.
13221   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13222   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13223                                 ClassDecl->hasTrivialDestructorForCall());
13224 
13225   // Note that we have declared this destructor.
13226   ++getASTContext().NumImplicitDestructorsDeclared;
13227 
13228   Scope *S = getScopeForContext(ClassDecl);
13229   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13230 
13231   // We can't check whether an implicit destructor is deleted before we complete
13232   // the definition of the class, because its validity depends on the alignment
13233   // of the class. We'll check this from ActOnFields once the class is complete.
13234   if (ClassDecl->isCompleteDefinition() &&
13235       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13236     SetDeclDeleted(Destructor, ClassLoc);
13237 
13238   // Introduce this destructor into its scope.
13239   if (S)
13240     PushOnScopeChains(Destructor, S, false);
13241   ClassDecl->addDecl(Destructor);
13242 
13243   return Destructor;
13244 }
13245 
13246 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13247                                     CXXDestructorDecl *Destructor) {
13248   assert((Destructor->isDefaulted() &&
13249           !Destructor->doesThisDeclarationHaveABody() &&
13250           !Destructor->isDeleted()) &&
13251          "DefineImplicitDestructor - call it for implicit default dtor");
13252   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13253     return;
13254 
13255   CXXRecordDecl *ClassDecl = Destructor->getParent();
13256   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13257 
13258   SynthesizedFunctionScope Scope(*this, Destructor);
13259 
13260   // The exception specification is needed because we are defining the
13261   // function.
13262   ResolveExceptionSpec(CurrentLocation,
13263                        Destructor->getType()->castAs<FunctionProtoType>());
13264   MarkVTableUsed(CurrentLocation, ClassDecl);
13265 
13266   // Add a context note for diagnostics produced after this point.
13267   Scope.addContextNote(CurrentLocation);
13268 
13269   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13270                                          Destructor->getParent());
13271 
13272   if (CheckDestructor(Destructor)) {
13273     Destructor->setInvalidDecl();
13274     return;
13275   }
13276 
13277   SourceLocation Loc = Destructor->getEndLoc().isValid()
13278                            ? Destructor->getEndLoc()
13279                            : Destructor->getLocation();
13280   Destructor->setBody(new (Context) CompoundStmt(Loc));
13281   Destructor->markUsed(Context);
13282 
13283   if (ASTMutationListener *L = getASTMutationListener()) {
13284     L->CompletedImplicitDefinition(Destructor);
13285   }
13286 }
13287 
13288 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13289                                           CXXDestructorDecl *Destructor) {
13290   if (Destructor->isInvalidDecl())
13291     return;
13292 
13293   CXXRecordDecl *ClassDecl = Destructor->getParent();
13294   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13295          "implicit complete dtors unneeded outside MS ABI");
13296   assert(ClassDecl->getNumVBases() > 0 &&
13297          "complete dtor only exists for classes with vbases");
13298 
13299   SynthesizedFunctionScope Scope(*this, Destructor);
13300 
13301   // Add a context note for diagnostics produced after this point.
13302   Scope.addContextNote(CurrentLocation);
13303 
13304   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13305 }
13306 
13307 /// Perform any semantic analysis which needs to be delayed until all
13308 /// pending class member declarations have been parsed.
13309 void Sema::ActOnFinishCXXMemberDecls() {
13310   // If the context is an invalid C++ class, just suppress these checks.
13311   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13312     if (Record->isInvalidDecl()) {
13313       DelayedOverridingExceptionSpecChecks.clear();
13314       DelayedEquivalentExceptionSpecChecks.clear();
13315       return;
13316     }
13317     checkForMultipleExportedDefaultConstructors(*this, Record);
13318   }
13319 }
13320 
13321 void Sema::ActOnFinishCXXNonNestedClass() {
13322   referenceDLLExportedClassMethods();
13323 
13324   if (!DelayedDllExportMemberFunctions.empty()) {
13325     SmallVector<CXXMethodDecl*, 4> WorkList;
13326     std::swap(DelayedDllExportMemberFunctions, WorkList);
13327     for (CXXMethodDecl *M : WorkList) {
13328       DefineDefaultedFunction(*this, M, M->getLocation());
13329 
13330       // Pass the method to the consumer to get emitted. This is not necessary
13331       // for explicit instantiation definitions, as they will get emitted
13332       // anyway.
13333       if (M->getParent()->getTemplateSpecializationKind() !=
13334           TSK_ExplicitInstantiationDefinition)
13335         ActOnFinishInlineFunctionDef(M);
13336     }
13337   }
13338 }
13339 
13340 void Sema::referenceDLLExportedClassMethods() {
13341   if (!DelayedDllExportClasses.empty()) {
13342     // Calling ReferenceDllExportedMembers might cause the current function to
13343     // be called again, so use a local copy of DelayedDllExportClasses.
13344     SmallVector<CXXRecordDecl *, 4> WorkList;
13345     std::swap(DelayedDllExportClasses, WorkList);
13346     for (CXXRecordDecl *Class : WorkList)
13347       ReferenceDllExportedMembers(*this, Class);
13348   }
13349 }
13350 
13351 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13352   assert(getLangOpts().CPlusPlus11 &&
13353          "adjusting dtor exception specs was introduced in c++11");
13354 
13355   if (Destructor->isDependentContext())
13356     return;
13357 
13358   // C++11 [class.dtor]p3:
13359   //   A declaration of a destructor that does not have an exception-
13360   //   specification is implicitly considered to have the same exception-
13361   //   specification as an implicit declaration.
13362   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13363   if (DtorType->hasExceptionSpec())
13364     return;
13365 
13366   // Replace the destructor's type, building off the existing one. Fortunately,
13367   // the only thing of interest in the destructor type is its extended info.
13368   // The return and arguments are fixed.
13369   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13370   EPI.ExceptionSpec.Type = EST_Unevaluated;
13371   EPI.ExceptionSpec.SourceDecl = Destructor;
13372   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13373 
13374   // FIXME: If the destructor has a body that could throw, and the newly created
13375   // spec doesn't allow exceptions, we should emit a warning, because this
13376   // change in behavior can break conforming C++03 programs at runtime.
13377   // However, we don't have a body or an exception specification yet, so it
13378   // needs to be done somewhere else.
13379 }
13380 
13381 namespace {
13382 /// An abstract base class for all helper classes used in building the
13383 //  copy/move operators. These classes serve as factory functions and help us
13384 //  avoid using the same Expr* in the AST twice.
13385 class ExprBuilder {
13386   ExprBuilder(const ExprBuilder&) = delete;
13387   ExprBuilder &operator=(const ExprBuilder&) = delete;
13388 
13389 protected:
13390   static Expr *assertNotNull(Expr *E) {
13391     assert(E && "Expression construction must not fail.");
13392     return E;
13393   }
13394 
13395 public:
13396   ExprBuilder() {}
13397   virtual ~ExprBuilder() {}
13398 
13399   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13400 };
13401 
13402 class RefBuilder: public ExprBuilder {
13403   VarDecl *Var;
13404   QualType VarType;
13405 
13406 public:
13407   Expr *build(Sema &S, SourceLocation Loc) const override {
13408     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13409   }
13410 
13411   RefBuilder(VarDecl *Var, QualType VarType)
13412       : Var(Var), VarType(VarType) {}
13413 };
13414 
13415 class ThisBuilder: public ExprBuilder {
13416 public:
13417   Expr *build(Sema &S, SourceLocation Loc) const override {
13418     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13419   }
13420 };
13421 
13422 class CastBuilder: public ExprBuilder {
13423   const ExprBuilder &Builder;
13424   QualType Type;
13425   ExprValueKind Kind;
13426   const CXXCastPath &Path;
13427 
13428 public:
13429   Expr *build(Sema &S, SourceLocation Loc) const override {
13430     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13431                                              CK_UncheckedDerivedToBase, Kind,
13432                                              &Path).get());
13433   }
13434 
13435   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13436               const CXXCastPath &Path)
13437       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13438 };
13439 
13440 class DerefBuilder: public ExprBuilder {
13441   const ExprBuilder &Builder;
13442 
13443 public:
13444   Expr *build(Sema &S, SourceLocation Loc) const override {
13445     return assertNotNull(
13446         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13447   }
13448 
13449   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13450 };
13451 
13452 class MemberBuilder: public ExprBuilder {
13453   const ExprBuilder &Builder;
13454   QualType Type;
13455   CXXScopeSpec SS;
13456   bool IsArrow;
13457   LookupResult &MemberLookup;
13458 
13459 public:
13460   Expr *build(Sema &S, SourceLocation Loc) const override {
13461     return assertNotNull(S.BuildMemberReferenceExpr(
13462         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13463         nullptr, MemberLookup, nullptr, nullptr).get());
13464   }
13465 
13466   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13467                 LookupResult &MemberLookup)
13468       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13469         MemberLookup(MemberLookup) {}
13470 };
13471 
13472 class MoveCastBuilder: public ExprBuilder {
13473   const ExprBuilder &Builder;
13474 
13475 public:
13476   Expr *build(Sema &S, SourceLocation Loc) const override {
13477     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13478   }
13479 
13480   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13481 };
13482 
13483 class LvalueConvBuilder: public ExprBuilder {
13484   const ExprBuilder &Builder;
13485 
13486 public:
13487   Expr *build(Sema &S, SourceLocation Loc) const override {
13488     return assertNotNull(
13489         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13490   }
13491 
13492   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13493 };
13494 
13495 class SubscriptBuilder: public ExprBuilder {
13496   const ExprBuilder &Base;
13497   const ExprBuilder &Index;
13498 
13499 public:
13500   Expr *build(Sema &S, SourceLocation Loc) const override {
13501     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13502         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13503   }
13504 
13505   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13506       : Base(Base), Index(Index) {}
13507 };
13508 
13509 } // end anonymous namespace
13510 
13511 /// When generating a defaulted copy or move assignment operator, if a field
13512 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13513 /// do so. This optimization only applies for arrays of scalars, and for arrays
13514 /// of class type where the selected copy/move-assignment operator is trivial.
13515 static StmtResult
13516 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13517                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13518   // Compute the size of the memory buffer to be copied.
13519   QualType SizeType = S.Context.getSizeType();
13520   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13521                    S.Context.getTypeSizeInChars(T).getQuantity());
13522 
13523   // Take the address of the field references for "from" and "to". We
13524   // directly construct UnaryOperators here because semantic analysis
13525   // does not permit us to take the address of an xvalue.
13526   Expr *From = FromB.build(S, Loc);
13527   From = UnaryOperator::Create(
13528       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13529       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatures);
13530   Expr *To = ToB.build(S, Loc);
13531   To = UnaryOperator::Create(S.Context, To, UO_AddrOf,
13532                              S.Context.getPointerType(To->getType()), VK_RValue,
13533                              OK_Ordinary, Loc, false, S.CurFPFeatures);
13534 
13535   const Type *E = T->getBaseElementTypeUnsafe();
13536   bool NeedsCollectableMemCpy =
13537       E->isRecordType() &&
13538       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13539 
13540   // Create a reference to the __builtin_objc_memmove_collectable function
13541   StringRef MemCpyName = NeedsCollectableMemCpy ?
13542     "__builtin_objc_memmove_collectable" :
13543     "__builtin_memcpy";
13544   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13545                  Sema::LookupOrdinaryName);
13546   S.LookupName(R, S.TUScope, true);
13547 
13548   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13549   if (!MemCpy)
13550     // Something went horribly wrong earlier, and we will have complained
13551     // about it.
13552     return StmtError();
13553 
13554   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13555                                             VK_RValue, Loc, nullptr);
13556   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13557 
13558   Expr *CallArgs[] = {
13559     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13560   };
13561   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13562                                     Loc, CallArgs, Loc);
13563 
13564   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13565   return Call.getAs<Stmt>();
13566 }
13567 
13568 /// Builds a statement that copies/moves the given entity from \p From to
13569 /// \c To.
13570 ///
13571 /// This routine is used to copy/move the members of a class with an
13572 /// implicitly-declared copy/move assignment operator. When the entities being
13573 /// copied are arrays, this routine builds for loops to copy them.
13574 ///
13575 /// \param S The Sema object used for type-checking.
13576 ///
13577 /// \param Loc The location where the implicit copy/move is being generated.
13578 ///
13579 /// \param T The type of the expressions being copied/moved. Both expressions
13580 /// must have this type.
13581 ///
13582 /// \param To The expression we are copying/moving to.
13583 ///
13584 /// \param From The expression we are copying/moving from.
13585 ///
13586 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13587 /// Otherwise, it's a non-static member subobject.
13588 ///
13589 /// \param Copying Whether we're copying or moving.
13590 ///
13591 /// \param Depth Internal parameter recording the depth of the recursion.
13592 ///
13593 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13594 /// if a memcpy should be used instead.
13595 static StmtResult
13596 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13597                                  const ExprBuilder &To, const ExprBuilder &From,
13598                                  bool CopyingBaseSubobject, bool Copying,
13599                                  unsigned Depth = 0) {
13600   // C++11 [class.copy]p28:
13601   //   Each subobject is assigned in the manner appropriate to its type:
13602   //
13603   //     - if the subobject is of class type, as if by a call to operator= with
13604   //       the subobject as the object expression and the corresponding
13605   //       subobject of x as a single function argument (as if by explicit
13606   //       qualification; that is, ignoring any possible virtual overriding
13607   //       functions in more derived classes);
13608   //
13609   // C++03 [class.copy]p13:
13610   //     - if the subobject is of class type, the copy assignment operator for
13611   //       the class is used (as if by explicit qualification; that is,
13612   //       ignoring any possible virtual overriding functions in more derived
13613   //       classes);
13614   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13615     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13616 
13617     // Look for operator=.
13618     DeclarationName Name
13619       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13620     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13621     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13622 
13623     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13624     // operator.
13625     if (!S.getLangOpts().CPlusPlus11) {
13626       LookupResult::Filter F = OpLookup.makeFilter();
13627       while (F.hasNext()) {
13628         NamedDecl *D = F.next();
13629         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13630           if (Method->isCopyAssignmentOperator() ||
13631               (!Copying && Method->isMoveAssignmentOperator()))
13632             continue;
13633 
13634         F.erase();
13635       }
13636       F.done();
13637     }
13638 
13639     // Suppress the protected check (C++ [class.protected]) for each of the
13640     // assignment operators we found. This strange dance is required when
13641     // we're assigning via a base classes's copy-assignment operator. To
13642     // ensure that we're getting the right base class subobject (without
13643     // ambiguities), we need to cast "this" to that subobject type; to
13644     // ensure that we don't go through the virtual call mechanism, we need
13645     // to qualify the operator= name with the base class (see below). However,
13646     // this means that if the base class has a protected copy assignment
13647     // operator, the protected member access check will fail. So, we
13648     // rewrite "protected" access to "public" access in this case, since we
13649     // know by construction that we're calling from a derived class.
13650     if (CopyingBaseSubobject) {
13651       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13652            L != LEnd; ++L) {
13653         if (L.getAccess() == AS_protected)
13654           L.setAccess(AS_public);
13655       }
13656     }
13657 
13658     // Create the nested-name-specifier that will be used to qualify the
13659     // reference to operator=; this is required to suppress the virtual
13660     // call mechanism.
13661     CXXScopeSpec SS;
13662     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13663     SS.MakeTrivial(S.Context,
13664                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13665                                                CanonicalT),
13666                    Loc);
13667 
13668     // Create the reference to operator=.
13669     ExprResult OpEqualRef
13670       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13671                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13672                                    /*FirstQualifierInScope=*/nullptr,
13673                                    OpLookup,
13674                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13675                                    /*SuppressQualifierCheck=*/true);
13676     if (OpEqualRef.isInvalid())
13677       return StmtError();
13678 
13679     // Build the call to the assignment operator.
13680 
13681     Expr *FromInst = From.build(S, Loc);
13682     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13683                                                   OpEqualRef.getAs<Expr>(),
13684                                                   Loc, FromInst, Loc);
13685     if (Call.isInvalid())
13686       return StmtError();
13687 
13688     // If we built a call to a trivial 'operator=' while copying an array,
13689     // bail out. We'll replace the whole shebang with a memcpy.
13690     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13691     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13692       return StmtResult((Stmt*)nullptr);
13693 
13694     // Convert to an expression-statement, and clean up any produced
13695     // temporaries.
13696     return S.ActOnExprStmt(Call);
13697   }
13698 
13699   //     - if the subobject is of scalar type, the built-in assignment
13700   //       operator is used.
13701   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13702   if (!ArrayTy) {
13703     ExprResult Assignment = S.CreateBuiltinBinOp(
13704         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13705     if (Assignment.isInvalid())
13706       return StmtError();
13707     return S.ActOnExprStmt(Assignment);
13708   }
13709 
13710   //     - if the subobject is an array, each element is assigned, in the
13711   //       manner appropriate to the element type;
13712 
13713   // Construct a loop over the array bounds, e.g.,
13714   //
13715   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13716   //
13717   // that will copy each of the array elements.
13718   QualType SizeType = S.Context.getSizeType();
13719 
13720   // Create the iteration variable.
13721   IdentifierInfo *IterationVarName = nullptr;
13722   {
13723     SmallString<8> Str;
13724     llvm::raw_svector_ostream OS(Str);
13725     OS << "__i" << Depth;
13726     IterationVarName = &S.Context.Idents.get(OS.str());
13727   }
13728   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13729                                           IterationVarName, SizeType,
13730                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13731                                           SC_None);
13732 
13733   // Initialize the iteration variable to zero.
13734   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13735   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13736 
13737   // Creates a reference to the iteration variable.
13738   RefBuilder IterationVarRef(IterationVar, SizeType);
13739   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13740 
13741   // Create the DeclStmt that holds the iteration variable.
13742   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13743 
13744   // Subscript the "from" and "to" expressions with the iteration variable.
13745   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13746   MoveCastBuilder FromIndexMove(FromIndexCopy);
13747   const ExprBuilder *FromIndex;
13748   if (Copying)
13749     FromIndex = &FromIndexCopy;
13750   else
13751     FromIndex = &FromIndexMove;
13752 
13753   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13754 
13755   // Build the copy/move for an individual element of the array.
13756   StmtResult Copy =
13757     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13758                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13759                                      Copying, Depth + 1);
13760   // Bail out if copying fails or if we determined that we should use memcpy.
13761   if (Copy.isInvalid() || !Copy.get())
13762     return Copy;
13763 
13764   // Create the comparison against the array bound.
13765   llvm::APInt Upper
13766     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13767   Expr *Comparison = BinaryOperator::Create(
13768       S.Context, IterationVarRefRVal.build(S, Loc),
13769       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13770       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatures);
13771 
13772   // Create the pre-increment of the iteration variable. We can determine
13773   // whether the increment will overflow based on the value of the array
13774   // bound.
13775   Expr *Increment = UnaryOperator::Create(
13776       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13777       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatures);
13778 
13779   // Construct the loop that copies all elements of this array.
13780   return S.ActOnForStmt(
13781       Loc, Loc, InitStmt,
13782       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13783       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13784 }
13785 
13786 static StmtResult
13787 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13788                       const ExprBuilder &To, const ExprBuilder &From,
13789                       bool CopyingBaseSubobject, bool Copying) {
13790   // Maybe we should use a memcpy?
13791   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13792       T.isTriviallyCopyableType(S.Context))
13793     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13794 
13795   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13796                                                      CopyingBaseSubobject,
13797                                                      Copying, 0));
13798 
13799   // If we ended up picking a trivial assignment operator for an array of a
13800   // non-trivially-copyable class type, just emit a memcpy.
13801   if (!Result.isInvalid() && !Result.get())
13802     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13803 
13804   return Result;
13805 }
13806 
13807 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13808   // Note: The following rules are largely analoguous to the copy
13809   // constructor rules. Note that virtual bases are not taken into account
13810   // for determining the argument type of the operator. Note also that
13811   // operators taking an object instead of a reference are allowed.
13812   assert(ClassDecl->needsImplicitCopyAssignment());
13813 
13814   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13815   if (DSM.isAlreadyBeingDeclared())
13816     return nullptr;
13817 
13818   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13819   LangAS AS = getDefaultCXXMethodAddrSpace();
13820   if (AS != LangAS::Default)
13821     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13822   QualType RetType = Context.getLValueReferenceType(ArgType);
13823   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13824   if (Const)
13825     ArgType = ArgType.withConst();
13826 
13827   ArgType = Context.getLValueReferenceType(ArgType);
13828 
13829   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13830                                                      CXXCopyAssignment,
13831                                                      Const);
13832 
13833   //   An implicitly-declared copy assignment operator is an inline public
13834   //   member of its class.
13835   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13836   SourceLocation ClassLoc = ClassDecl->getLocation();
13837   DeclarationNameInfo NameInfo(Name, ClassLoc);
13838   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13839       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13840       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13841       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13842       SourceLocation());
13843   CopyAssignment->setAccess(AS_public);
13844   CopyAssignment->setDefaulted();
13845   CopyAssignment->setImplicit();
13846 
13847   if (getLangOpts().CUDA) {
13848     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13849                                             CopyAssignment,
13850                                             /* ConstRHS */ Const,
13851                                             /* Diagnose */ false);
13852   }
13853 
13854   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13855 
13856   // Add the parameter to the operator.
13857   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13858                                                ClassLoc, ClassLoc,
13859                                                /*Id=*/nullptr, ArgType,
13860                                                /*TInfo=*/nullptr, SC_None,
13861                                                nullptr);
13862   CopyAssignment->setParams(FromParam);
13863 
13864   CopyAssignment->setTrivial(
13865     ClassDecl->needsOverloadResolutionForCopyAssignment()
13866       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13867       : ClassDecl->hasTrivialCopyAssignment());
13868 
13869   // Note that we have added this copy-assignment operator.
13870   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13871 
13872   Scope *S = getScopeForContext(ClassDecl);
13873   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13874 
13875   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13876     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13877     SetDeclDeleted(CopyAssignment, ClassLoc);
13878   }
13879 
13880   if (S)
13881     PushOnScopeChains(CopyAssignment, S, false);
13882   ClassDecl->addDecl(CopyAssignment);
13883 
13884   return CopyAssignment;
13885 }
13886 
13887 /// Diagnose an implicit copy operation for a class which is odr-used, but
13888 /// which is deprecated because the class has a user-declared copy constructor,
13889 /// copy assignment operator, or destructor.
13890 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13891   assert(CopyOp->isImplicit());
13892 
13893   CXXRecordDecl *RD = CopyOp->getParent();
13894   CXXMethodDecl *UserDeclaredOperation = nullptr;
13895 
13896   // In Microsoft mode, assignment operations don't affect constructors and
13897   // vice versa.
13898   if (RD->hasUserDeclaredDestructor()) {
13899     UserDeclaredOperation = RD->getDestructor();
13900   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13901              RD->hasUserDeclaredCopyConstructor() &&
13902              !S.getLangOpts().MSVCCompat) {
13903     // Find any user-declared copy constructor.
13904     for (auto *I : RD->ctors()) {
13905       if (I->isCopyConstructor()) {
13906         UserDeclaredOperation = I;
13907         break;
13908       }
13909     }
13910     assert(UserDeclaredOperation);
13911   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13912              RD->hasUserDeclaredCopyAssignment() &&
13913              !S.getLangOpts().MSVCCompat) {
13914     // Find any user-declared move assignment operator.
13915     for (auto *I : RD->methods()) {
13916       if (I->isCopyAssignmentOperator()) {
13917         UserDeclaredOperation = I;
13918         break;
13919       }
13920     }
13921     assert(UserDeclaredOperation);
13922   }
13923 
13924   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13925     S.Diag(UserDeclaredOperation->getLocation(),
13926            isa<CXXDestructorDecl>(UserDeclaredOperation)
13927                ? diag::warn_deprecated_copy_dtor_operation
13928                : diag::warn_deprecated_copy_operation)
13929         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13930   }
13931 }
13932 
13933 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13934                                         CXXMethodDecl *CopyAssignOperator) {
13935   assert((CopyAssignOperator->isDefaulted() &&
13936           CopyAssignOperator->isOverloadedOperator() &&
13937           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13938           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13939           !CopyAssignOperator->isDeleted()) &&
13940          "DefineImplicitCopyAssignment called for wrong function");
13941   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13942     return;
13943 
13944   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13945   if (ClassDecl->isInvalidDecl()) {
13946     CopyAssignOperator->setInvalidDecl();
13947     return;
13948   }
13949 
13950   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13951 
13952   // The exception specification is needed because we are defining the
13953   // function.
13954   ResolveExceptionSpec(CurrentLocation,
13955                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13956 
13957   // Add a context note for diagnostics produced after this point.
13958   Scope.addContextNote(CurrentLocation);
13959 
13960   // C++11 [class.copy]p18:
13961   //   The [definition of an implicitly declared copy assignment operator] is
13962   //   deprecated if the class has a user-declared copy constructor or a
13963   //   user-declared destructor.
13964   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13965     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13966 
13967   // C++0x [class.copy]p30:
13968   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13969   //   for a non-union class X performs memberwise copy assignment of its
13970   //   subobjects. The direct base classes of X are assigned first, in the
13971   //   order of their declaration in the base-specifier-list, and then the
13972   //   immediate non-static data members of X are assigned, in the order in
13973   //   which they were declared in the class definition.
13974 
13975   // The statements that form the synthesized function body.
13976   SmallVector<Stmt*, 8> Statements;
13977 
13978   // The parameter for the "other" object, which we are copying from.
13979   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13980   Qualifiers OtherQuals = Other->getType().getQualifiers();
13981   QualType OtherRefType = Other->getType();
13982   if (const LValueReferenceType *OtherRef
13983                                 = OtherRefType->getAs<LValueReferenceType>()) {
13984     OtherRefType = OtherRef->getPointeeType();
13985     OtherQuals = OtherRefType.getQualifiers();
13986   }
13987 
13988   // Our location for everything implicitly-generated.
13989   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
13990                            ? CopyAssignOperator->getEndLoc()
13991                            : CopyAssignOperator->getLocation();
13992 
13993   // Builds a DeclRefExpr for the "other" object.
13994   RefBuilder OtherRef(Other, OtherRefType);
13995 
13996   // Builds the "this" pointer.
13997   ThisBuilder This;
13998 
13999   // Assign base classes.
14000   bool Invalid = false;
14001   for (auto &Base : ClassDecl->bases()) {
14002     // Form the assignment:
14003     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14004     QualType BaseType = Base.getType().getUnqualifiedType();
14005     if (!BaseType->isRecordType()) {
14006       Invalid = true;
14007       continue;
14008     }
14009 
14010     CXXCastPath BasePath;
14011     BasePath.push_back(&Base);
14012 
14013     // Construct the "from" expression, which is an implicit cast to the
14014     // appropriately-qualified base type.
14015     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14016                      VK_LValue, BasePath);
14017 
14018     // Dereference "this".
14019     DerefBuilder DerefThis(This);
14020     CastBuilder To(DerefThis,
14021                    Context.getQualifiedType(
14022                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14023                    VK_LValue, BasePath);
14024 
14025     // Build the copy.
14026     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14027                                             To, From,
14028                                             /*CopyingBaseSubobject=*/true,
14029                                             /*Copying=*/true);
14030     if (Copy.isInvalid()) {
14031       CopyAssignOperator->setInvalidDecl();
14032       return;
14033     }
14034 
14035     // Success! Record the copy.
14036     Statements.push_back(Copy.getAs<Expr>());
14037   }
14038 
14039   // Assign non-static members.
14040   for (auto *Field : ClassDecl->fields()) {
14041     // FIXME: We should form some kind of AST representation for the implied
14042     // memcpy in a union copy operation.
14043     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14044       continue;
14045 
14046     if (Field->isInvalidDecl()) {
14047       Invalid = true;
14048       continue;
14049     }
14050 
14051     // Check for members of reference type; we can't copy those.
14052     if (Field->getType()->isReferenceType()) {
14053       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14054         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14055       Diag(Field->getLocation(), diag::note_declared_at);
14056       Invalid = true;
14057       continue;
14058     }
14059 
14060     // Check for members of const-qualified, non-class type.
14061     QualType BaseType = Context.getBaseElementType(Field->getType());
14062     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14063       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14064         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14065       Diag(Field->getLocation(), diag::note_declared_at);
14066       Invalid = true;
14067       continue;
14068     }
14069 
14070     // Suppress assigning zero-width bitfields.
14071     if (Field->isZeroLengthBitField(Context))
14072       continue;
14073 
14074     QualType FieldType = Field->getType().getNonReferenceType();
14075     if (FieldType->isIncompleteArrayType()) {
14076       assert(ClassDecl->hasFlexibleArrayMember() &&
14077              "Incomplete array type is not valid");
14078       continue;
14079     }
14080 
14081     // Build references to the field in the object we're copying from and to.
14082     CXXScopeSpec SS; // Intentionally empty
14083     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14084                               LookupMemberName);
14085     MemberLookup.addDecl(Field);
14086     MemberLookup.resolveKind();
14087 
14088     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14089 
14090     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14091 
14092     // Build the copy of this field.
14093     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14094                                             To, From,
14095                                             /*CopyingBaseSubobject=*/false,
14096                                             /*Copying=*/true);
14097     if (Copy.isInvalid()) {
14098       CopyAssignOperator->setInvalidDecl();
14099       return;
14100     }
14101 
14102     // Success! Record the copy.
14103     Statements.push_back(Copy.getAs<Stmt>());
14104   }
14105 
14106   if (!Invalid) {
14107     // Add a "return *this;"
14108     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14109 
14110     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14111     if (Return.isInvalid())
14112       Invalid = true;
14113     else
14114       Statements.push_back(Return.getAs<Stmt>());
14115   }
14116 
14117   if (Invalid) {
14118     CopyAssignOperator->setInvalidDecl();
14119     return;
14120   }
14121 
14122   StmtResult Body;
14123   {
14124     CompoundScopeRAII CompoundScope(*this);
14125     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14126                              /*isStmtExpr=*/false);
14127     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14128   }
14129   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14130   CopyAssignOperator->markUsed(Context);
14131 
14132   if (ASTMutationListener *L = getASTMutationListener()) {
14133     L->CompletedImplicitDefinition(CopyAssignOperator);
14134   }
14135 }
14136 
14137 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14138   assert(ClassDecl->needsImplicitMoveAssignment());
14139 
14140   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14141   if (DSM.isAlreadyBeingDeclared())
14142     return nullptr;
14143 
14144   // Note: The following rules are largely analoguous to the move
14145   // constructor rules.
14146 
14147   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14148   LangAS AS = getDefaultCXXMethodAddrSpace();
14149   if (AS != LangAS::Default)
14150     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14151   QualType RetType = Context.getLValueReferenceType(ArgType);
14152   ArgType = Context.getRValueReferenceType(ArgType);
14153 
14154   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14155                                                      CXXMoveAssignment,
14156                                                      false);
14157 
14158   //   An implicitly-declared move assignment operator is an inline public
14159   //   member of its class.
14160   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14161   SourceLocation ClassLoc = ClassDecl->getLocation();
14162   DeclarationNameInfo NameInfo(Name, ClassLoc);
14163   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14164       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14165       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14166       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14167       SourceLocation());
14168   MoveAssignment->setAccess(AS_public);
14169   MoveAssignment->setDefaulted();
14170   MoveAssignment->setImplicit();
14171 
14172   if (getLangOpts().CUDA) {
14173     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14174                                             MoveAssignment,
14175                                             /* ConstRHS */ false,
14176                                             /* Diagnose */ false);
14177   }
14178 
14179   // Build an exception specification pointing back at this member.
14180   FunctionProtoType::ExtProtoInfo EPI =
14181       getImplicitMethodEPI(*this, MoveAssignment);
14182   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14183 
14184   // Add the parameter to the operator.
14185   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14186                                                ClassLoc, ClassLoc,
14187                                                /*Id=*/nullptr, ArgType,
14188                                                /*TInfo=*/nullptr, SC_None,
14189                                                nullptr);
14190   MoveAssignment->setParams(FromParam);
14191 
14192   MoveAssignment->setTrivial(
14193     ClassDecl->needsOverloadResolutionForMoveAssignment()
14194       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14195       : ClassDecl->hasTrivialMoveAssignment());
14196 
14197   // Note that we have added this copy-assignment operator.
14198   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14199 
14200   Scope *S = getScopeForContext(ClassDecl);
14201   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14202 
14203   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14204     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14205     SetDeclDeleted(MoveAssignment, ClassLoc);
14206   }
14207 
14208   if (S)
14209     PushOnScopeChains(MoveAssignment, S, false);
14210   ClassDecl->addDecl(MoveAssignment);
14211 
14212   return MoveAssignment;
14213 }
14214 
14215 /// Check if we're implicitly defining a move assignment operator for a class
14216 /// with virtual bases. Such a move assignment might move-assign the virtual
14217 /// base multiple times.
14218 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14219                                                SourceLocation CurrentLocation) {
14220   assert(!Class->isDependentContext() && "should not define dependent move");
14221 
14222   // Only a virtual base could get implicitly move-assigned multiple times.
14223   // Only a non-trivial move assignment can observe this. We only want to
14224   // diagnose if we implicitly define an assignment operator that assigns
14225   // two base classes, both of which move-assign the same virtual base.
14226   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14227       Class->getNumBases() < 2)
14228     return;
14229 
14230   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14231   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14232   VBaseMap VBases;
14233 
14234   for (auto &BI : Class->bases()) {
14235     Worklist.push_back(&BI);
14236     while (!Worklist.empty()) {
14237       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14238       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14239 
14240       // If the base has no non-trivial move assignment operators,
14241       // we don't care about moves from it.
14242       if (!Base->hasNonTrivialMoveAssignment())
14243         continue;
14244 
14245       // If there's nothing virtual here, skip it.
14246       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14247         continue;
14248 
14249       // If we're not actually going to call a move assignment for this base,
14250       // or the selected move assignment is trivial, skip it.
14251       Sema::SpecialMemberOverloadResult SMOR =
14252         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14253                               /*ConstArg*/false, /*VolatileArg*/false,
14254                               /*RValueThis*/true, /*ConstThis*/false,
14255                               /*VolatileThis*/false);
14256       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14257           !SMOR.getMethod()->isMoveAssignmentOperator())
14258         continue;
14259 
14260       if (BaseSpec->isVirtual()) {
14261         // We're going to move-assign this virtual base, and its move
14262         // assignment operator is not trivial. If this can happen for
14263         // multiple distinct direct bases of Class, diagnose it. (If it
14264         // only happens in one base, we'll diagnose it when synthesizing
14265         // that base class's move assignment operator.)
14266         CXXBaseSpecifier *&Existing =
14267             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14268                 .first->second;
14269         if (Existing && Existing != &BI) {
14270           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14271             << Class << Base;
14272           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14273               << (Base->getCanonicalDecl() ==
14274                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14275               << Base << Existing->getType() << Existing->getSourceRange();
14276           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14277               << (Base->getCanonicalDecl() ==
14278                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14279               << Base << BI.getType() << BaseSpec->getSourceRange();
14280 
14281           // Only diagnose each vbase once.
14282           Existing = nullptr;
14283         }
14284       } else {
14285         // Only walk over bases that have defaulted move assignment operators.
14286         // We assume that any user-provided move assignment operator handles
14287         // the multiple-moves-of-vbase case itself somehow.
14288         if (!SMOR.getMethod()->isDefaulted())
14289           continue;
14290 
14291         // We're going to move the base classes of Base. Add them to the list.
14292         for (auto &BI : Base->bases())
14293           Worklist.push_back(&BI);
14294       }
14295     }
14296   }
14297 }
14298 
14299 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14300                                         CXXMethodDecl *MoveAssignOperator) {
14301   assert((MoveAssignOperator->isDefaulted() &&
14302           MoveAssignOperator->isOverloadedOperator() &&
14303           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14304           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14305           !MoveAssignOperator->isDeleted()) &&
14306          "DefineImplicitMoveAssignment called for wrong function");
14307   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14308     return;
14309 
14310   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14311   if (ClassDecl->isInvalidDecl()) {
14312     MoveAssignOperator->setInvalidDecl();
14313     return;
14314   }
14315 
14316   // C++0x [class.copy]p28:
14317   //   The implicitly-defined or move assignment operator for a non-union class
14318   //   X performs memberwise move assignment of its subobjects. The direct base
14319   //   classes of X are assigned first, in the order of their declaration in the
14320   //   base-specifier-list, and then the immediate non-static data members of X
14321   //   are assigned, in the order in which they were declared in the class
14322   //   definition.
14323 
14324   // Issue a warning if our implicit move assignment operator will move
14325   // from a virtual base more than once.
14326   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14327 
14328   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14329 
14330   // The exception specification is needed because we are defining the
14331   // function.
14332   ResolveExceptionSpec(CurrentLocation,
14333                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14334 
14335   // Add a context note for diagnostics produced after this point.
14336   Scope.addContextNote(CurrentLocation);
14337 
14338   // The statements that form the synthesized function body.
14339   SmallVector<Stmt*, 8> Statements;
14340 
14341   // The parameter for the "other" object, which we are move from.
14342   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14343   QualType OtherRefType =
14344       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14345 
14346   // Our location for everything implicitly-generated.
14347   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14348                            ? MoveAssignOperator->getEndLoc()
14349                            : MoveAssignOperator->getLocation();
14350 
14351   // Builds a reference to the "other" object.
14352   RefBuilder OtherRef(Other, OtherRefType);
14353   // Cast to rvalue.
14354   MoveCastBuilder MoveOther(OtherRef);
14355 
14356   // Builds the "this" pointer.
14357   ThisBuilder This;
14358 
14359   // Assign base classes.
14360   bool Invalid = false;
14361   for (auto &Base : ClassDecl->bases()) {
14362     // C++11 [class.copy]p28:
14363     //   It is unspecified whether subobjects representing virtual base classes
14364     //   are assigned more than once by the implicitly-defined copy assignment
14365     //   operator.
14366     // FIXME: Do not assign to a vbase that will be assigned by some other base
14367     // class. For a move-assignment, this can result in the vbase being moved
14368     // multiple times.
14369 
14370     // Form the assignment:
14371     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14372     QualType BaseType = Base.getType().getUnqualifiedType();
14373     if (!BaseType->isRecordType()) {
14374       Invalid = true;
14375       continue;
14376     }
14377 
14378     CXXCastPath BasePath;
14379     BasePath.push_back(&Base);
14380 
14381     // Construct the "from" expression, which is an implicit cast to the
14382     // appropriately-qualified base type.
14383     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14384 
14385     // Dereference "this".
14386     DerefBuilder DerefThis(This);
14387 
14388     // Implicitly cast "this" to the appropriately-qualified base type.
14389     CastBuilder To(DerefThis,
14390                    Context.getQualifiedType(
14391                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14392                    VK_LValue, BasePath);
14393 
14394     // Build the move.
14395     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14396                                             To, From,
14397                                             /*CopyingBaseSubobject=*/true,
14398                                             /*Copying=*/false);
14399     if (Move.isInvalid()) {
14400       MoveAssignOperator->setInvalidDecl();
14401       return;
14402     }
14403 
14404     // Success! Record the move.
14405     Statements.push_back(Move.getAs<Expr>());
14406   }
14407 
14408   // Assign non-static members.
14409   for (auto *Field : ClassDecl->fields()) {
14410     // FIXME: We should form some kind of AST representation for the implied
14411     // memcpy in a union copy operation.
14412     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14413       continue;
14414 
14415     if (Field->isInvalidDecl()) {
14416       Invalid = true;
14417       continue;
14418     }
14419 
14420     // Check for members of reference type; we can't move those.
14421     if (Field->getType()->isReferenceType()) {
14422       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14423         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14424       Diag(Field->getLocation(), diag::note_declared_at);
14425       Invalid = true;
14426       continue;
14427     }
14428 
14429     // Check for members of const-qualified, non-class type.
14430     QualType BaseType = Context.getBaseElementType(Field->getType());
14431     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14432       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14433         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14434       Diag(Field->getLocation(), diag::note_declared_at);
14435       Invalid = true;
14436       continue;
14437     }
14438 
14439     // Suppress assigning zero-width bitfields.
14440     if (Field->isZeroLengthBitField(Context))
14441       continue;
14442 
14443     QualType FieldType = Field->getType().getNonReferenceType();
14444     if (FieldType->isIncompleteArrayType()) {
14445       assert(ClassDecl->hasFlexibleArrayMember() &&
14446              "Incomplete array type is not valid");
14447       continue;
14448     }
14449 
14450     // Build references to the field in the object we're copying from and to.
14451     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14452                               LookupMemberName);
14453     MemberLookup.addDecl(Field);
14454     MemberLookup.resolveKind();
14455     MemberBuilder From(MoveOther, OtherRefType,
14456                        /*IsArrow=*/false, MemberLookup);
14457     MemberBuilder To(This, getCurrentThisType(),
14458                      /*IsArrow=*/true, MemberLookup);
14459 
14460     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14461         "Member reference with rvalue base must be rvalue except for reference "
14462         "members, which aren't allowed for move assignment.");
14463 
14464     // Build the move of this field.
14465     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14466                                             To, From,
14467                                             /*CopyingBaseSubobject=*/false,
14468                                             /*Copying=*/false);
14469     if (Move.isInvalid()) {
14470       MoveAssignOperator->setInvalidDecl();
14471       return;
14472     }
14473 
14474     // Success! Record the copy.
14475     Statements.push_back(Move.getAs<Stmt>());
14476   }
14477 
14478   if (!Invalid) {
14479     // Add a "return *this;"
14480     ExprResult ThisObj =
14481         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14482 
14483     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14484     if (Return.isInvalid())
14485       Invalid = true;
14486     else
14487       Statements.push_back(Return.getAs<Stmt>());
14488   }
14489 
14490   if (Invalid) {
14491     MoveAssignOperator->setInvalidDecl();
14492     return;
14493   }
14494 
14495   StmtResult Body;
14496   {
14497     CompoundScopeRAII CompoundScope(*this);
14498     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14499                              /*isStmtExpr=*/false);
14500     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14501   }
14502   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14503   MoveAssignOperator->markUsed(Context);
14504 
14505   if (ASTMutationListener *L = getASTMutationListener()) {
14506     L->CompletedImplicitDefinition(MoveAssignOperator);
14507   }
14508 }
14509 
14510 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14511                                                     CXXRecordDecl *ClassDecl) {
14512   // C++ [class.copy]p4:
14513   //   If the class definition does not explicitly declare a copy
14514   //   constructor, one is declared implicitly.
14515   assert(ClassDecl->needsImplicitCopyConstructor());
14516 
14517   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14518   if (DSM.isAlreadyBeingDeclared())
14519     return nullptr;
14520 
14521   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14522   QualType ArgType = ClassType;
14523   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14524   if (Const)
14525     ArgType = ArgType.withConst();
14526 
14527   LangAS AS = getDefaultCXXMethodAddrSpace();
14528   if (AS != LangAS::Default)
14529     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14530 
14531   ArgType = Context.getLValueReferenceType(ArgType);
14532 
14533   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14534                                                      CXXCopyConstructor,
14535                                                      Const);
14536 
14537   DeclarationName Name
14538     = Context.DeclarationNames.getCXXConstructorName(
14539                                            Context.getCanonicalType(ClassType));
14540   SourceLocation ClassLoc = ClassDecl->getLocation();
14541   DeclarationNameInfo NameInfo(Name, ClassLoc);
14542 
14543   //   An implicitly-declared copy constructor is an inline public
14544   //   member of its class.
14545   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14546       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14547       ExplicitSpecifier(),
14548       /*isInline=*/true,
14549       /*isImplicitlyDeclared=*/true,
14550       Constexpr ? CSK_constexpr : CSK_unspecified);
14551   CopyConstructor->setAccess(AS_public);
14552   CopyConstructor->setDefaulted();
14553 
14554   if (getLangOpts().CUDA) {
14555     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14556                                             CopyConstructor,
14557                                             /* ConstRHS */ Const,
14558                                             /* Diagnose */ false);
14559   }
14560 
14561   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14562 
14563   // Add the parameter to the constructor.
14564   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14565                                                ClassLoc, ClassLoc,
14566                                                /*IdentifierInfo=*/nullptr,
14567                                                ArgType, /*TInfo=*/nullptr,
14568                                                SC_None, nullptr);
14569   CopyConstructor->setParams(FromParam);
14570 
14571   CopyConstructor->setTrivial(
14572       ClassDecl->needsOverloadResolutionForCopyConstructor()
14573           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14574           : ClassDecl->hasTrivialCopyConstructor());
14575 
14576   CopyConstructor->setTrivialForCall(
14577       ClassDecl->hasAttr<TrivialABIAttr>() ||
14578       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14579            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14580              TAH_ConsiderTrivialABI)
14581            : ClassDecl->hasTrivialCopyConstructorForCall()));
14582 
14583   // Note that we have declared this constructor.
14584   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14585 
14586   Scope *S = getScopeForContext(ClassDecl);
14587   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14588 
14589   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14590     ClassDecl->setImplicitCopyConstructorIsDeleted();
14591     SetDeclDeleted(CopyConstructor, ClassLoc);
14592   }
14593 
14594   if (S)
14595     PushOnScopeChains(CopyConstructor, S, false);
14596   ClassDecl->addDecl(CopyConstructor);
14597 
14598   return CopyConstructor;
14599 }
14600 
14601 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14602                                          CXXConstructorDecl *CopyConstructor) {
14603   assert((CopyConstructor->isDefaulted() &&
14604           CopyConstructor->isCopyConstructor() &&
14605           !CopyConstructor->doesThisDeclarationHaveABody() &&
14606           !CopyConstructor->isDeleted()) &&
14607          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14608   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14609     return;
14610 
14611   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14612   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14613 
14614   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14615 
14616   // The exception specification is needed because we are defining the
14617   // function.
14618   ResolveExceptionSpec(CurrentLocation,
14619                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14620   MarkVTableUsed(CurrentLocation, ClassDecl);
14621 
14622   // Add a context note for diagnostics produced after this point.
14623   Scope.addContextNote(CurrentLocation);
14624 
14625   // C++11 [class.copy]p7:
14626   //   The [definition of an implicitly declared copy constructor] is
14627   //   deprecated if the class has a user-declared copy assignment operator
14628   //   or a user-declared destructor.
14629   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14630     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14631 
14632   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14633     CopyConstructor->setInvalidDecl();
14634   }  else {
14635     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14636                              ? CopyConstructor->getEndLoc()
14637                              : CopyConstructor->getLocation();
14638     Sema::CompoundScopeRAII CompoundScope(*this);
14639     CopyConstructor->setBody(
14640         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14641     CopyConstructor->markUsed(Context);
14642   }
14643 
14644   if (ASTMutationListener *L = getASTMutationListener()) {
14645     L->CompletedImplicitDefinition(CopyConstructor);
14646   }
14647 }
14648 
14649 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14650                                                     CXXRecordDecl *ClassDecl) {
14651   assert(ClassDecl->needsImplicitMoveConstructor());
14652 
14653   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14654   if (DSM.isAlreadyBeingDeclared())
14655     return nullptr;
14656 
14657   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14658 
14659   QualType ArgType = ClassType;
14660   LangAS AS = getDefaultCXXMethodAddrSpace();
14661   if (AS != LangAS::Default)
14662     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14663   ArgType = Context.getRValueReferenceType(ArgType);
14664 
14665   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14666                                                      CXXMoveConstructor,
14667                                                      false);
14668 
14669   DeclarationName Name
14670     = Context.DeclarationNames.getCXXConstructorName(
14671                                            Context.getCanonicalType(ClassType));
14672   SourceLocation ClassLoc = ClassDecl->getLocation();
14673   DeclarationNameInfo NameInfo(Name, ClassLoc);
14674 
14675   // C++11 [class.copy]p11:
14676   //   An implicitly-declared copy/move constructor is an inline public
14677   //   member of its class.
14678   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14679       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14680       ExplicitSpecifier(),
14681       /*isInline=*/true,
14682       /*isImplicitlyDeclared=*/true,
14683       Constexpr ? CSK_constexpr : CSK_unspecified);
14684   MoveConstructor->setAccess(AS_public);
14685   MoveConstructor->setDefaulted();
14686 
14687   if (getLangOpts().CUDA) {
14688     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14689                                             MoveConstructor,
14690                                             /* ConstRHS */ false,
14691                                             /* Diagnose */ false);
14692   }
14693 
14694   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14695 
14696   // Add the parameter to the constructor.
14697   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14698                                                ClassLoc, ClassLoc,
14699                                                /*IdentifierInfo=*/nullptr,
14700                                                ArgType, /*TInfo=*/nullptr,
14701                                                SC_None, nullptr);
14702   MoveConstructor->setParams(FromParam);
14703 
14704   MoveConstructor->setTrivial(
14705       ClassDecl->needsOverloadResolutionForMoveConstructor()
14706           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14707           : ClassDecl->hasTrivialMoveConstructor());
14708 
14709   MoveConstructor->setTrivialForCall(
14710       ClassDecl->hasAttr<TrivialABIAttr>() ||
14711       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14712            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14713                                     TAH_ConsiderTrivialABI)
14714            : ClassDecl->hasTrivialMoveConstructorForCall()));
14715 
14716   // Note that we have declared this constructor.
14717   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14718 
14719   Scope *S = getScopeForContext(ClassDecl);
14720   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14721 
14722   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14723     ClassDecl->setImplicitMoveConstructorIsDeleted();
14724     SetDeclDeleted(MoveConstructor, ClassLoc);
14725   }
14726 
14727   if (S)
14728     PushOnScopeChains(MoveConstructor, S, false);
14729   ClassDecl->addDecl(MoveConstructor);
14730 
14731   return MoveConstructor;
14732 }
14733 
14734 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14735                                          CXXConstructorDecl *MoveConstructor) {
14736   assert((MoveConstructor->isDefaulted() &&
14737           MoveConstructor->isMoveConstructor() &&
14738           !MoveConstructor->doesThisDeclarationHaveABody() &&
14739           !MoveConstructor->isDeleted()) &&
14740          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14741   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14742     return;
14743 
14744   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14745   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14746 
14747   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14748 
14749   // The exception specification is needed because we are defining the
14750   // function.
14751   ResolveExceptionSpec(CurrentLocation,
14752                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14753   MarkVTableUsed(CurrentLocation, ClassDecl);
14754 
14755   // Add a context note for diagnostics produced after this point.
14756   Scope.addContextNote(CurrentLocation);
14757 
14758   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14759     MoveConstructor->setInvalidDecl();
14760   } else {
14761     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14762                              ? MoveConstructor->getEndLoc()
14763                              : MoveConstructor->getLocation();
14764     Sema::CompoundScopeRAII CompoundScope(*this);
14765     MoveConstructor->setBody(ActOnCompoundStmt(
14766         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14767     MoveConstructor->markUsed(Context);
14768   }
14769 
14770   if (ASTMutationListener *L = getASTMutationListener()) {
14771     L->CompletedImplicitDefinition(MoveConstructor);
14772   }
14773 }
14774 
14775 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14776   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14777 }
14778 
14779 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14780                             SourceLocation CurrentLocation,
14781                             CXXConversionDecl *Conv) {
14782   SynthesizedFunctionScope Scope(*this, Conv);
14783   assert(!Conv->getReturnType()->isUndeducedType());
14784 
14785   CXXRecordDecl *Lambda = Conv->getParent();
14786   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14787   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14788 
14789   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14790     CallOp = InstantiateFunctionDeclaration(
14791         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14792     if (!CallOp)
14793       return;
14794 
14795     Invoker = InstantiateFunctionDeclaration(
14796         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14797     if (!Invoker)
14798       return;
14799   }
14800 
14801   if (CallOp->isInvalidDecl())
14802     return;
14803 
14804   // Mark the call operator referenced (and add to pending instantiations
14805   // if necessary).
14806   // For both the conversion and static-invoker template specializations
14807   // we construct their body's in this function, so no need to add them
14808   // to the PendingInstantiations.
14809   MarkFunctionReferenced(CurrentLocation, CallOp);
14810 
14811   // Fill in the __invoke function with a dummy implementation. IR generation
14812   // will fill in the actual details. Update its type in case it contained
14813   // an 'auto'.
14814   Invoker->markUsed(Context);
14815   Invoker->setReferenced();
14816   Invoker->setType(Conv->getReturnType()->getPointeeType());
14817   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14818 
14819   // Construct the body of the conversion function { return __invoke; }.
14820   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14821                                        VK_LValue, Conv->getLocation());
14822   assert(FunctionRef && "Can't refer to __invoke function?");
14823   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14824   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14825                                      Conv->getLocation()));
14826   Conv->markUsed(Context);
14827   Conv->setReferenced();
14828 
14829   if (ASTMutationListener *L = getASTMutationListener()) {
14830     L->CompletedImplicitDefinition(Conv);
14831     L->CompletedImplicitDefinition(Invoker);
14832   }
14833 }
14834 
14835 
14836 
14837 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14838        SourceLocation CurrentLocation,
14839        CXXConversionDecl *Conv)
14840 {
14841   assert(!Conv->getParent()->isGenericLambda());
14842 
14843   SynthesizedFunctionScope Scope(*this, Conv);
14844 
14845   // Copy-initialize the lambda object as needed to capture it.
14846   Expr *This = ActOnCXXThis(CurrentLocation).get();
14847   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14848 
14849   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14850                                                         Conv->getLocation(),
14851                                                         Conv, DerefThis);
14852 
14853   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14854   // behavior.  Note that only the general conversion function does this
14855   // (since it's unusable otherwise); in the case where we inline the
14856   // block literal, it has block literal lifetime semantics.
14857   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14858     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14859                                           CK_CopyAndAutoreleaseBlockObject,
14860                                           BuildBlock.get(), nullptr, VK_RValue);
14861 
14862   if (BuildBlock.isInvalid()) {
14863     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14864     Conv->setInvalidDecl();
14865     return;
14866   }
14867 
14868   // Create the return statement that returns the block from the conversion
14869   // function.
14870   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14871   if (Return.isInvalid()) {
14872     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14873     Conv->setInvalidDecl();
14874     return;
14875   }
14876 
14877   // Set the body of the conversion function.
14878   Stmt *ReturnS = Return.get();
14879   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14880                                      Conv->getLocation()));
14881   Conv->markUsed(Context);
14882 
14883   // We're done; notify the mutation listener, if any.
14884   if (ASTMutationListener *L = getASTMutationListener()) {
14885     L->CompletedImplicitDefinition(Conv);
14886   }
14887 }
14888 
14889 /// Determine whether the given list arguments contains exactly one
14890 /// "real" (non-default) argument.
14891 static bool hasOneRealArgument(MultiExprArg Args) {
14892   switch (Args.size()) {
14893   case 0:
14894     return false;
14895 
14896   default:
14897     if (!Args[1]->isDefaultArgument())
14898       return false;
14899 
14900     LLVM_FALLTHROUGH;
14901   case 1:
14902     return !Args[0]->isDefaultArgument();
14903   }
14904 
14905   return false;
14906 }
14907 
14908 ExprResult
14909 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14910                             NamedDecl *FoundDecl,
14911                             CXXConstructorDecl *Constructor,
14912                             MultiExprArg ExprArgs,
14913                             bool HadMultipleCandidates,
14914                             bool IsListInitialization,
14915                             bool IsStdInitListInitialization,
14916                             bool RequiresZeroInit,
14917                             unsigned ConstructKind,
14918                             SourceRange ParenRange) {
14919   bool Elidable = false;
14920 
14921   // C++0x [class.copy]p34:
14922   //   When certain criteria are met, an implementation is allowed to
14923   //   omit the copy/move construction of a class object, even if the
14924   //   copy/move constructor and/or destructor for the object have
14925   //   side effects. [...]
14926   //     - when a temporary class object that has not been bound to a
14927   //       reference (12.2) would be copied/moved to a class object
14928   //       with the same cv-unqualified type, the copy/move operation
14929   //       can be omitted by constructing the temporary object
14930   //       directly into the target of the omitted copy/move
14931   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14932       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14933     Expr *SubExpr = ExprArgs[0];
14934     Elidable = SubExpr->isTemporaryObject(
14935         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14936   }
14937 
14938   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14939                                FoundDecl, Constructor,
14940                                Elidable, ExprArgs, HadMultipleCandidates,
14941                                IsListInitialization,
14942                                IsStdInitListInitialization, RequiresZeroInit,
14943                                ConstructKind, ParenRange);
14944 }
14945 
14946 ExprResult
14947 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14948                             NamedDecl *FoundDecl,
14949                             CXXConstructorDecl *Constructor,
14950                             bool Elidable,
14951                             MultiExprArg ExprArgs,
14952                             bool HadMultipleCandidates,
14953                             bool IsListInitialization,
14954                             bool IsStdInitListInitialization,
14955                             bool RequiresZeroInit,
14956                             unsigned ConstructKind,
14957                             SourceRange ParenRange) {
14958   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14959     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14960     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14961       return ExprError();
14962   }
14963 
14964   return BuildCXXConstructExpr(
14965       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14966       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14967       RequiresZeroInit, ConstructKind, ParenRange);
14968 }
14969 
14970 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14971 /// including handling of its default argument expressions.
14972 ExprResult
14973 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14974                             CXXConstructorDecl *Constructor,
14975                             bool Elidable,
14976                             MultiExprArg ExprArgs,
14977                             bool HadMultipleCandidates,
14978                             bool IsListInitialization,
14979                             bool IsStdInitListInitialization,
14980                             bool RequiresZeroInit,
14981                             unsigned ConstructKind,
14982                             SourceRange ParenRange) {
14983   assert(declaresSameEntity(
14984              Constructor->getParent(),
14985              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14986          "given constructor for wrong type");
14987   MarkFunctionReferenced(ConstructLoc, Constructor);
14988   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
14989     return ExprError();
14990   if (getLangOpts().SYCLIsDevice &&
14991       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
14992     return ExprError();
14993 
14994   return CheckForImmediateInvocation(
14995       CXXConstructExpr::Create(
14996           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
14997           HadMultipleCandidates, IsListInitialization,
14998           IsStdInitListInitialization, RequiresZeroInit,
14999           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15000           ParenRange),
15001       Constructor);
15002 }
15003 
15004 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15005   assert(Field->hasInClassInitializer());
15006 
15007   // If we already have the in-class initializer nothing needs to be done.
15008   if (Field->getInClassInitializer())
15009     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15010 
15011   // If we might have already tried and failed to instantiate, don't try again.
15012   if (Field->isInvalidDecl())
15013     return ExprError();
15014 
15015   // Maybe we haven't instantiated the in-class initializer. Go check the
15016   // pattern FieldDecl to see if it has one.
15017   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15018 
15019   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15020     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15021     DeclContext::lookup_result Lookup =
15022         ClassPattern->lookup(Field->getDeclName());
15023 
15024     // Lookup can return at most two results: the pattern for the field, or the
15025     // injected class name of the parent record. No other member can have the
15026     // same name as the field.
15027     // In modules mode, lookup can return multiple results (coming from
15028     // different modules).
15029     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15030            "more than two lookup results for field name");
15031     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15032     if (!Pattern) {
15033       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15034              "cannot have other non-field member with same name");
15035       for (auto L : Lookup)
15036         if (isa<FieldDecl>(L)) {
15037           Pattern = cast<FieldDecl>(L);
15038           break;
15039         }
15040       assert(Pattern && "We must have set the Pattern!");
15041     }
15042 
15043     if (!Pattern->hasInClassInitializer() ||
15044         InstantiateInClassInitializer(Loc, Field, Pattern,
15045                                       getTemplateInstantiationArgs(Field))) {
15046       // Don't diagnose this again.
15047       Field->setInvalidDecl();
15048       return ExprError();
15049     }
15050     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15051   }
15052 
15053   // DR1351:
15054   //   If the brace-or-equal-initializer of a non-static data member
15055   //   invokes a defaulted default constructor of its class or of an
15056   //   enclosing class in a potentially evaluated subexpression, the
15057   //   program is ill-formed.
15058   //
15059   // This resolution is unworkable: the exception specification of the
15060   // default constructor can be needed in an unevaluated context, in
15061   // particular, in the operand of a noexcept-expression, and we can be
15062   // unable to compute an exception specification for an enclosed class.
15063   //
15064   // Any attempt to resolve the exception specification of a defaulted default
15065   // constructor before the initializer is lexically complete will ultimately
15066   // come here at which point we can diagnose it.
15067   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15068   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
15069       << OutermostClass << Field;
15070   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
15071   // Recover by marking the field invalid, unless we're in a SFINAE context.
15072   if (!isSFINAEContext())
15073     Field->setInvalidDecl();
15074   return ExprError();
15075 }
15076 
15077 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15078   if (VD->isInvalidDecl()) return;
15079   // If initializing the variable failed, don't also diagnose problems with
15080   // the desctructor, they're likely related.
15081   if (VD->getInit() && VD->getInit()->containsErrors())
15082     return;
15083 
15084   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15085   if (ClassDecl->isInvalidDecl()) return;
15086   if (ClassDecl->hasIrrelevantDestructor()) return;
15087   if (ClassDecl->isDependentContext()) return;
15088 
15089   if (VD->isNoDestroy(getASTContext()))
15090     return;
15091 
15092   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15093 
15094   // If this is an array, we'll require the destructor during initialization, so
15095   // we can skip over this. We still want to emit exit-time destructor warnings
15096   // though.
15097   if (!VD->getType()->isArrayType()) {
15098     MarkFunctionReferenced(VD->getLocation(), Destructor);
15099     CheckDestructorAccess(VD->getLocation(), Destructor,
15100                           PDiag(diag::err_access_dtor_var)
15101                               << VD->getDeclName() << VD->getType());
15102     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15103   }
15104 
15105   if (Destructor->isTrivial()) return;
15106 
15107   // If the destructor is constexpr, check whether the variable has constant
15108   // destruction now.
15109   if (Destructor->isConstexpr()) {
15110     bool HasConstantInit = false;
15111     if (VD->getInit() && !VD->getInit()->isValueDependent())
15112       HasConstantInit = VD->evaluateValue();
15113     SmallVector<PartialDiagnosticAt, 8> Notes;
15114     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15115         HasConstantInit) {
15116       Diag(VD->getLocation(),
15117            diag::err_constexpr_var_requires_const_destruction) << VD;
15118       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15119         Diag(Notes[I].first, Notes[I].second);
15120     }
15121   }
15122 
15123   if (!VD->hasGlobalStorage()) return;
15124 
15125   // Emit warning for non-trivial dtor in global scope (a real global,
15126   // class-static, function-static).
15127   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15128 
15129   // TODO: this should be re-enabled for static locals by !CXAAtExit
15130   if (!VD->isStaticLocal())
15131     Diag(VD->getLocation(), diag::warn_global_destructor);
15132 }
15133 
15134 /// Given a constructor and the set of arguments provided for the
15135 /// constructor, convert the arguments and add any required default arguments
15136 /// to form a proper call to this constructor.
15137 ///
15138 /// \returns true if an error occurred, false otherwise.
15139 bool
15140 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15141                               MultiExprArg ArgsPtr,
15142                               SourceLocation Loc,
15143                               SmallVectorImpl<Expr*> &ConvertedArgs,
15144                               bool AllowExplicit,
15145                               bool IsListInitialization) {
15146   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15147   unsigned NumArgs = ArgsPtr.size();
15148   Expr **Args = ArgsPtr.data();
15149 
15150   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15151   unsigned NumParams = Proto->getNumParams();
15152 
15153   // If too few arguments are available, we'll fill in the rest with defaults.
15154   if (NumArgs < NumParams)
15155     ConvertedArgs.reserve(NumParams);
15156   else
15157     ConvertedArgs.reserve(NumArgs);
15158 
15159   VariadicCallType CallType =
15160     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15161   SmallVector<Expr *, 8> AllArgs;
15162   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15163                                         Proto, 0,
15164                                         llvm::makeArrayRef(Args, NumArgs),
15165                                         AllArgs,
15166                                         CallType, AllowExplicit,
15167                                         IsListInitialization);
15168   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15169 
15170   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15171 
15172   CheckConstructorCall(Constructor,
15173                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15174                        Proto, Loc);
15175 
15176   return Invalid;
15177 }
15178 
15179 static inline bool
15180 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15181                                        const FunctionDecl *FnDecl) {
15182   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15183   if (isa<NamespaceDecl>(DC)) {
15184     return SemaRef.Diag(FnDecl->getLocation(),
15185                         diag::err_operator_new_delete_declared_in_namespace)
15186       << FnDecl->getDeclName();
15187   }
15188 
15189   if (isa<TranslationUnitDecl>(DC) &&
15190       FnDecl->getStorageClass() == SC_Static) {
15191     return SemaRef.Diag(FnDecl->getLocation(),
15192                         diag::err_operator_new_delete_declared_static)
15193       << FnDecl->getDeclName();
15194   }
15195 
15196   return false;
15197 }
15198 
15199 static QualType
15200 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15201   QualType QTy = PtrTy->getPointeeType();
15202   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15203   return SemaRef.Context.getPointerType(QTy);
15204 }
15205 
15206 static inline bool
15207 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15208                             CanQualType ExpectedResultType,
15209                             CanQualType ExpectedFirstParamType,
15210                             unsigned DependentParamTypeDiag,
15211                             unsigned InvalidParamTypeDiag) {
15212   QualType ResultType =
15213       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15214 
15215   // Check that the result type is not dependent.
15216   if (ResultType->isDependentType())
15217     return SemaRef.Diag(FnDecl->getLocation(),
15218                         diag::err_operator_new_delete_dependent_result_type)
15219     << FnDecl->getDeclName() << ExpectedResultType;
15220 
15221   // The operator is valid on any address space for OpenCL.
15222   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15223     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15224       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15225     }
15226   }
15227 
15228   // Check that the result type is what we expect.
15229   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
15230     return SemaRef.Diag(FnDecl->getLocation(),
15231                         diag::err_operator_new_delete_invalid_result_type)
15232     << FnDecl->getDeclName() << ExpectedResultType;
15233 
15234   // A function template must have at least 2 parameters.
15235   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15236     return SemaRef.Diag(FnDecl->getLocation(),
15237                       diag::err_operator_new_delete_template_too_few_parameters)
15238         << FnDecl->getDeclName();
15239 
15240   // The function decl must have at least 1 parameter.
15241   if (FnDecl->getNumParams() == 0)
15242     return SemaRef.Diag(FnDecl->getLocation(),
15243                         diag::err_operator_new_delete_too_few_parameters)
15244       << FnDecl->getDeclName();
15245 
15246   // Check the first parameter type is not dependent.
15247   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15248   if (FirstParamType->isDependentType())
15249     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
15250       << FnDecl->getDeclName() << ExpectedFirstParamType;
15251 
15252   // Check that the first parameter type is what we expect.
15253   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15254     // The operator is valid on any address space for OpenCL.
15255     if (auto *PtrTy =
15256             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15257       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15258     }
15259   }
15260   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15261       ExpectedFirstParamType)
15262     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
15263     << FnDecl->getDeclName() << ExpectedFirstParamType;
15264 
15265   return false;
15266 }
15267 
15268 static bool
15269 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15270   // C++ [basic.stc.dynamic.allocation]p1:
15271   //   A program is ill-formed if an allocation function is declared in a
15272   //   namespace scope other than global scope or declared static in global
15273   //   scope.
15274   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15275     return true;
15276 
15277   CanQualType SizeTy =
15278     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15279 
15280   // C++ [basic.stc.dynamic.allocation]p1:
15281   //  The return type shall be void*. The first parameter shall have type
15282   //  std::size_t.
15283   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15284                                   SizeTy,
15285                                   diag::err_operator_new_dependent_param_type,
15286                                   diag::err_operator_new_param_type))
15287     return true;
15288 
15289   // C++ [basic.stc.dynamic.allocation]p1:
15290   //  The first parameter shall not have an associated default argument.
15291   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15292     return SemaRef.Diag(FnDecl->getLocation(),
15293                         diag::err_operator_new_default_arg)
15294       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15295 
15296   return false;
15297 }
15298 
15299 static bool
15300 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15301   // C++ [basic.stc.dynamic.deallocation]p1:
15302   //   A program is ill-formed if deallocation functions are declared in a
15303   //   namespace scope other than global scope or declared static in global
15304   //   scope.
15305   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15306     return true;
15307 
15308   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15309 
15310   // C++ P0722:
15311   //   Within a class C, the first parameter of a destroying operator delete
15312   //   shall be of type C *. The first parameter of any other deallocation
15313   //   function shall be of type void *.
15314   CanQualType ExpectedFirstParamType =
15315       MD && MD->isDestroyingOperatorDelete()
15316           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15317                 SemaRef.Context.getRecordType(MD->getParent())))
15318           : SemaRef.Context.VoidPtrTy;
15319 
15320   // C++ [basic.stc.dynamic.deallocation]p2:
15321   //   Each deallocation function shall return void
15322   if (CheckOperatorNewDeleteTypes(
15323           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15324           diag::err_operator_delete_dependent_param_type,
15325           diag::err_operator_delete_param_type))
15326     return true;
15327 
15328   // C++ P0722:
15329   //   A destroying operator delete shall be a usual deallocation function.
15330   if (MD && !MD->getParent()->isDependentContext() &&
15331       MD->isDestroyingOperatorDelete() &&
15332       !SemaRef.isUsualDeallocationFunction(MD)) {
15333     SemaRef.Diag(MD->getLocation(),
15334                  diag::err_destroying_operator_delete_not_usual);
15335     return true;
15336   }
15337 
15338   return false;
15339 }
15340 
15341 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15342 /// of this overloaded operator is well-formed. If so, returns false;
15343 /// otherwise, emits appropriate diagnostics and returns true.
15344 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15345   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15346          "Expected an overloaded operator declaration");
15347 
15348   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15349 
15350   // C++ [over.oper]p5:
15351   //   The allocation and deallocation functions, operator new,
15352   //   operator new[], operator delete and operator delete[], are
15353   //   described completely in 3.7.3. The attributes and restrictions
15354   //   found in the rest of this subclause do not apply to them unless
15355   //   explicitly stated in 3.7.3.
15356   if (Op == OO_Delete || Op == OO_Array_Delete)
15357     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15358 
15359   if (Op == OO_New || Op == OO_Array_New)
15360     return CheckOperatorNewDeclaration(*this, FnDecl);
15361 
15362   // C++ [over.oper]p6:
15363   //   An operator function shall either be a non-static member
15364   //   function or be a non-member function and have at least one
15365   //   parameter whose type is a class, a reference to a class, an
15366   //   enumeration, or a reference to an enumeration.
15367   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15368     if (MethodDecl->isStatic())
15369       return Diag(FnDecl->getLocation(),
15370                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15371   } else {
15372     bool ClassOrEnumParam = false;
15373     for (auto Param : FnDecl->parameters()) {
15374       QualType ParamType = Param->getType().getNonReferenceType();
15375       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15376           ParamType->isEnumeralType()) {
15377         ClassOrEnumParam = true;
15378         break;
15379       }
15380     }
15381 
15382     if (!ClassOrEnumParam)
15383       return Diag(FnDecl->getLocation(),
15384                   diag::err_operator_overload_needs_class_or_enum)
15385         << FnDecl->getDeclName();
15386   }
15387 
15388   // C++ [over.oper]p8:
15389   //   An operator function cannot have default arguments (8.3.6),
15390   //   except where explicitly stated below.
15391   //
15392   // Only the function-call operator allows default arguments
15393   // (C++ [over.call]p1).
15394   if (Op != OO_Call) {
15395     for (auto Param : FnDecl->parameters()) {
15396       if (Param->hasDefaultArg())
15397         return Diag(Param->getLocation(),
15398                     diag::err_operator_overload_default_arg)
15399           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15400     }
15401   }
15402 
15403   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15404     { false, false, false }
15405 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15406     , { Unary, Binary, MemberOnly }
15407 #include "clang/Basic/OperatorKinds.def"
15408   };
15409 
15410   bool CanBeUnaryOperator = OperatorUses[Op][0];
15411   bool CanBeBinaryOperator = OperatorUses[Op][1];
15412   bool MustBeMemberOperator = OperatorUses[Op][2];
15413 
15414   // C++ [over.oper]p8:
15415   //   [...] Operator functions cannot have more or fewer parameters
15416   //   than the number required for the corresponding operator, as
15417   //   described in the rest of this subclause.
15418   unsigned NumParams = FnDecl->getNumParams()
15419                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15420   if (Op != OO_Call &&
15421       ((NumParams == 1 && !CanBeUnaryOperator) ||
15422        (NumParams == 2 && !CanBeBinaryOperator) ||
15423        (NumParams < 1) || (NumParams > 2))) {
15424     // We have the wrong number of parameters.
15425     unsigned ErrorKind;
15426     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15427       ErrorKind = 2;  // 2 -> unary or binary.
15428     } else if (CanBeUnaryOperator) {
15429       ErrorKind = 0;  // 0 -> unary
15430     } else {
15431       assert(CanBeBinaryOperator &&
15432              "All non-call overloaded operators are unary or binary!");
15433       ErrorKind = 1;  // 1 -> binary
15434     }
15435 
15436     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15437       << FnDecl->getDeclName() << NumParams << ErrorKind;
15438   }
15439 
15440   // Overloaded operators other than operator() cannot be variadic.
15441   if (Op != OO_Call &&
15442       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15443     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15444       << FnDecl->getDeclName();
15445   }
15446 
15447   // Some operators must be non-static member functions.
15448   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15449     return Diag(FnDecl->getLocation(),
15450                 diag::err_operator_overload_must_be_member)
15451       << FnDecl->getDeclName();
15452   }
15453 
15454   // C++ [over.inc]p1:
15455   //   The user-defined function called operator++ implements the
15456   //   prefix and postfix ++ operator. If this function is a member
15457   //   function with no parameters, or a non-member function with one
15458   //   parameter of class or enumeration type, it defines the prefix
15459   //   increment operator ++ for objects of that type. If the function
15460   //   is a member function with one parameter (which shall be of type
15461   //   int) or a non-member function with two parameters (the second
15462   //   of which shall be of type int), it defines the postfix
15463   //   increment operator ++ for objects of that type.
15464   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15465     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15466     QualType ParamType = LastParam->getType();
15467 
15468     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15469         !ParamType->isDependentType())
15470       return Diag(LastParam->getLocation(),
15471                   diag::err_operator_overload_post_incdec_must_be_int)
15472         << LastParam->getType() << (Op == OO_MinusMinus);
15473   }
15474 
15475   return false;
15476 }
15477 
15478 static bool
15479 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15480                                           FunctionTemplateDecl *TpDecl) {
15481   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15482 
15483   // Must have one or two template parameters.
15484   if (TemplateParams->size() == 1) {
15485     NonTypeTemplateParmDecl *PmDecl =
15486         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15487 
15488     // The template parameter must be a char parameter pack.
15489     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15490         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15491       return false;
15492 
15493   } else if (TemplateParams->size() == 2) {
15494     TemplateTypeParmDecl *PmType =
15495         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15496     NonTypeTemplateParmDecl *PmArgs =
15497         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15498 
15499     // The second template parameter must be a parameter pack with the
15500     // first template parameter as its type.
15501     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15502         PmArgs->isTemplateParameterPack()) {
15503       const TemplateTypeParmType *TArgs =
15504           PmArgs->getType()->getAs<TemplateTypeParmType>();
15505       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15506           TArgs->getIndex() == PmType->getIndex()) {
15507         if (!SemaRef.inTemplateInstantiation())
15508           SemaRef.Diag(TpDecl->getLocation(),
15509                        diag::ext_string_literal_operator_template);
15510         return false;
15511       }
15512     }
15513   }
15514 
15515   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15516                diag::err_literal_operator_template)
15517       << TpDecl->getTemplateParameters()->getSourceRange();
15518   return true;
15519 }
15520 
15521 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15522 /// of this literal operator function is well-formed. If so, returns
15523 /// false; otherwise, emits appropriate diagnostics and returns true.
15524 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15525   if (isa<CXXMethodDecl>(FnDecl)) {
15526     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15527       << FnDecl->getDeclName();
15528     return true;
15529   }
15530 
15531   if (FnDecl->isExternC()) {
15532     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15533     if (const LinkageSpecDecl *LSD =
15534             FnDecl->getDeclContext()->getExternCContext())
15535       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15536     return true;
15537   }
15538 
15539   // This might be the definition of a literal operator template.
15540   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15541 
15542   // This might be a specialization of a literal operator template.
15543   if (!TpDecl)
15544     TpDecl = FnDecl->getPrimaryTemplate();
15545 
15546   // template <char...> type operator "" name() and
15547   // template <class T, T...> type operator "" name() are the only valid
15548   // template signatures, and the only valid signatures with no parameters.
15549   if (TpDecl) {
15550     if (FnDecl->param_size() != 0) {
15551       Diag(FnDecl->getLocation(),
15552            diag::err_literal_operator_template_with_params);
15553       return true;
15554     }
15555 
15556     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15557       return true;
15558 
15559   } else if (FnDecl->param_size() == 1) {
15560     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15561 
15562     QualType ParamType = Param->getType().getUnqualifiedType();
15563 
15564     // Only unsigned long long int, long double, any character type, and const
15565     // char * are allowed as the only parameters.
15566     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15567         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15568         Context.hasSameType(ParamType, Context.CharTy) ||
15569         Context.hasSameType(ParamType, Context.WideCharTy) ||
15570         Context.hasSameType(ParamType, Context.Char8Ty) ||
15571         Context.hasSameType(ParamType, Context.Char16Ty) ||
15572         Context.hasSameType(ParamType, Context.Char32Ty)) {
15573     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15574       QualType InnerType = Ptr->getPointeeType();
15575 
15576       // Pointer parameter must be a const char *.
15577       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15578                                 Context.CharTy) &&
15579             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15580         Diag(Param->getSourceRange().getBegin(),
15581              diag::err_literal_operator_param)
15582             << ParamType << "'const char *'" << Param->getSourceRange();
15583         return true;
15584       }
15585 
15586     } else if (ParamType->isRealFloatingType()) {
15587       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15588           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15589       return true;
15590 
15591     } else if (ParamType->isIntegerType()) {
15592       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15593           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15594       return true;
15595 
15596     } else {
15597       Diag(Param->getSourceRange().getBegin(),
15598            diag::err_literal_operator_invalid_param)
15599           << ParamType << Param->getSourceRange();
15600       return true;
15601     }
15602 
15603   } else if (FnDecl->param_size() == 2) {
15604     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15605 
15606     // First, verify that the first parameter is correct.
15607 
15608     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15609 
15610     // Two parameter function must have a pointer to const as a
15611     // first parameter; let's strip those qualifiers.
15612     const PointerType *PT = FirstParamType->getAs<PointerType>();
15613 
15614     if (!PT) {
15615       Diag((*Param)->getSourceRange().getBegin(),
15616            diag::err_literal_operator_param)
15617           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15618       return true;
15619     }
15620 
15621     QualType PointeeType = PT->getPointeeType();
15622     // First parameter must be const
15623     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15624       Diag((*Param)->getSourceRange().getBegin(),
15625            diag::err_literal_operator_param)
15626           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15627       return true;
15628     }
15629 
15630     QualType InnerType = PointeeType.getUnqualifiedType();
15631     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15632     // const char32_t* are allowed as the first parameter to a two-parameter
15633     // function
15634     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15635           Context.hasSameType(InnerType, Context.WideCharTy) ||
15636           Context.hasSameType(InnerType, Context.Char8Ty) ||
15637           Context.hasSameType(InnerType, Context.Char16Ty) ||
15638           Context.hasSameType(InnerType, Context.Char32Ty))) {
15639       Diag((*Param)->getSourceRange().getBegin(),
15640            diag::err_literal_operator_param)
15641           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15642       return true;
15643     }
15644 
15645     // Move on to the second and final parameter.
15646     ++Param;
15647 
15648     // The second parameter must be a std::size_t.
15649     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15650     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15651       Diag((*Param)->getSourceRange().getBegin(),
15652            diag::err_literal_operator_param)
15653           << SecondParamType << Context.getSizeType()
15654           << (*Param)->getSourceRange();
15655       return true;
15656     }
15657   } else {
15658     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15659     return true;
15660   }
15661 
15662   // Parameters are good.
15663 
15664   // A parameter-declaration-clause containing a default argument is not
15665   // equivalent to any of the permitted forms.
15666   for (auto Param : FnDecl->parameters()) {
15667     if (Param->hasDefaultArg()) {
15668       Diag(Param->getDefaultArgRange().getBegin(),
15669            diag::err_literal_operator_default_argument)
15670         << Param->getDefaultArgRange();
15671       break;
15672     }
15673   }
15674 
15675   StringRef LiteralName
15676     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15677   if (LiteralName[0] != '_' &&
15678       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15679     // C++11 [usrlit.suffix]p1:
15680     //   Literal suffix identifiers that do not start with an underscore
15681     //   are reserved for future standardization.
15682     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15683       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15684   }
15685 
15686   return false;
15687 }
15688 
15689 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15690 /// linkage specification, including the language and (if present)
15691 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15692 /// language string literal. LBraceLoc, if valid, provides the location of
15693 /// the '{' brace. Otherwise, this linkage specification does not
15694 /// have any braces.
15695 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15696                                            Expr *LangStr,
15697                                            SourceLocation LBraceLoc) {
15698   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15699   if (!Lit->isAscii()) {
15700     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15701       << LangStr->getSourceRange();
15702     return nullptr;
15703   }
15704 
15705   StringRef Lang = Lit->getString();
15706   LinkageSpecDecl::LanguageIDs Language;
15707   if (Lang == "C")
15708     Language = LinkageSpecDecl::lang_c;
15709   else if (Lang == "C++")
15710     Language = LinkageSpecDecl::lang_cxx;
15711   else {
15712     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15713       << LangStr->getSourceRange();
15714     return nullptr;
15715   }
15716 
15717   // FIXME: Add all the various semantics of linkage specifications
15718 
15719   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15720                                                LangStr->getExprLoc(), Language,
15721                                                LBraceLoc.isValid());
15722   CurContext->addDecl(D);
15723   PushDeclContext(S, D);
15724   return D;
15725 }
15726 
15727 /// ActOnFinishLinkageSpecification - Complete the definition of
15728 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15729 /// valid, it's the position of the closing '}' brace in a linkage
15730 /// specification that uses braces.
15731 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15732                                             Decl *LinkageSpec,
15733                                             SourceLocation RBraceLoc) {
15734   if (RBraceLoc.isValid()) {
15735     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15736     LSDecl->setRBraceLoc(RBraceLoc);
15737   }
15738   PopDeclContext();
15739   return LinkageSpec;
15740 }
15741 
15742 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15743                                   const ParsedAttributesView &AttrList,
15744                                   SourceLocation SemiLoc) {
15745   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15746   // Attribute declarations appertain to empty declaration so we handle
15747   // them here.
15748   ProcessDeclAttributeList(S, ED, AttrList);
15749 
15750   CurContext->addDecl(ED);
15751   return ED;
15752 }
15753 
15754 /// Perform semantic analysis for the variable declaration that
15755 /// occurs within a C++ catch clause, returning the newly-created
15756 /// variable.
15757 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15758                                          TypeSourceInfo *TInfo,
15759                                          SourceLocation StartLoc,
15760                                          SourceLocation Loc,
15761                                          IdentifierInfo *Name) {
15762   bool Invalid = false;
15763   QualType ExDeclType = TInfo->getType();
15764 
15765   // Arrays and functions decay.
15766   if (ExDeclType->isArrayType())
15767     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15768   else if (ExDeclType->isFunctionType())
15769     ExDeclType = Context.getPointerType(ExDeclType);
15770 
15771   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15772   // The exception-declaration shall not denote a pointer or reference to an
15773   // incomplete type, other than [cv] void*.
15774   // N2844 forbids rvalue references.
15775   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15776     Diag(Loc, diag::err_catch_rvalue_ref);
15777     Invalid = true;
15778   }
15779 
15780   if (ExDeclType->isVariablyModifiedType()) {
15781     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15782     Invalid = true;
15783   }
15784 
15785   QualType BaseType = ExDeclType;
15786   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15787   unsigned DK = diag::err_catch_incomplete;
15788   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15789     BaseType = Ptr->getPointeeType();
15790     Mode = 1;
15791     DK = diag::err_catch_incomplete_ptr;
15792   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15793     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15794     BaseType = Ref->getPointeeType();
15795     Mode = 2;
15796     DK = diag::err_catch_incomplete_ref;
15797   }
15798   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15799       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15800     Invalid = true;
15801 
15802   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15803     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15804     Invalid = true;
15805   }
15806 
15807   if (!Invalid && !ExDeclType->isDependentType() &&
15808       RequireNonAbstractType(Loc, ExDeclType,
15809                              diag::err_abstract_type_in_decl,
15810                              AbstractVariableType))
15811     Invalid = true;
15812 
15813   // Only the non-fragile NeXT runtime currently supports C++ catches
15814   // of ObjC types, and no runtime supports catching ObjC types by value.
15815   if (!Invalid && getLangOpts().ObjC) {
15816     QualType T = ExDeclType;
15817     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15818       T = RT->getPointeeType();
15819 
15820     if (T->isObjCObjectType()) {
15821       Diag(Loc, diag::err_objc_object_catch);
15822       Invalid = true;
15823     } else if (T->isObjCObjectPointerType()) {
15824       // FIXME: should this be a test for macosx-fragile specifically?
15825       if (getLangOpts().ObjCRuntime.isFragile())
15826         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15827     }
15828   }
15829 
15830   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15831                                     ExDeclType, TInfo, SC_None);
15832   ExDecl->setExceptionVariable(true);
15833 
15834   // In ARC, infer 'retaining' for variables of retainable type.
15835   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15836     Invalid = true;
15837 
15838   if (!Invalid && !ExDeclType->isDependentType()) {
15839     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15840       // Insulate this from anything else we might currently be parsing.
15841       EnterExpressionEvaluationContext scope(
15842           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15843 
15844       // C++ [except.handle]p16:
15845       //   The object declared in an exception-declaration or, if the
15846       //   exception-declaration does not specify a name, a temporary (12.2) is
15847       //   copy-initialized (8.5) from the exception object. [...]
15848       //   The object is destroyed when the handler exits, after the destruction
15849       //   of any automatic objects initialized within the handler.
15850       //
15851       // We just pretend to initialize the object with itself, then make sure
15852       // it can be destroyed later.
15853       QualType initType = Context.getExceptionObjectType(ExDeclType);
15854 
15855       InitializedEntity entity =
15856         InitializedEntity::InitializeVariable(ExDecl);
15857       InitializationKind initKind =
15858         InitializationKind::CreateCopy(Loc, SourceLocation());
15859 
15860       Expr *opaqueValue =
15861         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15862       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15863       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15864       if (result.isInvalid())
15865         Invalid = true;
15866       else {
15867         // If the constructor used was non-trivial, set this as the
15868         // "initializer".
15869         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15870         if (!construct->getConstructor()->isTrivial()) {
15871           Expr *init = MaybeCreateExprWithCleanups(construct);
15872           ExDecl->setInit(init);
15873         }
15874 
15875         // And make sure it's destructable.
15876         FinalizeVarWithDestructor(ExDecl, recordType);
15877       }
15878     }
15879   }
15880 
15881   if (Invalid)
15882     ExDecl->setInvalidDecl();
15883 
15884   return ExDecl;
15885 }
15886 
15887 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15888 /// handler.
15889 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15890   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15891   bool Invalid = D.isInvalidType();
15892 
15893   // Check for unexpanded parameter packs.
15894   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15895                                       UPPC_ExceptionType)) {
15896     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15897                                              D.getIdentifierLoc());
15898     Invalid = true;
15899   }
15900 
15901   IdentifierInfo *II = D.getIdentifier();
15902   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15903                                              LookupOrdinaryName,
15904                                              ForVisibleRedeclaration)) {
15905     // The scope should be freshly made just for us. There is just no way
15906     // it contains any previous declaration, except for function parameters in
15907     // a function-try-block's catch statement.
15908     assert(!S->isDeclScope(PrevDecl));
15909     if (isDeclInScope(PrevDecl, CurContext, S)) {
15910       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15911         << D.getIdentifier();
15912       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15913       Invalid = true;
15914     } else if (PrevDecl->isTemplateParameter())
15915       // Maybe we will complain about the shadowed template parameter.
15916       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15917   }
15918 
15919   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15920     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15921       << D.getCXXScopeSpec().getRange();
15922     Invalid = true;
15923   }
15924 
15925   VarDecl *ExDecl = BuildExceptionDeclaration(
15926       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15927   if (Invalid)
15928     ExDecl->setInvalidDecl();
15929 
15930   // Add the exception declaration into this scope.
15931   if (II)
15932     PushOnScopeChains(ExDecl, S);
15933   else
15934     CurContext->addDecl(ExDecl);
15935 
15936   ProcessDeclAttributes(S, ExDecl, D);
15937   return ExDecl;
15938 }
15939 
15940 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15941                                          Expr *AssertExpr,
15942                                          Expr *AssertMessageExpr,
15943                                          SourceLocation RParenLoc) {
15944   StringLiteral *AssertMessage =
15945       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15946 
15947   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15948     return nullptr;
15949 
15950   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15951                                       AssertMessage, RParenLoc, false);
15952 }
15953 
15954 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15955                                          Expr *AssertExpr,
15956                                          StringLiteral *AssertMessage,
15957                                          SourceLocation RParenLoc,
15958                                          bool Failed) {
15959   assert(AssertExpr != nullptr && "Expected non-null condition");
15960   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15961       !Failed) {
15962     // In a static_assert-declaration, the constant-expression shall be a
15963     // constant expression that can be contextually converted to bool.
15964     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15965     if (Converted.isInvalid())
15966       Failed = true;
15967 
15968     ExprResult FullAssertExpr =
15969         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15970                             /*DiscardedValue*/ false,
15971                             /*IsConstexpr*/ true);
15972     if (FullAssertExpr.isInvalid())
15973       Failed = true;
15974     else
15975       AssertExpr = FullAssertExpr.get();
15976 
15977     llvm::APSInt Cond;
15978     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15979           diag::err_static_assert_expression_is_not_constant,
15980           /*AllowFold=*/false).isInvalid())
15981       Failed = true;
15982 
15983     if (!Failed && !Cond) {
15984       SmallString<256> MsgBuffer;
15985       llvm::raw_svector_ostream Msg(MsgBuffer);
15986       if (AssertMessage)
15987         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
15988 
15989       Expr *InnerCond = nullptr;
15990       std::string InnerCondDescription;
15991       std::tie(InnerCond, InnerCondDescription) =
15992         findFailedBooleanCondition(Converted.get());
15993       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
15994         // Drill down into concept specialization expressions to see why they
15995         // weren't satisfied.
15996         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15997           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15998         ConstraintSatisfaction Satisfaction;
15999         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16000           DiagnoseUnsatisfiedConstraint(Satisfaction);
16001       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16002                            && !isa<IntegerLiteral>(InnerCond)) {
16003         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16004           << InnerCondDescription << !AssertMessage
16005           << Msg.str() << InnerCond->getSourceRange();
16006       } else {
16007         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16008           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16009       }
16010       Failed = true;
16011     }
16012   } else {
16013     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16014                                                     /*DiscardedValue*/false,
16015                                                     /*IsConstexpr*/true);
16016     if (FullAssertExpr.isInvalid())
16017       Failed = true;
16018     else
16019       AssertExpr = FullAssertExpr.get();
16020   }
16021 
16022   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16023                                         AssertExpr, AssertMessage, RParenLoc,
16024                                         Failed);
16025 
16026   CurContext->addDecl(Decl);
16027   return Decl;
16028 }
16029 
16030 /// Perform semantic analysis of the given friend type declaration.
16031 ///
16032 /// \returns A friend declaration that.
16033 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16034                                       SourceLocation FriendLoc,
16035                                       TypeSourceInfo *TSInfo) {
16036   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16037 
16038   QualType T = TSInfo->getType();
16039   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16040 
16041   // C++03 [class.friend]p2:
16042   //   An elaborated-type-specifier shall be used in a friend declaration
16043   //   for a class.*
16044   //
16045   //   * The class-key of the elaborated-type-specifier is required.
16046   if (!CodeSynthesisContexts.empty()) {
16047     // Do not complain about the form of friend template types during any kind
16048     // of code synthesis. For template instantiation, we will have complained
16049     // when the template was defined.
16050   } else {
16051     if (!T->isElaboratedTypeSpecifier()) {
16052       // If we evaluated the type to a record type, suggest putting
16053       // a tag in front.
16054       if (const RecordType *RT = T->getAs<RecordType>()) {
16055         RecordDecl *RD = RT->getDecl();
16056 
16057         SmallString<16> InsertionText(" ");
16058         InsertionText += RD->getKindName();
16059 
16060         Diag(TypeRange.getBegin(),
16061              getLangOpts().CPlusPlus11 ?
16062                diag::warn_cxx98_compat_unelaborated_friend_type :
16063                diag::ext_unelaborated_friend_type)
16064           << (unsigned) RD->getTagKind()
16065           << T
16066           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16067                                         InsertionText);
16068       } else {
16069         Diag(FriendLoc,
16070              getLangOpts().CPlusPlus11 ?
16071                diag::warn_cxx98_compat_nonclass_type_friend :
16072                diag::ext_nonclass_type_friend)
16073           << T
16074           << TypeRange;
16075       }
16076     } else if (T->getAs<EnumType>()) {
16077       Diag(FriendLoc,
16078            getLangOpts().CPlusPlus11 ?
16079              diag::warn_cxx98_compat_enum_friend :
16080              diag::ext_enum_friend)
16081         << T
16082         << TypeRange;
16083     }
16084 
16085     // C++11 [class.friend]p3:
16086     //   A friend declaration that does not declare a function shall have one
16087     //   of the following forms:
16088     //     friend elaborated-type-specifier ;
16089     //     friend simple-type-specifier ;
16090     //     friend typename-specifier ;
16091     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16092       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16093   }
16094 
16095   //   If the type specifier in a friend declaration designates a (possibly
16096   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16097   //   the friend declaration is ignored.
16098   return FriendDecl::Create(Context, CurContext,
16099                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16100                             FriendLoc);
16101 }
16102 
16103 /// Handle a friend tag declaration where the scope specifier was
16104 /// templated.
16105 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16106                                     unsigned TagSpec, SourceLocation TagLoc,
16107                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16108                                     SourceLocation NameLoc,
16109                                     const ParsedAttributesView &Attr,
16110                                     MultiTemplateParamsArg TempParamLists) {
16111   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16112 
16113   bool IsMemberSpecialization = false;
16114   bool Invalid = false;
16115 
16116   if (TemplateParameterList *TemplateParams =
16117           MatchTemplateParametersToScopeSpecifier(
16118               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16119               IsMemberSpecialization, Invalid)) {
16120     if (TemplateParams->size() > 0) {
16121       // This is a declaration of a class template.
16122       if (Invalid)
16123         return nullptr;
16124 
16125       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16126                                 NameLoc, Attr, TemplateParams, AS_public,
16127                                 /*ModulePrivateLoc=*/SourceLocation(),
16128                                 FriendLoc, TempParamLists.size() - 1,
16129                                 TempParamLists.data()).get();
16130     } else {
16131       // The "template<>" header is extraneous.
16132       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16133         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16134       IsMemberSpecialization = true;
16135     }
16136   }
16137 
16138   if (Invalid) return nullptr;
16139 
16140   bool isAllExplicitSpecializations = true;
16141   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16142     if (TempParamLists[I]->size()) {
16143       isAllExplicitSpecializations = false;
16144       break;
16145     }
16146   }
16147 
16148   // FIXME: don't ignore attributes.
16149 
16150   // If it's explicit specializations all the way down, just forget
16151   // about the template header and build an appropriate non-templated
16152   // friend.  TODO: for source fidelity, remember the headers.
16153   if (isAllExplicitSpecializations) {
16154     if (SS.isEmpty()) {
16155       bool Owned = false;
16156       bool IsDependent = false;
16157       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16158                       Attr, AS_public,
16159                       /*ModulePrivateLoc=*/SourceLocation(),
16160                       MultiTemplateParamsArg(), Owned, IsDependent,
16161                       /*ScopedEnumKWLoc=*/SourceLocation(),
16162                       /*ScopedEnumUsesClassTag=*/false,
16163                       /*UnderlyingType=*/TypeResult(),
16164                       /*IsTypeSpecifier=*/false,
16165                       /*IsTemplateParamOrArg=*/false);
16166     }
16167 
16168     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16169     ElaboratedTypeKeyword Keyword
16170       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16171     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16172                                    *Name, NameLoc);
16173     if (T.isNull())
16174       return nullptr;
16175 
16176     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16177     if (isa<DependentNameType>(T)) {
16178       DependentNameTypeLoc TL =
16179           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16180       TL.setElaboratedKeywordLoc(TagLoc);
16181       TL.setQualifierLoc(QualifierLoc);
16182       TL.setNameLoc(NameLoc);
16183     } else {
16184       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16185       TL.setElaboratedKeywordLoc(TagLoc);
16186       TL.setQualifierLoc(QualifierLoc);
16187       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16188     }
16189 
16190     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16191                                             TSI, FriendLoc, TempParamLists);
16192     Friend->setAccess(AS_public);
16193     CurContext->addDecl(Friend);
16194     return Friend;
16195   }
16196 
16197   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16198 
16199 
16200 
16201   // Handle the case of a templated-scope friend class.  e.g.
16202   //   template <class T> class A<T>::B;
16203   // FIXME: we don't support these right now.
16204   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16205     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16206   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16207   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16208   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16209   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16210   TL.setElaboratedKeywordLoc(TagLoc);
16211   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16212   TL.setNameLoc(NameLoc);
16213 
16214   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16215                                           TSI, FriendLoc, TempParamLists);
16216   Friend->setAccess(AS_public);
16217   Friend->setUnsupportedFriend(true);
16218   CurContext->addDecl(Friend);
16219   return Friend;
16220 }
16221 
16222 /// Handle a friend type declaration.  This works in tandem with
16223 /// ActOnTag.
16224 ///
16225 /// Notes on friend class templates:
16226 ///
16227 /// We generally treat friend class declarations as if they were
16228 /// declaring a class.  So, for example, the elaborated type specifier
16229 /// in a friend declaration is required to obey the restrictions of a
16230 /// class-head (i.e. no typedefs in the scope chain), template
16231 /// parameters are required to match up with simple template-ids, &c.
16232 /// However, unlike when declaring a template specialization, it's
16233 /// okay to refer to a template specialization without an empty
16234 /// template parameter declaration, e.g.
16235 ///   friend class A<T>::B<unsigned>;
16236 /// We permit this as a special case; if there are any template
16237 /// parameters present at all, require proper matching, i.e.
16238 ///   template <> template \<class T> friend class A<int>::B;
16239 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16240                                 MultiTemplateParamsArg TempParams) {
16241   SourceLocation Loc = DS.getBeginLoc();
16242 
16243   assert(DS.isFriendSpecified());
16244   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16245 
16246   // C++ [class.friend]p3:
16247   // A friend declaration that does not declare a function shall have one of
16248   // the following forms:
16249   //     friend elaborated-type-specifier ;
16250   //     friend simple-type-specifier ;
16251   //     friend typename-specifier ;
16252   //
16253   // Any declaration with a type qualifier does not have that form. (It's
16254   // legal to specify a qualified type as a friend, you just can't write the
16255   // keywords.)
16256   if (DS.getTypeQualifiers()) {
16257     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16258       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16259     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16260       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16261     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16262       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16263     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16264       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16265     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16266       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16267   }
16268 
16269   // Try to convert the decl specifier to a type.  This works for
16270   // friend templates because ActOnTag never produces a ClassTemplateDecl
16271   // for a TUK_Friend.
16272   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16273   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16274   QualType T = TSI->getType();
16275   if (TheDeclarator.isInvalidType())
16276     return nullptr;
16277 
16278   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16279     return nullptr;
16280 
16281   // This is definitely an error in C++98.  It's probably meant to
16282   // be forbidden in C++0x, too, but the specification is just
16283   // poorly written.
16284   //
16285   // The problem is with declarations like the following:
16286   //   template <T> friend A<T>::foo;
16287   // where deciding whether a class C is a friend or not now hinges
16288   // on whether there exists an instantiation of A that causes
16289   // 'foo' to equal C.  There are restrictions on class-heads
16290   // (which we declare (by fiat) elaborated friend declarations to
16291   // be) that makes this tractable.
16292   //
16293   // FIXME: handle "template <> friend class A<T>;", which
16294   // is possibly well-formed?  Who even knows?
16295   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16296     Diag(Loc, diag::err_tagless_friend_type_template)
16297       << DS.getSourceRange();
16298     return nullptr;
16299   }
16300 
16301   // C++98 [class.friend]p1: A friend of a class is a function
16302   //   or class that is not a member of the class . . .
16303   // This is fixed in DR77, which just barely didn't make the C++03
16304   // deadline.  It's also a very silly restriction that seriously
16305   // affects inner classes and which nobody else seems to implement;
16306   // thus we never diagnose it, not even in -pedantic.
16307   //
16308   // But note that we could warn about it: it's always useless to
16309   // friend one of your own members (it's not, however, worthless to
16310   // friend a member of an arbitrary specialization of your template).
16311 
16312   Decl *D;
16313   if (!TempParams.empty())
16314     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16315                                    TempParams,
16316                                    TSI,
16317                                    DS.getFriendSpecLoc());
16318   else
16319     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16320 
16321   if (!D)
16322     return nullptr;
16323 
16324   D->setAccess(AS_public);
16325   CurContext->addDecl(D);
16326 
16327   return D;
16328 }
16329 
16330 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16331                                         MultiTemplateParamsArg TemplateParams) {
16332   const DeclSpec &DS = D.getDeclSpec();
16333 
16334   assert(DS.isFriendSpecified());
16335   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16336 
16337   SourceLocation Loc = D.getIdentifierLoc();
16338   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16339 
16340   // C++ [class.friend]p1
16341   //   A friend of a class is a function or class....
16342   // Note that this sees through typedefs, which is intended.
16343   // It *doesn't* see through dependent types, which is correct
16344   // according to [temp.arg.type]p3:
16345   //   If a declaration acquires a function type through a
16346   //   type dependent on a template-parameter and this causes
16347   //   a declaration that does not use the syntactic form of a
16348   //   function declarator to have a function type, the program
16349   //   is ill-formed.
16350   if (!TInfo->getType()->isFunctionType()) {
16351     Diag(Loc, diag::err_unexpected_friend);
16352 
16353     // It might be worthwhile to try to recover by creating an
16354     // appropriate declaration.
16355     return nullptr;
16356   }
16357 
16358   // C++ [namespace.memdef]p3
16359   //  - If a friend declaration in a non-local class first declares a
16360   //    class or function, the friend class or function is a member
16361   //    of the innermost enclosing namespace.
16362   //  - The name of the friend is not found by simple name lookup
16363   //    until a matching declaration is provided in that namespace
16364   //    scope (either before or after the class declaration granting
16365   //    friendship).
16366   //  - If a friend function is called, its name may be found by the
16367   //    name lookup that considers functions from namespaces and
16368   //    classes associated with the types of the function arguments.
16369   //  - When looking for a prior declaration of a class or a function
16370   //    declared as a friend, scopes outside the innermost enclosing
16371   //    namespace scope are not considered.
16372 
16373   CXXScopeSpec &SS = D.getCXXScopeSpec();
16374   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16375   assert(NameInfo.getName());
16376 
16377   // Check for unexpanded parameter packs.
16378   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16379       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16380       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16381     return nullptr;
16382 
16383   // The context we found the declaration in, or in which we should
16384   // create the declaration.
16385   DeclContext *DC;
16386   Scope *DCScope = S;
16387   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16388                         ForExternalRedeclaration);
16389 
16390   // There are five cases here.
16391   //   - There's no scope specifier and we're in a local class. Only look
16392   //     for functions declared in the immediately-enclosing block scope.
16393   // We recover from invalid scope qualifiers as if they just weren't there.
16394   FunctionDecl *FunctionContainingLocalClass = nullptr;
16395   if ((SS.isInvalid() || !SS.isSet()) &&
16396       (FunctionContainingLocalClass =
16397            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16398     // C++11 [class.friend]p11:
16399     //   If a friend declaration appears in a local class and the name
16400     //   specified is an unqualified name, a prior declaration is
16401     //   looked up without considering scopes that are outside the
16402     //   innermost enclosing non-class scope. For a friend function
16403     //   declaration, if there is no prior declaration, the program is
16404     //   ill-formed.
16405 
16406     // Find the innermost enclosing non-class scope. This is the block
16407     // scope containing the local class definition (or for a nested class,
16408     // the outer local class).
16409     DCScope = S->getFnParent();
16410 
16411     // Look up the function name in the scope.
16412     Previous.clear(LookupLocalFriendName);
16413     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16414 
16415     if (!Previous.empty()) {
16416       // All possible previous declarations must have the same context:
16417       // either they were declared at block scope or they are members of
16418       // one of the enclosing local classes.
16419       DC = Previous.getRepresentativeDecl()->getDeclContext();
16420     } else {
16421       // This is ill-formed, but provide the context that we would have
16422       // declared the function in, if we were permitted to, for error recovery.
16423       DC = FunctionContainingLocalClass;
16424     }
16425     adjustContextForLocalExternDecl(DC);
16426 
16427     // C++ [class.friend]p6:
16428     //   A function can be defined in a friend declaration of a class if and
16429     //   only if the class is a non-local class (9.8), the function name is
16430     //   unqualified, and the function has namespace scope.
16431     if (D.isFunctionDefinition()) {
16432       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16433     }
16434 
16435   //   - There's no scope specifier, in which case we just go to the
16436   //     appropriate scope and look for a function or function template
16437   //     there as appropriate.
16438   } else if (SS.isInvalid() || !SS.isSet()) {
16439     // C++11 [namespace.memdef]p3:
16440     //   If the name in a friend declaration is neither qualified nor
16441     //   a template-id and the declaration is a function or an
16442     //   elaborated-type-specifier, the lookup to determine whether
16443     //   the entity has been previously declared shall not consider
16444     //   any scopes outside the innermost enclosing namespace.
16445     bool isTemplateId =
16446         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16447 
16448     // Find the appropriate context according to the above.
16449     DC = CurContext;
16450 
16451     // Skip class contexts.  If someone can cite chapter and verse
16452     // for this behavior, that would be nice --- it's what GCC and
16453     // EDG do, and it seems like a reasonable intent, but the spec
16454     // really only says that checks for unqualified existing
16455     // declarations should stop at the nearest enclosing namespace,
16456     // not that they should only consider the nearest enclosing
16457     // namespace.
16458     while (DC->isRecord())
16459       DC = DC->getParent();
16460 
16461     DeclContext *LookupDC = DC;
16462     while (LookupDC->isTransparentContext())
16463       LookupDC = LookupDC->getParent();
16464 
16465     while (true) {
16466       LookupQualifiedName(Previous, LookupDC);
16467 
16468       if (!Previous.empty()) {
16469         DC = LookupDC;
16470         break;
16471       }
16472 
16473       if (isTemplateId) {
16474         if (isa<TranslationUnitDecl>(LookupDC)) break;
16475       } else {
16476         if (LookupDC->isFileContext()) break;
16477       }
16478       LookupDC = LookupDC->getParent();
16479     }
16480 
16481     DCScope = getScopeForDeclContext(S, DC);
16482 
16483   //   - There's a non-dependent scope specifier, in which case we
16484   //     compute it and do a previous lookup there for a function
16485   //     or function template.
16486   } else if (!SS.getScopeRep()->isDependent()) {
16487     DC = computeDeclContext(SS);
16488     if (!DC) return nullptr;
16489 
16490     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16491 
16492     LookupQualifiedName(Previous, DC);
16493 
16494     // C++ [class.friend]p1: A friend of a class is a function or
16495     //   class that is not a member of the class . . .
16496     if (DC->Equals(CurContext))
16497       Diag(DS.getFriendSpecLoc(),
16498            getLangOpts().CPlusPlus11 ?
16499              diag::warn_cxx98_compat_friend_is_member :
16500              diag::err_friend_is_member);
16501 
16502     if (D.isFunctionDefinition()) {
16503       // C++ [class.friend]p6:
16504       //   A function can be defined in a friend declaration of a class if and
16505       //   only if the class is a non-local class (9.8), the function name is
16506       //   unqualified, and the function has namespace scope.
16507       //
16508       // FIXME: We should only do this if the scope specifier names the
16509       // innermost enclosing namespace; otherwise the fixit changes the
16510       // meaning of the code.
16511       SemaDiagnosticBuilder DB
16512         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16513 
16514       DB << SS.getScopeRep();
16515       if (DC->isFileContext())
16516         DB << FixItHint::CreateRemoval(SS.getRange());
16517       SS.clear();
16518     }
16519 
16520   //   - There's a scope specifier that does not match any template
16521   //     parameter lists, in which case we use some arbitrary context,
16522   //     create a method or method template, and wait for instantiation.
16523   //   - There's a scope specifier that does match some template
16524   //     parameter lists, which we don't handle right now.
16525   } else {
16526     if (D.isFunctionDefinition()) {
16527       // C++ [class.friend]p6:
16528       //   A function can be defined in a friend declaration of a class if and
16529       //   only if the class is a non-local class (9.8), the function name is
16530       //   unqualified, and the function has namespace scope.
16531       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16532         << SS.getScopeRep();
16533     }
16534 
16535     DC = CurContext;
16536     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16537   }
16538 
16539   if (!DC->isRecord()) {
16540     int DiagArg = -1;
16541     switch (D.getName().getKind()) {
16542     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16543     case UnqualifiedIdKind::IK_ConstructorName:
16544       DiagArg = 0;
16545       break;
16546     case UnqualifiedIdKind::IK_DestructorName:
16547       DiagArg = 1;
16548       break;
16549     case UnqualifiedIdKind::IK_ConversionFunctionId:
16550       DiagArg = 2;
16551       break;
16552     case UnqualifiedIdKind::IK_DeductionGuideName:
16553       DiagArg = 3;
16554       break;
16555     case UnqualifiedIdKind::IK_Identifier:
16556     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16557     case UnqualifiedIdKind::IK_LiteralOperatorId:
16558     case UnqualifiedIdKind::IK_OperatorFunctionId:
16559     case UnqualifiedIdKind::IK_TemplateId:
16560       break;
16561     }
16562     // This implies that it has to be an operator or function.
16563     if (DiagArg >= 0) {
16564       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16565       return nullptr;
16566     }
16567   }
16568 
16569   // FIXME: This is an egregious hack to cope with cases where the scope stack
16570   // does not contain the declaration context, i.e., in an out-of-line
16571   // definition of a class.
16572   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16573   if (!DCScope) {
16574     FakeDCScope.setEntity(DC);
16575     DCScope = &FakeDCScope;
16576   }
16577 
16578   bool AddToScope = true;
16579   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16580                                           TemplateParams, AddToScope);
16581   if (!ND) return nullptr;
16582 
16583   assert(ND->getLexicalDeclContext() == CurContext);
16584 
16585   // If we performed typo correction, we might have added a scope specifier
16586   // and changed the decl context.
16587   DC = ND->getDeclContext();
16588 
16589   // Add the function declaration to the appropriate lookup tables,
16590   // adjusting the redeclarations list as necessary.  We don't
16591   // want to do this yet if the friending class is dependent.
16592   //
16593   // Also update the scope-based lookup if the target context's
16594   // lookup context is in lexical scope.
16595   if (!CurContext->isDependentContext()) {
16596     DC = DC->getRedeclContext();
16597     DC->makeDeclVisibleInContext(ND);
16598     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16599       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16600   }
16601 
16602   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16603                                        D.getIdentifierLoc(), ND,
16604                                        DS.getFriendSpecLoc());
16605   FrD->setAccess(AS_public);
16606   CurContext->addDecl(FrD);
16607 
16608   if (ND->isInvalidDecl()) {
16609     FrD->setInvalidDecl();
16610   } else {
16611     if (DC->isRecord()) CheckFriendAccess(ND);
16612 
16613     FunctionDecl *FD;
16614     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16615       FD = FTD->getTemplatedDecl();
16616     else
16617       FD = cast<FunctionDecl>(ND);
16618 
16619     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16620     // default argument expression, that declaration shall be a definition
16621     // and shall be the only declaration of the function or function
16622     // template in the translation unit.
16623     if (functionDeclHasDefaultArgument(FD)) {
16624       // We can't look at FD->getPreviousDecl() because it may not have been set
16625       // if we're in a dependent context. If the function is known to be a
16626       // redeclaration, we will have narrowed Previous down to the right decl.
16627       if (D.isRedeclaration()) {
16628         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16629         Diag(Previous.getRepresentativeDecl()->getLocation(),
16630              diag::note_previous_declaration);
16631       } else if (!D.isFunctionDefinition())
16632         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16633     }
16634 
16635     // Mark templated-scope function declarations as unsupported.
16636     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16637       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16638         << SS.getScopeRep() << SS.getRange()
16639         << cast<CXXRecordDecl>(CurContext);
16640       FrD->setUnsupportedFriend(true);
16641     }
16642   }
16643 
16644   return ND;
16645 }
16646 
16647 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16648   AdjustDeclIfTemplate(Dcl);
16649 
16650   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16651   if (!Fn) {
16652     Diag(DelLoc, diag::err_deleted_non_function);
16653     return;
16654   }
16655 
16656   // Deleted function does not have a body.
16657   Fn->setWillHaveBody(false);
16658 
16659   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16660     // Don't consider the implicit declaration we generate for explicit
16661     // specializations. FIXME: Do not generate these implicit declarations.
16662     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16663          Prev->getPreviousDecl()) &&
16664         !Prev->isDefined()) {
16665       Diag(DelLoc, diag::err_deleted_decl_not_first);
16666       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16667            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16668                               : diag::note_previous_declaration);
16669       // We can't recover from this; the declaration might have already
16670       // been used.
16671       Fn->setInvalidDecl();
16672       return;
16673     }
16674 
16675     // To maintain the invariant that functions are only deleted on their first
16676     // declaration, mark the implicitly-instantiated declaration of the
16677     // explicitly-specialized function as deleted instead of marking the
16678     // instantiated redeclaration.
16679     Fn = Fn->getCanonicalDecl();
16680   }
16681 
16682   // dllimport/dllexport cannot be deleted.
16683   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16684     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16685     Fn->setInvalidDecl();
16686   }
16687 
16688   // C++11 [basic.start.main]p3:
16689   //   A program that defines main as deleted [...] is ill-formed.
16690   if (Fn->isMain())
16691     Diag(DelLoc, diag::err_deleted_main);
16692 
16693   // C++11 [dcl.fct.def.delete]p4:
16694   //  A deleted function is implicitly inline.
16695   Fn->setImplicitlyInline();
16696   Fn->setDeletedAsWritten();
16697 }
16698 
16699 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16700   if (!Dcl || Dcl->isInvalidDecl())
16701     return;
16702 
16703   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16704   if (!FD) {
16705     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16706       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16707         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16708         return;
16709       }
16710     }
16711 
16712     Diag(DefaultLoc, diag::err_default_special_members)
16713         << getLangOpts().CPlusPlus20;
16714     return;
16715   }
16716 
16717   // Reject if this can't possibly be a defaultable function.
16718   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16719   if (!DefKind &&
16720       // A dependent function that doesn't locally look defaultable can
16721       // still instantiate to a defaultable function if it's a constructor
16722       // or assignment operator.
16723       (!FD->isDependentContext() ||
16724        (!isa<CXXConstructorDecl>(FD) &&
16725         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16726     Diag(DefaultLoc, diag::err_default_special_members)
16727         << getLangOpts().CPlusPlus20;
16728     return;
16729   }
16730 
16731   if (DefKind.isComparison() &&
16732       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16733     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16734         << (int)DefKind.asComparison();
16735     return;
16736   }
16737 
16738   // Issue compatibility warning. We already warned if the operator is
16739   // 'operator<=>' when parsing the '<=>' token.
16740   if (DefKind.isComparison() &&
16741       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16742     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16743                          ? diag::warn_cxx17_compat_defaulted_comparison
16744                          : diag::ext_defaulted_comparison);
16745   }
16746 
16747   FD->setDefaulted();
16748   FD->setExplicitlyDefaulted();
16749 
16750   // Defer checking functions that are defaulted in a dependent context.
16751   if (FD->isDependentContext())
16752     return;
16753 
16754   // Unset that we will have a body for this function. We might not,
16755   // if it turns out to be trivial, and we don't need this marking now
16756   // that we've marked it as defaulted.
16757   FD->setWillHaveBody(false);
16758 
16759   // If this definition appears within the record, do the checking when
16760   // the record is complete. This is always the case for a defaulted
16761   // comparison.
16762   if (DefKind.isComparison())
16763     return;
16764   auto *MD = cast<CXXMethodDecl>(FD);
16765 
16766   const FunctionDecl *Primary = FD;
16767   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16768     // Ask the template instantiation pattern that actually had the
16769     // '= default' on it.
16770     Primary = Pattern;
16771 
16772   // If the method was defaulted on its first declaration, we will have
16773   // already performed the checking in CheckCompletedCXXClass. Such a
16774   // declaration doesn't trigger an implicit definition.
16775   if (Primary->getCanonicalDecl()->isDefaulted())
16776     return;
16777 
16778   // FIXME: Once we support defining comparisons out of class, check for a
16779   // defaulted comparison here.
16780   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16781     MD->setInvalidDecl();
16782   else
16783     DefineDefaultedFunction(*this, MD, DefaultLoc);
16784 }
16785 
16786 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16787   for (Stmt *SubStmt : S->children()) {
16788     if (!SubStmt)
16789       continue;
16790     if (isa<ReturnStmt>(SubStmt))
16791       Self.Diag(SubStmt->getBeginLoc(),
16792                 diag::err_return_in_constructor_handler);
16793     if (!isa<Expr>(SubStmt))
16794       SearchForReturnInStmt(Self, SubStmt);
16795   }
16796 }
16797 
16798 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16799   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16800     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16801     SearchForReturnInStmt(*this, Handler);
16802   }
16803 }
16804 
16805 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16806                                              const CXXMethodDecl *Old) {
16807   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16808   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16809 
16810   if (OldFT->hasExtParameterInfos()) {
16811     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16812       // A parameter of the overriding method should be annotated with noescape
16813       // if the corresponding parameter of the overridden method is annotated.
16814       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16815           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16816         Diag(New->getParamDecl(I)->getLocation(),
16817              diag::warn_overriding_method_missing_noescape);
16818         Diag(Old->getParamDecl(I)->getLocation(),
16819              diag::note_overridden_marked_noescape);
16820       }
16821   }
16822 
16823   // Virtual overrides must have the same code_seg.
16824   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16825   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16826   if ((NewCSA || OldCSA) &&
16827       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16828     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16829     Diag(Old->getLocation(), diag::note_previous_declaration);
16830     return true;
16831   }
16832 
16833   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16834 
16835   // If the calling conventions match, everything is fine
16836   if (NewCC == OldCC)
16837     return false;
16838 
16839   // If the calling conventions mismatch because the new function is static,
16840   // suppress the calling convention mismatch error; the error about static
16841   // function override (err_static_overrides_virtual from
16842   // Sema::CheckFunctionDeclaration) is more clear.
16843   if (New->getStorageClass() == SC_Static)
16844     return false;
16845 
16846   Diag(New->getLocation(),
16847        diag::err_conflicting_overriding_cc_attributes)
16848     << New->getDeclName() << New->getType() << Old->getType();
16849   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16850   return true;
16851 }
16852 
16853 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16854                                              const CXXMethodDecl *Old) {
16855   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16856   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16857 
16858   if (Context.hasSameType(NewTy, OldTy) ||
16859       NewTy->isDependentType() || OldTy->isDependentType())
16860     return false;
16861 
16862   // Check if the return types are covariant
16863   QualType NewClassTy, OldClassTy;
16864 
16865   /// Both types must be pointers or references to classes.
16866   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16867     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16868       NewClassTy = NewPT->getPointeeType();
16869       OldClassTy = OldPT->getPointeeType();
16870     }
16871   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16872     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16873       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16874         NewClassTy = NewRT->getPointeeType();
16875         OldClassTy = OldRT->getPointeeType();
16876       }
16877     }
16878   }
16879 
16880   // The return types aren't either both pointers or references to a class type.
16881   if (NewClassTy.isNull()) {
16882     Diag(New->getLocation(),
16883          diag::err_different_return_type_for_overriding_virtual_function)
16884         << New->getDeclName() << NewTy << OldTy
16885         << New->getReturnTypeSourceRange();
16886     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16887         << Old->getReturnTypeSourceRange();
16888 
16889     return true;
16890   }
16891 
16892   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16893     // C++14 [class.virtual]p8:
16894     //   If the class type in the covariant return type of D::f differs from
16895     //   that of B::f, the class type in the return type of D::f shall be
16896     //   complete at the point of declaration of D::f or shall be the class
16897     //   type D.
16898     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16899       if (!RT->isBeingDefined() &&
16900           RequireCompleteType(New->getLocation(), NewClassTy,
16901                               diag::err_covariant_return_incomplete,
16902                               New->getDeclName()))
16903         return true;
16904     }
16905 
16906     // Check if the new class derives from the old class.
16907     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16908       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16909           << New->getDeclName() << NewTy << OldTy
16910           << New->getReturnTypeSourceRange();
16911       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16912           << Old->getReturnTypeSourceRange();
16913       return true;
16914     }
16915 
16916     // Check if we the conversion from derived to base is valid.
16917     if (CheckDerivedToBaseConversion(
16918             NewClassTy, OldClassTy,
16919             diag::err_covariant_return_inaccessible_base,
16920             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16921             New->getLocation(), New->getReturnTypeSourceRange(),
16922             New->getDeclName(), nullptr)) {
16923       // FIXME: this note won't trigger for delayed access control
16924       // diagnostics, and it's impossible to get an undelayed error
16925       // here from access control during the original parse because
16926       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16927       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16928           << Old->getReturnTypeSourceRange();
16929       return true;
16930     }
16931   }
16932 
16933   // The qualifiers of the return types must be the same.
16934   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16935     Diag(New->getLocation(),
16936          diag::err_covariant_return_type_different_qualifications)
16937         << New->getDeclName() << NewTy << OldTy
16938         << New->getReturnTypeSourceRange();
16939     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16940         << Old->getReturnTypeSourceRange();
16941     return true;
16942   }
16943 
16944 
16945   // The new class type must have the same or less qualifiers as the old type.
16946   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16947     Diag(New->getLocation(),
16948          diag::err_covariant_return_type_class_type_more_qualified)
16949         << New->getDeclName() << NewTy << OldTy
16950         << New->getReturnTypeSourceRange();
16951     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16952         << Old->getReturnTypeSourceRange();
16953     return true;
16954   }
16955 
16956   return false;
16957 }
16958 
16959 /// Mark the given method pure.
16960 ///
16961 /// \param Method the method to be marked pure.
16962 ///
16963 /// \param InitRange the source range that covers the "0" initializer.
16964 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16965   SourceLocation EndLoc = InitRange.getEnd();
16966   if (EndLoc.isValid())
16967     Method->setRangeEnd(EndLoc);
16968 
16969   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16970     Method->setPure();
16971     return false;
16972   }
16973 
16974   if (!Method->isInvalidDecl())
16975     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16976       << Method->getDeclName() << InitRange;
16977   return true;
16978 }
16979 
16980 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16981   if (D->getFriendObjectKind())
16982     Diag(D->getLocation(), diag::err_pure_friend);
16983   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16984     CheckPureMethod(M, ZeroLoc);
16985   else
16986     Diag(D->getLocation(), diag::err_illegal_initializer);
16987 }
16988 
16989 /// Determine whether the given declaration is a global variable or
16990 /// static data member.
16991 static bool isNonlocalVariable(const Decl *D) {
16992   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
16993     return Var->hasGlobalStorage();
16994 
16995   return false;
16996 }
16997 
16998 /// Invoked when we are about to parse an initializer for the declaration
16999 /// 'Dcl'.
17000 ///
17001 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17002 /// static data member of class X, names should be looked up in the scope of
17003 /// class X. If the declaration had a scope specifier, a scope will have
17004 /// been created and passed in for this purpose. Otherwise, S will be null.
17005 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17006   // If there is no declaration, there was an error parsing it.
17007   if (!D || D->isInvalidDecl())
17008     return;
17009 
17010   // We will always have a nested name specifier here, but this declaration
17011   // might not be out of line if the specifier names the current namespace:
17012   //   extern int n;
17013   //   int ::n = 0;
17014   if (S && D->isOutOfLine())
17015     EnterDeclaratorContext(S, D->getDeclContext());
17016 
17017   // If we are parsing the initializer for a static data member, push a
17018   // new expression evaluation context that is associated with this static
17019   // data member.
17020   if (isNonlocalVariable(D))
17021     PushExpressionEvaluationContext(
17022         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17023 }
17024 
17025 /// Invoked after we are finished parsing an initializer for the declaration D.
17026 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17027   // If there is no declaration, there was an error parsing it.
17028   if (!D || D->isInvalidDecl())
17029     return;
17030 
17031   if (isNonlocalVariable(D))
17032     PopExpressionEvaluationContext();
17033 
17034   if (S && D->isOutOfLine())
17035     ExitDeclaratorContext(S);
17036 }
17037 
17038 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17039 /// C++ if/switch/while/for statement.
17040 /// e.g: "if (int x = f()) {...}"
17041 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17042   // C++ 6.4p2:
17043   // The declarator shall not specify a function or an array.
17044   // The type-specifier-seq shall not contain typedef and shall not declare a
17045   // new class or enumeration.
17046   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17047          "Parser allowed 'typedef' as storage class of condition decl.");
17048 
17049   Decl *Dcl = ActOnDeclarator(S, D);
17050   if (!Dcl)
17051     return true;
17052 
17053   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17054     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17055       << D.getSourceRange();
17056     return true;
17057   }
17058 
17059   return Dcl;
17060 }
17061 
17062 void Sema::LoadExternalVTableUses() {
17063   if (!ExternalSource)
17064     return;
17065 
17066   SmallVector<ExternalVTableUse, 4> VTables;
17067   ExternalSource->ReadUsedVTables(VTables);
17068   SmallVector<VTableUse, 4> NewUses;
17069   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17070     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17071       = VTablesUsed.find(VTables[I].Record);
17072     // Even if a definition wasn't required before, it may be required now.
17073     if (Pos != VTablesUsed.end()) {
17074       if (!Pos->second && VTables[I].DefinitionRequired)
17075         Pos->second = true;
17076       continue;
17077     }
17078 
17079     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17080     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17081   }
17082 
17083   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17084 }
17085 
17086 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17087                           bool DefinitionRequired) {
17088   // Ignore any vtable uses in unevaluated operands or for classes that do
17089   // not have a vtable.
17090   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17091       CurContext->isDependentContext() || isUnevaluatedContext())
17092     return;
17093   // Do not mark as used if compiling for the device outside of the target
17094   // region.
17095   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17096       !isInOpenMPDeclareTargetContext() &&
17097       !isInOpenMPTargetExecutionDirective()) {
17098     if (!DefinitionRequired)
17099       MarkVirtualMembersReferenced(Loc, Class);
17100     return;
17101   }
17102 
17103   // Try to insert this class into the map.
17104   LoadExternalVTableUses();
17105   Class = Class->getCanonicalDecl();
17106   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17107     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17108   if (!Pos.second) {
17109     // If we already had an entry, check to see if we are promoting this vtable
17110     // to require a definition. If so, we need to reappend to the VTableUses
17111     // list, since we may have already processed the first entry.
17112     if (DefinitionRequired && !Pos.first->second) {
17113       Pos.first->second = true;
17114     } else {
17115       // Otherwise, we can early exit.
17116       return;
17117     }
17118   } else {
17119     // The Microsoft ABI requires that we perform the destructor body
17120     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17121     // the deleting destructor is emitted with the vtable, not with the
17122     // destructor definition as in the Itanium ABI.
17123     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17124       CXXDestructorDecl *DD = Class->getDestructor();
17125       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17126         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17127           // If this is an out-of-line declaration, marking it referenced will
17128           // not do anything. Manually call CheckDestructor to look up operator
17129           // delete().
17130           ContextRAII SavedContext(*this, DD);
17131           CheckDestructor(DD);
17132         } else {
17133           MarkFunctionReferenced(Loc, Class->getDestructor());
17134         }
17135       }
17136     }
17137   }
17138 
17139   // Local classes need to have their virtual members marked
17140   // immediately. For all other classes, we mark their virtual members
17141   // at the end of the translation unit.
17142   if (Class->isLocalClass())
17143     MarkVirtualMembersReferenced(Loc, Class);
17144   else
17145     VTableUses.push_back(std::make_pair(Class, Loc));
17146 }
17147 
17148 bool Sema::DefineUsedVTables() {
17149   LoadExternalVTableUses();
17150   if (VTableUses.empty())
17151     return false;
17152 
17153   // Note: The VTableUses vector could grow as a result of marking
17154   // the members of a class as "used", so we check the size each
17155   // time through the loop and prefer indices (which are stable) to
17156   // iterators (which are not).
17157   bool DefinedAnything = false;
17158   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17159     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17160     if (!Class)
17161       continue;
17162     TemplateSpecializationKind ClassTSK =
17163         Class->getTemplateSpecializationKind();
17164 
17165     SourceLocation Loc = VTableUses[I].second;
17166 
17167     bool DefineVTable = true;
17168 
17169     // If this class has a key function, but that key function is
17170     // defined in another translation unit, we don't need to emit the
17171     // vtable even though we're using it.
17172     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17173     if (KeyFunction && !KeyFunction->hasBody()) {
17174       // The key function is in another translation unit.
17175       DefineVTable = false;
17176       TemplateSpecializationKind TSK =
17177           KeyFunction->getTemplateSpecializationKind();
17178       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17179              TSK != TSK_ImplicitInstantiation &&
17180              "Instantiations don't have key functions");
17181       (void)TSK;
17182     } else if (!KeyFunction) {
17183       // If we have a class with no key function that is the subject
17184       // of an explicit instantiation declaration, suppress the
17185       // vtable; it will live with the explicit instantiation
17186       // definition.
17187       bool IsExplicitInstantiationDeclaration =
17188           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17189       for (auto R : Class->redecls()) {
17190         TemplateSpecializationKind TSK
17191           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17192         if (TSK == TSK_ExplicitInstantiationDeclaration)
17193           IsExplicitInstantiationDeclaration = true;
17194         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17195           IsExplicitInstantiationDeclaration = false;
17196           break;
17197         }
17198       }
17199 
17200       if (IsExplicitInstantiationDeclaration)
17201         DefineVTable = false;
17202     }
17203 
17204     // The exception specifications for all virtual members may be needed even
17205     // if we are not providing an authoritative form of the vtable in this TU.
17206     // We may choose to emit it available_externally anyway.
17207     if (!DefineVTable) {
17208       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17209       continue;
17210     }
17211 
17212     // Mark all of the virtual members of this class as referenced, so
17213     // that we can build a vtable. Then, tell the AST consumer that a
17214     // vtable for this class is required.
17215     DefinedAnything = true;
17216     MarkVirtualMembersReferenced(Loc, Class);
17217     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17218     if (VTablesUsed[Canonical])
17219       Consumer.HandleVTable(Class);
17220 
17221     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17222     // no key function or the key function is inlined. Don't warn in C++ ABIs
17223     // that lack key functions, since the user won't be able to make one.
17224     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17225         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17226       const FunctionDecl *KeyFunctionDef = nullptr;
17227       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17228                            KeyFunctionDef->isInlined())) {
17229         Diag(Class->getLocation(),
17230              ClassTSK == TSK_ExplicitInstantiationDefinition
17231                  ? diag::warn_weak_template_vtable
17232                  : diag::warn_weak_vtable)
17233             << Class;
17234       }
17235     }
17236   }
17237   VTableUses.clear();
17238 
17239   return DefinedAnything;
17240 }
17241 
17242 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17243                                                  const CXXRecordDecl *RD) {
17244   for (const auto *I : RD->methods())
17245     if (I->isVirtual() && !I->isPure())
17246       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17247 }
17248 
17249 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17250                                         const CXXRecordDecl *RD,
17251                                         bool ConstexprOnly) {
17252   // Mark all functions which will appear in RD's vtable as used.
17253   CXXFinalOverriderMap FinalOverriders;
17254   RD->getFinalOverriders(FinalOverriders);
17255   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17256                                             E = FinalOverriders.end();
17257        I != E; ++I) {
17258     for (OverridingMethods::const_iterator OI = I->second.begin(),
17259                                            OE = I->second.end();
17260          OI != OE; ++OI) {
17261       assert(OI->second.size() > 0 && "no final overrider");
17262       CXXMethodDecl *Overrider = OI->second.front().Method;
17263 
17264       // C++ [basic.def.odr]p2:
17265       //   [...] A virtual member function is used if it is not pure. [...]
17266       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17267         MarkFunctionReferenced(Loc, Overrider);
17268     }
17269   }
17270 
17271   // Only classes that have virtual bases need a VTT.
17272   if (RD->getNumVBases() == 0)
17273     return;
17274 
17275   for (const auto &I : RD->bases()) {
17276     const auto *Base =
17277         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17278     if (Base->getNumVBases() == 0)
17279       continue;
17280     MarkVirtualMembersReferenced(Loc, Base);
17281   }
17282 }
17283 
17284 /// SetIvarInitializers - This routine builds initialization ASTs for the
17285 /// Objective-C implementation whose ivars need be initialized.
17286 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17287   if (!getLangOpts().CPlusPlus)
17288     return;
17289   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17290     SmallVector<ObjCIvarDecl*, 8> ivars;
17291     CollectIvarsToConstructOrDestruct(OID, ivars);
17292     if (ivars.empty())
17293       return;
17294     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17295     for (unsigned i = 0; i < ivars.size(); i++) {
17296       FieldDecl *Field = ivars[i];
17297       if (Field->isInvalidDecl())
17298         continue;
17299 
17300       CXXCtorInitializer *Member;
17301       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17302       InitializationKind InitKind =
17303         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17304 
17305       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17306       ExprResult MemberInit =
17307         InitSeq.Perform(*this, InitEntity, InitKind, None);
17308       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17309       // Note, MemberInit could actually come back empty if no initialization
17310       // is required (e.g., because it would call a trivial default constructor)
17311       if (!MemberInit.get() || MemberInit.isInvalid())
17312         continue;
17313 
17314       Member =
17315         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17316                                          SourceLocation(),
17317                                          MemberInit.getAs<Expr>(),
17318                                          SourceLocation());
17319       AllToInit.push_back(Member);
17320 
17321       // Be sure that the destructor is accessible and is marked as referenced.
17322       if (const RecordType *RecordTy =
17323               Context.getBaseElementType(Field->getType())
17324                   ->getAs<RecordType>()) {
17325         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17326         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17327           MarkFunctionReferenced(Field->getLocation(), Destructor);
17328           CheckDestructorAccess(Field->getLocation(), Destructor,
17329                             PDiag(diag::err_access_dtor_ivar)
17330                               << Context.getBaseElementType(Field->getType()));
17331         }
17332       }
17333     }
17334     ObjCImplementation->setIvarInitializers(Context,
17335                                             AllToInit.data(), AllToInit.size());
17336   }
17337 }
17338 
17339 static
17340 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17341                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17342                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17343                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17344                            Sema &S) {
17345   if (Ctor->isInvalidDecl())
17346     return;
17347 
17348   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17349 
17350   // Target may not be determinable yet, for instance if this is a dependent
17351   // call in an uninstantiated template.
17352   if (Target) {
17353     const FunctionDecl *FNTarget = nullptr;
17354     (void)Target->hasBody(FNTarget);
17355     Target = const_cast<CXXConstructorDecl*>(
17356       cast_or_null<CXXConstructorDecl>(FNTarget));
17357   }
17358 
17359   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17360                      // Avoid dereferencing a null pointer here.
17361                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17362 
17363   if (!Current.insert(Canonical).second)
17364     return;
17365 
17366   // We know that beyond here, we aren't chaining into a cycle.
17367   if (!Target || !Target->isDelegatingConstructor() ||
17368       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17369     Valid.insert(Current.begin(), Current.end());
17370     Current.clear();
17371   // We've hit a cycle.
17372   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17373              Current.count(TCanonical)) {
17374     // If we haven't diagnosed this cycle yet, do so now.
17375     if (!Invalid.count(TCanonical)) {
17376       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17377              diag::warn_delegating_ctor_cycle)
17378         << Ctor;
17379 
17380       // Don't add a note for a function delegating directly to itself.
17381       if (TCanonical != Canonical)
17382         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17383 
17384       CXXConstructorDecl *C = Target;
17385       while (C->getCanonicalDecl() != Canonical) {
17386         const FunctionDecl *FNTarget = nullptr;
17387         (void)C->getTargetConstructor()->hasBody(FNTarget);
17388         assert(FNTarget && "Ctor cycle through bodiless function");
17389 
17390         C = const_cast<CXXConstructorDecl*>(
17391           cast<CXXConstructorDecl>(FNTarget));
17392         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17393       }
17394     }
17395 
17396     Invalid.insert(Current.begin(), Current.end());
17397     Current.clear();
17398   } else {
17399     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17400   }
17401 }
17402 
17403 
17404 void Sema::CheckDelegatingCtorCycles() {
17405   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17406 
17407   for (DelegatingCtorDeclsType::iterator
17408          I = DelegatingCtorDecls.begin(ExternalSource),
17409          E = DelegatingCtorDecls.end();
17410        I != E; ++I)
17411     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17412 
17413   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17414     (*CI)->setInvalidDecl();
17415 }
17416 
17417 namespace {
17418   /// AST visitor that finds references to the 'this' expression.
17419   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17420     Sema &S;
17421 
17422   public:
17423     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17424 
17425     bool VisitCXXThisExpr(CXXThisExpr *E) {
17426       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17427         << E->isImplicit();
17428       return false;
17429     }
17430   };
17431 }
17432 
17433 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17434   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17435   if (!TSInfo)
17436     return false;
17437 
17438   TypeLoc TL = TSInfo->getTypeLoc();
17439   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17440   if (!ProtoTL)
17441     return false;
17442 
17443   // C++11 [expr.prim.general]p3:
17444   //   [The expression this] shall not appear before the optional
17445   //   cv-qualifier-seq and it shall not appear within the declaration of a
17446   //   static member function (although its type and value category are defined
17447   //   within a static member function as they are within a non-static member
17448   //   function). [ Note: this is because declaration matching does not occur
17449   //  until the complete declarator is known. - end note ]
17450   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17451   FindCXXThisExpr Finder(*this);
17452 
17453   // If the return type came after the cv-qualifier-seq, check it now.
17454   if (Proto->hasTrailingReturn() &&
17455       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17456     return true;
17457 
17458   // Check the exception specification.
17459   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17460     return true;
17461 
17462   // Check the trailing requires clause
17463   if (Expr *E = Method->getTrailingRequiresClause())
17464     if (!Finder.TraverseStmt(E))
17465       return true;
17466 
17467   return checkThisInStaticMemberFunctionAttributes(Method);
17468 }
17469 
17470 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17471   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17472   if (!TSInfo)
17473     return false;
17474 
17475   TypeLoc TL = TSInfo->getTypeLoc();
17476   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17477   if (!ProtoTL)
17478     return false;
17479 
17480   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17481   FindCXXThisExpr Finder(*this);
17482 
17483   switch (Proto->getExceptionSpecType()) {
17484   case EST_Unparsed:
17485   case EST_Uninstantiated:
17486   case EST_Unevaluated:
17487   case EST_BasicNoexcept:
17488   case EST_NoThrow:
17489   case EST_DynamicNone:
17490   case EST_MSAny:
17491   case EST_None:
17492     break;
17493 
17494   case EST_DependentNoexcept:
17495   case EST_NoexceptFalse:
17496   case EST_NoexceptTrue:
17497     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17498       return true;
17499     LLVM_FALLTHROUGH;
17500 
17501   case EST_Dynamic:
17502     for (const auto &E : Proto->exceptions()) {
17503       if (!Finder.TraverseType(E))
17504         return true;
17505     }
17506     break;
17507   }
17508 
17509   return false;
17510 }
17511 
17512 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17513   FindCXXThisExpr Finder(*this);
17514 
17515   // Check attributes.
17516   for (const auto *A : Method->attrs()) {
17517     // FIXME: This should be emitted by tblgen.
17518     Expr *Arg = nullptr;
17519     ArrayRef<Expr *> Args;
17520     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17521       Arg = G->getArg();
17522     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17523       Arg = G->getArg();
17524     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17525       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17526     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17527       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17528     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17529       Arg = ETLF->getSuccessValue();
17530       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17531     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17532       Arg = STLF->getSuccessValue();
17533       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17534     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17535       Arg = LR->getArg();
17536     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17537       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17538     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17539       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17540     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17541       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17542     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17543       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17544     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17545       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17546 
17547     if (Arg && !Finder.TraverseStmt(Arg))
17548       return true;
17549 
17550     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17551       if (!Finder.TraverseStmt(Args[I]))
17552         return true;
17553     }
17554   }
17555 
17556   return false;
17557 }
17558 
17559 void Sema::checkExceptionSpecification(
17560     bool IsTopLevel, ExceptionSpecificationType EST,
17561     ArrayRef<ParsedType> DynamicExceptions,
17562     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17563     SmallVectorImpl<QualType> &Exceptions,
17564     FunctionProtoType::ExceptionSpecInfo &ESI) {
17565   Exceptions.clear();
17566   ESI.Type = EST;
17567   if (EST == EST_Dynamic) {
17568     Exceptions.reserve(DynamicExceptions.size());
17569     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17570       // FIXME: Preserve type source info.
17571       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17572 
17573       if (IsTopLevel) {
17574         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17575         collectUnexpandedParameterPacks(ET, Unexpanded);
17576         if (!Unexpanded.empty()) {
17577           DiagnoseUnexpandedParameterPacks(
17578               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17579               Unexpanded);
17580           continue;
17581         }
17582       }
17583 
17584       // Check that the type is valid for an exception spec, and
17585       // drop it if not.
17586       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17587         Exceptions.push_back(ET);
17588     }
17589     ESI.Exceptions = Exceptions;
17590     return;
17591   }
17592 
17593   if (isComputedNoexcept(EST)) {
17594     assert((NoexceptExpr->isTypeDependent() ||
17595             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17596             Context.BoolTy) &&
17597            "Parser should have made sure that the expression is boolean");
17598     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17599       ESI.Type = EST_BasicNoexcept;
17600       return;
17601     }
17602 
17603     ESI.NoexceptExpr = NoexceptExpr;
17604     return;
17605   }
17606 }
17607 
17608 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17609              ExceptionSpecificationType EST,
17610              SourceRange SpecificationRange,
17611              ArrayRef<ParsedType> DynamicExceptions,
17612              ArrayRef<SourceRange> DynamicExceptionRanges,
17613              Expr *NoexceptExpr) {
17614   if (!MethodD)
17615     return;
17616 
17617   // Dig out the method we're referring to.
17618   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17619     MethodD = FunTmpl->getTemplatedDecl();
17620 
17621   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17622   if (!Method)
17623     return;
17624 
17625   // Check the exception specification.
17626   llvm::SmallVector<QualType, 4> Exceptions;
17627   FunctionProtoType::ExceptionSpecInfo ESI;
17628   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17629                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17630                               ESI);
17631 
17632   // Update the exception specification on the function type.
17633   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17634 
17635   if (Method->isStatic())
17636     checkThisInStaticMemberFunctionExceptionSpec(Method);
17637 
17638   if (Method->isVirtual()) {
17639     // Check overrides, which we previously had to delay.
17640     for (const CXXMethodDecl *O : Method->overridden_methods())
17641       CheckOverridingFunctionExceptionSpec(Method, O);
17642   }
17643 }
17644 
17645 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17646 ///
17647 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17648                                        SourceLocation DeclStart, Declarator &D,
17649                                        Expr *BitWidth,
17650                                        InClassInitStyle InitStyle,
17651                                        AccessSpecifier AS,
17652                                        const ParsedAttr &MSPropertyAttr) {
17653   IdentifierInfo *II = D.getIdentifier();
17654   if (!II) {
17655     Diag(DeclStart, diag::err_anonymous_property);
17656     return nullptr;
17657   }
17658   SourceLocation Loc = D.getIdentifierLoc();
17659 
17660   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17661   QualType T = TInfo->getType();
17662   if (getLangOpts().CPlusPlus) {
17663     CheckExtraCXXDefaultArguments(D);
17664 
17665     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17666                                         UPPC_DataMemberType)) {
17667       D.setInvalidType();
17668       T = Context.IntTy;
17669       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17670     }
17671   }
17672 
17673   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17674 
17675   if (D.getDeclSpec().isInlineSpecified())
17676     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17677         << getLangOpts().CPlusPlus17;
17678   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17679     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17680          diag::err_invalid_thread)
17681       << DeclSpec::getSpecifierName(TSCS);
17682 
17683   // Check to see if this name was declared as a member previously
17684   NamedDecl *PrevDecl = nullptr;
17685   LookupResult Previous(*this, II, Loc, LookupMemberName,
17686                         ForVisibleRedeclaration);
17687   LookupName(Previous, S);
17688   switch (Previous.getResultKind()) {
17689   case LookupResult::Found:
17690   case LookupResult::FoundUnresolvedValue:
17691     PrevDecl = Previous.getAsSingle<NamedDecl>();
17692     break;
17693 
17694   case LookupResult::FoundOverloaded:
17695     PrevDecl = Previous.getRepresentativeDecl();
17696     break;
17697 
17698   case LookupResult::NotFound:
17699   case LookupResult::NotFoundInCurrentInstantiation:
17700   case LookupResult::Ambiguous:
17701     break;
17702   }
17703 
17704   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17705     // Maybe we will complain about the shadowed template parameter.
17706     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17707     // Just pretend that we didn't see the previous declaration.
17708     PrevDecl = nullptr;
17709   }
17710 
17711   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17712     PrevDecl = nullptr;
17713 
17714   SourceLocation TSSL = D.getBeginLoc();
17715   MSPropertyDecl *NewPD =
17716       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17717                              MSPropertyAttr.getPropertyDataGetter(),
17718                              MSPropertyAttr.getPropertyDataSetter());
17719   ProcessDeclAttributes(TUScope, NewPD, D);
17720   NewPD->setAccess(AS);
17721 
17722   if (NewPD->isInvalidDecl())
17723     Record->setInvalidDecl();
17724 
17725   if (D.getDeclSpec().isModulePrivateSpecified())
17726     NewPD->setModulePrivate();
17727 
17728   if (NewPD->isInvalidDecl() && PrevDecl) {
17729     // Don't introduce NewFD into scope; there's already something
17730     // with the same name in the same scope.
17731   } else if (II) {
17732     PushOnScopeChains(NewPD, S);
17733   } else
17734     Record->addDecl(NewPD);
17735 
17736   return NewPD;
17737 }
17738 
17739 void Sema::ActOnStartFunctionDeclarationDeclarator(
17740     Declarator &Declarator, unsigned TemplateParameterDepth) {
17741   auto &Info = InventedParameterInfos.emplace_back();
17742   TemplateParameterList *ExplicitParams = nullptr;
17743   ArrayRef<TemplateParameterList *> ExplicitLists =
17744       Declarator.getTemplateParameterLists();
17745   if (!ExplicitLists.empty()) {
17746     bool IsMemberSpecialization, IsInvalid;
17747     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17748         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17749         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17750         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17751         /*SuppressDiagnostic=*/true);
17752   }
17753   if (ExplicitParams) {
17754     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17755     for (NamedDecl *Param : *ExplicitParams)
17756       Info.TemplateParams.push_back(Param);
17757     Info.NumExplicitTemplateParams = ExplicitParams->size();
17758   } else {
17759     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17760     Info.NumExplicitTemplateParams = 0;
17761   }
17762 }
17763 
17764 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17765   auto &FSI = InventedParameterInfos.back();
17766   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17767     if (FSI.NumExplicitTemplateParams != 0) {
17768       TemplateParameterList *ExplicitParams =
17769           Declarator.getTemplateParameterLists().back();
17770       Declarator.setInventedTemplateParameterList(
17771           TemplateParameterList::Create(
17772               Context, ExplicitParams->getTemplateLoc(),
17773               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17774               ExplicitParams->getRAngleLoc(),
17775               ExplicitParams->getRequiresClause()));
17776     } else {
17777       Declarator.setInventedTemplateParameterList(
17778           TemplateParameterList::Create(
17779               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17780               SourceLocation(), /*RequiresClause=*/nullptr));
17781     }
17782   }
17783   InventedParameterInfos.pop_back();
17784 }
17785