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 the type is dependent, then assume it might have
9723     // implicit copy or move ctor because we won't know yet at this point.
9724     if (RD.isDependentType())
9725       return true;
9726     if (RD.needsImplicitCopyConstructor() &&
9727         !RD.defaultedCopyConstructorIsDeleted())
9728       return true;
9729     if (RD.needsImplicitMoveConstructor() &&
9730         !RD.defaultedMoveConstructorIsDeleted())
9731       return true;
9732     for (const CXXConstructorDecl *CD : RD.ctors())
9733       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9734         return true;
9735     return false;
9736   };
9737 
9738   if (!HasNonDeletedCopyOrMoveConstructor()) {
9739     PrintDiagAndRemoveAttr(0);
9740     return;
9741   }
9742 
9743   // Ill-formed if the struct has virtual functions.
9744   if (RD.isPolymorphic()) {
9745     PrintDiagAndRemoveAttr(1);
9746     return;
9747   }
9748 
9749   for (const auto &B : RD.bases()) {
9750     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9751     // virtual base.
9752     if (!B.getType()->isDependentType() &&
9753         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9754       PrintDiagAndRemoveAttr(2);
9755       return;
9756     }
9757 
9758     if (B.isVirtual()) {
9759       PrintDiagAndRemoveAttr(3);
9760       return;
9761     }
9762   }
9763 
9764   for (const auto *FD : RD.fields()) {
9765     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9766     // non-trivial for the purpose of calls.
9767     QualType FT = FD->getType();
9768     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9769       PrintDiagAndRemoveAttr(4);
9770       return;
9771     }
9772 
9773     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9774       if (!RT->isDependentType() &&
9775           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9776         PrintDiagAndRemoveAttr(5);
9777         return;
9778       }
9779   }
9780 }
9781 
9782 void Sema::ActOnFinishCXXMemberSpecification(
9783     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9784     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9785   if (!TagDecl)
9786     return;
9787 
9788   AdjustDeclIfTemplate(TagDecl);
9789 
9790   for (const ParsedAttr &AL : AttrList) {
9791     if (AL.getKind() != ParsedAttr::AT_Visibility)
9792       continue;
9793     AL.setInvalid();
9794     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9795   }
9796 
9797   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9798               // strict aliasing violation!
9799               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9800               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9801 
9802   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9803 }
9804 
9805 /// Find the equality comparison functions that should be implicitly declared
9806 /// in a given class definition, per C++2a [class.compare.default]p3.
9807 static void findImplicitlyDeclaredEqualityComparisons(
9808     ASTContext &Ctx, CXXRecordDecl *RD,
9809     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9810   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9811   if (!RD->lookup(EqEq).empty())
9812     // Member operator== explicitly declared: no implicit operator==s.
9813     return;
9814 
9815   // Traverse friends looking for an '==' or a '<=>'.
9816   for (FriendDecl *Friend : RD->friends()) {
9817     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9818     if (!FD) continue;
9819 
9820     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9821       // Friend operator== explicitly declared: no implicit operator==s.
9822       Spaceships.clear();
9823       return;
9824     }
9825 
9826     if (FD->getOverloadedOperator() == OO_Spaceship &&
9827         FD->isExplicitlyDefaulted())
9828       Spaceships.push_back(FD);
9829   }
9830 
9831   // Look for members named 'operator<=>'.
9832   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9833   for (NamedDecl *ND : RD->lookup(Cmp)) {
9834     // Note that we could find a non-function here (either a function template
9835     // or a using-declaration). Neither case results in an implicit
9836     // 'operator=='.
9837     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9838       if (FD->isExplicitlyDefaulted())
9839         Spaceships.push_back(FD);
9840   }
9841 }
9842 
9843 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9844 /// special functions, such as the default constructor, copy
9845 /// constructor, or destructor, to the given C++ class (C++
9846 /// [special]p1).  This routine can only be executed just before the
9847 /// definition of the class is complete.
9848 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9849   // Don't add implicit special members to templated classes.
9850   // FIXME: This means unqualified lookups for 'operator=' within a class
9851   // template don't work properly.
9852   if (!ClassDecl->isDependentType()) {
9853     if (ClassDecl->needsImplicitDefaultConstructor()) {
9854       ++getASTContext().NumImplicitDefaultConstructors;
9855 
9856       if (ClassDecl->hasInheritedConstructor())
9857         DeclareImplicitDefaultConstructor(ClassDecl);
9858     }
9859 
9860     if (ClassDecl->needsImplicitCopyConstructor()) {
9861       ++getASTContext().NumImplicitCopyConstructors;
9862 
9863       // If the properties or semantics of the copy constructor couldn't be
9864       // determined while the class was being declared, force a declaration
9865       // of it now.
9866       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9867           ClassDecl->hasInheritedConstructor())
9868         DeclareImplicitCopyConstructor(ClassDecl);
9869       // For the MS ABI we need to know whether the copy ctor is deleted. A
9870       // prerequisite for deleting the implicit copy ctor is that the class has
9871       // a move ctor or move assignment that is either user-declared or whose
9872       // semantics are inherited from a subobject. FIXME: We should provide a
9873       // more direct way for CodeGen to ask whether the constructor was deleted.
9874       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9875                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9876                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9877                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9878                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9879         DeclareImplicitCopyConstructor(ClassDecl);
9880     }
9881 
9882     if (getLangOpts().CPlusPlus11 &&
9883         ClassDecl->needsImplicitMoveConstructor()) {
9884       ++getASTContext().NumImplicitMoveConstructors;
9885 
9886       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9887           ClassDecl->hasInheritedConstructor())
9888         DeclareImplicitMoveConstructor(ClassDecl);
9889     }
9890 
9891     if (ClassDecl->needsImplicitCopyAssignment()) {
9892       ++getASTContext().NumImplicitCopyAssignmentOperators;
9893 
9894       // If we have a dynamic class, then the copy assignment operator may be
9895       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9896       // it shows up in the right place in the vtable and that we diagnose
9897       // problems with the implicit exception specification.
9898       if (ClassDecl->isDynamicClass() ||
9899           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9900           ClassDecl->hasInheritedAssignment())
9901         DeclareImplicitCopyAssignment(ClassDecl);
9902     }
9903 
9904     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9905       ++getASTContext().NumImplicitMoveAssignmentOperators;
9906 
9907       // Likewise for the move assignment operator.
9908       if (ClassDecl->isDynamicClass() ||
9909           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9910           ClassDecl->hasInheritedAssignment())
9911         DeclareImplicitMoveAssignment(ClassDecl);
9912     }
9913 
9914     if (ClassDecl->needsImplicitDestructor()) {
9915       ++getASTContext().NumImplicitDestructors;
9916 
9917       // If we have a dynamic class, then the destructor may be virtual, so we
9918       // have to declare the destructor immediately. This ensures that, e.g., it
9919       // shows up in the right place in the vtable and that we diagnose problems
9920       // with the implicit exception specification.
9921       if (ClassDecl->isDynamicClass() ||
9922           ClassDecl->needsOverloadResolutionForDestructor())
9923         DeclareImplicitDestructor(ClassDecl);
9924     }
9925   }
9926 
9927   // C++2a [class.compare.default]p3:
9928   //   If the member-specification does not explicitly declare any member or
9929   //   friend named operator==, an == operator function is declared implicitly
9930   //   for each defaulted three-way comparison operator function defined in
9931   //   the member-specification
9932   // FIXME: Consider doing this lazily.
9933   // We do this during the initial parse for a class template, not during
9934   // instantiation, so that we can handle unqualified lookups for 'operator=='
9935   // when parsing the template.
9936   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9937     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9938     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9939                                               DefaultedSpaceships);
9940     for (auto *FD : DefaultedSpaceships)
9941       DeclareImplicitEqualityComparison(ClassDecl, FD);
9942   }
9943 }
9944 
9945 unsigned
9946 Sema::ActOnReenterTemplateScope(Decl *D,
9947                                 llvm::function_ref<Scope *()> EnterScope) {
9948   if (!D)
9949     return 0;
9950   AdjustDeclIfTemplate(D);
9951 
9952   // In order to get name lookup right, reenter template scopes in order from
9953   // outermost to innermost.
9954   SmallVector<TemplateParameterList *, 4> ParameterLists;
9955   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9956 
9957   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9958     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9959       ParameterLists.push_back(DD->getTemplateParameterList(i));
9960 
9961     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9962       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9963         ParameterLists.push_back(FTD->getTemplateParameters());
9964     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9965       LookupDC = VD->getDeclContext();
9966 
9967       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9968         ParameterLists.push_back(VTD->getTemplateParameters());
9969       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9970         ParameterLists.push_back(PSD->getTemplateParameters());
9971     }
9972   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9973     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9974       ParameterLists.push_back(TD->getTemplateParameterList(i));
9975 
9976     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9977       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9978         ParameterLists.push_back(CTD->getTemplateParameters());
9979       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9980         ParameterLists.push_back(PSD->getTemplateParameters());
9981     }
9982   }
9983   // FIXME: Alias declarations and concepts.
9984 
9985   unsigned Count = 0;
9986   Scope *InnermostTemplateScope = nullptr;
9987   for (TemplateParameterList *Params : ParameterLists) {
9988     // Ignore explicit specializations; they don't contribute to the template
9989     // depth.
9990     if (Params->size() == 0)
9991       continue;
9992 
9993     InnermostTemplateScope = EnterScope();
9994     for (NamedDecl *Param : *Params) {
9995       if (Param->getDeclName()) {
9996         InnermostTemplateScope->AddDecl(Param);
9997         IdResolver.AddDecl(Param);
9998       }
9999     }
10000     ++Count;
10001   }
10002 
10003   // Associate the new template scopes with the corresponding entities.
10004   if (InnermostTemplateScope) {
10005     assert(LookupDC && "no enclosing DeclContext for template lookup");
10006     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10007   }
10008 
10009   return Count;
10010 }
10011 
10012 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10013   if (!RecordD) return;
10014   AdjustDeclIfTemplate(RecordD);
10015   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10016   PushDeclContext(S, Record);
10017 }
10018 
10019 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10020   if (!RecordD) return;
10021   PopDeclContext();
10022 }
10023 
10024 /// This is used to implement the constant expression evaluation part of the
10025 /// attribute enable_if extension. There is nothing in standard C++ which would
10026 /// require reentering parameters.
10027 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10028   if (!Param)
10029     return;
10030 
10031   S->AddDecl(Param);
10032   if (Param->getDeclName())
10033     IdResolver.AddDecl(Param);
10034 }
10035 
10036 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10037 /// parsing a top-level (non-nested) C++ class, and we are now
10038 /// parsing those parts of the given Method declaration that could
10039 /// not be parsed earlier (C++ [class.mem]p2), such as default
10040 /// arguments. This action should enter the scope of the given
10041 /// Method declaration as if we had just parsed the qualified method
10042 /// name. However, it should not bring the parameters into scope;
10043 /// that will be performed by ActOnDelayedCXXMethodParameter.
10044 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10045 }
10046 
10047 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10048 /// C++ method declaration. We're (re-)introducing the given
10049 /// function parameter into scope for use in parsing later parts of
10050 /// the method declaration. For example, we could see an
10051 /// ActOnParamDefaultArgument event for this parameter.
10052 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10053   if (!ParamD)
10054     return;
10055 
10056   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10057 
10058   S->AddDecl(Param);
10059   if (Param->getDeclName())
10060     IdResolver.AddDecl(Param);
10061 }
10062 
10063 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10064 /// processing the delayed method declaration for Method. The method
10065 /// declaration is now considered finished. There may be a separate
10066 /// ActOnStartOfFunctionDef action later (not necessarily
10067 /// immediately!) for this method, if it was also defined inside the
10068 /// class body.
10069 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10070   if (!MethodD)
10071     return;
10072 
10073   AdjustDeclIfTemplate(MethodD);
10074 
10075   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10076 
10077   // Now that we have our default arguments, check the constructor
10078   // again. It could produce additional diagnostics or affect whether
10079   // the class has implicitly-declared destructors, among other
10080   // things.
10081   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10082     CheckConstructor(Constructor);
10083 
10084   // Check the default arguments, which we may have added.
10085   if (!Method->isInvalidDecl())
10086     CheckCXXDefaultArguments(Method);
10087 }
10088 
10089 // Emit the given diagnostic for each non-address-space qualifier.
10090 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10091 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10092   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10093   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10094     bool DiagOccured = false;
10095     FTI.MethodQualifiers->forEachQualifier(
10096         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10097                                    SourceLocation SL) {
10098           // This diagnostic should be emitted on any qualifier except an addr
10099           // space qualifier. However, forEachQualifier currently doesn't visit
10100           // addr space qualifiers, so there's no way to write this condition
10101           // right now; we just diagnose on everything.
10102           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10103           DiagOccured = true;
10104         });
10105     if (DiagOccured)
10106       D.setInvalidType();
10107   }
10108 }
10109 
10110 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10111 /// the well-formedness of the constructor declarator @p D with type @p
10112 /// R. If there are any errors in the declarator, this routine will
10113 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10114 /// will be updated to reflect a well-formed type for the constructor and
10115 /// returned.
10116 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10117                                           StorageClass &SC) {
10118   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10119 
10120   // C++ [class.ctor]p3:
10121   //   A constructor shall not be virtual (10.3) or static (9.4). A
10122   //   constructor can be invoked for a const, volatile or const
10123   //   volatile object. A constructor shall not be declared const,
10124   //   volatile, or const volatile (9.3.2).
10125   if (isVirtual) {
10126     if (!D.isInvalidType())
10127       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10128         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10129         << SourceRange(D.getIdentifierLoc());
10130     D.setInvalidType();
10131   }
10132   if (SC == SC_Static) {
10133     if (!D.isInvalidType())
10134       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10135         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10136         << SourceRange(D.getIdentifierLoc());
10137     D.setInvalidType();
10138     SC = SC_None;
10139   }
10140 
10141   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10142     diagnoseIgnoredQualifiers(
10143         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10144         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10145         D.getDeclSpec().getRestrictSpecLoc(),
10146         D.getDeclSpec().getAtomicSpecLoc());
10147     D.setInvalidType();
10148   }
10149 
10150   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10151 
10152   // C++0x [class.ctor]p4:
10153   //   A constructor shall not be declared with a ref-qualifier.
10154   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10155   if (FTI.hasRefQualifier()) {
10156     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10157       << FTI.RefQualifierIsLValueRef
10158       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10159     D.setInvalidType();
10160   }
10161 
10162   // Rebuild the function type "R" without any type qualifiers (in
10163   // case any of the errors above fired) and with "void" as the
10164   // return type, since constructors don't have return types.
10165   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10166   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10167     return R;
10168 
10169   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10170   EPI.TypeQuals = Qualifiers();
10171   EPI.RefQualifier = RQ_None;
10172 
10173   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10174 }
10175 
10176 /// CheckConstructor - Checks a fully-formed constructor for
10177 /// well-formedness, issuing any diagnostics required. Returns true if
10178 /// the constructor declarator is invalid.
10179 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10180   CXXRecordDecl *ClassDecl
10181     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10182   if (!ClassDecl)
10183     return Constructor->setInvalidDecl();
10184 
10185   // C++ [class.copy]p3:
10186   //   A declaration of a constructor for a class X is ill-formed if
10187   //   its first parameter is of type (optionally cv-qualified) X and
10188   //   either there are no other parameters or else all other
10189   //   parameters have default arguments.
10190   if (!Constructor->isInvalidDecl() &&
10191       Constructor->hasOneParamOrDefaultArgs() &&
10192       Constructor->getTemplateSpecializationKind() !=
10193           TSK_ImplicitInstantiation) {
10194     QualType ParamType = Constructor->getParamDecl(0)->getType();
10195     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10196     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10197       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10198       const char *ConstRef
10199         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10200                                                         : " const &";
10201       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10202         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10203 
10204       // FIXME: Rather that making the constructor invalid, we should endeavor
10205       // to fix the type.
10206       Constructor->setInvalidDecl();
10207     }
10208   }
10209 }
10210 
10211 /// CheckDestructor - Checks a fully-formed destructor definition for
10212 /// well-formedness, issuing any diagnostics required.  Returns true
10213 /// on error.
10214 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10215   CXXRecordDecl *RD = Destructor->getParent();
10216 
10217   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10218     SourceLocation Loc;
10219 
10220     if (!Destructor->isImplicit())
10221       Loc = Destructor->getLocation();
10222     else
10223       Loc = RD->getLocation();
10224 
10225     // If we have a virtual destructor, look up the deallocation function
10226     if (FunctionDecl *OperatorDelete =
10227             FindDeallocationFunctionForDestructor(Loc, RD)) {
10228       Expr *ThisArg = nullptr;
10229 
10230       // If the notional 'delete this' expression requires a non-trivial
10231       // conversion from 'this' to the type of a destroying operator delete's
10232       // first parameter, perform that conversion now.
10233       if (OperatorDelete->isDestroyingOperatorDelete()) {
10234         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10235         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10236           // C++ [class.dtor]p13:
10237           //   ... as if for the expression 'delete this' appearing in a
10238           //   non-virtual destructor of the destructor's class.
10239           ContextRAII SwitchContext(*this, Destructor);
10240           ExprResult This =
10241               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10242           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10243           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10244           if (This.isInvalid()) {
10245             // FIXME: Register this as a context note so that it comes out
10246             // in the right order.
10247             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10248             return true;
10249           }
10250           ThisArg = This.get();
10251         }
10252       }
10253 
10254       DiagnoseUseOfDecl(OperatorDelete, Loc);
10255       MarkFunctionReferenced(Loc, OperatorDelete);
10256       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10257     }
10258   }
10259 
10260   return false;
10261 }
10262 
10263 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10264 /// the well-formednes of the destructor declarator @p D with type @p
10265 /// R. If there are any errors in the declarator, this routine will
10266 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10267 /// will be updated to reflect a well-formed type for the destructor and
10268 /// returned.
10269 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10270                                          StorageClass& SC) {
10271   // C++ [class.dtor]p1:
10272   //   [...] A typedef-name that names a class is a class-name
10273   //   (7.1.3); however, a typedef-name that names a class shall not
10274   //   be used as the identifier in the declarator for a destructor
10275   //   declaration.
10276   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10277   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10278     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10279       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10280   else if (const TemplateSpecializationType *TST =
10281              DeclaratorType->getAs<TemplateSpecializationType>())
10282     if (TST->isTypeAlias())
10283       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10284         << DeclaratorType << 1;
10285 
10286   // C++ [class.dtor]p2:
10287   //   A destructor is used to destroy objects of its class type. A
10288   //   destructor takes no parameters, and no return type can be
10289   //   specified for it (not even void). The address of a destructor
10290   //   shall not be taken. A destructor shall not be static. A
10291   //   destructor can be invoked for a const, volatile or const
10292   //   volatile object. A destructor shall not be declared const,
10293   //   volatile or const volatile (9.3.2).
10294   if (SC == SC_Static) {
10295     if (!D.isInvalidType())
10296       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10297         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10298         << SourceRange(D.getIdentifierLoc())
10299         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10300 
10301     SC = SC_None;
10302   }
10303   if (!D.isInvalidType()) {
10304     // Destructors don't have return types, but the parser will
10305     // happily parse something like:
10306     //
10307     //   class X {
10308     //     float ~X();
10309     //   };
10310     //
10311     // The return type will be eliminated later.
10312     if (D.getDeclSpec().hasTypeSpecifier())
10313       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10314         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10315         << SourceRange(D.getIdentifierLoc());
10316     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10317       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10318                                 SourceLocation(),
10319                                 D.getDeclSpec().getConstSpecLoc(),
10320                                 D.getDeclSpec().getVolatileSpecLoc(),
10321                                 D.getDeclSpec().getRestrictSpecLoc(),
10322                                 D.getDeclSpec().getAtomicSpecLoc());
10323       D.setInvalidType();
10324     }
10325   }
10326 
10327   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10328 
10329   // C++0x [class.dtor]p2:
10330   //   A destructor shall not be declared with a ref-qualifier.
10331   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10332   if (FTI.hasRefQualifier()) {
10333     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10334       << FTI.RefQualifierIsLValueRef
10335       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10336     D.setInvalidType();
10337   }
10338 
10339   // Make sure we don't have any parameters.
10340   if (FTIHasNonVoidParameters(FTI)) {
10341     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10342 
10343     // Delete the parameters.
10344     FTI.freeParams();
10345     D.setInvalidType();
10346   }
10347 
10348   // Make sure the destructor isn't variadic.
10349   if (FTI.isVariadic) {
10350     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10351     D.setInvalidType();
10352   }
10353 
10354   // Rebuild the function type "R" without any type qualifiers or
10355   // parameters (in case any of the errors above fired) and with
10356   // "void" as the return type, since destructors don't have return
10357   // types.
10358   if (!D.isInvalidType())
10359     return R;
10360 
10361   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10362   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10363   EPI.Variadic = false;
10364   EPI.TypeQuals = Qualifiers();
10365   EPI.RefQualifier = RQ_None;
10366   return Context.getFunctionType(Context.VoidTy, None, EPI);
10367 }
10368 
10369 static void extendLeft(SourceRange &R, SourceRange Before) {
10370   if (Before.isInvalid())
10371     return;
10372   R.setBegin(Before.getBegin());
10373   if (R.getEnd().isInvalid())
10374     R.setEnd(Before.getEnd());
10375 }
10376 
10377 static void extendRight(SourceRange &R, SourceRange After) {
10378   if (After.isInvalid())
10379     return;
10380   if (R.getBegin().isInvalid())
10381     R.setBegin(After.getBegin());
10382   R.setEnd(After.getEnd());
10383 }
10384 
10385 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10386 /// well-formednes of the conversion function declarator @p D with
10387 /// type @p R. If there are any errors in the declarator, this routine
10388 /// will emit diagnostics and return true. Otherwise, it will return
10389 /// false. Either way, the type @p R will be updated to reflect a
10390 /// well-formed type for the conversion operator.
10391 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10392                                      StorageClass& SC) {
10393   // C++ [class.conv.fct]p1:
10394   //   Neither parameter types nor return type can be specified. The
10395   //   type of a conversion function (8.3.5) is "function taking no
10396   //   parameter returning conversion-type-id."
10397   if (SC == SC_Static) {
10398     if (!D.isInvalidType())
10399       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10400         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10401         << D.getName().getSourceRange();
10402     D.setInvalidType();
10403     SC = SC_None;
10404   }
10405 
10406   TypeSourceInfo *ConvTSI = nullptr;
10407   QualType ConvType =
10408       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10409 
10410   const DeclSpec &DS = D.getDeclSpec();
10411   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10412     // Conversion functions don't have return types, but the parser will
10413     // happily parse something like:
10414     //
10415     //   class X {
10416     //     float operator bool();
10417     //   };
10418     //
10419     // The return type will be changed later anyway.
10420     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10421       << SourceRange(DS.getTypeSpecTypeLoc())
10422       << SourceRange(D.getIdentifierLoc());
10423     D.setInvalidType();
10424   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10425     // It's also plausible that the user writes type qualifiers in the wrong
10426     // place, such as:
10427     //   struct S { const operator int(); };
10428     // FIXME: we could provide a fixit to move the qualifiers onto the
10429     // conversion type.
10430     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10431         << SourceRange(D.getIdentifierLoc()) << 0;
10432     D.setInvalidType();
10433   }
10434 
10435   const auto *Proto = R->castAs<FunctionProtoType>();
10436 
10437   // Make sure we don't have any parameters.
10438   if (Proto->getNumParams() > 0) {
10439     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10440 
10441     // Delete the parameters.
10442     D.getFunctionTypeInfo().freeParams();
10443     D.setInvalidType();
10444   } else if (Proto->isVariadic()) {
10445     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10446     D.setInvalidType();
10447   }
10448 
10449   // Diagnose "&operator bool()" and other such nonsense.  This
10450   // is actually a gcc extension which we don't support.
10451   if (Proto->getReturnType() != ConvType) {
10452     bool NeedsTypedef = false;
10453     SourceRange Before, After;
10454 
10455     // Walk the chunks and extract information on them for our diagnostic.
10456     bool PastFunctionChunk = false;
10457     for (auto &Chunk : D.type_objects()) {
10458       switch (Chunk.Kind) {
10459       case DeclaratorChunk::Function:
10460         if (!PastFunctionChunk) {
10461           if (Chunk.Fun.HasTrailingReturnType) {
10462             TypeSourceInfo *TRT = nullptr;
10463             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10464             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10465           }
10466           PastFunctionChunk = true;
10467           break;
10468         }
10469         LLVM_FALLTHROUGH;
10470       case DeclaratorChunk::Array:
10471         NeedsTypedef = true;
10472         extendRight(After, Chunk.getSourceRange());
10473         break;
10474 
10475       case DeclaratorChunk::Pointer:
10476       case DeclaratorChunk::BlockPointer:
10477       case DeclaratorChunk::Reference:
10478       case DeclaratorChunk::MemberPointer:
10479       case DeclaratorChunk::Pipe:
10480         extendLeft(Before, Chunk.getSourceRange());
10481         break;
10482 
10483       case DeclaratorChunk::Paren:
10484         extendLeft(Before, Chunk.Loc);
10485         extendRight(After, Chunk.EndLoc);
10486         break;
10487       }
10488     }
10489 
10490     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10491                          After.isValid()  ? After.getBegin() :
10492                                             D.getIdentifierLoc();
10493     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10494     DB << Before << After;
10495 
10496     if (!NeedsTypedef) {
10497       DB << /*don't need a typedef*/0;
10498 
10499       // If we can provide a correct fix-it hint, do so.
10500       if (After.isInvalid() && ConvTSI) {
10501         SourceLocation InsertLoc =
10502             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10503         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10504            << FixItHint::CreateInsertionFromRange(
10505                   InsertLoc, CharSourceRange::getTokenRange(Before))
10506            << FixItHint::CreateRemoval(Before);
10507       }
10508     } else if (!Proto->getReturnType()->isDependentType()) {
10509       DB << /*typedef*/1 << Proto->getReturnType();
10510     } else if (getLangOpts().CPlusPlus11) {
10511       DB << /*alias template*/2 << Proto->getReturnType();
10512     } else {
10513       DB << /*might not be fixable*/3;
10514     }
10515 
10516     // Recover by incorporating the other type chunks into the result type.
10517     // Note, this does *not* change the name of the function. This is compatible
10518     // with the GCC extension:
10519     //   struct S { &operator int(); } s;
10520     //   int &r = s.operator int(); // ok in GCC
10521     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10522     ConvType = Proto->getReturnType();
10523   }
10524 
10525   // C++ [class.conv.fct]p4:
10526   //   The conversion-type-id shall not represent a function type nor
10527   //   an array type.
10528   if (ConvType->isArrayType()) {
10529     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10530     ConvType = Context.getPointerType(ConvType);
10531     D.setInvalidType();
10532   } else if (ConvType->isFunctionType()) {
10533     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10534     ConvType = Context.getPointerType(ConvType);
10535     D.setInvalidType();
10536   }
10537 
10538   // Rebuild the function type "R" without any parameters (in case any
10539   // of the errors above fired) and with the conversion type as the
10540   // return type.
10541   if (D.isInvalidType())
10542     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10543 
10544   // C++0x explicit conversion operators.
10545   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10546     Diag(DS.getExplicitSpecLoc(),
10547          getLangOpts().CPlusPlus11
10548              ? diag::warn_cxx98_compat_explicit_conversion_functions
10549              : diag::ext_explicit_conversion_functions)
10550         << SourceRange(DS.getExplicitSpecRange());
10551 }
10552 
10553 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10554 /// the declaration of the given C++ conversion function. This routine
10555 /// is responsible for recording the conversion function in the C++
10556 /// class, if possible.
10557 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10558   assert(Conversion && "Expected to receive a conversion function declaration");
10559 
10560   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10561 
10562   // Make sure we aren't redeclaring the conversion function.
10563   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10564   // C++ [class.conv.fct]p1:
10565   //   [...] A conversion function is never used to convert a
10566   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10567   //   same object type (or a reference to it), to a (possibly
10568   //   cv-qualified) base class of that type (or a reference to it),
10569   //   or to (possibly cv-qualified) void.
10570   QualType ClassType
10571     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10572   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10573     ConvType = ConvTypeRef->getPointeeType();
10574   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10575       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10576     /* Suppress diagnostics for instantiations. */;
10577   else if (Conversion->size_overridden_methods() != 0)
10578     /* Suppress diagnostics for overriding virtual function in a base class. */;
10579   else if (ConvType->isRecordType()) {
10580     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10581     if (ConvType == ClassType)
10582       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10583         << ClassType;
10584     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10585       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10586         <<  ClassType << ConvType;
10587   } else if (ConvType->isVoidType()) {
10588     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10589       << ClassType << ConvType;
10590   }
10591 
10592   if (FunctionTemplateDecl *ConversionTemplate
10593                                 = Conversion->getDescribedFunctionTemplate())
10594     return ConversionTemplate;
10595 
10596   return Conversion;
10597 }
10598 
10599 namespace {
10600 /// Utility class to accumulate and print a diagnostic listing the invalid
10601 /// specifier(s) on a declaration.
10602 struct BadSpecifierDiagnoser {
10603   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10604       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10605   ~BadSpecifierDiagnoser() {
10606     Diagnostic << Specifiers;
10607   }
10608 
10609   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10610     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10611   }
10612   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10613     return check(SpecLoc,
10614                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10615   }
10616   void check(SourceLocation SpecLoc, const char *Spec) {
10617     if (SpecLoc.isInvalid()) return;
10618     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10619     if (!Specifiers.empty()) Specifiers += " ";
10620     Specifiers += Spec;
10621   }
10622 
10623   Sema &S;
10624   Sema::SemaDiagnosticBuilder Diagnostic;
10625   std::string Specifiers;
10626 };
10627 }
10628 
10629 /// Check the validity of a declarator that we parsed for a deduction-guide.
10630 /// These aren't actually declarators in the grammar, so we need to check that
10631 /// the user didn't specify any pieces that are not part of the deduction-guide
10632 /// grammar.
10633 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10634                                          StorageClass &SC) {
10635   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10636   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10637   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10638 
10639   // C++ [temp.deduct.guide]p3:
10640   //   A deduction-gide shall be declared in the same scope as the
10641   //   corresponding class template.
10642   if (!CurContext->getRedeclContext()->Equals(
10643           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10644     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10645       << GuidedTemplateDecl;
10646     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10647   }
10648 
10649   auto &DS = D.getMutableDeclSpec();
10650   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10651   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10652       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10653       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10654     BadSpecifierDiagnoser Diagnoser(
10655         *this, D.getIdentifierLoc(),
10656         diag::err_deduction_guide_invalid_specifier);
10657 
10658     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10659     DS.ClearStorageClassSpecs();
10660     SC = SC_None;
10661 
10662     // 'explicit' is permitted.
10663     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10664     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10665     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10666     DS.ClearConstexprSpec();
10667 
10668     Diagnoser.check(DS.getConstSpecLoc(), "const");
10669     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10670     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10671     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10672     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10673     DS.ClearTypeQualifiers();
10674 
10675     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10676     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10677     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10678     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10679     DS.ClearTypeSpecType();
10680   }
10681 
10682   if (D.isInvalidType())
10683     return;
10684 
10685   // Check the declarator is simple enough.
10686   bool FoundFunction = false;
10687   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10688     if (Chunk.Kind == DeclaratorChunk::Paren)
10689       continue;
10690     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10691       Diag(D.getDeclSpec().getBeginLoc(),
10692            diag::err_deduction_guide_with_complex_decl)
10693           << D.getSourceRange();
10694       break;
10695     }
10696     if (!Chunk.Fun.hasTrailingReturnType()) {
10697       Diag(D.getName().getBeginLoc(),
10698            diag::err_deduction_guide_no_trailing_return_type);
10699       break;
10700     }
10701 
10702     // Check that the return type is written as a specialization of
10703     // the template specified as the deduction-guide's name.
10704     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10705     TypeSourceInfo *TSI = nullptr;
10706     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10707     assert(TSI && "deduction guide has valid type but invalid return type?");
10708     bool AcceptableReturnType = false;
10709     bool MightInstantiateToSpecialization = false;
10710     if (auto RetTST =
10711             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10712       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10713       bool TemplateMatches =
10714           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10715       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10716         AcceptableReturnType = true;
10717       else {
10718         // This could still instantiate to the right type, unless we know it
10719         // names the wrong class template.
10720         auto *TD = SpecifiedName.getAsTemplateDecl();
10721         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10722                                              !TemplateMatches);
10723       }
10724     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10725       MightInstantiateToSpecialization = true;
10726     }
10727 
10728     if (!AcceptableReturnType) {
10729       Diag(TSI->getTypeLoc().getBeginLoc(),
10730            diag::err_deduction_guide_bad_trailing_return_type)
10731           << GuidedTemplate << TSI->getType()
10732           << MightInstantiateToSpecialization
10733           << TSI->getTypeLoc().getSourceRange();
10734     }
10735 
10736     // Keep going to check that we don't have any inner declarator pieces (we
10737     // could still have a function returning a pointer to a function).
10738     FoundFunction = true;
10739   }
10740 
10741   if (D.isFunctionDefinition())
10742     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10743 }
10744 
10745 //===----------------------------------------------------------------------===//
10746 // Namespace Handling
10747 //===----------------------------------------------------------------------===//
10748 
10749 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10750 /// reopened.
10751 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10752                                             SourceLocation Loc,
10753                                             IdentifierInfo *II, bool *IsInline,
10754                                             NamespaceDecl *PrevNS) {
10755   assert(*IsInline != PrevNS->isInline());
10756 
10757   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10758   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10759   // inline namespaces, with the intention of bringing names into namespace std.
10760   //
10761   // We support this just well enough to get that case working; this is not
10762   // sufficient to support reopening namespaces as inline in general.
10763   if (*IsInline && II && II->getName().startswith("__atomic") &&
10764       S.getSourceManager().isInSystemHeader(Loc)) {
10765     // Mark all prior declarations of the namespace as inline.
10766     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10767          NS = NS->getPreviousDecl())
10768       NS->setInline(*IsInline);
10769     // Patch up the lookup table for the containing namespace. This isn't really
10770     // correct, but it's good enough for this particular case.
10771     for (auto *I : PrevNS->decls())
10772       if (auto *ND = dyn_cast<NamedDecl>(I))
10773         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10774     return;
10775   }
10776 
10777   if (PrevNS->isInline())
10778     // The user probably just forgot the 'inline', so suggest that it
10779     // be added back.
10780     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10781       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10782   else
10783     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10784 
10785   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10786   *IsInline = PrevNS->isInline();
10787 }
10788 
10789 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10790 /// definition.
10791 Decl *Sema::ActOnStartNamespaceDef(
10792     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10793     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10794     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10795   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10796   // For anonymous namespace, take the location of the left brace.
10797   SourceLocation Loc = II ? IdentLoc : LBrace;
10798   bool IsInline = InlineLoc.isValid();
10799   bool IsInvalid = false;
10800   bool IsStd = false;
10801   bool AddToKnown = false;
10802   Scope *DeclRegionScope = NamespcScope->getParent();
10803 
10804   NamespaceDecl *PrevNS = nullptr;
10805   if (II) {
10806     // C++ [namespace.def]p2:
10807     //   The identifier in an original-namespace-definition shall not
10808     //   have been previously defined in the declarative region in
10809     //   which the original-namespace-definition appears. The
10810     //   identifier in an original-namespace-definition is the name of
10811     //   the namespace. Subsequently in that declarative region, it is
10812     //   treated as an original-namespace-name.
10813     //
10814     // Since namespace names are unique in their scope, and we don't
10815     // look through using directives, just look for any ordinary names
10816     // as if by qualified name lookup.
10817     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10818                    ForExternalRedeclaration);
10819     LookupQualifiedName(R, CurContext->getRedeclContext());
10820     NamedDecl *PrevDecl =
10821         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10822     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10823 
10824     if (PrevNS) {
10825       // This is an extended namespace definition.
10826       if (IsInline != PrevNS->isInline())
10827         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10828                                         &IsInline, PrevNS);
10829     } else if (PrevDecl) {
10830       // This is an invalid name redefinition.
10831       Diag(Loc, diag::err_redefinition_different_kind)
10832         << II;
10833       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10834       IsInvalid = true;
10835       // Continue on to push Namespc as current DeclContext and return it.
10836     } else if (II->isStr("std") &&
10837                CurContext->getRedeclContext()->isTranslationUnit()) {
10838       // This is the first "real" definition of the namespace "std", so update
10839       // our cache of the "std" namespace to point at this definition.
10840       PrevNS = getStdNamespace();
10841       IsStd = true;
10842       AddToKnown = !IsInline;
10843     } else {
10844       // We've seen this namespace for the first time.
10845       AddToKnown = !IsInline;
10846     }
10847   } else {
10848     // Anonymous namespaces.
10849 
10850     // Determine whether the parent already has an anonymous namespace.
10851     DeclContext *Parent = CurContext->getRedeclContext();
10852     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10853       PrevNS = TU->getAnonymousNamespace();
10854     } else {
10855       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10856       PrevNS = ND->getAnonymousNamespace();
10857     }
10858 
10859     if (PrevNS && IsInline != PrevNS->isInline())
10860       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10861                                       &IsInline, PrevNS);
10862   }
10863 
10864   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10865                                                  StartLoc, Loc, II, PrevNS);
10866   if (IsInvalid)
10867     Namespc->setInvalidDecl();
10868 
10869   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10870   AddPragmaAttributes(DeclRegionScope, Namespc);
10871 
10872   // FIXME: Should we be merging attributes?
10873   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10874     PushNamespaceVisibilityAttr(Attr, Loc);
10875 
10876   if (IsStd)
10877     StdNamespace = Namespc;
10878   if (AddToKnown)
10879     KnownNamespaces[Namespc] = false;
10880 
10881   if (II) {
10882     PushOnScopeChains(Namespc, DeclRegionScope);
10883   } else {
10884     // Link the anonymous namespace into its parent.
10885     DeclContext *Parent = CurContext->getRedeclContext();
10886     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10887       TU->setAnonymousNamespace(Namespc);
10888     } else {
10889       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10890     }
10891 
10892     CurContext->addDecl(Namespc);
10893 
10894     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10895     //   behaves as if it were replaced by
10896     //     namespace unique { /* empty body */ }
10897     //     using namespace unique;
10898     //     namespace unique { namespace-body }
10899     //   where all occurrences of 'unique' in a translation unit are
10900     //   replaced by the same identifier and this identifier differs
10901     //   from all other identifiers in the entire program.
10902 
10903     // We just create the namespace with an empty name and then add an
10904     // implicit using declaration, just like the standard suggests.
10905     //
10906     // CodeGen enforces the "universally unique" aspect by giving all
10907     // declarations semantically contained within an anonymous
10908     // namespace internal linkage.
10909 
10910     if (!PrevNS) {
10911       UD = UsingDirectiveDecl::Create(Context, Parent,
10912                                       /* 'using' */ LBrace,
10913                                       /* 'namespace' */ SourceLocation(),
10914                                       /* qualifier */ NestedNameSpecifierLoc(),
10915                                       /* identifier */ SourceLocation(),
10916                                       Namespc,
10917                                       /* Ancestor */ Parent);
10918       UD->setImplicit();
10919       Parent->addDecl(UD);
10920     }
10921   }
10922 
10923   ActOnDocumentableDecl(Namespc);
10924 
10925   // Although we could have an invalid decl (i.e. the namespace name is a
10926   // redefinition), push it as current DeclContext and try to continue parsing.
10927   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10928   // for the namespace has the declarations that showed up in that particular
10929   // namespace definition.
10930   PushDeclContext(NamespcScope, Namespc);
10931   return Namespc;
10932 }
10933 
10934 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10935 /// is a namespace alias, returns the namespace it points to.
10936 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10937   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10938     return AD->getNamespace();
10939   return dyn_cast_or_null<NamespaceDecl>(D);
10940 }
10941 
10942 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10943 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10944 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10945   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10946   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10947   Namespc->setRBraceLoc(RBrace);
10948   PopDeclContext();
10949   if (Namespc->hasAttr<VisibilityAttr>())
10950     PopPragmaVisibility(true, RBrace);
10951   // If this namespace contains an export-declaration, export it now.
10952   if (DeferredExportedNamespaces.erase(Namespc))
10953     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10954 }
10955 
10956 CXXRecordDecl *Sema::getStdBadAlloc() const {
10957   return cast_or_null<CXXRecordDecl>(
10958                                   StdBadAlloc.get(Context.getExternalSource()));
10959 }
10960 
10961 EnumDecl *Sema::getStdAlignValT() const {
10962   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10963 }
10964 
10965 NamespaceDecl *Sema::getStdNamespace() const {
10966   return cast_or_null<NamespaceDecl>(
10967                                  StdNamespace.get(Context.getExternalSource()));
10968 }
10969 
10970 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10971   if (!StdExperimentalNamespaceCache) {
10972     if (auto Std = getStdNamespace()) {
10973       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10974                           SourceLocation(), LookupNamespaceName);
10975       if (!LookupQualifiedName(Result, Std) ||
10976           !(StdExperimentalNamespaceCache =
10977                 Result.getAsSingle<NamespaceDecl>()))
10978         Result.suppressDiagnostics();
10979     }
10980   }
10981   return StdExperimentalNamespaceCache;
10982 }
10983 
10984 namespace {
10985 
10986 enum UnsupportedSTLSelect {
10987   USS_InvalidMember,
10988   USS_MissingMember,
10989   USS_NonTrivial,
10990   USS_Other
10991 };
10992 
10993 struct InvalidSTLDiagnoser {
10994   Sema &S;
10995   SourceLocation Loc;
10996   QualType TyForDiags;
10997 
10998   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
10999                       const VarDecl *VD = nullptr) {
11000     {
11001       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11002                << TyForDiags << ((int)Sel);
11003       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11004         assert(!Name.empty());
11005         D << Name;
11006       }
11007     }
11008     if (Sel == USS_InvalidMember) {
11009       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11010           << VD << VD->getSourceRange();
11011     }
11012     return QualType();
11013   }
11014 };
11015 } // namespace
11016 
11017 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11018                                            SourceLocation Loc,
11019                                            ComparisonCategoryUsage Usage) {
11020   assert(getLangOpts().CPlusPlus &&
11021          "Looking for comparison category type outside of C++.");
11022 
11023   // Use an elaborated type for diagnostics which has a name containing the
11024   // prepended 'std' namespace but not any inline namespace names.
11025   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11026     auto *NNS =
11027         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11028     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11029   };
11030 
11031   // Check if we've already successfully checked the comparison category type
11032   // before. If so, skip checking it again.
11033   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11034   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11035     // The only thing we need to check is that the type has a reachable
11036     // definition in the current context.
11037     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11038       return QualType();
11039 
11040     return Info->getType();
11041   }
11042 
11043   // If lookup failed
11044   if (!Info) {
11045     std::string NameForDiags = "std::";
11046     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11047     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11048         << NameForDiags << (int)Usage;
11049     return QualType();
11050   }
11051 
11052   assert(Info->Kind == Kind);
11053   assert(Info->Record);
11054 
11055   // Update the Record decl in case we encountered a forward declaration on our
11056   // first pass. FIXME: This is a bit of a hack.
11057   if (Info->Record->hasDefinition())
11058     Info->Record = Info->Record->getDefinition();
11059 
11060   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11061     return QualType();
11062 
11063   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11064 
11065   if (!Info->Record->isTriviallyCopyable())
11066     return UnsupportedSTLError(USS_NonTrivial);
11067 
11068   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11069     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11070     // Tolerate empty base classes.
11071     if (Base->isEmpty())
11072       continue;
11073     // Reject STL implementations which have at least one non-empty base.
11074     return UnsupportedSTLError();
11075   }
11076 
11077   // Check that the STL has implemented the types using a single integer field.
11078   // This expectation allows better codegen for builtin operators. We require:
11079   //   (1) The class has exactly one field.
11080   //   (2) The field is an integral or enumeration type.
11081   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11082   if (std::distance(FIt, FEnd) != 1 ||
11083       !FIt->getType()->isIntegralOrEnumerationType()) {
11084     return UnsupportedSTLError();
11085   }
11086 
11087   // Build each of the require values and store them in Info.
11088   for (ComparisonCategoryResult CCR :
11089        ComparisonCategories::getPossibleResultsForType(Kind)) {
11090     StringRef MemName = ComparisonCategories::getResultString(CCR);
11091     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11092 
11093     if (!ValInfo)
11094       return UnsupportedSTLError(USS_MissingMember, MemName);
11095 
11096     VarDecl *VD = ValInfo->VD;
11097     assert(VD && "should not be null!");
11098 
11099     // Attempt to diagnose reasons why the STL definition of this type
11100     // might be foobar, including it failing to be a constant expression.
11101     // TODO Handle more ways the lookup or result can be invalid.
11102     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11103         !VD->checkInitIsICE())
11104       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11105 
11106     // Attempt to evaluate the var decl as a constant expression and extract
11107     // the value of its first field as a ICE. If this fails, the STL
11108     // implementation is not supported.
11109     if (!ValInfo->hasValidIntValue())
11110       return UnsupportedSTLError();
11111 
11112     MarkVariableReferenced(Loc, VD);
11113   }
11114 
11115   // We've successfully built the required types and expressions. Update
11116   // the cache and return the newly cached value.
11117   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11118   return Info->getType();
11119 }
11120 
11121 /// Retrieve the special "std" namespace, which may require us to
11122 /// implicitly define the namespace.
11123 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11124   if (!StdNamespace) {
11125     // The "std" namespace has not yet been defined, so build one implicitly.
11126     StdNamespace = NamespaceDecl::Create(Context,
11127                                          Context.getTranslationUnitDecl(),
11128                                          /*Inline=*/false,
11129                                          SourceLocation(), SourceLocation(),
11130                                          &PP.getIdentifierTable().get("std"),
11131                                          /*PrevDecl=*/nullptr);
11132     getStdNamespace()->setImplicit(true);
11133   }
11134 
11135   return getStdNamespace();
11136 }
11137 
11138 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11139   assert(getLangOpts().CPlusPlus &&
11140          "Looking for std::initializer_list outside of C++.");
11141 
11142   // We're looking for implicit instantiations of
11143   // template <typename E> class std::initializer_list.
11144 
11145   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11146     return false;
11147 
11148   ClassTemplateDecl *Template = nullptr;
11149   const TemplateArgument *Arguments = nullptr;
11150 
11151   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11152 
11153     ClassTemplateSpecializationDecl *Specialization =
11154         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11155     if (!Specialization)
11156       return false;
11157 
11158     Template = Specialization->getSpecializedTemplate();
11159     Arguments = Specialization->getTemplateArgs().data();
11160   } else if (const TemplateSpecializationType *TST =
11161                  Ty->getAs<TemplateSpecializationType>()) {
11162     Template = dyn_cast_or_null<ClassTemplateDecl>(
11163         TST->getTemplateName().getAsTemplateDecl());
11164     Arguments = TST->getArgs();
11165   }
11166   if (!Template)
11167     return false;
11168 
11169   if (!StdInitializerList) {
11170     // Haven't recognized std::initializer_list yet, maybe this is it.
11171     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11172     if (TemplateClass->getIdentifier() !=
11173             &PP.getIdentifierTable().get("initializer_list") ||
11174         !getStdNamespace()->InEnclosingNamespaceSetOf(
11175             TemplateClass->getDeclContext()))
11176       return false;
11177     // This is a template called std::initializer_list, but is it the right
11178     // template?
11179     TemplateParameterList *Params = Template->getTemplateParameters();
11180     if (Params->getMinRequiredArguments() != 1)
11181       return false;
11182     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11183       return false;
11184 
11185     // It's the right template.
11186     StdInitializerList = Template;
11187   }
11188 
11189   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11190     return false;
11191 
11192   // This is an instance of std::initializer_list. Find the argument type.
11193   if (Element)
11194     *Element = Arguments[0].getAsType();
11195   return true;
11196 }
11197 
11198 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11199   NamespaceDecl *Std = S.getStdNamespace();
11200   if (!Std) {
11201     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11202     return nullptr;
11203   }
11204 
11205   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11206                       Loc, Sema::LookupOrdinaryName);
11207   if (!S.LookupQualifiedName(Result, Std)) {
11208     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11209     return nullptr;
11210   }
11211   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11212   if (!Template) {
11213     Result.suppressDiagnostics();
11214     // We found something weird. Complain about the first thing we found.
11215     NamedDecl *Found = *Result.begin();
11216     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11217     return nullptr;
11218   }
11219 
11220   // We found some template called std::initializer_list. Now verify that it's
11221   // correct.
11222   TemplateParameterList *Params = Template->getTemplateParameters();
11223   if (Params->getMinRequiredArguments() != 1 ||
11224       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11225     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11226     return nullptr;
11227   }
11228 
11229   return Template;
11230 }
11231 
11232 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11233   if (!StdInitializerList) {
11234     StdInitializerList = LookupStdInitializerList(*this, Loc);
11235     if (!StdInitializerList)
11236       return QualType();
11237   }
11238 
11239   TemplateArgumentListInfo Args(Loc, Loc);
11240   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11241                                        Context.getTrivialTypeSourceInfo(Element,
11242                                                                         Loc)));
11243   return Context.getCanonicalType(
11244       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11245 }
11246 
11247 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11248   // C++ [dcl.init.list]p2:
11249   //   A constructor is an initializer-list constructor if its first parameter
11250   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11251   //   std::initializer_list<E> for some type E, and either there are no other
11252   //   parameters or else all other parameters have default arguments.
11253   if (!Ctor->hasOneParamOrDefaultArgs())
11254     return false;
11255 
11256   QualType ArgType = Ctor->getParamDecl(0)->getType();
11257   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11258     ArgType = RT->getPointeeType().getUnqualifiedType();
11259 
11260   return isStdInitializerList(ArgType, nullptr);
11261 }
11262 
11263 /// Determine whether a using statement is in a context where it will be
11264 /// apply in all contexts.
11265 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11266   switch (CurContext->getDeclKind()) {
11267     case Decl::TranslationUnit:
11268       return true;
11269     case Decl::LinkageSpec:
11270       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11271     default:
11272       return false;
11273   }
11274 }
11275 
11276 namespace {
11277 
11278 // Callback to only accept typo corrections that are namespaces.
11279 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11280 public:
11281   bool ValidateCandidate(const TypoCorrection &candidate) override {
11282     if (NamedDecl *ND = candidate.getCorrectionDecl())
11283       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11284     return false;
11285   }
11286 
11287   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11288     return std::make_unique<NamespaceValidatorCCC>(*this);
11289   }
11290 };
11291 
11292 }
11293 
11294 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11295                                        CXXScopeSpec &SS,
11296                                        SourceLocation IdentLoc,
11297                                        IdentifierInfo *Ident) {
11298   R.clear();
11299   NamespaceValidatorCCC CCC{};
11300   if (TypoCorrection Corrected =
11301           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11302                         Sema::CTK_ErrorRecovery)) {
11303     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11304       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11305       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11306                               Ident->getName().equals(CorrectedStr);
11307       S.diagnoseTypo(Corrected,
11308                      S.PDiag(diag::err_using_directive_member_suggest)
11309                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11310                      S.PDiag(diag::note_namespace_defined_here));
11311     } else {
11312       S.diagnoseTypo(Corrected,
11313                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11314                      S.PDiag(diag::note_namespace_defined_here));
11315     }
11316     R.addDecl(Corrected.getFoundDecl());
11317     return true;
11318   }
11319   return false;
11320 }
11321 
11322 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11323                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11324                                 SourceLocation IdentLoc,
11325                                 IdentifierInfo *NamespcName,
11326                                 const ParsedAttributesView &AttrList) {
11327   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11328   assert(NamespcName && "Invalid NamespcName.");
11329   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11330 
11331   // This can only happen along a recovery path.
11332   while (S->isTemplateParamScope())
11333     S = S->getParent();
11334   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11335 
11336   UsingDirectiveDecl *UDir = nullptr;
11337   NestedNameSpecifier *Qualifier = nullptr;
11338   if (SS.isSet())
11339     Qualifier = SS.getScopeRep();
11340 
11341   // Lookup namespace name.
11342   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11343   LookupParsedName(R, S, &SS);
11344   if (R.isAmbiguous())
11345     return nullptr;
11346 
11347   if (R.empty()) {
11348     R.clear();
11349     // Allow "using namespace std;" or "using namespace ::std;" even if
11350     // "std" hasn't been defined yet, for GCC compatibility.
11351     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11352         NamespcName->isStr("std")) {
11353       Diag(IdentLoc, diag::ext_using_undefined_std);
11354       R.addDecl(getOrCreateStdNamespace());
11355       R.resolveKind();
11356     }
11357     // Otherwise, attempt typo correction.
11358     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11359   }
11360 
11361   if (!R.empty()) {
11362     NamedDecl *Named = R.getRepresentativeDecl();
11363     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11364     assert(NS && "expected namespace decl");
11365 
11366     // The use of a nested name specifier may trigger deprecation warnings.
11367     DiagnoseUseOfDecl(Named, IdentLoc);
11368 
11369     // C++ [namespace.udir]p1:
11370     //   A using-directive specifies that the names in the nominated
11371     //   namespace can be used in the scope in which the
11372     //   using-directive appears after the using-directive. During
11373     //   unqualified name lookup (3.4.1), the names appear as if they
11374     //   were declared in the nearest enclosing namespace which
11375     //   contains both the using-directive and the nominated
11376     //   namespace. [Note: in this context, "contains" means "contains
11377     //   directly or indirectly". ]
11378 
11379     // Find enclosing context containing both using-directive and
11380     // nominated namespace.
11381     DeclContext *CommonAncestor = NS;
11382     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11383       CommonAncestor = CommonAncestor->getParent();
11384 
11385     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11386                                       SS.getWithLocInContext(Context),
11387                                       IdentLoc, Named, CommonAncestor);
11388 
11389     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11390         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11391       Diag(IdentLoc, diag::warn_using_directive_in_header);
11392     }
11393 
11394     PushUsingDirective(S, UDir);
11395   } else {
11396     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11397   }
11398 
11399   if (UDir)
11400     ProcessDeclAttributeList(S, UDir, AttrList);
11401 
11402   return UDir;
11403 }
11404 
11405 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11406   // If the scope has an associated entity and the using directive is at
11407   // namespace or translation unit scope, add the UsingDirectiveDecl into
11408   // its lookup structure so qualified name lookup can find it.
11409   DeclContext *Ctx = S->getEntity();
11410   if (Ctx && !Ctx->isFunctionOrMethod())
11411     Ctx->addDecl(UDir);
11412   else
11413     // Otherwise, it is at block scope. The using-directives will affect lookup
11414     // only to the end of the scope.
11415     S->PushUsingDirective(UDir);
11416 }
11417 
11418 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11419                                   SourceLocation UsingLoc,
11420                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11421                                   UnqualifiedId &Name,
11422                                   SourceLocation EllipsisLoc,
11423                                   const ParsedAttributesView &AttrList) {
11424   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11425 
11426   if (SS.isEmpty()) {
11427     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11428     return nullptr;
11429   }
11430 
11431   switch (Name.getKind()) {
11432   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11433   case UnqualifiedIdKind::IK_Identifier:
11434   case UnqualifiedIdKind::IK_OperatorFunctionId:
11435   case UnqualifiedIdKind::IK_LiteralOperatorId:
11436   case UnqualifiedIdKind::IK_ConversionFunctionId:
11437     break;
11438 
11439   case UnqualifiedIdKind::IK_ConstructorName:
11440   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11441     // C++11 inheriting constructors.
11442     Diag(Name.getBeginLoc(),
11443          getLangOpts().CPlusPlus11
11444              ? diag::warn_cxx98_compat_using_decl_constructor
11445              : diag::err_using_decl_constructor)
11446         << SS.getRange();
11447 
11448     if (getLangOpts().CPlusPlus11) break;
11449 
11450     return nullptr;
11451 
11452   case UnqualifiedIdKind::IK_DestructorName:
11453     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11454     return nullptr;
11455 
11456   case UnqualifiedIdKind::IK_TemplateId:
11457     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11458         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11459     return nullptr;
11460 
11461   case UnqualifiedIdKind::IK_DeductionGuideName:
11462     llvm_unreachable("cannot parse qualified deduction guide name");
11463   }
11464 
11465   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11466   DeclarationName TargetName = TargetNameInfo.getName();
11467   if (!TargetName)
11468     return nullptr;
11469 
11470   // Warn about access declarations.
11471   if (UsingLoc.isInvalid()) {
11472     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11473                                  ? diag::err_access_decl
11474                                  : diag::warn_access_decl_deprecated)
11475         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11476   }
11477 
11478   if (EllipsisLoc.isInvalid()) {
11479     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11480         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11481       return nullptr;
11482   } else {
11483     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11484         !TargetNameInfo.containsUnexpandedParameterPack()) {
11485       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11486         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11487       EllipsisLoc = SourceLocation();
11488     }
11489   }
11490 
11491   NamedDecl *UD =
11492       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11493                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11494                             /*IsInstantiation*/false);
11495   if (UD)
11496     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11497 
11498   return UD;
11499 }
11500 
11501 /// Determine whether a using declaration considers the given
11502 /// declarations as "equivalent", e.g., if they are redeclarations of
11503 /// the same entity or are both typedefs of the same type.
11504 static bool
11505 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11506   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11507     return true;
11508 
11509   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11510     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11511       return Context.hasSameType(TD1->getUnderlyingType(),
11512                                  TD2->getUnderlyingType());
11513 
11514   return false;
11515 }
11516 
11517 
11518 /// Determines whether to create a using shadow decl for a particular
11519 /// decl, given the set of decls existing prior to this using lookup.
11520 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11521                                 const LookupResult &Previous,
11522                                 UsingShadowDecl *&PrevShadow) {
11523   // Diagnose finding a decl which is not from a base class of the
11524   // current class.  We do this now because there are cases where this
11525   // function will silently decide not to build a shadow decl, which
11526   // will pre-empt further diagnostics.
11527   //
11528   // We don't need to do this in C++11 because we do the check once on
11529   // the qualifier.
11530   //
11531   // FIXME: diagnose the following if we care enough:
11532   //   struct A { int foo; };
11533   //   struct B : A { using A::foo; };
11534   //   template <class T> struct C : A {};
11535   //   template <class T> struct D : C<T> { using B::foo; } // <---
11536   // This is invalid (during instantiation) in C++03 because B::foo
11537   // resolves to the using decl in B, which is not a base class of D<T>.
11538   // We can't diagnose it immediately because C<T> is an unknown
11539   // specialization.  The UsingShadowDecl in D<T> then points directly
11540   // to A::foo, which will look well-formed when we instantiate.
11541   // The right solution is to not collapse the shadow-decl chain.
11542   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11543     DeclContext *OrigDC = Orig->getDeclContext();
11544 
11545     // Handle enums and anonymous structs.
11546     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11547     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11548     while (OrigRec->isAnonymousStructOrUnion())
11549       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11550 
11551     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11552       if (OrigDC == CurContext) {
11553         Diag(Using->getLocation(),
11554              diag::err_using_decl_nested_name_specifier_is_current_class)
11555           << Using->getQualifierLoc().getSourceRange();
11556         Diag(Orig->getLocation(), diag::note_using_decl_target);
11557         Using->setInvalidDecl();
11558         return true;
11559       }
11560 
11561       Diag(Using->getQualifierLoc().getBeginLoc(),
11562            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11563         << Using->getQualifier()
11564         << cast<CXXRecordDecl>(CurContext)
11565         << Using->getQualifierLoc().getSourceRange();
11566       Diag(Orig->getLocation(), diag::note_using_decl_target);
11567       Using->setInvalidDecl();
11568       return true;
11569     }
11570   }
11571 
11572   if (Previous.empty()) return false;
11573 
11574   NamedDecl *Target = Orig;
11575   if (isa<UsingShadowDecl>(Target))
11576     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11577 
11578   // If the target happens to be one of the previous declarations, we
11579   // don't have a conflict.
11580   //
11581   // FIXME: but we might be increasing its access, in which case we
11582   // should redeclare it.
11583   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11584   bool FoundEquivalentDecl = false;
11585   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11586          I != E; ++I) {
11587     NamedDecl *D = (*I)->getUnderlyingDecl();
11588     // We can have UsingDecls in our Previous results because we use the same
11589     // LookupResult for checking whether the UsingDecl itself is a valid
11590     // redeclaration.
11591     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11592       continue;
11593 
11594     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11595       // C++ [class.mem]p19:
11596       //   If T is the name of a class, then [every named member other than
11597       //   a non-static data member] shall have a name different from T
11598       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11599           !isa<IndirectFieldDecl>(Target) &&
11600           !isa<UnresolvedUsingValueDecl>(Target) &&
11601           DiagnoseClassNameShadow(
11602               CurContext,
11603               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11604         return true;
11605     }
11606 
11607     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11608       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11609         PrevShadow = Shadow;
11610       FoundEquivalentDecl = true;
11611     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11612       // We don't conflict with an existing using shadow decl of an equivalent
11613       // declaration, but we're not a redeclaration of it.
11614       FoundEquivalentDecl = true;
11615     }
11616 
11617     if (isVisible(D))
11618       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11619   }
11620 
11621   if (FoundEquivalentDecl)
11622     return false;
11623 
11624   if (FunctionDecl *FD = Target->getAsFunction()) {
11625     NamedDecl *OldDecl = nullptr;
11626     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11627                           /*IsForUsingDecl*/ true)) {
11628     case Ovl_Overload:
11629       return false;
11630 
11631     case Ovl_NonFunction:
11632       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11633       break;
11634 
11635     // We found a decl with the exact signature.
11636     case Ovl_Match:
11637       // If we're in a record, we want to hide the target, so we
11638       // return true (without a diagnostic) to tell the caller not to
11639       // build a shadow decl.
11640       if (CurContext->isRecord())
11641         return true;
11642 
11643       // If we're not in a record, this is an error.
11644       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11645       break;
11646     }
11647 
11648     Diag(Target->getLocation(), diag::note_using_decl_target);
11649     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11650     Using->setInvalidDecl();
11651     return true;
11652   }
11653 
11654   // Target is not a function.
11655 
11656   if (isa<TagDecl>(Target)) {
11657     // No conflict between a tag and a non-tag.
11658     if (!Tag) return false;
11659 
11660     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11661     Diag(Target->getLocation(), diag::note_using_decl_target);
11662     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11663     Using->setInvalidDecl();
11664     return true;
11665   }
11666 
11667   // No conflict between a tag and a non-tag.
11668   if (!NonTag) return false;
11669 
11670   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11671   Diag(Target->getLocation(), diag::note_using_decl_target);
11672   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11673   Using->setInvalidDecl();
11674   return true;
11675 }
11676 
11677 /// Determine whether a direct base class is a virtual base class.
11678 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11679   if (!Derived->getNumVBases())
11680     return false;
11681   for (auto &B : Derived->bases())
11682     if (B.getType()->getAsCXXRecordDecl() == Base)
11683       return B.isVirtual();
11684   llvm_unreachable("not a direct base class");
11685 }
11686 
11687 /// Builds a shadow declaration corresponding to a 'using' declaration.
11688 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11689                                             UsingDecl *UD,
11690                                             NamedDecl *Orig,
11691                                             UsingShadowDecl *PrevDecl) {
11692   // If we resolved to another shadow declaration, just coalesce them.
11693   NamedDecl *Target = Orig;
11694   if (isa<UsingShadowDecl>(Target)) {
11695     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11696     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11697   }
11698 
11699   NamedDecl *NonTemplateTarget = Target;
11700   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11701     NonTemplateTarget = TargetTD->getTemplatedDecl();
11702 
11703   UsingShadowDecl *Shadow;
11704   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11705     bool IsVirtualBase =
11706         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11707                             UD->getQualifier()->getAsRecordDecl());
11708     Shadow = ConstructorUsingShadowDecl::Create(
11709         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11710   } else {
11711     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11712                                      Target);
11713   }
11714   UD->addShadowDecl(Shadow);
11715 
11716   Shadow->setAccess(UD->getAccess());
11717   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11718     Shadow->setInvalidDecl();
11719 
11720   Shadow->setPreviousDecl(PrevDecl);
11721 
11722   if (S)
11723     PushOnScopeChains(Shadow, S);
11724   else
11725     CurContext->addDecl(Shadow);
11726 
11727 
11728   return Shadow;
11729 }
11730 
11731 /// Hides a using shadow declaration.  This is required by the current
11732 /// using-decl implementation when a resolvable using declaration in a
11733 /// class is followed by a declaration which would hide or override
11734 /// one or more of the using decl's targets; for example:
11735 ///
11736 ///   struct Base { void foo(int); };
11737 ///   struct Derived : Base {
11738 ///     using Base::foo;
11739 ///     void foo(int);
11740 ///   };
11741 ///
11742 /// The governing language is C++03 [namespace.udecl]p12:
11743 ///
11744 ///   When a using-declaration brings names from a base class into a
11745 ///   derived class scope, member functions in the derived class
11746 ///   override and/or hide member functions with the same name and
11747 ///   parameter types in a base class (rather than conflicting).
11748 ///
11749 /// There are two ways to implement this:
11750 ///   (1) optimistically create shadow decls when they're not hidden
11751 ///       by existing declarations, or
11752 ///   (2) don't create any shadow decls (or at least don't make them
11753 ///       visible) until we've fully parsed/instantiated the class.
11754 /// The problem with (1) is that we might have to retroactively remove
11755 /// a shadow decl, which requires several O(n) operations because the
11756 /// decl structures are (very reasonably) not designed for removal.
11757 /// (2) avoids this but is very fiddly and phase-dependent.
11758 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11759   if (Shadow->getDeclName().getNameKind() ==
11760         DeclarationName::CXXConversionFunctionName)
11761     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11762 
11763   // Remove it from the DeclContext...
11764   Shadow->getDeclContext()->removeDecl(Shadow);
11765 
11766   // ...and the scope, if applicable...
11767   if (S) {
11768     S->RemoveDecl(Shadow);
11769     IdResolver.RemoveDecl(Shadow);
11770   }
11771 
11772   // ...and the using decl.
11773   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11774 
11775   // TODO: complain somehow if Shadow was used.  It shouldn't
11776   // be possible for this to happen, because...?
11777 }
11778 
11779 /// Find the base specifier for a base class with the given type.
11780 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11781                                                 QualType DesiredBase,
11782                                                 bool &AnyDependentBases) {
11783   // Check whether the named type is a direct base class.
11784   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11785     .getUnqualifiedType();
11786   for (auto &Base : Derived->bases()) {
11787     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11788     if (CanonicalDesiredBase == BaseType)
11789       return &Base;
11790     if (BaseType->isDependentType())
11791       AnyDependentBases = true;
11792   }
11793   return nullptr;
11794 }
11795 
11796 namespace {
11797 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11798 public:
11799   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11800                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11801       : HasTypenameKeyword(HasTypenameKeyword),
11802         IsInstantiation(IsInstantiation), OldNNS(NNS),
11803         RequireMemberOf(RequireMemberOf) {}
11804 
11805   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11806     NamedDecl *ND = Candidate.getCorrectionDecl();
11807 
11808     // Keywords are not valid here.
11809     if (!ND || isa<NamespaceDecl>(ND))
11810       return false;
11811 
11812     // Completely unqualified names are invalid for a 'using' declaration.
11813     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11814       return false;
11815 
11816     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11817     // reject.
11818 
11819     if (RequireMemberOf) {
11820       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11821       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11822         // No-one ever wants a using-declaration to name an injected-class-name
11823         // of a base class, unless they're declaring an inheriting constructor.
11824         ASTContext &Ctx = ND->getASTContext();
11825         if (!Ctx.getLangOpts().CPlusPlus11)
11826           return false;
11827         QualType FoundType = Ctx.getRecordType(FoundRecord);
11828 
11829         // Check that the injected-class-name is named as a member of its own
11830         // type; we don't want to suggest 'using Derived::Base;', since that
11831         // means something else.
11832         NestedNameSpecifier *Specifier =
11833             Candidate.WillReplaceSpecifier()
11834                 ? Candidate.getCorrectionSpecifier()
11835                 : OldNNS;
11836         if (!Specifier->getAsType() ||
11837             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11838           return false;
11839 
11840         // Check that this inheriting constructor declaration actually names a
11841         // direct base class of the current class.
11842         bool AnyDependentBases = false;
11843         if (!findDirectBaseWithType(RequireMemberOf,
11844                                     Ctx.getRecordType(FoundRecord),
11845                                     AnyDependentBases) &&
11846             !AnyDependentBases)
11847           return false;
11848       } else {
11849         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11850         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11851           return false;
11852 
11853         // FIXME: Check that the base class member is accessible?
11854       }
11855     } else {
11856       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11857       if (FoundRecord && FoundRecord->isInjectedClassName())
11858         return false;
11859     }
11860 
11861     if (isa<TypeDecl>(ND))
11862       return HasTypenameKeyword || !IsInstantiation;
11863 
11864     return !HasTypenameKeyword;
11865   }
11866 
11867   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11868     return std::make_unique<UsingValidatorCCC>(*this);
11869   }
11870 
11871 private:
11872   bool HasTypenameKeyword;
11873   bool IsInstantiation;
11874   NestedNameSpecifier *OldNNS;
11875   CXXRecordDecl *RequireMemberOf;
11876 };
11877 } // end anonymous namespace
11878 
11879 /// Builds a using declaration.
11880 ///
11881 /// \param IsInstantiation - Whether this call arises from an
11882 ///   instantiation of an unresolved using declaration.  We treat
11883 ///   the lookup differently for these declarations.
11884 NamedDecl *Sema::BuildUsingDeclaration(
11885     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11886     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11887     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11888     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11889   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11890   SourceLocation IdentLoc = NameInfo.getLoc();
11891   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11892 
11893   // FIXME: We ignore attributes for now.
11894 
11895   // For an inheriting constructor declaration, the name of the using
11896   // declaration is the name of a constructor in this class, not in the
11897   // base class.
11898   DeclarationNameInfo UsingName = NameInfo;
11899   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11900     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11901       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11902           Context.getCanonicalType(Context.getRecordType(RD))));
11903 
11904   // Do the redeclaration lookup in the current scope.
11905   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11906                         ForVisibleRedeclaration);
11907   Previous.setHideTags(false);
11908   if (S) {
11909     LookupName(Previous, S);
11910 
11911     // It is really dumb that we have to do this.
11912     LookupResult::Filter F = Previous.makeFilter();
11913     while (F.hasNext()) {
11914       NamedDecl *D = F.next();
11915       if (!isDeclInScope(D, CurContext, S))
11916         F.erase();
11917       // If we found a local extern declaration that's not ordinarily visible,
11918       // and this declaration is being added to a non-block scope, ignore it.
11919       // We're only checking for scope conflicts here, not also for violations
11920       // of the linkage rules.
11921       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11922                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11923         F.erase();
11924     }
11925     F.done();
11926   } else {
11927     assert(IsInstantiation && "no scope in non-instantiation");
11928     if (CurContext->isRecord())
11929       LookupQualifiedName(Previous, CurContext);
11930     else {
11931       // No redeclaration check is needed here; in non-member contexts we
11932       // diagnosed all possible conflicts with other using-declarations when
11933       // building the template:
11934       //
11935       // For a dependent non-type using declaration, the only valid case is
11936       // if we instantiate to a single enumerator. We check for conflicts
11937       // between shadow declarations we introduce, and we check in the template
11938       // definition for conflicts between a non-type using declaration and any
11939       // other declaration, which together covers all cases.
11940       //
11941       // A dependent typename using declaration will never successfully
11942       // instantiate, since it will always name a class member, so we reject
11943       // that in the template definition.
11944     }
11945   }
11946 
11947   // Check for invalid redeclarations.
11948   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11949                                   SS, IdentLoc, Previous))
11950     return nullptr;
11951 
11952   // Check for bad qualifiers.
11953   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11954                               IdentLoc))
11955     return nullptr;
11956 
11957   DeclContext *LookupContext = computeDeclContext(SS);
11958   NamedDecl *D;
11959   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11960   if (!LookupContext || EllipsisLoc.isValid()) {
11961     if (HasTypenameKeyword) {
11962       // FIXME: not all declaration name kinds are legal here
11963       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11964                                               UsingLoc, TypenameLoc,
11965                                               QualifierLoc,
11966                                               IdentLoc, NameInfo.getName(),
11967                                               EllipsisLoc);
11968     } else {
11969       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11970                                            QualifierLoc, NameInfo, EllipsisLoc);
11971     }
11972     D->setAccess(AS);
11973     CurContext->addDecl(D);
11974     return D;
11975   }
11976 
11977   auto Build = [&](bool Invalid) {
11978     UsingDecl *UD =
11979         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11980                           UsingName, HasTypenameKeyword);
11981     UD->setAccess(AS);
11982     CurContext->addDecl(UD);
11983     UD->setInvalidDecl(Invalid);
11984     return UD;
11985   };
11986   auto BuildInvalid = [&]{ return Build(true); };
11987   auto BuildValid = [&]{ return Build(false); };
11988 
11989   if (RequireCompleteDeclContext(SS, LookupContext))
11990     return BuildInvalid();
11991 
11992   // Look up the target name.
11993   LookupResult R(*this, NameInfo, LookupOrdinaryName);
11994 
11995   // Unlike most lookups, we don't always want to hide tag
11996   // declarations: tag names are visible through the using declaration
11997   // even if hidden by ordinary names, *except* in a dependent context
11998   // where it's important for the sanity of two-phase lookup.
11999   if (!IsInstantiation)
12000     R.setHideTags(false);
12001 
12002   // For the purposes of this lookup, we have a base object type
12003   // equal to that of the current context.
12004   if (CurContext->isRecord()) {
12005     R.setBaseObjectType(
12006                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12007   }
12008 
12009   LookupQualifiedName(R, LookupContext);
12010 
12011   // Try to correct typos if possible. If constructor name lookup finds no
12012   // results, that means the named class has no explicit constructors, and we
12013   // suppressed declaring implicit ones (probably because it's dependent or
12014   // invalid).
12015   if (R.empty() &&
12016       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12017     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12018     // it will believe that glibc provides a ::gets in cases where it does not,
12019     // and will try to pull it into namespace std with a using-declaration.
12020     // Just ignore the using-declaration in that case.
12021     auto *II = NameInfo.getName().getAsIdentifierInfo();
12022     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12023         CurContext->isStdNamespace() &&
12024         isa<TranslationUnitDecl>(LookupContext) &&
12025         getSourceManager().isInSystemHeader(UsingLoc))
12026       return nullptr;
12027     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12028                           dyn_cast<CXXRecordDecl>(CurContext));
12029     if (TypoCorrection Corrected =
12030             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12031                         CTK_ErrorRecovery)) {
12032       // We reject candidates where DroppedSpecifier == true, hence the
12033       // literal '0' below.
12034       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12035                                 << NameInfo.getName() << LookupContext << 0
12036                                 << SS.getRange());
12037 
12038       // If we picked a correction with no attached Decl we can't do anything
12039       // useful with it, bail out.
12040       NamedDecl *ND = Corrected.getCorrectionDecl();
12041       if (!ND)
12042         return BuildInvalid();
12043 
12044       // If we corrected to an inheriting constructor, handle it as one.
12045       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12046       if (RD && RD->isInjectedClassName()) {
12047         // The parent of the injected class name is the class itself.
12048         RD = cast<CXXRecordDecl>(RD->getParent());
12049 
12050         // Fix up the information we'll use to build the using declaration.
12051         if (Corrected.WillReplaceSpecifier()) {
12052           NestedNameSpecifierLocBuilder Builder;
12053           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12054                               QualifierLoc.getSourceRange());
12055           QualifierLoc = Builder.getWithLocInContext(Context);
12056         }
12057 
12058         // In this case, the name we introduce is the name of a derived class
12059         // constructor.
12060         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12061         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12062             Context.getCanonicalType(Context.getRecordType(CurClass))));
12063         UsingName.setNamedTypeInfo(nullptr);
12064         for (auto *Ctor : LookupConstructors(RD))
12065           R.addDecl(Ctor);
12066         R.resolveKind();
12067       } else {
12068         // FIXME: Pick up all the declarations if we found an overloaded
12069         // function.
12070         UsingName.setName(ND->getDeclName());
12071         R.addDecl(ND);
12072       }
12073     } else {
12074       Diag(IdentLoc, diag::err_no_member)
12075         << NameInfo.getName() << LookupContext << SS.getRange();
12076       return BuildInvalid();
12077     }
12078   }
12079 
12080   if (R.isAmbiguous())
12081     return BuildInvalid();
12082 
12083   if (HasTypenameKeyword) {
12084     // If we asked for a typename and got a non-type decl, error out.
12085     if (!R.getAsSingle<TypeDecl>()) {
12086       Diag(IdentLoc, diag::err_using_typename_non_type);
12087       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12088         Diag((*I)->getUnderlyingDecl()->getLocation(),
12089              diag::note_using_decl_target);
12090       return BuildInvalid();
12091     }
12092   } else {
12093     // If we asked for a non-typename and we got a type, error out,
12094     // but only if this is an instantiation of an unresolved using
12095     // decl.  Otherwise just silently find the type name.
12096     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12097       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12098       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12099       return BuildInvalid();
12100     }
12101   }
12102 
12103   // C++14 [namespace.udecl]p6:
12104   // A using-declaration shall not name a namespace.
12105   if (R.getAsSingle<NamespaceDecl>()) {
12106     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12107       << SS.getRange();
12108     return BuildInvalid();
12109   }
12110 
12111   // C++14 [namespace.udecl]p7:
12112   // A using-declaration shall not name a scoped enumerator.
12113   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12114     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12115       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12116         << SS.getRange();
12117       return BuildInvalid();
12118     }
12119   }
12120 
12121   UsingDecl *UD = BuildValid();
12122 
12123   // Some additional rules apply to inheriting constructors.
12124   if (UsingName.getName().getNameKind() ==
12125         DeclarationName::CXXConstructorName) {
12126     // Suppress access diagnostics; the access check is instead performed at the
12127     // point of use for an inheriting constructor.
12128     R.suppressDiagnostics();
12129     if (CheckInheritingConstructorUsingDecl(UD))
12130       return UD;
12131   }
12132 
12133   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12134     UsingShadowDecl *PrevDecl = nullptr;
12135     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12136       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12137   }
12138 
12139   return UD;
12140 }
12141 
12142 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12143                                     ArrayRef<NamedDecl *> Expansions) {
12144   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12145          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12146          isa<UsingPackDecl>(InstantiatedFrom));
12147 
12148   auto *UPD =
12149       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12150   UPD->setAccess(InstantiatedFrom->getAccess());
12151   CurContext->addDecl(UPD);
12152   return UPD;
12153 }
12154 
12155 /// Additional checks for a using declaration referring to a constructor name.
12156 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12157   assert(!UD->hasTypename() && "expecting a constructor name");
12158 
12159   const Type *SourceType = UD->getQualifier()->getAsType();
12160   assert(SourceType &&
12161          "Using decl naming constructor doesn't have type in scope spec.");
12162   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12163 
12164   // Check whether the named type is a direct base class.
12165   bool AnyDependentBases = false;
12166   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12167                                       AnyDependentBases);
12168   if (!Base && !AnyDependentBases) {
12169     Diag(UD->getUsingLoc(),
12170          diag::err_using_decl_constructor_not_in_direct_base)
12171       << UD->getNameInfo().getSourceRange()
12172       << QualType(SourceType, 0) << TargetClass;
12173     UD->setInvalidDecl();
12174     return true;
12175   }
12176 
12177   if (Base)
12178     Base->setInheritConstructors();
12179 
12180   return false;
12181 }
12182 
12183 /// Checks that the given using declaration is not an invalid
12184 /// redeclaration.  Note that this is checking only for the using decl
12185 /// itself, not for any ill-formedness among the UsingShadowDecls.
12186 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12187                                        bool HasTypenameKeyword,
12188                                        const CXXScopeSpec &SS,
12189                                        SourceLocation NameLoc,
12190                                        const LookupResult &Prev) {
12191   NestedNameSpecifier *Qual = SS.getScopeRep();
12192 
12193   // C++03 [namespace.udecl]p8:
12194   // C++0x [namespace.udecl]p10:
12195   //   A using-declaration is a declaration and can therefore be used
12196   //   repeatedly where (and only where) multiple declarations are
12197   //   allowed.
12198   //
12199   // That's in non-member contexts.
12200   if (!CurContext->getRedeclContext()->isRecord()) {
12201     // A dependent qualifier outside a class can only ever resolve to an
12202     // enumeration type. Therefore it conflicts with any other non-type
12203     // declaration in the same scope.
12204     // FIXME: How should we check for dependent type-type conflicts at block
12205     // scope?
12206     if (Qual->isDependent() && !HasTypenameKeyword) {
12207       for (auto *D : Prev) {
12208         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12209           bool OldCouldBeEnumerator =
12210               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12211           Diag(NameLoc,
12212                OldCouldBeEnumerator ? diag::err_redefinition
12213                                     : diag::err_redefinition_different_kind)
12214               << Prev.getLookupName();
12215           Diag(D->getLocation(), diag::note_previous_definition);
12216           return true;
12217         }
12218       }
12219     }
12220     return false;
12221   }
12222 
12223   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12224     NamedDecl *D = *I;
12225 
12226     bool DTypename;
12227     NestedNameSpecifier *DQual;
12228     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12229       DTypename = UD->hasTypename();
12230       DQual = UD->getQualifier();
12231     } else if (UnresolvedUsingValueDecl *UD
12232                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12233       DTypename = false;
12234       DQual = UD->getQualifier();
12235     } else if (UnresolvedUsingTypenameDecl *UD
12236                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12237       DTypename = true;
12238       DQual = UD->getQualifier();
12239     } else continue;
12240 
12241     // using decls differ if one says 'typename' and the other doesn't.
12242     // FIXME: non-dependent using decls?
12243     if (HasTypenameKeyword != DTypename) continue;
12244 
12245     // using decls differ if they name different scopes (but note that
12246     // template instantiation can cause this check to trigger when it
12247     // didn't before instantiation).
12248     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12249         Context.getCanonicalNestedNameSpecifier(DQual))
12250       continue;
12251 
12252     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12253     Diag(D->getLocation(), diag::note_using_decl) << 1;
12254     return true;
12255   }
12256 
12257   return false;
12258 }
12259 
12260 
12261 /// Checks that the given nested-name qualifier used in a using decl
12262 /// in the current context is appropriately related to the current
12263 /// scope.  If an error is found, diagnoses it and returns true.
12264 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12265                                    bool HasTypename,
12266                                    const CXXScopeSpec &SS,
12267                                    const DeclarationNameInfo &NameInfo,
12268                                    SourceLocation NameLoc) {
12269   DeclContext *NamedContext = computeDeclContext(SS);
12270 
12271   if (!CurContext->isRecord()) {
12272     // C++03 [namespace.udecl]p3:
12273     // C++0x [namespace.udecl]p8:
12274     //   A using-declaration for a class member shall be a member-declaration.
12275 
12276     // If we weren't able to compute a valid scope, it might validly be a
12277     // dependent class scope or a dependent enumeration unscoped scope. If
12278     // we have a 'typename' keyword, the scope must resolve to a class type.
12279     if ((HasTypename && !NamedContext) ||
12280         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12281       auto *RD = NamedContext
12282                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12283                      : nullptr;
12284       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12285         RD = nullptr;
12286 
12287       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12288         << SS.getRange();
12289 
12290       // If we have a complete, non-dependent source type, try to suggest a
12291       // way to get the same effect.
12292       if (!RD)
12293         return true;
12294 
12295       // Find what this using-declaration was referring to.
12296       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12297       R.setHideTags(false);
12298       R.suppressDiagnostics();
12299       LookupQualifiedName(R, RD);
12300 
12301       if (R.getAsSingle<TypeDecl>()) {
12302         if (getLangOpts().CPlusPlus11) {
12303           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12304           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12305             << 0 // alias declaration
12306             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12307                                           NameInfo.getName().getAsString() +
12308                                               " = ");
12309         } else {
12310           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12311           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12312           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12313             << 1 // typedef declaration
12314             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12315             << FixItHint::CreateInsertion(
12316                    InsertLoc, " " + NameInfo.getName().getAsString());
12317         }
12318       } else if (R.getAsSingle<VarDecl>()) {
12319         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12320         // repeating the type of the static data member here.
12321         FixItHint FixIt;
12322         if (getLangOpts().CPlusPlus11) {
12323           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12324           FixIt = FixItHint::CreateReplacement(
12325               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12326         }
12327 
12328         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12329           << 2 // reference declaration
12330           << FixIt;
12331       } else if (R.getAsSingle<EnumConstantDecl>()) {
12332         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12333         // repeating the type of the enumeration here, and we can't do so if
12334         // the type is anonymous.
12335         FixItHint FixIt;
12336         if (getLangOpts().CPlusPlus11) {
12337           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12338           FixIt = FixItHint::CreateReplacement(
12339               UsingLoc,
12340               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12341         }
12342 
12343         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12344           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12345           << FixIt;
12346       }
12347       return true;
12348     }
12349 
12350     // Otherwise, this might be valid.
12351     return false;
12352   }
12353 
12354   // The current scope is a record.
12355 
12356   // If the named context is dependent, we can't decide much.
12357   if (!NamedContext) {
12358     // FIXME: in C++0x, we can diagnose if we can prove that the
12359     // nested-name-specifier does not refer to a base class, which is
12360     // still possible in some cases.
12361 
12362     // Otherwise we have to conservatively report that things might be
12363     // okay.
12364     return false;
12365   }
12366 
12367   if (!NamedContext->isRecord()) {
12368     // Ideally this would point at the last name in the specifier,
12369     // but we don't have that level of source info.
12370     Diag(SS.getRange().getBegin(),
12371          diag::err_using_decl_nested_name_specifier_is_not_class)
12372       << SS.getScopeRep() << SS.getRange();
12373     return true;
12374   }
12375 
12376   if (!NamedContext->isDependentContext() &&
12377       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12378     return true;
12379 
12380   if (getLangOpts().CPlusPlus11) {
12381     // C++11 [namespace.udecl]p3:
12382     //   In a using-declaration used as a member-declaration, the
12383     //   nested-name-specifier shall name a base class of the class
12384     //   being defined.
12385 
12386     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12387                                  cast<CXXRecordDecl>(NamedContext))) {
12388       if (CurContext == NamedContext) {
12389         Diag(NameLoc,
12390              diag::err_using_decl_nested_name_specifier_is_current_class)
12391           << SS.getRange();
12392         return true;
12393       }
12394 
12395       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12396         Diag(SS.getRange().getBegin(),
12397              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12398           << SS.getScopeRep()
12399           << cast<CXXRecordDecl>(CurContext)
12400           << SS.getRange();
12401       }
12402       return true;
12403     }
12404 
12405     return false;
12406   }
12407 
12408   // C++03 [namespace.udecl]p4:
12409   //   A using-declaration used as a member-declaration shall refer
12410   //   to a member of a base class of the class being defined [etc.].
12411 
12412   // Salient point: SS doesn't have to name a base class as long as
12413   // lookup only finds members from base classes.  Therefore we can
12414   // diagnose here only if we can prove that that can't happen,
12415   // i.e. if the class hierarchies provably don't intersect.
12416 
12417   // TODO: it would be nice if "definitely valid" results were cached
12418   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12419   // need to be repeated.
12420 
12421   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12422   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12423     Bases.insert(Base);
12424     return true;
12425   };
12426 
12427   // Collect all bases. Return false if we find a dependent base.
12428   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12429     return false;
12430 
12431   // Returns true if the base is dependent or is one of the accumulated base
12432   // classes.
12433   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12434     return !Bases.count(Base);
12435   };
12436 
12437   // Return false if the class has a dependent base or if it or one
12438   // of its bases is present in the base set of the current context.
12439   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12440       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12441     return false;
12442 
12443   Diag(SS.getRange().getBegin(),
12444        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12445     << SS.getScopeRep()
12446     << cast<CXXRecordDecl>(CurContext)
12447     << SS.getRange();
12448 
12449   return true;
12450 }
12451 
12452 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12453                                   MultiTemplateParamsArg TemplateParamLists,
12454                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12455                                   const ParsedAttributesView &AttrList,
12456                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12457   // Skip up to the relevant declaration scope.
12458   while (S->isTemplateParamScope())
12459     S = S->getParent();
12460   assert((S->getFlags() & Scope::DeclScope) &&
12461          "got alias-declaration outside of declaration scope");
12462 
12463   if (Type.isInvalid())
12464     return nullptr;
12465 
12466   bool Invalid = false;
12467   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12468   TypeSourceInfo *TInfo = nullptr;
12469   GetTypeFromParser(Type.get(), &TInfo);
12470 
12471   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12472     return nullptr;
12473 
12474   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12475                                       UPPC_DeclarationType)) {
12476     Invalid = true;
12477     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12478                                              TInfo->getTypeLoc().getBeginLoc());
12479   }
12480 
12481   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12482                         TemplateParamLists.size()
12483                             ? forRedeclarationInCurContext()
12484                             : ForVisibleRedeclaration);
12485   LookupName(Previous, S);
12486 
12487   // Warn about shadowing the name of a template parameter.
12488   if (Previous.isSingleResult() &&
12489       Previous.getFoundDecl()->isTemplateParameter()) {
12490     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12491     Previous.clear();
12492   }
12493 
12494   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12495          "name in alias declaration must be an identifier");
12496   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12497                                                Name.StartLocation,
12498                                                Name.Identifier, TInfo);
12499 
12500   NewTD->setAccess(AS);
12501 
12502   if (Invalid)
12503     NewTD->setInvalidDecl();
12504 
12505   ProcessDeclAttributeList(S, NewTD, AttrList);
12506   AddPragmaAttributes(S, NewTD);
12507 
12508   CheckTypedefForVariablyModifiedType(S, NewTD);
12509   Invalid |= NewTD->isInvalidDecl();
12510 
12511   bool Redeclaration = false;
12512 
12513   NamedDecl *NewND;
12514   if (TemplateParamLists.size()) {
12515     TypeAliasTemplateDecl *OldDecl = nullptr;
12516     TemplateParameterList *OldTemplateParams = nullptr;
12517 
12518     if (TemplateParamLists.size() != 1) {
12519       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12520         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12521          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12522     }
12523     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12524 
12525     // Check that we can declare a template here.
12526     if (CheckTemplateDeclScope(S, TemplateParams))
12527       return nullptr;
12528 
12529     // Only consider previous declarations in the same scope.
12530     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12531                          /*ExplicitInstantiationOrSpecialization*/false);
12532     if (!Previous.empty()) {
12533       Redeclaration = true;
12534 
12535       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12536       if (!OldDecl && !Invalid) {
12537         Diag(UsingLoc, diag::err_redefinition_different_kind)
12538           << Name.Identifier;
12539 
12540         NamedDecl *OldD = Previous.getRepresentativeDecl();
12541         if (OldD->getLocation().isValid())
12542           Diag(OldD->getLocation(), diag::note_previous_definition);
12543 
12544         Invalid = true;
12545       }
12546 
12547       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12548         if (TemplateParameterListsAreEqual(TemplateParams,
12549                                            OldDecl->getTemplateParameters(),
12550                                            /*Complain=*/true,
12551                                            TPL_TemplateMatch))
12552           OldTemplateParams =
12553               OldDecl->getMostRecentDecl()->getTemplateParameters();
12554         else
12555           Invalid = true;
12556 
12557         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12558         if (!Invalid &&
12559             !Context.hasSameType(OldTD->getUnderlyingType(),
12560                                  NewTD->getUnderlyingType())) {
12561           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12562           // but we can't reasonably accept it.
12563           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12564             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12565           if (OldTD->getLocation().isValid())
12566             Diag(OldTD->getLocation(), diag::note_previous_definition);
12567           Invalid = true;
12568         }
12569       }
12570     }
12571 
12572     // Merge any previous default template arguments into our parameters,
12573     // and check the parameter list.
12574     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12575                                    TPC_TypeAliasTemplate))
12576       return nullptr;
12577 
12578     TypeAliasTemplateDecl *NewDecl =
12579       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12580                                     Name.Identifier, TemplateParams,
12581                                     NewTD);
12582     NewTD->setDescribedAliasTemplate(NewDecl);
12583 
12584     NewDecl->setAccess(AS);
12585 
12586     if (Invalid)
12587       NewDecl->setInvalidDecl();
12588     else if (OldDecl) {
12589       NewDecl->setPreviousDecl(OldDecl);
12590       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12591     }
12592 
12593     NewND = NewDecl;
12594   } else {
12595     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12596       setTagNameForLinkagePurposes(TD, NewTD);
12597       handleTagNumbering(TD, S);
12598     }
12599     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12600     NewND = NewTD;
12601   }
12602 
12603   PushOnScopeChains(NewND, S);
12604   ActOnDocumentableDecl(NewND);
12605   return NewND;
12606 }
12607 
12608 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12609                                    SourceLocation AliasLoc,
12610                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12611                                    SourceLocation IdentLoc,
12612                                    IdentifierInfo *Ident) {
12613 
12614   // Lookup the namespace name.
12615   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12616   LookupParsedName(R, S, &SS);
12617 
12618   if (R.isAmbiguous())
12619     return nullptr;
12620 
12621   if (R.empty()) {
12622     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12623       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12624       return nullptr;
12625     }
12626   }
12627   assert(!R.isAmbiguous() && !R.empty());
12628   NamedDecl *ND = R.getRepresentativeDecl();
12629 
12630   // Check if we have a previous declaration with the same name.
12631   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12632                      ForVisibleRedeclaration);
12633   LookupName(PrevR, S);
12634 
12635   // Check we're not shadowing a template parameter.
12636   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12637     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12638     PrevR.clear();
12639   }
12640 
12641   // Filter out any other lookup result from an enclosing scope.
12642   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12643                        /*AllowInlineNamespace*/false);
12644 
12645   // Find the previous declaration and check that we can redeclare it.
12646   NamespaceAliasDecl *Prev = nullptr;
12647   if (PrevR.isSingleResult()) {
12648     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12649     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12650       // We already have an alias with the same name that points to the same
12651       // namespace; check that it matches.
12652       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12653         Prev = AD;
12654       } else if (isVisible(PrevDecl)) {
12655         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12656           << Alias;
12657         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12658           << AD->getNamespace();
12659         return nullptr;
12660       }
12661     } else if (isVisible(PrevDecl)) {
12662       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12663                             ? diag::err_redefinition
12664                             : diag::err_redefinition_different_kind;
12665       Diag(AliasLoc, DiagID) << Alias;
12666       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12667       return nullptr;
12668     }
12669   }
12670 
12671   // The use of a nested name specifier may trigger deprecation warnings.
12672   DiagnoseUseOfDecl(ND, IdentLoc);
12673 
12674   NamespaceAliasDecl *AliasDecl =
12675     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12676                                Alias, SS.getWithLocInContext(Context),
12677                                IdentLoc, ND);
12678   if (Prev)
12679     AliasDecl->setPreviousDecl(Prev);
12680 
12681   PushOnScopeChains(AliasDecl, S);
12682   return AliasDecl;
12683 }
12684 
12685 namespace {
12686 struct SpecialMemberExceptionSpecInfo
12687     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12688   SourceLocation Loc;
12689   Sema::ImplicitExceptionSpecification ExceptSpec;
12690 
12691   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12692                                  Sema::CXXSpecialMember CSM,
12693                                  Sema::InheritedConstructorInfo *ICI,
12694                                  SourceLocation Loc)
12695       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12696 
12697   bool visitBase(CXXBaseSpecifier *Base);
12698   bool visitField(FieldDecl *FD);
12699 
12700   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12701                            unsigned Quals);
12702 
12703   void visitSubobjectCall(Subobject Subobj,
12704                           Sema::SpecialMemberOverloadResult SMOR);
12705 };
12706 }
12707 
12708 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12709   auto *RT = Base->getType()->getAs<RecordType>();
12710   if (!RT)
12711     return false;
12712 
12713   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12714   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12715   if (auto *BaseCtor = SMOR.getMethod()) {
12716     visitSubobjectCall(Base, BaseCtor);
12717     return false;
12718   }
12719 
12720   visitClassSubobject(BaseClass, Base, 0);
12721   return false;
12722 }
12723 
12724 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12725   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12726     Expr *E = FD->getInClassInitializer();
12727     if (!E)
12728       // FIXME: It's a little wasteful to build and throw away a
12729       // CXXDefaultInitExpr here.
12730       // FIXME: We should have a single context note pointing at Loc, and
12731       // this location should be MD->getLocation() instead, since that's
12732       // the location where we actually use the default init expression.
12733       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12734     if (E)
12735       ExceptSpec.CalledExpr(E);
12736   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12737                             ->getAs<RecordType>()) {
12738     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12739                         FD->getType().getCVRQualifiers());
12740   }
12741   return false;
12742 }
12743 
12744 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12745                                                          Subobject Subobj,
12746                                                          unsigned Quals) {
12747   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12748   bool IsMutable = Field && Field->isMutable();
12749   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12750 }
12751 
12752 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12753     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12754   // Note, if lookup fails, it doesn't matter what exception specification we
12755   // choose because the special member will be deleted.
12756   if (CXXMethodDecl *MD = SMOR.getMethod())
12757     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12758 }
12759 
12760 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12761   llvm::APSInt Result;
12762   ExprResult Converted = CheckConvertedConstantExpression(
12763       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12764   ExplicitSpec.setExpr(Converted.get());
12765   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12766     ExplicitSpec.setKind(Result.getBoolValue()
12767                              ? ExplicitSpecKind::ResolvedTrue
12768                              : ExplicitSpecKind::ResolvedFalse);
12769     return true;
12770   }
12771   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12772   return false;
12773 }
12774 
12775 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12776   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12777   if (!ExplicitExpr->isTypeDependent())
12778     tryResolveExplicitSpecifier(ES);
12779   return ES;
12780 }
12781 
12782 static Sema::ImplicitExceptionSpecification
12783 ComputeDefaultedSpecialMemberExceptionSpec(
12784     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12785     Sema::InheritedConstructorInfo *ICI) {
12786   ComputingExceptionSpec CES(S, MD, Loc);
12787 
12788   CXXRecordDecl *ClassDecl = MD->getParent();
12789 
12790   // C++ [except.spec]p14:
12791   //   An implicitly declared special member function (Clause 12) shall have an
12792   //   exception-specification. [...]
12793   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12794   if (ClassDecl->isInvalidDecl())
12795     return Info.ExceptSpec;
12796 
12797   // FIXME: If this diagnostic fires, we're probably missing a check for
12798   // attempting to resolve an exception specification before it's known
12799   // at a higher level.
12800   if (S.RequireCompleteType(MD->getLocation(),
12801                             S.Context.getRecordType(ClassDecl),
12802                             diag::err_exception_spec_incomplete_type))
12803     return Info.ExceptSpec;
12804 
12805   // C++1z [except.spec]p7:
12806   //   [Look for exceptions thrown by] a constructor selected [...] to
12807   //   initialize a potentially constructed subobject,
12808   // C++1z [except.spec]p8:
12809   //   The exception specification for an implicitly-declared destructor, or a
12810   //   destructor without a noexcept-specifier, is potentially-throwing if and
12811   //   only if any of the destructors for any of its potentially constructed
12812   //   subojects is potentially throwing.
12813   // FIXME: We respect the first rule but ignore the "potentially constructed"
12814   // in the second rule to resolve a core issue (no number yet) that would have
12815   // us reject:
12816   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12817   //   struct B : A {};
12818   //   struct C : B { void f(); };
12819   // ... due to giving B::~B() a non-throwing exception specification.
12820   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12821                                 : Info.VisitAllBases);
12822 
12823   return Info.ExceptSpec;
12824 }
12825 
12826 namespace {
12827 /// RAII object to register a special member as being currently declared.
12828 struct DeclaringSpecialMember {
12829   Sema &S;
12830   Sema::SpecialMemberDecl D;
12831   Sema::ContextRAII SavedContext;
12832   bool WasAlreadyBeingDeclared;
12833 
12834   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12835       : S(S), D(RD, CSM), SavedContext(S, RD) {
12836     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12837     if (WasAlreadyBeingDeclared)
12838       // This almost never happens, but if it does, ensure that our cache
12839       // doesn't contain a stale result.
12840       S.SpecialMemberCache.clear();
12841     else {
12842       // Register a note to be produced if we encounter an error while
12843       // declaring the special member.
12844       Sema::CodeSynthesisContext Ctx;
12845       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12846       // FIXME: We don't have a location to use here. Using the class's
12847       // location maintains the fiction that we declare all special members
12848       // with the class, but (1) it's not clear that lying about that helps our
12849       // users understand what's going on, and (2) there may be outer contexts
12850       // on the stack (some of which are relevant) and printing them exposes
12851       // our lies.
12852       Ctx.PointOfInstantiation = RD->getLocation();
12853       Ctx.Entity = RD;
12854       Ctx.SpecialMember = CSM;
12855       S.pushCodeSynthesisContext(Ctx);
12856     }
12857   }
12858   ~DeclaringSpecialMember() {
12859     if (!WasAlreadyBeingDeclared) {
12860       S.SpecialMembersBeingDeclared.erase(D);
12861       S.popCodeSynthesisContext();
12862     }
12863   }
12864 
12865   /// Are we already trying to declare this special member?
12866   bool isAlreadyBeingDeclared() const {
12867     return WasAlreadyBeingDeclared;
12868   }
12869 };
12870 }
12871 
12872 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12873   // Look up any existing declarations, but don't trigger declaration of all
12874   // implicit special members with this name.
12875   DeclarationName Name = FD->getDeclName();
12876   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12877                  ForExternalRedeclaration);
12878   for (auto *D : FD->getParent()->lookup(Name))
12879     if (auto *Acceptable = R.getAcceptableDecl(D))
12880       R.addDecl(Acceptable);
12881   R.resolveKind();
12882   R.suppressDiagnostics();
12883 
12884   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12885 }
12886 
12887 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12888                                           QualType ResultTy,
12889                                           ArrayRef<QualType> Args) {
12890   // Build an exception specification pointing back at this constructor.
12891   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12892 
12893   LangAS AS = getDefaultCXXMethodAddrSpace();
12894   if (AS != LangAS::Default) {
12895     EPI.TypeQuals.addAddressSpace(AS);
12896   }
12897 
12898   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12899   SpecialMem->setType(QT);
12900 }
12901 
12902 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12903                                                      CXXRecordDecl *ClassDecl) {
12904   // C++ [class.ctor]p5:
12905   //   A default constructor for a class X is a constructor of class X
12906   //   that can be called without an argument. If there is no
12907   //   user-declared constructor for class X, a default constructor is
12908   //   implicitly declared. An implicitly-declared default constructor
12909   //   is an inline public member of its class.
12910   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12911          "Should not build implicit default constructor!");
12912 
12913   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12914   if (DSM.isAlreadyBeingDeclared())
12915     return nullptr;
12916 
12917   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12918                                                      CXXDefaultConstructor,
12919                                                      false);
12920 
12921   // Create the actual constructor declaration.
12922   CanQualType ClassType
12923     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12924   SourceLocation ClassLoc = ClassDecl->getLocation();
12925   DeclarationName Name
12926     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12927   DeclarationNameInfo NameInfo(Name, ClassLoc);
12928   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12929       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12930       /*TInfo=*/nullptr, ExplicitSpecifier(),
12931       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12932       Constexpr ? CSK_constexpr : CSK_unspecified);
12933   DefaultCon->setAccess(AS_public);
12934   DefaultCon->setDefaulted();
12935 
12936   if (getLangOpts().CUDA) {
12937     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12938                                             DefaultCon,
12939                                             /* ConstRHS */ false,
12940                                             /* Diagnose */ false);
12941   }
12942 
12943   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12944 
12945   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12946   // constructors is easy to compute.
12947   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12948 
12949   // Note that we have declared this constructor.
12950   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12951 
12952   Scope *S = getScopeForContext(ClassDecl);
12953   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12954 
12955   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12956     SetDeclDeleted(DefaultCon, ClassLoc);
12957 
12958   if (S)
12959     PushOnScopeChains(DefaultCon, S, false);
12960   ClassDecl->addDecl(DefaultCon);
12961 
12962   return DefaultCon;
12963 }
12964 
12965 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12966                                             CXXConstructorDecl *Constructor) {
12967   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12968           !Constructor->doesThisDeclarationHaveABody() &&
12969           !Constructor->isDeleted()) &&
12970     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12971   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12972     return;
12973 
12974   CXXRecordDecl *ClassDecl = Constructor->getParent();
12975   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12976 
12977   SynthesizedFunctionScope Scope(*this, Constructor);
12978 
12979   // The exception specification is needed because we are defining the
12980   // function.
12981   ResolveExceptionSpec(CurrentLocation,
12982                        Constructor->getType()->castAs<FunctionProtoType>());
12983   MarkVTableUsed(CurrentLocation, ClassDecl);
12984 
12985   // Add a context note for diagnostics produced after this point.
12986   Scope.addContextNote(CurrentLocation);
12987 
12988   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12989     Constructor->setInvalidDecl();
12990     return;
12991   }
12992 
12993   SourceLocation Loc = Constructor->getEndLoc().isValid()
12994                            ? Constructor->getEndLoc()
12995                            : Constructor->getLocation();
12996   Constructor->setBody(new (Context) CompoundStmt(Loc));
12997   Constructor->markUsed(Context);
12998 
12999   if (ASTMutationListener *L = getASTMutationListener()) {
13000     L->CompletedImplicitDefinition(Constructor);
13001   }
13002 
13003   DiagnoseUninitializedFields(*this, Constructor);
13004 }
13005 
13006 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13007   // Perform any delayed checks on exception specifications.
13008   CheckDelayedMemberExceptionSpecs();
13009 }
13010 
13011 /// Find or create the fake constructor we synthesize to model constructing an
13012 /// object of a derived class via a constructor of a base class.
13013 CXXConstructorDecl *
13014 Sema::findInheritingConstructor(SourceLocation Loc,
13015                                 CXXConstructorDecl *BaseCtor,
13016                                 ConstructorUsingShadowDecl *Shadow) {
13017   CXXRecordDecl *Derived = Shadow->getParent();
13018   SourceLocation UsingLoc = Shadow->getLocation();
13019 
13020   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13021   // For now we use the name of the base class constructor as a member of the
13022   // derived class to indicate a (fake) inherited constructor name.
13023   DeclarationName Name = BaseCtor->getDeclName();
13024 
13025   // Check to see if we already have a fake constructor for this inherited
13026   // constructor call.
13027   for (NamedDecl *Ctor : Derived->lookup(Name))
13028     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13029                                ->getInheritedConstructor()
13030                                .getConstructor(),
13031                            BaseCtor))
13032       return cast<CXXConstructorDecl>(Ctor);
13033 
13034   DeclarationNameInfo NameInfo(Name, UsingLoc);
13035   TypeSourceInfo *TInfo =
13036       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13037   FunctionProtoTypeLoc ProtoLoc =
13038       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13039 
13040   // Check the inherited constructor is valid and find the list of base classes
13041   // from which it was inherited.
13042   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13043 
13044   bool Constexpr =
13045       BaseCtor->isConstexpr() &&
13046       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13047                                         false, BaseCtor, &ICI);
13048 
13049   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13050       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13051       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13052       /*isImplicitlyDeclared=*/true,
13053       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13054       InheritedConstructor(Shadow, BaseCtor),
13055       BaseCtor->getTrailingRequiresClause());
13056   if (Shadow->isInvalidDecl())
13057     DerivedCtor->setInvalidDecl();
13058 
13059   // Build an unevaluated exception specification for this fake constructor.
13060   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13061   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13062   EPI.ExceptionSpec.Type = EST_Unevaluated;
13063   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13064   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13065                                                FPT->getParamTypes(), EPI));
13066 
13067   // Build the parameter declarations.
13068   SmallVector<ParmVarDecl *, 16> ParamDecls;
13069   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13070     TypeSourceInfo *TInfo =
13071         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13072     ParmVarDecl *PD = ParmVarDecl::Create(
13073         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13074         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13075     PD->setScopeInfo(0, I);
13076     PD->setImplicit();
13077     // Ensure attributes are propagated onto parameters (this matters for
13078     // format, pass_object_size, ...).
13079     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13080     ParamDecls.push_back(PD);
13081     ProtoLoc.setParam(I, PD);
13082   }
13083 
13084   // Set up the new constructor.
13085   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13086   DerivedCtor->setAccess(BaseCtor->getAccess());
13087   DerivedCtor->setParams(ParamDecls);
13088   Derived->addDecl(DerivedCtor);
13089 
13090   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13091     SetDeclDeleted(DerivedCtor, UsingLoc);
13092 
13093   return DerivedCtor;
13094 }
13095 
13096 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13097   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13098                                Ctor->getInheritedConstructor().getShadowDecl());
13099   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13100                             /*Diagnose*/true);
13101 }
13102 
13103 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13104                                        CXXConstructorDecl *Constructor) {
13105   CXXRecordDecl *ClassDecl = Constructor->getParent();
13106   assert(Constructor->getInheritedConstructor() &&
13107          !Constructor->doesThisDeclarationHaveABody() &&
13108          !Constructor->isDeleted());
13109   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13110     return;
13111 
13112   // Initializations are performed "as if by a defaulted default constructor",
13113   // so enter the appropriate scope.
13114   SynthesizedFunctionScope Scope(*this, Constructor);
13115 
13116   // The exception specification is needed because we are defining the
13117   // function.
13118   ResolveExceptionSpec(CurrentLocation,
13119                        Constructor->getType()->castAs<FunctionProtoType>());
13120   MarkVTableUsed(CurrentLocation, ClassDecl);
13121 
13122   // Add a context note for diagnostics produced after this point.
13123   Scope.addContextNote(CurrentLocation);
13124 
13125   ConstructorUsingShadowDecl *Shadow =
13126       Constructor->getInheritedConstructor().getShadowDecl();
13127   CXXConstructorDecl *InheritedCtor =
13128       Constructor->getInheritedConstructor().getConstructor();
13129 
13130   // [class.inhctor.init]p1:
13131   //   initialization proceeds as if a defaulted default constructor is used to
13132   //   initialize the D object and each base class subobject from which the
13133   //   constructor was inherited
13134 
13135   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13136   CXXRecordDecl *RD = Shadow->getParent();
13137   SourceLocation InitLoc = Shadow->getLocation();
13138 
13139   // Build explicit initializers for all base classes from which the
13140   // constructor was inherited.
13141   SmallVector<CXXCtorInitializer*, 8> Inits;
13142   for (bool VBase : {false, true}) {
13143     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13144       if (B.isVirtual() != VBase)
13145         continue;
13146 
13147       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13148       if (!BaseRD)
13149         continue;
13150 
13151       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13152       if (!BaseCtor.first)
13153         continue;
13154 
13155       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13156       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13157           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13158 
13159       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13160       Inits.push_back(new (Context) CXXCtorInitializer(
13161           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13162           SourceLocation()));
13163     }
13164   }
13165 
13166   // We now proceed as if for a defaulted default constructor, with the relevant
13167   // initializers replaced.
13168 
13169   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13170     Constructor->setInvalidDecl();
13171     return;
13172   }
13173 
13174   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13175   Constructor->markUsed(Context);
13176 
13177   if (ASTMutationListener *L = getASTMutationListener()) {
13178     L->CompletedImplicitDefinition(Constructor);
13179   }
13180 
13181   DiagnoseUninitializedFields(*this, Constructor);
13182 }
13183 
13184 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13185   // C++ [class.dtor]p2:
13186   //   If a class has no user-declared destructor, a destructor is
13187   //   declared implicitly. An implicitly-declared destructor is an
13188   //   inline public member of its class.
13189   assert(ClassDecl->needsImplicitDestructor());
13190 
13191   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13192   if (DSM.isAlreadyBeingDeclared())
13193     return nullptr;
13194 
13195   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13196                                                      CXXDestructor,
13197                                                      false);
13198 
13199   // Create the actual destructor declaration.
13200   CanQualType ClassType
13201     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13202   SourceLocation ClassLoc = ClassDecl->getLocation();
13203   DeclarationName Name
13204     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13205   DeclarationNameInfo NameInfo(Name, ClassLoc);
13206   CXXDestructorDecl *Destructor =
13207       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13208                                 QualType(), nullptr, /*isInline=*/true,
13209                                 /*isImplicitlyDeclared=*/true,
13210                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13211   Destructor->setAccess(AS_public);
13212   Destructor->setDefaulted();
13213 
13214   if (getLangOpts().CUDA) {
13215     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13216                                             Destructor,
13217                                             /* ConstRHS */ false,
13218                                             /* Diagnose */ false);
13219   }
13220 
13221   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13222 
13223   // We don't need to use SpecialMemberIsTrivial here; triviality for
13224   // destructors is easy to compute.
13225   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13226   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13227                                 ClassDecl->hasTrivialDestructorForCall());
13228 
13229   // Note that we have declared this destructor.
13230   ++getASTContext().NumImplicitDestructorsDeclared;
13231 
13232   Scope *S = getScopeForContext(ClassDecl);
13233   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13234 
13235   // We can't check whether an implicit destructor is deleted before we complete
13236   // the definition of the class, because its validity depends on the alignment
13237   // of the class. We'll check this from ActOnFields once the class is complete.
13238   if (ClassDecl->isCompleteDefinition() &&
13239       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13240     SetDeclDeleted(Destructor, ClassLoc);
13241 
13242   // Introduce this destructor into its scope.
13243   if (S)
13244     PushOnScopeChains(Destructor, S, false);
13245   ClassDecl->addDecl(Destructor);
13246 
13247   return Destructor;
13248 }
13249 
13250 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13251                                     CXXDestructorDecl *Destructor) {
13252   assert((Destructor->isDefaulted() &&
13253           !Destructor->doesThisDeclarationHaveABody() &&
13254           !Destructor->isDeleted()) &&
13255          "DefineImplicitDestructor - call it for implicit default dtor");
13256   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13257     return;
13258 
13259   CXXRecordDecl *ClassDecl = Destructor->getParent();
13260   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13261 
13262   SynthesizedFunctionScope Scope(*this, Destructor);
13263 
13264   // The exception specification is needed because we are defining the
13265   // function.
13266   ResolveExceptionSpec(CurrentLocation,
13267                        Destructor->getType()->castAs<FunctionProtoType>());
13268   MarkVTableUsed(CurrentLocation, ClassDecl);
13269 
13270   // Add a context note for diagnostics produced after this point.
13271   Scope.addContextNote(CurrentLocation);
13272 
13273   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13274                                          Destructor->getParent());
13275 
13276   if (CheckDestructor(Destructor)) {
13277     Destructor->setInvalidDecl();
13278     return;
13279   }
13280 
13281   SourceLocation Loc = Destructor->getEndLoc().isValid()
13282                            ? Destructor->getEndLoc()
13283                            : Destructor->getLocation();
13284   Destructor->setBody(new (Context) CompoundStmt(Loc));
13285   Destructor->markUsed(Context);
13286 
13287   if (ASTMutationListener *L = getASTMutationListener()) {
13288     L->CompletedImplicitDefinition(Destructor);
13289   }
13290 }
13291 
13292 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13293                                           CXXDestructorDecl *Destructor) {
13294   if (Destructor->isInvalidDecl())
13295     return;
13296 
13297   CXXRecordDecl *ClassDecl = Destructor->getParent();
13298   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13299          "implicit complete dtors unneeded outside MS ABI");
13300   assert(ClassDecl->getNumVBases() > 0 &&
13301          "complete dtor only exists for classes with vbases");
13302 
13303   SynthesizedFunctionScope Scope(*this, Destructor);
13304 
13305   // Add a context note for diagnostics produced after this point.
13306   Scope.addContextNote(CurrentLocation);
13307 
13308   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13309 }
13310 
13311 /// Perform any semantic analysis which needs to be delayed until all
13312 /// pending class member declarations have been parsed.
13313 void Sema::ActOnFinishCXXMemberDecls() {
13314   // If the context is an invalid C++ class, just suppress these checks.
13315   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13316     if (Record->isInvalidDecl()) {
13317       DelayedOverridingExceptionSpecChecks.clear();
13318       DelayedEquivalentExceptionSpecChecks.clear();
13319       return;
13320     }
13321     checkForMultipleExportedDefaultConstructors(*this, Record);
13322   }
13323 }
13324 
13325 void Sema::ActOnFinishCXXNonNestedClass() {
13326   referenceDLLExportedClassMethods();
13327 
13328   if (!DelayedDllExportMemberFunctions.empty()) {
13329     SmallVector<CXXMethodDecl*, 4> WorkList;
13330     std::swap(DelayedDllExportMemberFunctions, WorkList);
13331     for (CXXMethodDecl *M : WorkList) {
13332       DefineDefaultedFunction(*this, M, M->getLocation());
13333 
13334       // Pass the method to the consumer to get emitted. This is not necessary
13335       // for explicit instantiation definitions, as they will get emitted
13336       // anyway.
13337       if (M->getParent()->getTemplateSpecializationKind() !=
13338           TSK_ExplicitInstantiationDefinition)
13339         ActOnFinishInlineFunctionDef(M);
13340     }
13341   }
13342 }
13343 
13344 void Sema::referenceDLLExportedClassMethods() {
13345   if (!DelayedDllExportClasses.empty()) {
13346     // Calling ReferenceDllExportedMembers might cause the current function to
13347     // be called again, so use a local copy of DelayedDllExportClasses.
13348     SmallVector<CXXRecordDecl *, 4> WorkList;
13349     std::swap(DelayedDllExportClasses, WorkList);
13350     for (CXXRecordDecl *Class : WorkList)
13351       ReferenceDllExportedMembers(*this, Class);
13352   }
13353 }
13354 
13355 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13356   assert(getLangOpts().CPlusPlus11 &&
13357          "adjusting dtor exception specs was introduced in c++11");
13358 
13359   if (Destructor->isDependentContext())
13360     return;
13361 
13362   // C++11 [class.dtor]p3:
13363   //   A declaration of a destructor that does not have an exception-
13364   //   specification is implicitly considered to have the same exception-
13365   //   specification as an implicit declaration.
13366   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13367   if (DtorType->hasExceptionSpec())
13368     return;
13369 
13370   // Replace the destructor's type, building off the existing one. Fortunately,
13371   // the only thing of interest in the destructor type is its extended info.
13372   // The return and arguments are fixed.
13373   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13374   EPI.ExceptionSpec.Type = EST_Unevaluated;
13375   EPI.ExceptionSpec.SourceDecl = Destructor;
13376   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13377 
13378   // FIXME: If the destructor has a body that could throw, and the newly created
13379   // spec doesn't allow exceptions, we should emit a warning, because this
13380   // change in behavior can break conforming C++03 programs at runtime.
13381   // However, we don't have a body or an exception specification yet, so it
13382   // needs to be done somewhere else.
13383 }
13384 
13385 namespace {
13386 /// An abstract base class for all helper classes used in building the
13387 //  copy/move operators. These classes serve as factory functions and help us
13388 //  avoid using the same Expr* in the AST twice.
13389 class ExprBuilder {
13390   ExprBuilder(const ExprBuilder&) = delete;
13391   ExprBuilder &operator=(const ExprBuilder&) = delete;
13392 
13393 protected:
13394   static Expr *assertNotNull(Expr *E) {
13395     assert(E && "Expression construction must not fail.");
13396     return E;
13397   }
13398 
13399 public:
13400   ExprBuilder() {}
13401   virtual ~ExprBuilder() {}
13402 
13403   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13404 };
13405 
13406 class RefBuilder: public ExprBuilder {
13407   VarDecl *Var;
13408   QualType VarType;
13409 
13410 public:
13411   Expr *build(Sema &S, SourceLocation Loc) const override {
13412     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13413   }
13414 
13415   RefBuilder(VarDecl *Var, QualType VarType)
13416       : Var(Var), VarType(VarType) {}
13417 };
13418 
13419 class ThisBuilder: public ExprBuilder {
13420 public:
13421   Expr *build(Sema &S, SourceLocation Loc) const override {
13422     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13423   }
13424 };
13425 
13426 class CastBuilder: public ExprBuilder {
13427   const ExprBuilder &Builder;
13428   QualType Type;
13429   ExprValueKind Kind;
13430   const CXXCastPath &Path;
13431 
13432 public:
13433   Expr *build(Sema &S, SourceLocation Loc) const override {
13434     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13435                                              CK_UncheckedDerivedToBase, Kind,
13436                                              &Path).get());
13437   }
13438 
13439   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13440               const CXXCastPath &Path)
13441       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13442 };
13443 
13444 class DerefBuilder: public ExprBuilder {
13445   const ExprBuilder &Builder;
13446 
13447 public:
13448   Expr *build(Sema &S, SourceLocation Loc) const override {
13449     return assertNotNull(
13450         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13451   }
13452 
13453   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13454 };
13455 
13456 class MemberBuilder: public ExprBuilder {
13457   const ExprBuilder &Builder;
13458   QualType Type;
13459   CXXScopeSpec SS;
13460   bool IsArrow;
13461   LookupResult &MemberLookup;
13462 
13463 public:
13464   Expr *build(Sema &S, SourceLocation Loc) const override {
13465     return assertNotNull(S.BuildMemberReferenceExpr(
13466         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13467         nullptr, MemberLookup, nullptr, nullptr).get());
13468   }
13469 
13470   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13471                 LookupResult &MemberLookup)
13472       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13473         MemberLookup(MemberLookup) {}
13474 };
13475 
13476 class MoveCastBuilder: public ExprBuilder {
13477   const ExprBuilder &Builder;
13478 
13479 public:
13480   Expr *build(Sema &S, SourceLocation Loc) const override {
13481     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13482   }
13483 
13484   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13485 };
13486 
13487 class LvalueConvBuilder: public ExprBuilder {
13488   const ExprBuilder &Builder;
13489 
13490 public:
13491   Expr *build(Sema &S, SourceLocation Loc) const override {
13492     return assertNotNull(
13493         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13494   }
13495 
13496   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13497 };
13498 
13499 class SubscriptBuilder: public ExprBuilder {
13500   const ExprBuilder &Base;
13501   const ExprBuilder &Index;
13502 
13503 public:
13504   Expr *build(Sema &S, SourceLocation Loc) const override {
13505     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13506         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13507   }
13508 
13509   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13510       : Base(Base), Index(Index) {}
13511 };
13512 
13513 } // end anonymous namespace
13514 
13515 /// When generating a defaulted copy or move assignment operator, if a field
13516 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13517 /// do so. This optimization only applies for arrays of scalars, and for arrays
13518 /// of class type where the selected copy/move-assignment operator is trivial.
13519 static StmtResult
13520 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13521                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13522   // Compute the size of the memory buffer to be copied.
13523   QualType SizeType = S.Context.getSizeType();
13524   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13525                    S.Context.getTypeSizeInChars(T).getQuantity());
13526 
13527   // Take the address of the field references for "from" and "to". We
13528   // directly construct UnaryOperators here because semantic analysis
13529   // does not permit us to take the address of an xvalue.
13530   Expr *From = FromB.build(S, Loc);
13531   From = UnaryOperator::Create(
13532       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13533       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13534   Expr *To = ToB.build(S, Loc);
13535   To = UnaryOperator::Create(
13536       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13537       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13538 
13539   const Type *E = T->getBaseElementTypeUnsafe();
13540   bool NeedsCollectableMemCpy =
13541       E->isRecordType() &&
13542       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13543 
13544   // Create a reference to the __builtin_objc_memmove_collectable function
13545   StringRef MemCpyName = NeedsCollectableMemCpy ?
13546     "__builtin_objc_memmove_collectable" :
13547     "__builtin_memcpy";
13548   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13549                  Sema::LookupOrdinaryName);
13550   S.LookupName(R, S.TUScope, true);
13551 
13552   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13553   if (!MemCpy)
13554     // Something went horribly wrong earlier, and we will have complained
13555     // about it.
13556     return StmtError();
13557 
13558   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13559                                             VK_RValue, Loc, nullptr);
13560   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13561 
13562   Expr *CallArgs[] = {
13563     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13564   };
13565   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13566                                     Loc, CallArgs, Loc);
13567 
13568   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13569   return Call.getAs<Stmt>();
13570 }
13571 
13572 /// Builds a statement that copies/moves the given entity from \p From to
13573 /// \c To.
13574 ///
13575 /// This routine is used to copy/move the members of a class with an
13576 /// implicitly-declared copy/move assignment operator. When the entities being
13577 /// copied are arrays, this routine builds for loops to copy them.
13578 ///
13579 /// \param S The Sema object used for type-checking.
13580 ///
13581 /// \param Loc The location where the implicit copy/move is being generated.
13582 ///
13583 /// \param T The type of the expressions being copied/moved. Both expressions
13584 /// must have this type.
13585 ///
13586 /// \param To The expression we are copying/moving to.
13587 ///
13588 /// \param From The expression we are copying/moving from.
13589 ///
13590 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13591 /// Otherwise, it's a non-static member subobject.
13592 ///
13593 /// \param Copying Whether we're copying or moving.
13594 ///
13595 /// \param Depth Internal parameter recording the depth of the recursion.
13596 ///
13597 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13598 /// if a memcpy should be used instead.
13599 static StmtResult
13600 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13601                                  const ExprBuilder &To, const ExprBuilder &From,
13602                                  bool CopyingBaseSubobject, bool Copying,
13603                                  unsigned Depth = 0) {
13604   // C++11 [class.copy]p28:
13605   //   Each subobject is assigned in the manner appropriate to its type:
13606   //
13607   //     - if the subobject is of class type, as if by a call to operator= with
13608   //       the subobject as the object expression and the corresponding
13609   //       subobject of x as a single function argument (as if by explicit
13610   //       qualification; that is, ignoring any possible virtual overriding
13611   //       functions in more derived classes);
13612   //
13613   // C++03 [class.copy]p13:
13614   //     - if the subobject is of class type, the copy assignment operator for
13615   //       the class is used (as if by explicit qualification; that is,
13616   //       ignoring any possible virtual overriding functions in more derived
13617   //       classes);
13618   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13619     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13620 
13621     // Look for operator=.
13622     DeclarationName Name
13623       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13624     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13625     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13626 
13627     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13628     // operator.
13629     if (!S.getLangOpts().CPlusPlus11) {
13630       LookupResult::Filter F = OpLookup.makeFilter();
13631       while (F.hasNext()) {
13632         NamedDecl *D = F.next();
13633         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13634           if (Method->isCopyAssignmentOperator() ||
13635               (!Copying && Method->isMoveAssignmentOperator()))
13636             continue;
13637 
13638         F.erase();
13639       }
13640       F.done();
13641     }
13642 
13643     // Suppress the protected check (C++ [class.protected]) for each of the
13644     // assignment operators we found. This strange dance is required when
13645     // we're assigning via a base classes's copy-assignment operator. To
13646     // ensure that we're getting the right base class subobject (without
13647     // ambiguities), we need to cast "this" to that subobject type; to
13648     // ensure that we don't go through the virtual call mechanism, we need
13649     // to qualify the operator= name with the base class (see below). However,
13650     // this means that if the base class has a protected copy assignment
13651     // operator, the protected member access check will fail. So, we
13652     // rewrite "protected" access to "public" access in this case, since we
13653     // know by construction that we're calling from a derived class.
13654     if (CopyingBaseSubobject) {
13655       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13656            L != LEnd; ++L) {
13657         if (L.getAccess() == AS_protected)
13658           L.setAccess(AS_public);
13659       }
13660     }
13661 
13662     // Create the nested-name-specifier that will be used to qualify the
13663     // reference to operator=; this is required to suppress the virtual
13664     // call mechanism.
13665     CXXScopeSpec SS;
13666     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13667     SS.MakeTrivial(S.Context,
13668                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13669                                                CanonicalT),
13670                    Loc);
13671 
13672     // Create the reference to operator=.
13673     ExprResult OpEqualRef
13674       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13675                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13676                                    /*FirstQualifierInScope=*/nullptr,
13677                                    OpLookup,
13678                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13679                                    /*SuppressQualifierCheck=*/true);
13680     if (OpEqualRef.isInvalid())
13681       return StmtError();
13682 
13683     // Build the call to the assignment operator.
13684 
13685     Expr *FromInst = From.build(S, Loc);
13686     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13687                                                   OpEqualRef.getAs<Expr>(),
13688                                                   Loc, FromInst, Loc);
13689     if (Call.isInvalid())
13690       return StmtError();
13691 
13692     // If we built a call to a trivial 'operator=' while copying an array,
13693     // bail out. We'll replace the whole shebang with a memcpy.
13694     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13695     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13696       return StmtResult((Stmt*)nullptr);
13697 
13698     // Convert to an expression-statement, and clean up any produced
13699     // temporaries.
13700     return S.ActOnExprStmt(Call);
13701   }
13702 
13703   //     - if the subobject is of scalar type, the built-in assignment
13704   //       operator is used.
13705   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13706   if (!ArrayTy) {
13707     ExprResult Assignment = S.CreateBuiltinBinOp(
13708         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13709     if (Assignment.isInvalid())
13710       return StmtError();
13711     return S.ActOnExprStmt(Assignment);
13712   }
13713 
13714   //     - if the subobject is an array, each element is assigned, in the
13715   //       manner appropriate to the element type;
13716 
13717   // Construct a loop over the array bounds, e.g.,
13718   //
13719   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13720   //
13721   // that will copy each of the array elements.
13722   QualType SizeType = S.Context.getSizeType();
13723 
13724   // Create the iteration variable.
13725   IdentifierInfo *IterationVarName = nullptr;
13726   {
13727     SmallString<8> Str;
13728     llvm::raw_svector_ostream OS(Str);
13729     OS << "__i" << Depth;
13730     IterationVarName = &S.Context.Idents.get(OS.str());
13731   }
13732   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13733                                           IterationVarName, SizeType,
13734                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13735                                           SC_None);
13736 
13737   // Initialize the iteration variable to zero.
13738   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13739   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13740 
13741   // Creates a reference to the iteration variable.
13742   RefBuilder IterationVarRef(IterationVar, SizeType);
13743   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13744 
13745   // Create the DeclStmt that holds the iteration variable.
13746   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13747 
13748   // Subscript the "from" and "to" expressions with the iteration variable.
13749   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13750   MoveCastBuilder FromIndexMove(FromIndexCopy);
13751   const ExprBuilder *FromIndex;
13752   if (Copying)
13753     FromIndex = &FromIndexCopy;
13754   else
13755     FromIndex = &FromIndexMove;
13756 
13757   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13758 
13759   // Build the copy/move for an individual element of the array.
13760   StmtResult Copy =
13761     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13762                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13763                                      Copying, Depth + 1);
13764   // Bail out if copying fails or if we determined that we should use memcpy.
13765   if (Copy.isInvalid() || !Copy.get())
13766     return Copy;
13767 
13768   // Create the comparison against the array bound.
13769   llvm::APInt Upper
13770     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13771   Expr *Comparison = BinaryOperator::Create(
13772       S.Context, IterationVarRefRVal.build(S, Loc),
13773       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13774       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13775 
13776   // Create the pre-increment of the iteration variable. We can determine
13777   // whether the increment will overflow based on the value of the array
13778   // bound.
13779   Expr *Increment = UnaryOperator::Create(
13780       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13781       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13782 
13783   // Construct the loop that copies all elements of this array.
13784   return S.ActOnForStmt(
13785       Loc, Loc, InitStmt,
13786       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13787       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13788 }
13789 
13790 static StmtResult
13791 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13792                       const ExprBuilder &To, const ExprBuilder &From,
13793                       bool CopyingBaseSubobject, bool Copying) {
13794   // Maybe we should use a memcpy?
13795   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13796       T.isTriviallyCopyableType(S.Context))
13797     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13798 
13799   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13800                                                      CopyingBaseSubobject,
13801                                                      Copying, 0));
13802 
13803   // If we ended up picking a trivial assignment operator for an array of a
13804   // non-trivially-copyable class type, just emit a memcpy.
13805   if (!Result.isInvalid() && !Result.get())
13806     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13807 
13808   return Result;
13809 }
13810 
13811 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13812   // Note: The following rules are largely analoguous to the copy
13813   // constructor rules. Note that virtual bases are not taken into account
13814   // for determining the argument type of the operator. Note also that
13815   // operators taking an object instead of a reference are allowed.
13816   assert(ClassDecl->needsImplicitCopyAssignment());
13817 
13818   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13819   if (DSM.isAlreadyBeingDeclared())
13820     return nullptr;
13821 
13822   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13823   LangAS AS = getDefaultCXXMethodAddrSpace();
13824   if (AS != LangAS::Default)
13825     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13826   QualType RetType = Context.getLValueReferenceType(ArgType);
13827   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13828   if (Const)
13829     ArgType = ArgType.withConst();
13830 
13831   ArgType = Context.getLValueReferenceType(ArgType);
13832 
13833   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13834                                                      CXXCopyAssignment,
13835                                                      Const);
13836 
13837   //   An implicitly-declared copy assignment operator is an inline public
13838   //   member of its class.
13839   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13840   SourceLocation ClassLoc = ClassDecl->getLocation();
13841   DeclarationNameInfo NameInfo(Name, ClassLoc);
13842   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13843       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13844       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13845       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13846       SourceLocation());
13847   CopyAssignment->setAccess(AS_public);
13848   CopyAssignment->setDefaulted();
13849   CopyAssignment->setImplicit();
13850 
13851   if (getLangOpts().CUDA) {
13852     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13853                                             CopyAssignment,
13854                                             /* ConstRHS */ Const,
13855                                             /* Diagnose */ false);
13856   }
13857 
13858   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13859 
13860   // Add the parameter to the operator.
13861   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13862                                                ClassLoc, ClassLoc,
13863                                                /*Id=*/nullptr, ArgType,
13864                                                /*TInfo=*/nullptr, SC_None,
13865                                                nullptr);
13866   CopyAssignment->setParams(FromParam);
13867 
13868   CopyAssignment->setTrivial(
13869     ClassDecl->needsOverloadResolutionForCopyAssignment()
13870       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13871       : ClassDecl->hasTrivialCopyAssignment());
13872 
13873   // Note that we have added this copy-assignment operator.
13874   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13875 
13876   Scope *S = getScopeForContext(ClassDecl);
13877   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13878 
13879   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13880     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13881     SetDeclDeleted(CopyAssignment, ClassLoc);
13882   }
13883 
13884   if (S)
13885     PushOnScopeChains(CopyAssignment, S, false);
13886   ClassDecl->addDecl(CopyAssignment);
13887 
13888   return CopyAssignment;
13889 }
13890 
13891 /// Diagnose an implicit copy operation for a class which is odr-used, but
13892 /// which is deprecated because the class has a user-declared copy constructor,
13893 /// copy assignment operator, or destructor.
13894 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13895   assert(CopyOp->isImplicit());
13896 
13897   CXXRecordDecl *RD = CopyOp->getParent();
13898   CXXMethodDecl *UserDeclaredOperation = nullptr;
13899 
13900   // In Microsoft mode, assignment operations don't affect constructors and
13901   // vice versa.
13902   if (RD->hasUserDeclaredDestructor()) {
13903     UserDeclaredOperation = RD->getDestructor();
13904   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13905              RD->hasUserDeclaredCopyConstructor() &&
13906              !S.getLangOpts().MSVCCompat) {
13907     // Find any user-declared copy constructor.
13908     for (auto *I : RD->ctors()) {
13909       if (I->isCopyConstructor()) {
13910         UserDeclaredOperation = I;
13911         break;
13912       }
13913     }
13914     assert(UserDeclaredOperation);
13915   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13916              RD->hasUserDeclaredCopyAssignment() &&
13917              !S.getLangOpts().MSVCCompat) {
13918     // Find any user-declared move assignment operator.
13919     for (auto *I : RD->methods()) {
13920       if (I->isCopyAssignmentOperator()) {
13921         UserDeclaredOperation = I;
13922         break;
13923       }
13924     }
13925     assert(UserDeclaredOperation);
13926   }
13927 
13928   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13929     S.Diag(UserDeclaredOperation->getLocation(),
13930            isa<CXXDestructorDecl>(UserDeclaredOperation)
13931                ? diag::warn_deprecated_copy_dtor_operation
13932                : diag::warn_deprecated_copy_operation)
13933         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13934   }
13935 }
13936 
13937 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13938                                         CXXMethodDecl *CopyAssignOperator) {
13939   assert((CopyAssignOperator->isDefaulted() &&
13940           CopyAssignOperator->isOverloadedOperator() &&
13941           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13942           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13943           !CopyAssignOperator->isDeleted()) &&
13944          "DefineImplicitCopyAssignment called for wrong function");
13945   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13946     return;
13947 
13948   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13949   if (ClassDecl->isInvalidDecl()) {
13950     CopyAssignOperator->setInvalidDecl();
13951     return;
13952   }
13953 
13954   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13955 
13956   // The exception specification is needed because we are defining the
13957   // function.
13958   ResolveExceptionSpec(CurrentLocation,
13959                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13960 
13961   // Add a context note for diagnostics produced after this point.
13962   Scope.addContextNote(CurrentLocation);
13963 
13964   // C++11 [class.copy]p18:
13965   //   The [definition of an implicitly declared copy assignment operator] is
13966   //   deprecated if the class has a user-declared copy constructor or a
13967   //   user-declared destructor.
13968   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13969     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13970 
13971   // C++0x [class.copy]p30:
13972   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13973   //   for a non-union class X performs memberwise copy assignment of its
13974   //   subobjects. The direct base classes of X are assigned first, in the
13975   //   order of their declaration in the base-specifier-list, and then the
13976   //   immediate non-static data members of X are assigned, in the order in
13977   //   which they were declared in the class definition.
13978 
13979   // The statements that form the synthesized function body.
13980   SmallVector<Stmt*, 8> Statements;
13981 
13982   // The parameter for the "other" object, which we are copying from.
13983   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13984   Qualifiers OtherQuals = Other->getType().getQualifiers();
13985   QualType OtherRefType = Other->getType();
13986   if (const LValueReferenceType *OtherRef
13987                                 = OtherRefType->getAs<LValueReferenceType>()) {
13988     OtherRefType = OtherRef->getPointeeType();
13989     OtherQuals = OtherRefType.getQualifiers();
13990   }
13991 
13992   // Our location for everything implicitly-generated.
13993   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
13994                            ? CopyAssignOperator->getEndLoc()
13995                            : CopyAssignOperator->getLocation();
13996 
13997   // Builds a DeclRefExpr for the "other" object.
13998   RefBuilder OtherRef(Other, OtherRefType);
13999 
14000   // Builds the "this" pointer.
14001   ThisBuilder This;
14002 
14003   // Assign base classes.
14004   bool Invalid = false;
14005   for (auto &Base : ClassDecl->bases()) {
14006     // Form the assignment:
14007     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14008     QualType BaseType = Base.getType().getUnqualifiedType();
14009     if (!BaseType->isRecordType()) {
14010       Invalid = true;
14011       continue;
14012     }
14013 
14014     CXXCastPath BasePath;
14015     BasePath.push_back(&Base);
14016 
14017     // Construct the "from" expression, which is an implicit cast to the
14018     // appropriately-qualified base type.
14019     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14020                      VK_LValue, BasePath);
14021 
14022     // Dereference "this".
14023     DerefBuilder DerefThis(This);
14024     CastBuilder To(DerefThis,
14025                    Context.getQualifiedType(
14026                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14027                    VK_LValue, BasePath);
14028 
14029     // Build the copy.
14030     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14031                                             To, From,
14032                                             /*CopyingBaseSubobject=*/true,
14033                                             /*Copying=*/true);
14034     if (Copy.isInvalid()) {
14035       CopyAssignOperator->setInvalidDecl();
14036       return;
14037     }
14038 
14039     // Success! Record the copy.
14040     Statements.push_back(Copy.getAs<Expr>());
14041   }
14042 
14043   // Assign non-static members.
14044   for (auto *Field : ClassDecl->fields()) {
14045     // FIXME: We should form some kind of AST representation for the implied
14046     // memcpy in a union copy operation.
14047     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14048       continue;
14049 
14050     if (Field->isInvalidDecl()) {
14051       Invalid = true;
14052       continue;
14053     }
14054 
14055     // Check for members of reference type; we can't copy those.
14056     if (Field->getType()->isReferenceType()) {
14057       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14058         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14059       Diag(Field->getLocation(), diag::note_declared_at);
14060       Invalid = true;
14061       continue;
14062     }
14063 
14064     // Check for members of const-qualified, non-class type.
14065     QualType BaseType = Context.getBaseElementType(Field->getType());
14066     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14067       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14068         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14069       Diag(Field->getLocation(), diag::note_declared_at);
14070       Invalid = true;
14071       continue;
14072     }
14073 
14074     // Suppress assigning zero-width bitfields.
14075     if (Field->isZeroLengthBitField(Context))
14076       continue;
14077 
14078     QualType FieldType = Field->getType().getNonReferenceType();
14079     if (FieldType->isIncompleteArrayType()) {
14080       assert(ClassDecl->hasFlexibleArrayMember() &&
14081              "Incomplete array type is not valid");
14082       continue;
14083     }
14084 
14085     // Build references to the field in the object we're copying from and to.
14086     CXXScopeSpec SS; // Intentionally empty
14087     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14088                               LookupMemberName);
14089     MemberLookup.addDecl(Field);
14090     MemberLookup.resolveKind();
14091 
14092     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14093 
14094     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14095 
14096     // Build the copy of this field.
14097     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14098                                             To, From,
14099                                             /*CopyingBaseSubobject=*/false,
14100                                             /*Copying=*/true);
14101     if (Copy.isInvalid()) {
14102       CopyAssignOperator->setInvalidDecl();
14103       return;
14104     }
14105 
14106     // Success! Record the copy.
14107     Statements.push_back(Copy.getAs<Stmt>());
14108   }
14109 
14110   if (!Invalid) {
14111     // Add a "return *this;"
14112     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14113 
14114     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14115     if (Return.isInvalid())
14116       Invalid = true;
14117     else
14118       Statements.push_back(Return.getAs<Stmt>());
14119   }
14120 
14121   if (Invalid) {
14122     CopyAssignOperator->setInvalidDecl();
14123     return;
14124   }
14125 
14126   StmtResult Body;
14127   {
14128     CompoundScopeRAII CompoundScope(*this);
14129     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14130                              /*isStmtExpr=*/false);
14131     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14132   }
14133   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14134   CopyAssignOperator->markUsed(Context);
14135 
14136   if (ASTMutationListener *L = getASTMutationListener()) {
14137     L->CompletedImplicitDefinition(CopyAssignOperator);
14138   }
14139 }
14140 
14141 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14142   assert(ClassDecl->needsImplicitMoveAssignment());
14143 
14144   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14145   if (DSM.isAlreadyBeingDeclared())
14146     return nullptr;
14147 
14148   // Note: The following rules are largely analoguous to the move
14149   // constructor rules.
14150 
14151   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14152   LangAS AS = getDefaultCXXMethodAddrSpace();
14153   if (AS != LangAS::Default)
14154     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14155   QualType RetType = Context.getLValueReferenceType(ArgType);
14156   ArgType = Context.getRValueReferenceType(ArgType);
14157 
14158   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14159                                                      CXXMoveAssignment,
14160                                                      false);
14161 
14162   //   An implicitly-declared move assignment operator is an inline public
14163   //   member of its class.
14164   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14165   SourceLocation ClassLoc = ClassDecl->getLocation();
14166   DeclarationNameInfo NameInfo(Name, ClassLoc);
14167   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14168       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14169       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14170       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14171       SourceLocation());
14172   MoveAssignment->setAccess(AS_public);
14173   MoveAssignment->setDefaulted();
14174   MoveAssignment->setImplicit();
14175 
14176   if (getLangOpts().CUDA) {
14177     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14178                                             MoveAssignment,
14179                                             /* ConstRHS */ false,
14180                                             /* Diagnose */ false);
14181   }
14182 
14183   // Build an exception specification pointing back at this member.
14184   FunctionProtoType::ExtProtoInfo EPI =
14185       getImplicitMethodEPI(*this, MoveAssignment);
14186   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14187 
14188   // Add the parameter to the operator.
14189   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14190                                                ClassLoc, ClassLoc,
14191                                                /*Id=*/nullptr, ArgType,
14192                                                /*TInfo=*/nullptr, SC_None,
14193                                                nullptr);
14194   MoveAssignment->setParams(FromParam);
14195 
14196   MoveAssignment->setTrivial(
14197     ClassDecl->needsOverloadResolutionForMoveAssignment()
14198       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14199       : ClassDecl->hasTrivialMoveAssignment());
14200 
14201   // Note that we have added this copy-assignment operator.
14202   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14203 
14204   Scope *S = getScopeForContext(ClassDecl);
14205   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14206 
14207   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14208     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14209     SetDeclDeleted(MoveAssignment, ClassLoc);
14210   }
14211 
14212   if (S)
14213     PushOnScopeChains(MoveAssignment, S, false);
14214   ClassDecl->addDecl(MoveAssignment);
14215 
14216   return MoveAssignment;
14217 }
14218 
14219 /// Check if we're implicitly defining a move assignment operator for a class
14220 /// with virtual bases. Such a move assignment might move-assign the virtual
14221 /// base multiple times.
14222 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14223                                                SourceLocation CurrentLocation) {
14224   assert(!Class->isDependentContext() && "should not define dependent move");
14225 
14226   // Only a virtual base could get implicitly move-assigned multiple times.
14227   // Only a non-trivial move assignment can observe this. We only want to
14228   // diagnose if we implicitly define an assignment operator that assigns
14229   // two base classes, both of which move-assign the same virtual base.
14230   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14231       Class->getNumBases() < 2)
14232     return;
14233 
14234   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14235   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14236   VBaseMap VBases;
14237 
14238   for (auto &BI : Class->bases()) {
14239     Worklist.push_back(&BI);
14240     while (!Worklist.empty()) {
14241       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14242       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14243 
14244       // If the base has no non-trivial move assignment operators,
14245       // we don't care about moves from it.
14246       if (!Base->hasNonTrivialMoveAssignment())
14247         continue;
14248 
14249       // If there's nothing virtual here, skip it.
14250       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14251         continue;
14252 
14253       // If we're not actually going to call a move assignment for this base,
14254       // or the selected move assignment is trivial, skip it.
14255       Sema::SpecialMemberOverloadResult SMOR =
14256         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14257                               /*ConstArg*/false, /*VolatileArg*/false,
14258                               /*RValueThis*/true, /*ConstThis*/false,
14259                               /*VolatileThis*/false);
14260       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14261           !SMOR.getMethod()->isMoveAssignmentOperator())
14262         continue;
14263 
14264       if (BaseSpec->isVirtual()) {
14265         // We're going to move-assign this virtual base, and its move
14266         // assignment operator is not trivial. If this can happen for
14267         // multiple distinct direct bases of Class, diagnose it. (If it
14268         // only happens in one base, we'll diagnose it when synthesizing
14269         // that base class's move assignment operator.)
14270         CXXBaseSpecifier *&Existing =
14271             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14272                 .first->second;
14273         if (Existing && Existing != &BI) {
14274           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14275             << Class << Base;
14276           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14277               << (Base->getCanonicalDecl() ==
14278                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14279               << Base << Existing->getType() << Existing->getSourceRange();
14280           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14281               << (Base->getCanonicalDecl() ==
14282                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14283               << Base << BI.getType() << BaseSpec->getSourceRange();
14284 
14285           // Only diagnose each vbase once.
14286           Existing = nullptr;
14287         }
14288       } else {
14289         // Only walk over bases that have defaulted move assignment operators.
14290         // We assume that any user-provided move assignment operator handles
14291         // the multiple-moves-of-vbase case itself somehow.
14292         if (!SMOR.getMethod()->isDefaulted())
14293           continue;
14294 
14295         // We're going to move the base classes of Base. Add them to the list.
14296         for (auto &BI : Base->bases())
14297           Worklist.push_back(&BI);
14298       }
14299     }
14300   }
14301 }
14302 
14303 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14304                                         CXXMethodDecl *MoveAssignOperator) {
14305   assert((MoveAssignOperator->isDefaulted() &&
14306           MoveAssignOperator->isOverloadedOperator() &&
14307           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14308           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14309           !MoveAssignOperator->isDeleted()) &&
14310          "DefineImplicitMoveAssignment called for wrong function");
14311   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14312     return;
14313 
14314   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14315   if (ClassDecl->isInvalidDecl()) {
14316     MoveAssignOperator->setInvalidDecl();
14317     return;
14318   }
14319 
14320   // C++0x [class.copy]p28:
14321   //   The implicitly-defined or move assignment operator for a non-union class
14322   //   X performs memberwise move assignment of its subobjects. The direct base
14323   //   classes of X are assigned first, in the order of their declaration in the
14324   //   base-specifier-list, and then the immediate non-static data members of X
14325   //   are assigned, in the order in which they were declared in the class
14326   //   definition.
14327 
14328   // Issue a warning if our implicit move assignment operator will move
14329   // from a virtual base more than once.
14330   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14331 
14332   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14333 
14334   // The exception specification is needed because we are defining the
14335   // function.
14336   ResolveExceptionSpec(CurrentLocation,
14337                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14338 
14339   // Add a context note for diagnostics produced after this point.
14340   Scope.addContextNote(CurrentLocation);
14341 
14342   // The statements that form the synthesized function body.
14343   SmallVector<Stmt*, 8> Statements;
14344 
14345   // The parameter for the "other" object, which we are move from.
14346   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14347   QualType OtherRefType =
14348       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14349 
14350   // Our location for everything implicitly-generated.
14351   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14352                            ? MoveAssignOperator->getEndLoc()
14353                            : MoveAssignOperator->getLocation();
14354 
14355   // Builds a reference to the "other" object.
14356   RefBuilder OtherRef(Other, OtherRefType);
14357   // Cast to rvalue.
14358   MoveCastBuilder MoveOther(OtherRef);
14359 
14360   // Builds the "this" pointer.
14361   ThisBuilder This;
14362 
14363   // Assign base classes.
14364   bool Invalid = false;
14365   for (auto &Base : ClassDecl->bases()) {
14366     // C++11 [class.copy]p28:
14367     //   It is unspecified whether subobjects representing virtual base classes
14368     //   are assigned more than once by the implicitly-defined copy assignment
14369     //   operator.
14370     // FIXME: Do not assign to a vbase that will be assigned by some other base
14371     // class. For a move-assignment, this can result in the vbase being moved
14372     // multiple times.
14373 
14374     // Form the assignment:
14375     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14376     QualType BaseType = Base.getType().getUnqualifiedType();
14377     if (!BaseType->isRecordType()) {
14378       Invalid = true;
14379       continue;
14380     }
14381 
14382     CXXCastPath BasePath;
14383     BasePath.push_back(&Base);
14384 
14385     // Construct the "from" expression, which is an implicit cast to the
14386     // appropriately-qualified base type.
14387     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14388 
14389     // Dereference "this".
14390     DerefBuilder DerefThis(This);
14391 
14392     // Implicitly cast "this" to the appropriately-qualified base type.
14393     CastBuilder To(DerefThis,
14394                    Context.getQualifiedType(
14395                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14396                    VK_LValue, BasePath);
14397 
14398     // Build the move.
14399     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14400                                             To, From,
14401                                             /*CopyingBaseSubobject=*/true,
14402                                             /*Copying=*/false);
14403     if (Move.isInvalid()) {
14404       MoveAssignOperator->setInvalidDecl();
14405       return;
14406     }
14407 
14408     // Success! Record the move.
14409     Statements.push_back(Move.getAs<Expr>());
14410   }
14411 
14412   // Assign non-static members.
14413   for (auto *Field : ClassDecl->fields()) {
14414     // FIXME: We should form some kind of AST representation for the implied
14415     // memcpy in a union copy operation.
14416     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14417       continue;
14418 
14419     if (Field->isInvalidDecl()) {
14420       Invalid = true;
14421       continue;
14422     }
14423 
14424     // Check for members of reference type; we can't move those.
14425     if (Field->getType()->isReferenceType()) {
14426       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14427         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14428       Diag(Field->getLocation(), diag::note_declared_at);
14429       Invalid = true;
14430       continue;
14431     }
14432 
14433     // Check for members of const-qualified, non-class type.
14434     QualType BaseType = Context.getBaseElementType(Field->getType());
14435     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14436       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14437         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14438       Diag(Field->getLocation(), diag::note_declared_at);
14439       Invalid = true;
14440       continue;
14441     }
14442 
14443     // Suppress assigning zero-width bitfields.
14444     if (Field->isZeroLengthBitField(Context))
14445       continue;
14446 
14447     QualType FieldType = Field->getType().getNonReferenceType();
14448     if (FieldType->isIncompleteArrayType()) {
14449       assert(ClassDecl->hasFlexibleArrayMember() &&
14450              "Incomplete array type is not valid");
14451       continue;
14452     }
14453 
14454     // Build references to the field in the object we're copying from and to.
14455     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14456                               LookupMemberName);
14457     MemberLookup.addDecl(Field);
14458     MemberLookup.resolveKind();
14459     MemberBuilder From(MoveOther, OtherRefType,
14460                        /*IsArrow=*/false, MemberLookup);
14461     MemberBuilder To(This, getCurrentThisType(),
14462                      /*IsArrow=*/true, MemberLookup);
14463 
14464     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14465         "Member reference with rvalue base must be rvalue except for reference "
14466         "members, which aren't allowed for move assignment.");
14467 
14468     // Build the move of this field.
14469     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14470                                             To, From,
14471                                             /*CopyingBaseSubobject=*/false,
14472                                             /*Copying=*/false);
14473     if (Move.isInvalid()) {
14474       MoveAssignOperator->setInvalidDecl();
14475       return;
14476     }
14477 
14478     // Success! Record the copy.
14479     Statements.push_back(Move.getAs<Stmt>());
14480   }
14481 
14482   if (!Invalid) {
14483     // Add a "return *this;"
14484     ExprResult ThisObj =
14485         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14486 
14487     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14488     if (Return.isInvalid())
14489       Invalid = true;
14490     else
14491       Statements.push_back(Return.getAs<Stmt>());
14492   }
14493 
14494   if (Invalid) {
14495     MoveAssignOperator->setInvalidDecl();
14496     return;
14497   }
14498 
14499   StmtResult Body;
14500   {
14501     CompoundScopeRAII CompoundScope(*this);
14502     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14503                              /*isStmtExpr=*/false);
14504     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14505   }
14506   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14507   MoveAssignOperator->markUsed(Context);
14508 
14509   if (ASTMutationListener *L = getASTMutationListener()) {
14510     L->CompletedImplicitDefinition(MoveAssignOperator);
14511   }
14512 }
14513 
14514 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14515                                                     CXXRecordDecl *ClassDecl) {
14516   // C++ [class.copy]p4:
14517   //   If the class definition does not explicitly declare a copy
14518   //   constructor, one is declared implicitly.
14519   assert(ClassDecl->needsImplicitCopyConstructor());
14520 
14521   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14522   if (DSM.isAlreadyBeingDeclared())
14523     return nullptr;
14524 
14525   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14526   QualType ArgType = ClassType;
14527   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14528   if (Const)
14529     ArgType = ArgType.withConst();
14530 
14531   LangAS AS = getDefaultCXXMethodAddrSpace();
14532   if (AS != LangAS::Default)
14533     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14534 
14535   ArgType = Context.getLValueReferenceType(ArgType);
14536 
14537   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14538                                                      CXXCopyConstructor,
14539                                                      Const);
14540 
14541   DeclarationName Name
14542     = Context.DeclarationNames.getCXXConstructorName(
14543                                            Context.getCanonicalType(ClassType));
14544   SourceLocation ClassLoc = ClassDecl->getLocation();
14545   DeclarationNameInfo NameInfo(Name, ClassLoc);
14546 
14547   //   An implicitly-declared copy constructor is an inline public
14548   //   member of its class.
14549   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14550       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14551       ExplicitSpecifier(),
14552       /*isInline=*/true,
14553       /*isImplicitlyDeclared=*/true,
14554       Constexpr ? CSK_constexpr : CSK_unspecified);
14555   CopyConstructor->setAccess(AS_public);
14556   CopyConstructor->setDefaulted();
14557 
14558   if (getLangOpts().CUDA) {
14559     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14560                                             CopyConstructor,
14561                                             /* ConstRHS */ Const,
14562                                             /* Diagnose */ false);
14563   }
14564 
14565   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14566 
14567   // Add the parameter to the constructor.
14568   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14569                                                ClassLoc, ClassLoc,
14570                                                /*IdentifierInfo=*/nullptr,
14571                                                ArgType, /*TInfo=*/nullptr,
14572                                                SC_None, nullptr);
14573   CopyConstructor->setParams(FromParam);
14574 
14575   CopyConstructor->setTrivial(
14576       ClassDecl->needsOverloadResolutionForCopyConstructor()
14577           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14578           : ClassDecl->hasTrivialCopyConstructor());
14579 
14580   CopyConstructor->setTrivialForCall(
14581       ClassDecl->hasAttr<TrivialABIAttr>() ||
14582       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14583            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14584              TAH_ConsiderTrivialABI)
14585            : ClassDecl->hasTrivialCopyConstructorForCall()));
14586 
14587   // Note that we have declared this constructor.
14588   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14589 
14590   Scope *S = getScopeForContext(ClassDecl);
14591   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14592 
14593   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14594     ClassDecl->setImplicitCopyConstructorIsDeleted();
14595     SetDeclDeleted(CopyConstructor, ClassLoc);
14596   }
14597 
14598   if (S)
14599     PushOnScopeChains(CopyConstructor, S, false);
14600   ClassDecl->addDecl(CopyConstructor);
14601 
14602   return CopyConstructor;
14603 }
14604 
14605 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14606                                          CXXConstructorDecl *CopyConstructor) {
14607   assert((CopyConstructor->isDefaulted() &&
14608           CopyConstructor->isCopyConstructor() &&
14609           !CopyConstructor->doesThisDeclarationHaveABody() &&
14610           !CopyConstructor->isDeleted()) &&
14611          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14612   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14613     return;
14614 
14615   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14616   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14617 
14618   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14619 
14620   // The exception specification is needed because we are defining the
14621   // function.
14622   ResolveExceptionSpec(CurrentLocation,
14623                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14624   MarkVTableUsed(CurrentLocation, ClassDecl);
14625 
14626   // Add a context note for diagnostics produced after this point.
14627   Scope.addContextNote(CurrentLocation);
14628 
14629   // C++11 [class.copy]p7:
14630   //   The [definition of an implicitly declared copy constructor] is
14631   //   deprecated if the class has a user-declared copy assignment operator
14632   //   or a user-declared destructor.
14633   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14634     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14635 
14636   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14637     CopyConstructor->setInvalidDecl();
14638   }  else {
14639     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14640                              ? CopyConstructor->getEndLoc()
14641                              : CopyConstructor->getLocation();
14642     Sema::CompoundScopeRAII CompoundScope(*this);
14643     CopyConstructor->setBody(
14644         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14645     CopyConstructor->markUsed(Context);
14646   }
14647 
14648   if (ASTMutationListener *L = getASTMutationListener()) {
14649     L->CompletedImplicitDefinition(CopyConstructor);
14650   }
14651 }
14652 
14653 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14654                                                     CXXRecordDecl *ClassDecl) {
14655   assert(ClassDecl->needsImplicitMoveConstructor());
14656 
14657   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14658   if (DSM.isAlreadyBeingDeclared())
14659     return nullptr;
14660 
14661   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14662 
14663   QualType ArgType = ClassType;
14664   LangAS AS = getDefaultCXXMethodAddrSpace();
14665   if (AS != LangAS::Default)
14666     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14667   ArgType = Context.getRValueReferenceType(ArgType);
14668 
14669   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14670                                                      CXXMoveConstructor,
14671                                                      false);
14672 
14673   DeclarationName Name
14674     = Context.DeclarationNames.getCXXConstructorName(
14675                                            Context.getCanonicalType(ClassType));
14676   SourceLocation ClassLoc = ClassDecl->getLocation();
14677   DeclarationNameInfo NameInfo(Name, ClassLoc);
14678 
14679   // C++11 [class.copy]p11:
14680   //   An implicitly-declared copy/move constructor is an inline public
14681   //   member of its class.
14682   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14683       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14684       ExplicitSpecifier(),
14685       /*isInline=*/true,
14686       /*isImplicitlyDeclared=*/true,
14687       Constexpr ? CSK_constexpr : CSK_unspecified);
14688   MoveConstructor->setAccess(AS_public);
14689   MoveConstructor->setDefaulted();
14690 
14691   if (getLangOpts().CUDA) {
14692     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14693                                             MoveConstructor,
14694                                             /* ConstRHS */ false,
14695                                             /* Diagnose */ false);
14696   }
14697 
14698   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14699 
14700   // Add the parameter to the constructor.
14701   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14702                                                ClassLoc, ClassLoc,
14703                                                /*IdentifierInfo=*/nullptr,
14704                                                ArgType, /*TInfo=*/nullptr,
14705                                                SC_None, nullptr);
14706   MoveConstructor->setParams(FromParam);
14707 
14708   MoveConstructor->setTrivial(
14709       ClassDecl->needsOverloadResolutionForMoveConstructor()
14710           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14711           : ClassDecl->hasTrivialMoveConstructor());
14712 
14713   MoveConstructor->setTrivialForCall(
14714       ClassDecl->hasAttr<TrivialABIAttr>() ||
14715       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14716            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14717                                     TAH_ConsiderTrivialABI)
14718            : ClassDecl->hasTrivialMoveConstructorForCall()));
14719 
14720   // Note that we have declared this constructor.
14721   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14722 
14723   Scope *S = getScopeForContext(ClassDecl);
14724   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14725 
14726   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14727     ClassDecl->setImplicitMoveConstructorIsDeleted();
14728     SetDeclDeleted(MoveConstructor, ClassLoc);
14729   }
14730 
14731   if (S)
14732     PushOnScopeChains(MoveConstructor, S, false);
14733   ClassDecl->addDecl(MoveConstructor);
14734 
14735   return MoveConstructor;
14736 }
14737 
14738 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14739                                          CXXConstructorDecl *MoveConstructor) {
14740   assert((MoveConstructor->isDefaulted() &&
14741           MoveConstructor->isMoveConstructor() &&
14742           !MoveConstructor->doesThisDeclarationHaveABody() &&
14743           !MoveConstructor->isDeleted()) &&
14744          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14745   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14746     return;
14747 
14748   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14749   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14750 
14751   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14752 
14753   // The exception specification is needed because we are defining the
14754   // function.
14755   ResolveExceptionSpec(CurrentLocation,
14756                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14757   MarkVTableUsed(CurrentLocation, ClassDecl);
14758 
14759   // Add a context note for diagnostics produced after this point.
14760   Scope.addContextNote(CurrentLocation);
14761 
14762   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14763     MoveConstructor->setInvalidDecl();
14764   } else {
14765     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14766                              ? MoveConstructor->getEndLoc()
14767                              : MoveConstructor->getLocation();
14768     Sema::CompoundScopeRAII CompoundScope(*this);
14769     MoveConstructor->setBody(ActOnCompoundStmt(
14770         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14771     MoveConstructor->markUsed(Context);
14772   }
14773 
14774   if (ASTMutationListener *L = getASTMutationListener()) {
14775     L->CompletedImplicitDefinition(MoveConstructor);
14776   }
14777 }
14778 
14779 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14780   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14781 }
14782 
14783 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14784                             SourceLocation CurrentLocation,
14785                             CXXConversionDecl *Conv) {
14786   SynthesizedFunctionScope Scope(*this, Conv);
14787   assert(!Conv->getReturnType()->isUndeducedType());
14788 
14789   CXXRecordDecl *Lambda = Conv->getParent();
14790   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14791   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14792 
14793   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14794     CallOp = InstantiateFunctionDeclaration(
14795         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14796     if (!CallOp)
14797       return;
14798 
14799     Invoker = InstantiateFunctionDeclaration(
14800         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14801     if (!Invoker)
14802       return;
14803   }
14804 
14805   if (CallOp->isInvalidDecl())
14806     return;
14807 
14808   // Mark the call operator referenced (and add to pending instantiations
14809   // if necessary).
14810   // For both the conversion and static-invoker template specializations
14811   // we construct their body's in this function, so no need to add them
14812   // to the PendingInstantiations.
14813   MarkFunctionReferenced(CurrentLocation, CallOp);
14814 
14815   // Fill in the __invoke function with a dummy implementation. IR generation
14816   // will fill in the actual details. Update its type in case it contained
14817   // an 'auto'.
14818   Invoker->markUsed(Context);
14819   Invoker->setReferenced();
14820   Invoker->setType(Conv->getReturnType()->getPointeeType());
14821   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14822 
14823   // Construct the body of the conversion function { return __invoke; }.
14824   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14825                                        VK_LValue, Conv->getLocation());
14826   assert(FunctionRef && "Can't refer to __invoke function?");
14827   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14828   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14829                                      Conv->getLocation()));
14830   Conv->markUsed(Context);
14831   Conv->setReferenced();
14832 
14833   if (ASTMutationListener *L = getASTMutationListener()) {
14834     L->CompletedImplicitDefinition(Conv);
14835     L->CompletedImplicitDefinition(Invoker);
14836   }
14837 }
14838 
14839 
14840 
14841 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14842        SourceLocation CurrentLocation,
14843        CXXConversionDecl *Conv)
14844 {
14845   assert(!Conv->getParent()->isGenericLambda());
14846 
14847   SynthesizedFunctionScope Scope(*this, Conv);
14848 
14849   // Copy-initialize the lambda object as needed to capture it.
14850   Expr *This = ActOnCXXThis(CurrentLocation).get();
14851   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14852 
14853   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14854                                                         Conv->getLocation(),
14855                                                         Conv, DerefThis);
14856 
14857   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14858   // behavior.  Note that only the general conversion function does this
14859   // (since it's unusable otherwise); in the case where we inline the
14860   // block literal, it has block literal lifetime semantics.
14861   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14862     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14863                                           CK_CopyAndAutoreleaseBlockObject,
14864                                           BuildBlock.get(), nullptr, VK_RValue);
14865 
14866   if (BuildBlock.isInvalid()) {
14867     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14868     Conv->setInvalidDecl();
14869     return;
14870   }
14871 
14872   // Create the return statement that returns the block from the conversion
14873   // function.
14874   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14875   if (Return.isInvalid()) {
14876     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14877     Conv->setInvalidDecl();
14878     return;
14879   }
14880 
14881   // Set the body of the conversion function.
14882   Stmt *ReturnS = Return.get();
14883   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14884                                      Conv->getLocation()));
14885   Conv->markUsed(Context);
14886 
14887   // We're done; notify the mutation listener, if any.
14888   if (ASTMutationListener *L = getASTMutationListener()) {
14889     L->CompletedImplicitDefinition(Conv);
14890   }
14891 }
14892 
14893 /// Determine whether the given list arguments contains exactly one
14894 /// "real" (non-default) argument.
14895 static bool hasOneRealArgument(MultiExprArg Args) {
14896   switch (Args.size()) {
14897   case 0:
14898     return false;
14899 
14900   default:
14901     if (!Args[1]->isDefaultArgument())
14902       return false;
14903 
14904     LLVM_FALLTHROUGH;
14905   case 1:
14906     return !Args[0]->isDefaultArgument();
14907   }
14908 
14909   return false;
14910 }
14911 
14912 ExprResult
14913 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14914                             NamedDecl *FoundDecl,
14915                             CXXConstructorDecl *Constructor,
14916                             MultiExprArg ExprArgs,
14917                             bool HadMultipleCandidates,
14918                             bool IsListInitialization,
14919                             bool IsStdInitListInitialization,
14920                             bool RequiresZeroInit,
14921                             unsigned ConstructKind,
14922                             SourceRange ParenRange) {
14923   bool Elidable = false;
14924 
14925   // C++0x [class.copy]p34:
14926   //   When certain criteria are met, an implementation is allowed to
14927   //   omit the copy/move construction of a class object, even if the
14928   //   copy/move constructor and/or destructor for the object have
14929   //   side effects. [...]
14930   //     - when a temporary class object that has not been bound to a
14931   //       reference (12.2) would be copied/moved to a class object
14932   //       with the same cv-unqualified type, the copy/move operation
14933   //       can be omitted by constructing the temporary object
14934   //       directly into the target of the omitted copy/move
14935   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14936       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14937     Expr *SubExpr = ExprArgs[0];
14938     Elidable = SubExpr->isTemporaryObject(
14939         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14940   }
14941 
14942   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14943                                FoundDecl, Constructor,
14944                                Elidable, ExprArgs, HadMultipleCandidates,
14945                                IsListInitialization,
14946                                IsStdInitListInitialization, RequiresZeroInit,
14947                                ConstructKind, ParenRange);
14948 }
14949 
14950 ExprResult
14951 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14952                             NamedDecl *FoundDecl,
14953                             CXXConstructorDecl *Constructor,
14954                             bool Elidable,
14955                             MultiExprArg ExprArgs,
14956                             bool HadMultipleCandidates,
14957                             bool IsListInitialization,
14958                             bool IsStdInitListInitialization,
14959                             bool RequiresZeroInit,
14960                             unsigned ConstructKind,
14961                             SourceRange ParenRange) {
14962   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14963     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14964     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14965       return ExprError();
14966   }
14967 
14968   return BuildCXXConstructExpr(
14969       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14970       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14971       RequiresZeroInit, ConstructKind, ParenRange);
14972 }
14973 
14974 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14975 /// including handling of its default argument expressions.
14976 ExprResult
14977 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14978                             CXXConstructorDecl *Constructor,
14979                             bool Elidable,
14980                             MultiExprArg ExprArgs,
14981                             bool HadMultipleCandidates,
14982                             bool IsListInitialization,
14983                             bool IsStdInitListInitialization,
14984                             bool RequiresZeroInit,
14985                             unsigned ConstructKind,
14986                             SourceRange ParenRange) {
14987   assert(declaresSameEntity(
14988              Constructor->getParent(),
14989              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14990          "given constructor for wrong type");
14991   MarkFunctionReferenced(ConstructLoc, Constructor);
14992   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
14993     return ExprError();
14994   if (getLangOpts().SYCLIsDevice &&
14995       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
14996     return ExprError();
14997 
14998   return CheckForImmediateInvocation(
14999       CXXConstructExpr::Create(
15000           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15001           HadMultipleCandidates, IsListInitialization,
15002           IsStdInitListInitialization, RequiresZeroInit,
15003           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15004           ParenRange),
15005       Constructor);
15006 }
15007 
15008 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15009   assert(Field->hasInClassInitializer());
15010 
15011   // If we already have the in-class initializer nothing needs to be done.
15012   if (Field->getInClassInitializer())
15013     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15014 
15015   // If we might have already tried and failed to instantiate, don't try again.
15016   if (Field->isInvalidDecl())
15017     return ExprError();
15018 
15019   // Maybe we haven't instantiated the in-class initializer. Go check the
15020   // pattern FieldDecl to see if it has one.
15021   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15022 
15023   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15024     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15025     DeclContext::lookup_result Lookup =
15026         ClassPattern->lookup(Field->getDeclName());
15027 
15028     // Lookup can return at most two results: the pattern for the field, or the
15029     // injected class name of the parent record. No other member can have the
15030     // same name as the field.
15031     // In modules mode, lookup can return multiple results (coming from
15032     // different modules).
15033     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15034            "more than two lookup results for field name");
15035     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15036     if (!Pattern) {
15037       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15038              "cannot have other non-field member with same name");
15039       for (auto L : Lookup)
15040         if (isa<FieldDecl>(L)) {
15041           Pattern = cast<FieldDecl>(L);
15042           break;
15043         }
15044       assert(Pattern && "We must have set the Pattern!");
15045     }
15046 
15047     if (!Pattern->hasInClassInitializer() ||
15048         InstantiateInClassInitializer(Loc, Field, Pattern,
15049                                       getTemplateInstantiationArgs(Field))) {
15050       // Don't diagnose this again.
15051       Field->setInvalidDecl();
15052       return ExprError();
15053     }
15054     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15055   }
15056 
15057   // DR1351:
15058   //   If the brace-or-equal-initializer of a non-static data member
15059   //   invokes a defaulted default constructor of its class or of an
15060   //   enclosing class in a potentially evaluated subexpression, the
15061   //   program is ill-formed.
15062   //
15063   // This resolution is unworkable: the exception specification of the
15064   // default constructor can be needed in an unevaluated context, in
15065   // particular, in the operand of a noexcept-expression, and we can be
15066   // unable to compute an exception specification for an enclosed class.
15067   //
15068   // Any attempt to resolve the exception specification of a defaulted default
15069   // constructor before the initializer is lexically complete will ultimately
15070   // come here at which point we can diagnose it.
15071   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15072   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
15073       << OutermostClass << Field;
15074   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
15075   // Recover by marking the field invalid, unless we're in a SFINAE context.
15076   if (!isSFINAEContext())
15077     Field->setInvalidDecl();
15078   return ExprError();
15079 }
15080 
15081 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15082   if (VD->isInvalidDecl()) return;
15083   // If initializing the variable failed, don't also diagnose problems with
15084   // the desctructor, they're likely related.
15085   if (VD->getInit() && VD->getInit()->containsErrors())
15086     return;
15087 
15088   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15089   if (ClassDecl->isInvalidDecl()) return;
15090   if (ClassDecl->hasIrrelevantDestructor()) return;
15091   if (ClassDecl->isDependentContext()) return;
15092 
15093   if (VD->isNoDestroy(getASTContext()))
15094     return;
15095 
15096   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15097 
15098   // If this is an array, we'll require the destructor during initialization, so
15099   // we can skip over this. We still want to emit exit-time destructor warnings
15100   // though.
15101   if (!VD->getType()->isArrayType()) {
15102     MarkFunctionReferenced(VD->getLocation(), Destructor);
15103     CheckDestructorAccess(VD->getLocation(), Destructor,
15104                           PDiag(diag::err_access_dtor_var)
15105                               << VD->getDeclName() << VD->getType());
15106     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15107   }
15108 
15109   if (Destructor->isTrivial()) return;
15110 
15111   // If the destructor is constexpr, check whether the variable has constant
15112   // destruction now.
15113   if (Destructor->isConstexpr()) {
15114     bool HasConstantInit = false;
15115     if (VD->getInit() && !VD->getInit()->isValueDependent())
15116       HasConstantInit = VD->evaluateValue();
15117     SmallVector<PartialDiagnosticAt, 8> Notes;
15118     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15119         HasConstantInit) {
15120       Diag(VD->getLocation(),
15121            diag::err_constexpr_var_requires_const_destruction) << VD;
15122       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15123         Diag(Notes[I].first, Notes[I].second);
15124     }
15125   }
15126 
15127   if (!VD->hasGlobalStorage()) return;
15128 
15129   // Emit warning for non-trivial dtor in global scope (a real global,
15130   // class-static, function-static).
15131   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15132 
15133   // TODO: this should be re-enabled for static locals by !CXAAtExit
15134   if (!VD->isStaticLocal())
15135     Diag(VD->getLocation(), diag::warn_global_destructor);
15136 }
15137 
15138 /// Given a constructor and the set of arguments provided for the
15139 /// constructor, convert the arguments and add any required default arguments
15140 /// to form a proper call to this constructor.
15141 ///
15142 /// \returns true if an error occurred, false otherwise.
15143 bool
15144 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15145                               MultiExprArg ArgsPtr,
15146                               SourceLocation Loc,
15147                               SmallVectorImpl<Expr*> &ConvertedArgs,
15148                               bool AllowExplicit,
15149                               bool IsListInitialization) {
15150   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15151   unsigned NumArgs = ArgsPtr.size();
15152   Expr **Args = ArgsPtr.data();
15153 
15154   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15155   unsigned NumParams = Proto->getNumParams();
15156 
15157   // If too few arguments are available, we'll fill in the rest with defaults.
15158   if (NumArgs < NumParams)
15159     ConvertedArgs.reserve(NumParams);
15160   else
15161     ConvertedArgs.reserve(NumArgs);
15162 
15163   VariadicCallType CallType =
15164     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15165   SmallVector<Expr *, 8> AllArgs;
15166   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15167                                         Proto, 0,
15168                                         llvm::makeArrayRef(Args, NumArgs),
15169                                         AllArgs,
15170                                         CallType, AllowExplicit,
15171                                         IsListInitialization);
15172   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15173 
15174   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15175 
15176   CheckConstructorCall(Constructor,
15177                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15178                        Proto, Loc);
15179 
15180   return Invalid;
15181 }
15182 
15183 static inline bool
15184 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15185                                        const FunctionDecl *FnDecl) {
15186   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15187   if (isa<NamespaceDecl>(DC)) {
15188     return SemaRef.Diag(FnDecl->getLocation(),
15189                         diag::err_operator_new_delete_declared_in_namespace)
15190       << FnDecl->getDeclName();
15191   }
15192 
15193   if (isa<TranslationUnitDecl>(DC) &&
15194       FnDecl->getStorageClass() == SC_Static) {
15195     return SemaRef.Diag(FnDecl->getLocation(),
15196                         diag::err_operator_new_delete_declared_static)
15197       << FnDecl->getDeclName();
15198   }
15199 
15200   return false;
15201 }
15202 
15203 static QualType
15204 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15205   QualType QTy = PtrTy->getPointeeType();
15206   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15207   return SemaRef.Context.getPointerType(QTy);
15208 }
15209 
15210 static inline bool
15211 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15212                             CanQualType ExpectedResultType,
15213                             CanQualType ExpectedFirstParamType,
15214                             unsigned DependentParamTypeDiag,
15215                             unsigned InvalidParamTypeDiag) {
15216   QualType ResultType =
15217       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15218 
15219   // The operator is valid on any address space for OpenCL.
15220   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15221     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15222       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15223     }
15224   }
15225 
15226   // Check that the result type is what we expect.
15227   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15228     // Reject even if the type is dependent; an operator delete function is
15229     // required to have a non-dependent result type.
15230     return SemaRef.Diag(
15231                FnDecl->getLocation(),
15232                ResultType->isDependentType()
15233                    ? diag::err_operator_new_delete_dependent_result_type
15234                    : diag::err_operator_new_delete_invalid_result_type)
15235            << FnDecl->getDeclName() << ExpectedResultType;
15236   }
15237 
15238   // A function template must have at least 2 parameters.
15239   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15240     return SemaRef.Diag(FnDecl->getLocation(),
15241                       diag::err_operator_new_delete_template_too_few_parameters)
15242         << FnDecl->getDeclName();
15243 
15244   // The function decl must have at least 1 parameter.
15245   if (FnDecl->getNumParams() == 0)
15246     return SemaRef.Diag(FnDecl->getLocation(),
15247                         diag::err_operator_new_delete_too_few_parameters)
15248       << FnDecl->getDeclName();
15249 
15250   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15251   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15252     // The operator is valid on any address space for OpenCL.
15253     if (auto *PtrTy =
15254             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15255       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15256     }
15257   }
15258 
15259   // Check that the first parameter type is what we expect.
15260   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15261       ExpectedFirstParamType) {
15262     // The first parameter type is not allowed to be dependent. As a tentative
15263     // DR resolution, we allow a dependent parameter type if it is the right
15264     // type anyway, to allow destroying operator delete in class templates.
15265     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15266                                                    ? DependentParamTypeDiag
15267                                                    : InvalidParamTypeDiag)
15268            << FnDecl->getDeclName() << ExpectedFirstParamType;
15269   }
15270 
15271   return false;
15272 }
15273 
15274 static bool
15275 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15276   // C++ [basic.stc.dynamic.allocation]p1:
15277   //   A program is ill-formed if an allocation function is declared in a
15278   //   namespace scope other than global scope or declared static in global
15279   //   scope.
15280   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15281     return true;
15282 
15283   CanQualType SizeTy =
15284     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15285 
15286   // C++ [basic.stc.dynamic.allocation]p1:
15287   //  The return type shall be void*. The first parameter shall have type
15288   //  std::size_t.
15289   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15290                                   SizeTy,
15291                                   diag::err_operator_new_dependent_param_type,
15292                                   diag::err_operator_new_param_type))
15293     return true;
15294 
15295   // C++ [basic.stc.dynamic.allocation]p1:
15296   //  The first parameter shall not have an associated default argument.
15297   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15298     return SemaRef.Diag(FnDecl->getLocation(),
15299                         diag::err_operator_new_default_arg)
15300       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15301 
15302   return false;
15303 }
15304 
15305 static bool
15306 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15307   // C++ [basic.stc.dynamic.deallocation]p1:
15308   //   A program is ill-formed if deallocation functions are declared in a
15309   //   namespace scope other than global scope or declared static in global
15310   //   scope.
15311   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15312     return true;
15313 
15314   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15315 
15316   // C++ P0722:
15317   //   Within a class C, the first parameter of a destroying operator delete
15318   //   shall be of type C *. The first parameter of any other deallocation
15319   //   function shall be of type void *.
15320   CanQualType ExpectedFirstParamType =
15321       MD && MD->isDestroyingOperatorDelete()
15322           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15323                 SemaRef.Context.getRecordType(MD->getParent())))
15324           : SemaRef.Context.VoidPtrTy;
15325 
15326   // C++ [basic.stc.dynamic.deallocation]p2:
15327   //   Each deallocation function shall return void
15328   if (CheckOperatorNewDeleteTypes(
15329           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15330           diag::err_operator_delete_dependent_param_type,
15331           diag::err_operator_delete_param_type))
15332     return true;
15333 
15334   // C++ P0722:
15335   //   A destroying operator delete shall be a usual deallocation function.
15336   if (MD && !MD->getParent()->isDependentContext() &&
15337       MD->isDestroyingOperatorDelete() &&
15338       !SemaRef.isUsualDeallocationFunction(MD)) {
15339     SemaRef.Diag(MD->getLocation(),
15340                  diag::err_destroying_operator_delete_not_usual);
15341     return true;
15342   }
15343 
15344   return false;
15345 }
15346 
15347 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15348 /// of this overloaded operator is well-formed. If so, returns false;
15349 /// otherwise, emits appropriate diagnostics and returns true.
15350 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15351   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15352          "Expected an overloaded operator declaration");
15353 
15354   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15355 
15356   // C++ [over.oper]p5:
15357   //   The allocation and deallocation functions, operator new,
15358   //   operator new[], operator delete and operator delete[], are
15359   //   described completely in 3.7.3. The attributes and restrictions
15360   //   found in the rest of this subclause do not apply to them unless
15361   //   explicitly stated in 3.7.3.
15362   if (Op == OO_Delete || Op == OO_Array_Delete)
15363     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15364 
15365   if (Op == OO_New || Op == OO_Array_New)
15366     return CheckOperatorNewDeclaration(*this, FnDecl);
15367 
15368   // C++ [over.oper]p6:
15369   //   An operator function shall either be a non-static member
15370   //   function or be a non-member function and have at least one
15371   //   parameter whose type is a class, a reference to a class, an
15372   //   enumeration, or a reference to an enumeration.
15373   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15374     if (MethodDecl->isStatic())
15375       return Diag(FnDecl->getLocation(),
15376                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15377   } else {
15378     bool ClassOrEnumParam = false;
15379     for (auto Param : FnDecl->parameters()) {
15380       QualType ParamType = Param->getType().getNonReferenceType();
15381       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15382           ParamType->isEnumeralType()) {
15383         ClassOrEnumParam = true;
15384         break;
15385       }
15386     }
15387 
15388     if (!ClassOrEnumParam)
15389       return Diag(FnDecl->getLocation(),
15390                   diag::err_operator_overload_needs_class_or_enum)
15391         << FnDecl->getDeclName();
15392   }
15393 
15394   // C++ [over.oper]p8:
15395   //   An operator function cannot have default arguments (8.3.6),
15396   //   except where explicitly stated below.
15397   //
15398   // Only the function-call operator allows default arguments
15399   // (C++ [over.call]p1).
15400   if (Op != OO_Call) {
15401     for (auto Param : FnDecl->parameters()) {
15402       if (Param->hasDefaultArg())
15403         return Diag(Param->getLocation(),
15404                     diag::err_operator_overload_default_arg)
15405           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15406     }
15407   }
15408 
15409   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15410     { false, false, false }
15411 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15412     , { Unary, Binary, MemberOnly }
15413 #include "clang/Basic/OperatorKinds.def"
15414   };
15415 
15416   bool CanBeUnaryOperator = OperatorUses[Op][0];
15417   bool CanBeBinaryOperator = OperatorUses[Op][1];
15418   bool MustBeMemberOperator = OperatorUses[Op][2];
15419 
15420   // C++ [over.oper]p8:
15421   //   [...] Operator functions cannot have more or fewer parameters
15422   //   than the number required for the corresponding operator, as
15423   //   described in the rest of this subclause.
15424   unsigned NumParams = FnDecl->getNumParams()
15425                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15426   if (Op != OO_Call &&
15427       ((NumParams == 1 && !CanBeUnaryOperator) ||
15428        (NumParams == 2 && !CanBeBinaryOperator) ||
15429        (NumParams < 1) || (NumParams > 2))) {
15430     // We have the wrong number of parameters.
15431     unsigned ErrorKind;
15432     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15433       ErrorKind = 2;  // 2 -> unary or binary.
15434     } else if (CanBeUnaryOperator) {
15435       ErrorKind = 0;  // 0 -> unary
15436     } else {
15437       assert(CanBeBinaryOperator &&
15438              "All non-call overloaded operators are unary or binary!");
15439       ErrorKind = 1;  // 1 -> binary
15440     }
15441 
15442     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15443       << FnDecl->getDeclName() << NumParams << ErrorKind;
15444   }
15445 
15446   // Overloaded operators other than operator() cannot be variadic.
15447   if (Op != OO_Call &&
15448       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15449     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15450       << FnDecl->getDeclName();
15451   }
15452 
15453   // Some operators must be non-static member functions.
15454   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15455     return Diag(FnDecl->getLocation(),
15456                 diag::err_operator_overload_must_be_member)
15457       << FnDecl->getDeclName();
15458   }
15459 
15460   // C++ [over.inc]p1:
15461   //   The user-defined function called operator++ implements the
15462   //   prefix and postfix ++ operator. If this function is a member
15463   //   function with no parameters, or a non-member function with one
15464   //   parameter of class or enumeration type, it defines the prefix
15465   //   increment operator ++ for objects of that type. If the function
15466   //   is a member function with one parameter (which shall be of type
15467   //   int) or a non-member function with two parameters (the second
15468   //   of which shall be of type int), it defines the postfix
15469   //   increment operator ++ for objects of that type.
15470   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15471     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15472     QualType ParamType = LastParam->getType();
15473 
15474     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15475         !ParamType->isDependentType())
15476       return Diag(LastParam->getLocation(),
15477                   diag::err_operator_overload_post_incdec_must_be_int)
15478         << LastParam->getType() << (Op == OO_MinusMinus);
15479   }
15480 
15481   return false;
15482 }
15483 
15484 static bool
15485 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15486                                           FunctionTemplateDecl *TpDecl) {
15487   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15488 
15489   // Must have one or two template parameters.
15490   if (TemplateParams->size() == 1) {
15491     NonTypeTemplateParmDecl *PmDecl =
15492         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15493 
15494     // The template parameter must be a char parameter pack.
15495     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15496         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15497       return false;
15498 
15499   } else if (TemplateParams->size() == 2) {
15500     TemplateTypeParmDecl *PmType =
15501         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15502     NonTypeTemplateParmDecl *PmArgs =
15503         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15504 
15505     // The second template parameter must be a parameter pack with the
15506     // first template parameter as its type.
15507     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15508         PmArgs->isTemplateParameterPack()) {
15509       const TemplateTypeParmType *TArgs =
15510           PmArgs->getType()->getAs<TemplateTypeParmType>();
15511       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15512           TArgs->getIndex() == PmType->getIndex()) {
15513         if (!SemaRef.inTemplateInstantiation())
15514           SemaRef.Diag(TpDecl->getLocation(),
15515                        diag::ext_string_literal_operator_template);
15516         return false;
15517       }
15518     }
15519   }
15520 
15521   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15522                diag::err_literal_operator_template)
15523       << TpDecl->getTemplateParameters()->getSourceRange();
15524   return true;
15525 }
15526 
15527 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15528 /// of this literal operator function is well-formed. If so, returns
15529 /// false; otherwise, emits appropriate diagnostics and returns true.
15530 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15531   if (isa<CXXMethodDecl>(FnDecl)) {
15532     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15533       << FnDecl->getDeclName();
15534     return true;
15535   }
15536 
15537   if (FnDecl->isExternC()) {
15538     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15539     if (const LinkageSpecDecl *LSD =
15540             FnDecl->getDeclContext()->getExternCContext())
15541       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15542     return true;
15543   }
15544 
15545   // This might be the definition of a literal operator template.
15546   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15547 
15548   // This might be a specialization of a literal operator template.
15549   if (!TpDecl)
15550     TpDecl = FnDecl->getPrimaryTemplate();
15551 
15552   // template <char...> type operator "" name() and
15553   // template <class T, T...> type operator "" name() are the only valid
15554   // template signatures, and the only valid signatures with no parameters.
15555   if (TpDecl) {
15556     if (FnDecl->param_size() != 0) {
15557       Diag(FnDecl->getLocation(),
15558            diag::err_literal_operator_template_with_params);
15559       return true;
15560     }
15561 
15562     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15563       return true;
15564 
15565   } else if (FnDecl->param_size() == 1) {
15566     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15567 
15568     QualType ParamType = Param->getType().getUnqualifiedType();
15569 
15570     // Only unsigned long long int, long double, any character type, and const
15571     // char * are allowed as the only parameters.
15572     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15573         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15574         Context.hasSameType(ParamType, Context.CharTy) ||
15575         Context.hasSameType(ParamType, Context.WideCharTy) ||
15576         Context.hasSameType(ParamType, Context.Char8Ty) ||
15577         Context.hasSameType(ParamType, Context.Char16Ty) ||
15578         Context.hasSameType(ParamType, Context.Char32Ty)) {
15579     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15580       QualType InnerType = Ptr->getPointeeType();
15581 
15582       // Pointer parameter must be a const char *.
15583       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15584                                 Context.CharTy) &&
15585             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15586         Diag(Param->getSourceRange().getBegin(),
15587              diag::err_literal_operator_param)
15588             << ParamType << "'const char *'" << Param->getSourceRange();
15589         return true;
15590       }
15591 
15592     } else if (ParamType->isRealFloatingType()) {
15593       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15594           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15595       return true;
15596 
15597     } else if (ParamType->isIntegerType()) {
15598       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15599           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15600       return true;
15601 
15602     } else {
15603       Diag(Param->getSourceRange().getBegin(),
15604            diag::err_literal_operator_invalid_param)
15605           << ParamType << Param->getSourceRange();
15606       return true;
15607     }
15608 
15609   } else if (FnDecl->param_size() == 2) {
15610     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15611 
15612     // First, verify that the first parameter is correct.
15613 
15614     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15615 
15616     // Two parameter function must have a pointer to const as a
15617     // first parameter; let's strip those qualifiers.
15618     const PointerType *PT = FirstParamType->getAs<PointerType>();
15619 
15620     if (!PT) {
15621       Diag((*Param)->getSourceRange().getBegin(),
15622            diag::err_literal_operator_param)
15623           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15624       return true;
15625     }
15626 
15627     QualType PointeeType = PT->getPointeeType();
15628     // First parameter must be const
15629     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15630       Diag((*Param)->getSourceRange().getBegin(),
15631            diag::err_literal_operator_param)
15632           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15633       return true;
15634     }
15635 
15636     QualType InnerType = PointeeType.getUnqualifiedType();
15637     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15638     // const char32_t* are allowed as the first parameter to a two-parameter
15639     // function
15640     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15641           Context.hasSameType(InnerType, Context.WideCharTy) ||
15642           Context.hasSameType(InnerType, Context.Char8Ty) ||
15643           Context.hasSameType(InnerType, Context.Char16Ty) ||
15644           Context.hasSameType(InnerType, Context.Char32Ty))) {
15645       Diag((*Param)->getSourceRange().getBegin(),
15646            diag::err_literal_operator_param)
15647           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15648       return true;
15649     }
15650 
15651     // Move on to the second and final parameter.
15652     ++Param;
15653 
15654     // The second parameter must be a std::size_t.
15655     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15656     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15657       Diag((*Param)->getSourceRange().getBegin(),
15658            diag::err_literal_operator_param)
15659           << SecondParamType << Context.getSizeType()
15660           << (*Param)->getSourceRange();
15661       return true;
15662     }
15663   } else {
15664     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15665     return true;
15666   }
15667 
15668   // Parameters are good.
15669 
15670   // A parameter-declaration-clause containing a default argument is not
15671   // equivalent to any of the permitted forms.
15672   for (auto Param : FnDecl->parameters()) {
15673     if (Param->hasDefaultArg()) {
15674       Diag(Param->getDefaultArgRange().getBegin(),
15675            diag::err_literal_operator_default_argument)
15676         << Param->getDefaultArgRange();
15677       break;
15678     }
15679   }
15680 
15681   StringRef LiteralName
15682     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15683   if (LiteralName[0] != '_' &&
15684       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15685     // C++11 [usrlit.suffix]p1:
15686     //   Literal suffix identifiers that do not start with an underscore
15687     //   are reserved for future standardization.
15688     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15689       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15690   }
15691 
15692   return false;
15693 }
15694 
15695 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15696 /// linkage specification, including the language and (if present)
15697 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15698 /// language string literal. LBraceLoc, if valid, provides the location of
15699 /// the '{' brace. Otherwise, this linkage specification does not
15700 /// have any braces.
15701 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15702                                            Expr *LangStr,
15703                                            SourceLocation LBraceLoc) {
15704   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15705   if (!Lit->isAscii()) {
15706     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15707       << LangStr->getSourceRange();
15708     return nullptr;
15709   }
15710 
15711   StringRef Lang = Lit->getString();
15712   LinkageSpecDecl::LanguageIDs Language;
15713   if (Lang == "C")
15714     Language = LinkageSpecDecl::lang_c;
15715   else if (Lang == "C++")
15716     Language = LinkageSpecDecl::lang_cxx;
15717   else {
15718     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15719       << LangStr->getSourceRange();
15720     return nullptr;
15721   }
15722 
15723   // FIXME: Add all the various semantics of linkage specifications
15724 
15725   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15726                                                LangStr->getExprLoc(), Language,
15727                                                LBraceLoc.isValid());
15728   CurContext->addDecl(D);
15729   PushDeclContext(S, D);
15730   return D;
15731 }
15732 
15733 /// ActOnFinishLinkageSpecification - Complete the definition of
15734 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15735 /// valid, it's the position of the closing '}' brace in a linkage
15736 /// specification that uses braces.
15737 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15738                                             Decl *LinkageSpec,
15739                                             SourceLocation RBraceLoc) {
15740   if (RBraceLoc.isValid()) {
15741     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15742     LSDecl->setRBraceLoc(RBraceLoc);
15743   }
15744   PopDeclContext();
15745   return LinkageSpec;
15746 }
15747 
15748 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15749                                   const ParsedAttributesView &AttrList,
15750                                   SourceLocation SemiLoc) {
15751   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15752   // Attribute declarations appertain to empty declaration so we handle
15753   // them here.
15754   ProcessDeclAttributeList(S, ED, AttrList);
15755 
15756   CurContext->addDecl(ED);
15757   return ED;
15758 }
15759 
15760 /// Perform semantic analysis for the variable declaration that
15761 /// occurs within a C++ catch clause, returning the newly-created
15762 /// variable.
15763 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15764                                          TypeSourceInfo *TInfo,
15765                                          SourceLocation StartLoc,
15766                                          SourceLocation Loc,
15767                                          IdentifierInfo *Name) {
15768   bool Invalid = false;
15769   QualType ExDeclType = TInfo->getType();
15770 
15771   // Arrays and functions decay.
15772   if (ExDeclType->isArrayType())
15773     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15774   else if (ExDeclType->isFunctionType())
15775     ExDeclType = Context.getPointerType(ExDeclType);
15776 
15777   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15778   // The exception-declaration shall not denote a pointer or reference to an
15779   // incomplete type, other than [cv] void*.
15780   // N2844 forbids rvalue references.
15781   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15782     Diag(Loc, diag::err_catch_rvalue_ref);
15783     Invalid = true;
15784   }
15785 
15786   if (ExDeclType->isVariablyModifiedType()) {
15787     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15788     Invalid = true;
15789   }
15790 
15791   QualType BaseType = ExDeclType;
15792   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15793   unsigned DK = diag::err_catch_incomplete;
15794   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15795     BaseType = Ptr->getPointeeType();
15796     Mode = 1;
15797     DK = diag::err_catch_incomplete_ptr;
15798   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15799     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15800     BaseType = Ref->getPointeeType();
15801     Mode = 2;
15802     DK = diag::err_catch_incomplete_ref;
15803   }
15804   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15805       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15806     Invalid = true;
15807 
15808   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15809     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15810     Invalid = true;
15811   }
15812 
15813   if (!Invalid && !ExDeclType->isDependentType() &&
15814       RequireNonAbstractType(Loc, ExDeclType,
15815                              diag::err_abstract_type_in_decl,
15816                              AbstractVariableType))
15817     Invalid = true;
15818 
15819   // Only the non-fragile NeXT runtime currently supports C++ catches
15820   // of ObjC types, and no runtime supports catching ObjC types by value.
15821   if (!Invalid && getLangOpts().ObjC) {
15822     QualType T = ExDeclType;
15823     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15824       T = RT->getPointeeType();
15825 
15826     if (T->isObjCObjectType()) {
15827       Diag(Loc, diag::err_objc_object_catch);
15828       Invalid = true;
15829     } else if (T->isObjCObjectPointerType()) {
15830       // FIXME: should this be a test for macosx-fragile specifically?
15831       if (getLangOpts().ObjCRuntime.isFragile())
15832         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15833     }
15834   }
15835 
15836   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15837                                     ExDeclType, TInfo, SC_None);
15838   ExDecl->setExceptionVariable(true);
15839 
15840   // In ARC, infer 'retaining' for variables of retainable type.
15841   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15842     Invalid = true;
15843 
15844   if (!Invalid && !ExDeclType->isDependentType()) {
15845     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15846       // Insulate this from anything else we might currently be parsing.
15847       EnterExpressionEvaluationContext scope(
15848           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15849 
15850       // C++ [except.handle]p16:
15851       //   The object declared in an exception-declaration or, if the
15852       //   exception-declaration does not specify a name, a temporary (12.2) is
15853       //   copy-initialized (8.5) from the exception object. [...]
15854       //   The object is destroyed when the handler exits, after the destruction
15855       //   of any automatic objects initialized within the handler.
15856       //
15857       // We just pretend to initialize the object with itself, then make sure
15858       // it can be destroyed later.
15859       QualType initType = Context.getExceptionObjectType(ExDeclType);
15860 
15861       InitializedEntity entity =
15862         InitializedEntity::InitializeVariable(ExDecl);
15863       InitializationKind initKind =
15864         InitializationKind::CreateCopy(Loc, SourceLocation());
15865 
15866       Expr *opaqueValue =
15867         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15868       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15869       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15870       if (result.isInvalid())
15871         Invalid = true;
15872       else {
15873         // If the constructor used was non-trivial, set this as the
15874         // "initializer".
15875         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15876         if (!construct->getConstructor()->isTrivial()) {
15877           Expr *init = MaybeCreateExprWithCleanups(construct);
15878           ExDecl->setInit(init);
15879         }
15880 
15881         // And make sure it's destructable.
15882         FinalizeVarWithDestructor(ExDecl, recordType);
15883       }
15884     }
15885   }
15886 
15887   if (Invalid)
15888     ExDecl->setInvalidDecl();
15889 
15890   return ExDecl;
15891 }
15892 
15893 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15894 /// handler.
15895 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15896   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15897   bool Invalid = D.isInvalidType();
15898 
15899   // Check for unexpanded parameter packs.
15900   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15901                                       UPPC_ExceptionType)) {
15902     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15903                                              D.getIdentifierLoc());
15904     Invalid = true;
15905   }
15906 
15907   IdentifierInfo *II = D.getIdentifier();
15908   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15909                                              LookupOrdinaryName,
15910                                              ForVisibleRedeclaration)) {
15911     // The scope should be freshly made just for us. There is just no way
15912     // it contains any previous declaration, except for function parameters in
15913     // a function-try-block's catch statement.
15914     assert(!S->isDeclScope(PrevDecl));
15915     if (isDeclInScope(PrevDecl, CurContext, S)) {
15916       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15917         << D.getIdentifier();
15918       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15919       Invalid = true;
15920     } else if (PrevDecl->isTemplateParameter())
15921       // Maybe we will complain about the shadowed template parameter.
15922       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15923   }
15924 
15925   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15926     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15927       << D.getCXXScopeSpec().getRange();
15928     Invalid = true;
15929   }
15930 
15931   VarDecl *ExDecl = BuildExceptionDeclaration(
15932       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15933   if (Invalid)
15934     ExDecl->setInvalidDecl();
15935 
15936   // Add the exception declaration into this scope.
15937   if (II)
15938     PushOnScopeChains(ExDecl, S);
15939   else
15940     CurContext->addDecl(ExDecl);
15941 
15942   ProcessDeclAttributes(S, ExDecl, D);
15943   return ExDecl;
15944 }
15945 
15946 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15947                                          Expr *AssertExpr,
15948                                          Expr *AssertMessageExpr,
15949                                          SourceLocation RParenLoc) {
15950   StringLiteral *AssertMessage =
15951       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15952 
15953   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15954     return nullptr;
15955 
15956   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15957                                       AssertMessage, RParenLoc, false);
15958 }
15959 
15960 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15961                                          Expr *AssertExpr,
15962                                          StringLiteral *AssertMessage,
15963                                          SourceLocation RParenLoc,
15964                                          bool Failed) {
15965   assert(AssertExpr != nullptr && "Expected non-null condition");
15966   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15967       !Failed) {
15968     // In a static_assert-declaration, the constant-expression shall be a
15969     // constant expression that can be contextually converted to bool.
15970     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15971     if (Converted.isInvalid())
15972       Failed = true;
15973 
15974     ExprResult FullAssertExpr =
15975         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15976                             /*DiscardedValue*/ false,
15977                             /*IsConstexpr*/ true);
15978     if (FullAssertExpr.isInvalid())
15979       Failed = true;
15980     else
15981       AssertExpr = FullAssertExpr.get();
15982 
15983     llvm::APSInt Cond;
15984     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15985           diag::err_static_assert_expression_is_not_constant,
15986           /*AllowFold=*/false).isInvalid())
15987       Failed = true;
15988 
15989     if (!Failed && !Cond) {
15990       SmallString<256> MsgBuffer;
15991       llvm::raw_svector_ostream Msg(MsgBuffer);
15992       if (AssertMessage)
15993         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
15994 
15995       Expr *InnerCond = nullptr;
15996       std::string InnerCondDescription;
15997       std::tie(InnerCond, InnerCondDescription) =
15998         findFailedBooleanCondition(Converted.get());
15999       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16000         // Drill down into concept specialization expressions to see why they
16001         // weren't satisfied.
16002         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16003           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16004         ConstraintSatisfaction Satisfaction;
16005         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16006           DiagnoseUnsatisfiedConstraint(Satisfaction);
16007       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16008                            && !isa<IntegerLiteral>(InnerCond)) {
16009         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16010           << InnerCondDescription << !AssertMessage
16011           << Msg.str() << InnerCond->getSourceRange();
16012       } else {
16013         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16014           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16015       }
16016       Failed = true;
16017     }
16018   } else {
16019     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16020                                                     /*DiscardedValue*/false,
16021                                                     /*IsConstexpr*/true);
16022     if (FullAssertExpr.isInvalid())
16023       Failed = true;
16024     else
16025       AssertExpr = FullAssertExpr.get();
16026   }
16027 
16028   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16029                                         AssertExpr, AssertMessage, RParenLoc,
16030                                         Failed);
16031 
16032   CurContext->addDecl(Decl);
16033   return Decl;
16034 }
16035 
16036 /// Perform semantic analysis of the given friend type declaration.
16037 ///
16038 /// \returns A friend declaration that.
16039 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16040                                       SourceLocation FriendLoc,
16041                                       TypeSourceInfo *TSInfo) {
16042   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16043 
16044   QualType T = TSInfo->getType();
16045   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16046 
16047   // C++03 [class.friend]p2:
16048   //   An elaborated-type-specifier shall be used in a friend declaration
16049   //   for a class.*
16050   //
16051   //   * The class-key of the elaborated-type-specifier is required.
16052   if (!CodeSynthesisContexts.empty()) {
16053     // Do not complain about the form of friend template types during any kind
16054     // of code synthesis. For template instantiation, we will have complained
16055     // when the template was defined.
16056   } else {
16057     if (!T->isElaboratedTypeSpecifier()) {
16058       // If we evaluated the type to a record type, suggest putting
16059       // a tag in front.
16060       if (const RecordType *RT = T->getAs<RecordType>()) {
16061         RecordDecl *RD = RT->getDecl();
16062 
16063         SmallString<16> InsertionText(" ");
16064         InsertionText += RD->getKindName();
16065 
16066         Diag(TypeRange.getBegin(),
16067              getLangOpts().CPlusPlus11 ?
16068                diag::warn_cxx98_compat_unelaborated_friend_type :
16069                diag::ext_unelaborated_friend_type)
16070           << (unsigned) RD->getTagKind()
16071           << T
16072           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16073                                         InsertionText);
16074       } else {
16075         Diag(FriendLoc,
16076              getLangOpts().CPlusPlus11 ?
16077                diag::warn_cxx98_compat_nonclass_type_friend :
16078                diag::ext_nonclass_type_friend)
16079           << T
16080           << TypeRange;
16081       }
16082     } else if (T->getAs<EnumType>()) {
16083       Diag(FriendLoc,
16084            getLangOpts().CPlusPlus11 ?
16085              diag::warn_cxx98_compat_enum_friend :
16086              diag::ext_enum_friend)
16087         << T
16088         << TypeRange;
16089     }
16090 
16091     // C++11 [class.friend]p3:
16092     //   A friend declaration that does not declare a function shall have one
16093     //   of the following forms:
16094     //     friend elaborated-type-specifier ;
16095     //     friend simple-type-specifier ;
16096     //     friend typename-specifier ;
16097     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16098       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16099   }
16100 
16101   //   If the type specifier in a friend declaration designates a (possibly
16102   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16103   //   the friend declaration is ignored.
16104   return FriendDecl::Create(Context, CurContext,
16105                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16106                             FriendLoc);
16107 }
16108 
16109 /// Handle a friend tag declaration where the scope specifier was
16110 /// templated.
16111 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16112                                     unsigned TagSpec, SourceLocation TagLoc,
16113                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16114                                     SourceLocation NameLoc,
16115                                     const ParsedAttributesView &Attr,
16116                                     MultiTemplateParamsArg TempParamLists) {
16117   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16118 
16119   bool IsMemberSpecialization = false;
16120   bool Invalid = false;
16121 
16122   if (TemplateParameterList *TemplateParams =
16123           MatchTemplateParametersToScopeSpecifier(
16124               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16125               IsMemberSpecialization, Invalid)) {
16126     if (TemplateParams->size() > 0) {
16127       // This is a declaration of a class template.
16128       if (Invalid)
16129         return nullptr;
16130 
16131       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16132                                 NameLoc, Attr, TemplateParams, AS_public,
16133                                 /*ModulePrivateLoc=*/SourceLocation(),
16134                                 FriendLoc, TempParamLists.size() - 1,
16135                                 TempParamLists.data()).get();
16136     } else {
16137       // The "template<>" header is extraneous.
16138       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16139         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16140       IsMemberSpecialization = true;
16141     }
16142   }
16143 
16144   if (Invalid) return nullptr;
16145 
16146   bool isAllExplicitSpecializations = true;
16147   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16148     if (TempParamLists[I]->size()) {
16149       isAllExplicitSpecializations = false;
16150       break;
16151     }
16152   }
16153 
16154   // FIXME: don't ignore attributes.
16155 
16156   // If it's explicit specializations all the way down, just forget
16157   // about the template header and build an appropriate non-templated
16158   // friend.  TODO: for source fidelity, remember the headers.
16159   if (isAllExplicitSpecializations) {
16160     if (SS.isEmpty()) {
16161       bool Owned = false;
16162       bool IsDependent = false;
16163       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16164                       Attr, AS_public,
16165                       /*ModulePrivateLoc=*/SourceLocation(),
16166                       MultiTemplateParamsArg(), Owned, IsDependent,
16167                       /*ScopedEnumKWLoc=*/SourceLocation(),
16168                       /*ScopedEnumUsesClassTag=*/false,
16169                       /*UnderlyingType=*/TypeResult(),
16170                       /*IsTypeSpecifier=*/false,
16171                       /*IsTemplateParamOrArg=*/false);
16172     }
16173 
16174     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16175     ElaboratedTypeKeyword Keyword
16176       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16177     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16178                                    *Name, NameLoc);
16179     if (T.isNull())
16180       return nullptr;
16181 
16182     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16183     if (isa<DependentNameType>(T)) {
16184       DependentNameTypeLoc TL =
16185           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16186       TL.setElaboratedKeywordLoc(TagLoc);
16187       TL.setQualifierLoc(QualifierLoc);
16188       TL.setNameLoc(NameLoc);
16189     } else {
16190       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16191       TL.setElaboratedKeywordLoc(TagLoc);
16192       TL.setQualifierLoc(QualifierLoc);
16193       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16194     }
16195 
16196     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16197                                             TSI, FriendLoc, TempParamLists);
16198     Friend->setAccess(AS_public);
16199     CurContext->addDecl(Friend);
16200     return Friend;
16201   }
16202 
16203   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16204 
16205 
16206 
16207   // Handle the case of a templated-scope friend class.  e.g.
16208   //   template <class T> class A<T>::B;
16209   // FIXME: we don't support these right now.
16210   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16211     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16212   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16213   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16214   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16215   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16216   TL.setElaboratedKeywordLoc(TagLoc);
16217   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16218   TL.setNameLoc(NameLoc);
16219 
16220   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16221                                           TSI, FriendLoc, TempParamLists);
16222   Friend->setAccess(AS_public);
16223   Friend->setUnsupportedFriend(true);
16224   CurContext->addDecl(Friend);
16225   return Friend;
16226 }
16227 
16228 /// Handle a friend type declaration.  This works in tandem with
16229 /// ActOnTag.
16230 ///
16231 /// Notes on friend class templates:
16232 ///
16233 /// We generally treat friend class declarations as if they were
16234 /// declaring a class.  So, for example, the elaborated type specifier
16235 /// in a friend declaration is required to obey the restrictions of a
16236 /// class-head (i.e. no typedefs in the scope chain), template
16237 /// parameters are required to match up with simple template-ids, &c.
16238 /// However, unlike when declaring a template specialization, it's
16239 /// okay to refer to a template specialization without an empty
16240 /// template parameter declaration, e.g.
16241 ///   friend class A<T>::B<unsigned>;
16242 /// We permit this as a special case; if there are any template
16243 /// parameters present at all, require proper matching, i.e.
16244 ///   template <> template \<class T> friend class A<int>::B;
16245 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16246                                 MultiTemplateParamsArg TempParams) {
16247   SourceLocation Loc = DS.getBeginLoc();
16248 
16249   assert(DS.isFriendSpecified());
16250   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16251 
16252   // C++ [class.friend]p3:
16253   // A friend declaration that does not declare a function shall have one of
16254   // the following forms:
16255   //     friend elaborated-type-specifier ;
16256   //     friend simple-type-specifier ;
16257   //     friend typename-specifier ;
16258   //
16259   // Any declaration with a type qualifier does not have that form. (It's
16260   // legal to specify a qualified type as a friend, you just can't write the
16261   // keywords.)
16262   if (DS.getTypeQualifiers()) {
16263     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16264       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16265     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16266       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16267     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16268       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16269     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16270       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16271     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16272       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16273   }
16274 
16275   // Try to convert the decl specifier to a type.  This works for
16276   // friend templates because ActOnTag never produces a ClassTemplateDecl
16277   // for a TUK_Friend.
16278   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16279   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16280   QualType T = TSI->getType();
16281   if (TheDeclarator.isInvalidType())
16282     return nullptr;
16283 
16284   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16285     return nullptr;
16286 
16287   // This is definitely an error in C++98.  It's probably meant to
16288   // be forbidden in C++0x, too, but the specification is just
16289   // poorly written.
16290   //
16291   // The problem is with declarations like the following:
16292   //   template <T> friend A<T>::foo;
16293   // where deciding whether a class C is a friend or not now hinges
16294   // on whether there exists an instantiation of A that causes
16295   // 'foo' to equal C.  There are restrictions on class-heads
16296   // (which we declare (by fiat) elaborated friend declarations to
16297   // be) that makes this tractable.
16298   //
16299   // FIXME: handle "template <> friend class A<T>;", which
16300   // is possibly well-formed?  Who even knows?
16301   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16302     Diag(Loc, diag::err_tagless_friend_type_template)
16303       << DS.getSourceRange();
16304     return nullptr;
16305   }
16306 
16307   // C++98 [class.friend]p1: A friend of a class is a function
16308   //   or class that is not a member of the class . . .
16309   // This is fixed in DR77, which just barely didn't make the C++03
16310   // deadline.  It's also a very silly restriction that seriously
16311   // affects inner classes and which nobody else seems to implement;
16312   // thus we never diagnose it, not even in -pedantic.
16313   //
16314   // But note that we could warn about it: it's always useless to
16315   // friend one of your own members (it's not, however, worthless to
16316   // friend a member of an arbitrary specialization of your template).
16317 
16318   Decl *D;
16319   if (!TempParams.empty())
16320     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16321                                    TempParams,
16322                                    TSI,
16323                                    DS.getFriendSpecLoc());
16324   else
16325     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16326 
16327   if (!D)
16328     return nullptr;
16329 
16330   D->setAccess(AS_public);
16331   CurContext->addDecl(D);
16332 
16333   return D;
16334 }
16335 
16336 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16337                                         MultiTemplateParamsArg TemplateParams) {
16338   const DeclSpec &DS = D.getDeclSpec();
16339 
16340   assert(DS.isFriendSpecified());
16341   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16342 
16343   SourceLocation Loc = D.getIdentifierLoc();
16344   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16345 
16346   // C++ [class.friend]p1
16347   //   A friend of a class is a function or class....
16348   // Note that this sees through typedefs, which is intended.
16349   // It *doesn't* see through dependent types, which is correct
16350   // according to [temp.arg.type]p3:
16351   //   If a declaration acquires a function type through a
16352   //   type dependent on a template-parameter and this causes
16353   //   a declaration that does not use the syntactic form of a
16354   //   function declarator to have a function type, the program
16355   //   is ill-formed.
16356   if (!TInfo->getType()->isFunctionType()) {
16357     Diag(Loc, diag::err_unexpected_friend);
16358 
16359     // It might be worthwhile to try to recover by creating an
16360     // appropriate declaration.
16361     return nullptr;
16362   }
16363 
16364   // C++ [namespace.memdef]p3
16365   //  - If a friend declaration in a non-local class first declares a
16366   //    class or function, the friend class or function is a member
16367   //    of the innermost enclosing namespace.
16368   //  - The name of the friend is not found by simple name lookup
16369   //    until a matching declaration is provided in that namespace
16370   //    scope (either before or after the class declaration granting
16371   //    friendship).
16372   //  - If a friend function is called, its name may be found by the
16373   //    name lookup that considers functions from namespaces and
16374   //    classes associated with the types of the function arguments.
16375   //  - When looking for a prior declaration of a class or a function
16376   //    declared as a friend, scopes outside the innermost enclosing
16377   //    namespace scope are not considered.
16378 
16379   CXXScopeSpec &SS = D.getCXXScopeSpec();
16380   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16381   assert(NameInfo.getName());
16382 
16383   // Check for unexpanded parameter packs.
16384   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16385       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16386       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16387     return nullptr;
16388 
16389   // The context we found the declaration in, or in which we should
16390   // create the declaration.
16391   DeclContext *DC;
16392   Scope *DCScope = S;
16393   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16394                         ForExternalRedeclaration);
16395 
16396   // There are five cases here.
16397   //   - There's no scope specifier and we're in a local class. Only look
16398   //     for functions declared in the immediately-enclosing block scope.
16399   // We recover from invalid scope qualifiers as if they just weren't there.
16400   FunctionDecl *FunctionContainingLocalClass = nullptr;
16401   if ((SS.isInvalid() || !SS.isSet()) &&
16402       (FunctionContainingLocalClass =
16403            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16404     // C++11 [class.friend]p11:
16405     //   If a friend declaration appears in a local class and the name
16406     //   specified is an unqualified name, a prior declaration is
16407     //   looked up without considering scopes that are outside the
16408     //   innermost enclosing non-class scope. For a friend function
16409     //   declaration, if there is no prior declaration, the program is
16410     //   ill-formed.
16411 
16412     // Find the innermost enclosing non-class scope. This is the block
16413     // scope containing the local class definition (or for a nested class,
16414     // the outer local class).
16415     DCScope = S->getFnParent();
16416 
16417     // Look up the function name in the scope.
16418     Previous.clear(LookupLocalFriendName);
16419     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16420 
16421     if (!Previous.empty()) {
16422       // All possible previous declarations must have the same context:
16423       // either they were declared at block scope or they are members of
16424       // one of the enclosing local classes.
16425       DC = Previous.getRepresentativeDecl()->getDeclContext();
16426     } else {
16427       // This is ill-formed, but provide the context that we would have
16428       // declared the function in, if we were permitted to, for error recovery.
16429       DC = FunctionContainingLocalClass;
16430     }
16431     adjustContextForLocalExternDecl(DC);
16432 
16433     // C++ [class.friend]p6:
16434     //   A function can be defined in a friend declaration of a class if and
16435     //   only if the class is a non-local class (9.8), the function name is
16436     //   unqualified, and the function has namespace scope.
16437     if (D.isFunctionDefinition()) {
16438       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16439     }
16440 
16441   //   - There's no scope specifier, in which case we just go to the
16442   //     appropriate scope and look for a function or function template
16443   //     there as appropriate.
16444   } else if (SS.isInvalid() || !SS.isSet()) {
16445     // C++11 [namespace.memdef]p3:
16446     //   If the name in a friend declaration is neither qualified nor
16447     //   a template-id and the declaration is a function or an
16448     //   elaborated-type-specifier, the lookup to determine whether
16449     //   the entity has been previously declared shall not consider
16450     //   any scopes outside the innermost enclosing namespace.
16451     bool isTemplateId =
16452         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16453 
16454     // Find the appropriate context according to the above.
16455     DC = CurContext;
16456 
16457     // Skip class contexts.  If someone can cite chapter and verse
16458     // for this behavior, that would be nice --- it's what GCC and
16459     // EDG do, and it seems like a reasonable intent, but the spec
16460     // really only says that checks for unqualified existing
16461     // declarations should stop at the nearest enclosing namespace,
16462     // not that they should only consider the nearest enclosing
16463     // namespace.
16464     while (DC->isRecord())
16465       DC = DC->getParent();
16466 
16467     DeclContext *LookupDC = DC;
16468     while (LookupDC->isTransparentContext())
16469       LookupDC = LookupDC->getParent();
16470 
16471     while (true) {
16472       LookupQualifiedName(Previous, LookupDC);
16473 
16474       if (!Previous.empty()) {
16475         DC = LookupDC;
16476         break;
16477       }
16478 
16479       if (isTemplateId) {
16480         if (isa<TranslationUnitDecl>(LookupDC)) break;
16481       } else {
16482         if (LookupDC->isFileContext()) break;
16483       }
16484       LookupDC = LookupDC->getParent();
16485     }
16486 
16487     DCScope = getScopeForDeclContext(S, DC);
16488 
16489   //   - There's a non-dependent scope specifier, in which case we
16490   //     compute it and do a previous lookup there for a function
16491   //     or function template.
16492   } else if (!SS.getScopeRep()->isDependent()) {
16493     DC = computeDeclContext(SS);
16494     if (!DC) return nullptr;
16495 
16496     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16497 
16498     LookupQualifiedName(Previous, DC);
16499 
16500     // C++ [class.friend]p1: A friend of a class is a function or
16501     //   class that is not a member of the class . . .
16502     if (DC->Equals(CurContext))
16503       Diag(DS.getFriendSpecLoc(),
16504            getLangOpts().CPlusPlus11 ?
16505              diag::warn_cxx98_compat_friend_is_member :
16506              diag::err_friend_is_member);
16507 
16508     if (D.isFunctionDefinition()) {
16509       // C++ [class.friend]p6:
16510       //   A function can be defined in a friend declaration of a class if and
16511       //   only if the class is a non-local class (9.8), the function name is
16512       //   unqualified, and the function has namespace scope.
16513       //
16514       // FIXME: We should only do this if the scope specifier names the
16515       // innermost enclosing namespace; otherwise the fixit changes the
16516       // meaning of the code.
16517       SemaDiagnosticBuilder DB
16518         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16519 
16520       DB << SS.getScopeRep();
16521       if (DC->isFileContext())
16522         DB << FixItHint::CreateRemoval(SS.getRange());
16523       SS.clear();
16524     }
16525 
16526   //   - There's a scope specifier that does not match any template
16527   //     parameter lists, in which case we use some arbitrary context,
16528   //     create a method or method template, and wait for instantiation.
16529   //   - There's a scope specifier that does match some template
16530   //     parameter lists, which we don't handle right now.
16531   } else {
16532     if (D.isFunctionDefinition()) {
16533       // C++ [class.friend]p6:
16534       //   A function can be defined in a friend declaration of a class if and
16535       //   only if the class is a non-local class (9.8), the function name is
16536       //   unqualified, and the function has namespace scope.
16537       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16538         << SS.getScopeRep();
16539     }
16540 
16541     DC = CurContext;
16542     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16543   }
16544 
16545   if (!DC->isRecord()) {
16546     int DiagArg = -1;
16547     switch (D.getName().getKind()) {
16548     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16549     case UnqualifiedIdKind::IK_ConstructorName:
16550       DiagArg = 0;
16551       break;
16552     case UnqualifiedIdKind::IK_DestructorName:
16553       DiagArg = 1;
16554       break;
16555     case UnqualifiedIdKind::IK_ConversionFunctionId:
16556       DiagArg = 2;
16557       break;
16558     case UnqualifiedIdKind::IK_DeductionGuideName:
16559       DiagArg = 3;
16560       break;
16561     case UnqualifiedIdKind::IK_Identifier:
16562     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16563     case UnqualifiedIdKind::IK_LiteralOperatorId:
16564     case UnqualifiedIdKind::IK_OperatorFunctionId:
16565     case UnqualifiedIdKind::IK_TemplateId:
16566       break;
16567     }
16568     // This implies that it has to be an operator or function.
16569     if (DiagArg >= 0) {
16570       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16571       return nullptr;
16572     }
16573   }
16574 
16575   // FIXME: This is an egregious hack to cope with cases where the scope stack
16576   // does not contain the declaration context, i.e., in an out-of-line
16577   // definition of a class.
16578   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16579   if (!DCScope) {
16580     FakeDCScope.setEntity(DC);
16581     DCScope = &FakeDCScope;
16582   }
16583 
16584   bool AddToScope = true;
16585   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16586                                           TemplateParams, AddToScope);
16587   if (!ND) return nullptr;
16588 
16589   assert(ND->getLexicalDeclContext() == CurContext);
16590 
16591   // If we performed typo correction, we might have added a scope specifier
16592   // and changed the decl context.
16593   DC = ND->getDeclContext();
16594 
16595   // Add the function declaration to the appropriate lookup tables,
16596   // adjusting the redeclarations list as necessary.  We don't
16597   // want to do this yet if the friending class is dependent.
16598   //
16599   // Also update the scope-based lookup if the target context's
16600   // lookup context is in lexical scope.
16601   if (!CurContext->isDependentContext()) {
16602     DC = DC->getRedeclContext();
16603     DC->makeDeclVisibleInContext(ND);
16604     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16605       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16606   }
16607 
16608   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16609                                        D.getIdentifierLoc(), ND,
16610                                        DS.getFriendSpecLoc());
16611   FrD->setAccess(AS_public);
16612   CurContext->addDecl(FrD);
16613 
16614   if (ND->isInvalidDecl()) {
16615     FrD->setInvalidDecl();
16616   } else {
16617     if (DC->isRecord()) CheckFriendAccess(ND);
16618 
16619     FunctionDecl *FD;
16620     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16621       FD = FTD->getTemplatedDecl();
16622     else
16623       FD = cast<FunctionDecl>(ND);
16624 
16625     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16626     // default argument expression, that declaration shall be a definition
16627     // and shall be the only declaration of the function or function
16628     // template in the translation unit.
16629     if (functionDeclHasDefaultArgument(FD)) {
16630       // We can't look at FD->getPreviousDecl() because it may not have been set
16631       // if we're in a dependent context. If the function is known to be a
16632       // redeclaration, we will have narrowed Previous down to the right decl.
16633       if (D.isRedeclaration()) {
16634         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16635         Diag(Previous.getRepresentativeDecl()->getLocation(),
16636              diag::note_previous_declaration);
16637       } else if (!D.isFunctionDefinition())
16638         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16639     }
16640 
16641     // Mark templated-scope function declarations as unsupported.
16642     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16643       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16644         << SS.getScopeRep() << SS.getRange()
16645         << cast<CXXRecordDecl>(CurContext);
16646       FrD->setUnsupportedFriend(true);
16647     }
16648   }
16649 
16650   return ND;
16651 }
16652 
16653 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16654   AdjustDeclIfTemplate(Dcl);
16655 
16656   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16657   if (!Fn) {
16658     Diag(DelLoc, diag::err_deleted_non_function);
16659     return;
16660   }
16661 
16662   // Deleted function does not have a body.
16663   Fn->setWillHaveBody(false);
16664 
16665   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16666     // Don't consider the implicit declaration we generate for explicit
16667     // specializations. FIXME: Do not generate these implicit declarations.
16668     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16669          Prev->getPreviousDecl()) &&
16670         !Prev->isDefined()) {
16671       Diag(DelLoc, diag::err_deleted_decl_not_first);
16672       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16673            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16674                               : diag::note_previous_declaration);
16675       // We can't recover from this; the declaration might have already
16676       // been used.
16677       Fn->setInvalidDecl();
16678       return;
16679     }
16680 
16681     // To maintain the invariant that functions are only deleted on their first
16682     // declaration, mark the implicitly-instantiated declaration of the
16683     // explicitly-specialized function as deleted instead of marking the
16684     // instantiated redeclaration.
16685     Fn = Fn->getCanonicalDecl();
16686   }
16687 
16688   // dllimport/dllexport cannot be deleted.
16689   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16690     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16691     Fn->setInvalidDecl();
16692   }
16693 
16694   // C++11 [basic.start.main]p3:
16695   //   A program that defines main as deleted [...] is ill-formed.
16696   if (Fn->isMain())
16697     Diag(DelLoc, diag::err_deleted_main);
16698 
16699   // C++11 [dcl.fct.def.delete]p4:
16700   //  A deleted function is implicitly inline.
16701   Fn->setImplicitlyInline();
16702   Fn->setDeletedAsWritten();
16703 }
16704 
16705 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16706   if (!Dcl || Dcl->isInvalidDecl())
16707     return;
16708 
16709   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16710   if (!FD) {
16711     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16712       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16713         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16714         return;
16715       }
16716     }
16717 
16718     Diag(DefaultLoc, diag::err_default_special_members)
16719         << getLangOpts().CPlusPlus20;
16720     return;
16721   }
16722 
16723   // Reject if this can't possibly be a defaultable function.
16724   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16725   if (!DefKind &&
16726       // A dependent function that doesn't locally look defaultable can
16727       // still instantiate to a defaultable function if it's a constructor
16728       // or assignment operator.
16729       (!FD->isDependentContext() ||
16730        (!isa<CXXConstructorDecl>(FD) &&
16731         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16732     Diag(DefaultLoc, diag::err_default_special_members)
16733         << getLangOpts().CPlusPlus20;
16734     return;
16735   }
16736 
16737   if (DefKind.isComparison() &&
16738       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16739     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16740         << (int)DefKind.asComparison();
16741     return;
16742   }
16743 
16744   // Issue compatibility warning. We already warned if the operator is
16745   // 'operator<=>' when parsing the '<=>' token.
16746   if (DefKind.isComparison() &&
16747       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16748     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16749                          ? diag::warn_cxx17_compat_defaulted_comparison
16750                          : diag::ext_defaulted_comparison);
16751   }
16752 
16753   FD->setDefaulted();
16754   FD->setExplicitlyDefaulted();
16755 
16756   // Defer checking functions that are defaulted in a dependent context.
16757   if (FD->isDependentContext())
16758     return;
16759 
16760   // Unset that we will have a body for this function. We might not,
16761   // if it turns out to be trivial, and we don't need this marking now
16762   // that we've marked it as defaulted.
16763   FD->setWillHaveBody(false);
16764 
16765   // If this definition appears within the record, do the checking when
16766   // the record is complete. This is always the case for a defaulted
16767   // comparison.
16768   if (DefKind.isComparison())
16769     return;
16770   auto *MD = cast<CXXMethodDecl>(FD);
16771 
16772   const FunctionDecl *Primary = FD;
16773   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16774     // Ask the template instantiation pattern that actually had the
16775     // '= default' on it.
16776     Primary = Pattern;
16777 
16778   // If the method was defaulted on its first declaration, we will have
16779   // already performed the checking in CheckCompletedCXXClass. Such a
16780   // declaration doesn't trigger an implicit definition.
16781   if (Primary->getCanonicalDecl()->isDefaulted())
16782     return;
16783 
16784   // FIXME: Once we support defining comparisons out of class, check for a
16785   // defaulted comparison here.
16786   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16787     MD->setInvalidDecl();
16788   else
16789     DefineDefaultedFunction(*this, MD, DefaultLoc);
16790 }
16791 
16792 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16793   for (Stmt *SubStmt : S->children()) {
16794     if (!SubStmt)
16795       continue;
16796     if (isa<ReturnStmt>(SubStmt))
16797       Self.Diag(SubStmt->getBeginLoc(),
16798                 diag::err_return_in_constructor_handler);
16799     if (!isa<Expr>(SubStmt))
16800       SearchForReturnInStmt(Self, SubStmt);
16801   }
16802 }
16803 
16804 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16805   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16806     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16807     SearchForReturnInStmt(*this, Handler);
16808   }
16809 }
16810 
16811 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16812                                              const CXXMethodDecl *Old) {
16813   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16814   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16815 
16816   if (OldFT->hasExtParameterInfos()) {
16817     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16818       // A parameter of the overriding method should be annotated with noescape
16819       // if the corresponding parameter of the overridden method is annotated.
16820       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16821           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16822         Diag(New->getParamDecl(I)->getLocation(),
16823              diag::warn_overriding_method_missing_noescape);
16824         Diag(Old->getParamDecl(I)->getLocation(),
16825              diag::note_overridden_marked_noescape);
16826       }
16827   }
16828 
16829   // Virtual overrides must have the same code_seg.
16830   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16831   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16832   if ((NewCSA || OldCSA) &&
16833       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16834     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16835     Diag(Old->getLocation(), diag::note_previous_declaration);
16836     return true;
16837   }
16838 
16839   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16840 
16841   // If the calling conventions match, everything is fine
16842   if (NewCC == OldCC)
16843     return false;
16844 
16845   // If the calling conventions mismatch because the new function is static,
16846   // suppress the calling convention mismatch error; the error about static
16847   // function override (err_static_overrides_virtual from
16848   // Sema::CheckFunctionDeclaration) is more clear.
16849   if (New->getStorageClass() == SC_Static)
16850     return false;
16851 
16852   Diag(New->getLocation(),
16853        diag::err_conflicting_overriding_cc_attributes)
16854     << New->getDeclName() << New->getType() << Old->getType();
16855   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16856   return true;
16857 }
16858 
16859 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16860                                              const CXXMethodDecl *Old) {
16861   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16862   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16863 
16864   if (Context.hasSameType(NewTy, OldTy) ||
16865       NewTy->isDependentType() || OldTy->isDependentType())
16866     return false;
16867 
16868   // Check if the return types are covariant
16869   QualType NewClassTy, OldClassTy;
16870 
16871   /// Both types must be pointers or references to classes.
16872   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16873     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16874       NewClassTy = NewPT->getPointeeType();
16875       OldClassTy = OldPT->getPointeeType();
16876     }
16877   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16878     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16879       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16880         NewClassTy = NewRT->getPointeeType();
16881         OldClassTy = OldRT->getPointeeType();
16882       }
16883     }
16884   }
16885 
16886   // The return types aren't either both pointers or references to a class type.
16887   if (NewClassTy.isNull()) {
16888     Diag(New->getLocation(),
16889          diag::err_different_return_type_for_overriding_virtual_function)
16890         << New->getDeclName() << NewTy << OldTy
16891         << New->getReturnTypeSourceRange();
16892     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16893         << Old->getReturnTypeSourceRange();
16894 
16895     return true;
16896   }
16897 
16898   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16899     // C++14 [class.virtual]p8:
16900     //   If the class type in the covariant return type of D::f differs from
16901     //   that of B::f, the class type in the return type of D::f shall be
16902     //   complete at the point of declaration of D::f or shall be the class
16903     //   type D.
16904     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16905       if (!RT->isBeingDefined() &&
16906           RequireCompleteType(New->getLocation(), NewClassTy,
16907                               diag::err_covariant_return_incomplete,
16908                               New->getDeclName()))
16909         return true;
16910     }
16911 
16912     // Check if the new class derives from the old class.
16913     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16914       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16915           << New->getDeclName() << NewTy << OldTy
16916           << New->getReturnTypeSourceRange();
16917       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16918           << Old->getReturnTypeSourceRange();
16919       return true;
16920     }
16921 
16922     // Check if we the conversion from derived to base is valid.
16923     if (CheckDerivedToBaseConversion(
16924             NewClassTy, OldClassTy,
16925             diag::err_covariant_return_inaccessible_base,
16926             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16927             New->getLocation(), New->getReturnTypeSourceRange(),
16928             New->getDeclName(), nullptr)) {
16929       // FIXME: this note won't trigger for delayed access control
16930       // diagnostics, and it's impossible to get an undelayed error
16931       // here from access control during the original parse because
16932       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16933       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16934           << Old->getReturnTypeSourceRange();
16935       return true;
16936     }
16937   }
16938 
16939   // The qualifiers of the return types must be the same.
16940   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16941     Diag(New->getLocation(),
16942          diag::err_covariant_return_type_different_qualifications)
16943         << New->getDeclName() << NewTy << OldTy
16944         << New->getReturnTypeSourceRange();
16945     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16946         << Old->getReturnTypeSourceRange();
16947     return true;
16948   }
16949 
16950 
16951   // The new class type must have the same or less qualifiers as the old type.
16952   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16953     Diag(New->getLocation(),
16954          diag::err_covariant_return_type_class_type_more_qualified)
16955         << New->getDeclName() << NewTy << OldTy
16956         << New->getReturnTypeSourceRange();
16957     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16958         << Old->getReturnTypeSourceRange();
16959     return true;
16960   }
16961 
16962   return false;
16963 }
16964 
16965 /// Mark the given method pure.
16966 ///
16967 /// \param Method the method to be marked pure.
16968 ///
16969 /// \param InitRange the source range that covers the "0" initializer.
16970 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16971   SourceLocation EndLoc = InitRange.getEnd();
16972   if (EndLoc.isValid())
16973     Method->setRangeEnd(EndLoc);
16974 
16975   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16976     Method->setPure();
16977     return false;
16978   }
16979 
16980   if (!Method->isInvalidDecl())
16981     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16982       << Method->getDeclName() << InitRange;
16983   return true;
16984 }
16985 
16986 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16987   if (D->getFriendObjectKind())
16988     Diag(D->getLocation(), diag::err_pure_friend);
16989   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16990     CheckPureMethod(M, ZeroLoc);
16991   else
16992     Diag(D->getLocation(), diag::err_illegal_initializer);
16993 }
16994 
16995 /// Determine whether the given declaration is a global variable or
16996 /// static data member.
16997 static bool isNonlocalVariable(const Decl *D) {
16998   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
16999     return Var->hasGlobalStorage();
17000 
17001   return false;
17002 }
17003 
17004 /// Invoked when we are about to parse an initializer for the declaration
17005 /// 'Dcl'.
17006 ///
17007 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17008 /// static data member of class X, names should be looked up in the scope of
17009 /// class X. If the declaration had a scope specifier, a scope will have
17010 /// been created and passed in for this purpose. Otherwise, S will be null.
17011 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17012   // If there is no declaration, there was an error parsing it.
17013   if (!D || D->isInvalidDecl())
17014     return;
17015 
17016   // We will always have a nested name specifier here, but this declaration
17017   // might not be out of line if the specifier names the current namespace:
17018   //   extern int n;
17019   //   int ::n = 0;
17020   if (S && D->isOutOfLine())
17021     EnterDeclaratorContext(S, D->getDeclContext());
17022 
17023   // If we are parsing the initializer for a static data member, push a
17024   // new expression evaluation context that is associated with this static
17025   // data member.
17026   if (isNonlocalVariable(D))
17027     PushExpressionEvaluationContext(
17028         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17029 }
17030 
17031 /// Invoked after we are finished parsing an initializer for the declaration D.
17032 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17033   // If there is no declaration, there was an error parsing it.
17034   if (!D || D->isInvalidDecl())
17035     return;
17036 
17037   if (isNonlocalVariable(D))
17038     PopExpressionEvaluationContext();
17039 
17040   if (S && D->isOutOfLine())
17041     ExitDeclaratorContext(S);
17042 }
17043 
17044 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17045 /// C++ if/switch/while/for statement.
17046 /// e.g: "if (int x = f()) {...}"
17047 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17048   // C++ 6.4p2:
17049   // The declarator shall not specify a function or an array.
17050   // The type-specifier-seq shall not contain typedef and shall not declare a
17051   // new class or enumeration.
17052   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17053          "Parser allowed 'typedef' as storage class of condition decl.");
17054 
17055   Decl *Dcl = ActOnDeclarator(S, D);
17056   if (!Dcl)
17057     return true;
17058 
17059   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17060     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17061       << D.getSourceRange();
17062     return true;
17063   }
17064 
17065   return Dcl;
17066 }
17067 
17068 void Sema::LoadExternalVTableUses() {
17069   if (!ExternalSource)
17070     return;
17071 
17072   SmallVector<ExternalVTableUse, 4> VTables;
17073   ExternalSource->ReadUsedVTables(VTables);
17074   SmallVector<VTableUse, 4> NewUses;
17075   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17076     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17077       = VTablesUsed.find(VTables[I].Record);
17078     // Even if a definition wasn't required before, it may be required now.
17079     if (Pos != VTablesUsed.end()) {
17080       if (!Pos->second && VTables[I].DefinitionRequired)
17081         Pos->second = true;
17082       continue;
17083     }
17084 
17085     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17086     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17087   }
17088 
17089   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17090 }
17091 
17092 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17093                           bool DefinitionRequired) {
17094   // Ignore any vtable uses in unevaluated operands or for classes that do
17095   // not have a vtable.
17096   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17097       CurContext->isDependentContext() || isUnevaluatedContext())
17098     return;
17099   // Do not mark as used if compiling for the device outside of the target
17100   // region.
17101   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17102       !isInOpenMPDeclareTargetContext() &&
17103       !isInOpenMPTargetExecutionDirective()) {
17104     if (!DefinitionRequired)
17105       MarkVirtualMembersReferenced(Loc, Class);
17106     return;
17107   }
17108 
17109   // Try to insert this class into the map.
17110   LoadExternalVTableUses();
17111   Class = Class->getCanonicalDecl();
17112   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17113     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17114   if (!Pos.second) {
17115     // If we already had an entry, check to see if we are promoting this vtable
17116     // to require a definition. If so, we need to reappend to the VTableUses
17117     // list, since we may have already processed the first entry.
17118     if (DefinitionRequired && !Pos.first->second) {
17119       Pos.first->second = true;
17120     } else {
17121       // Otherwise, we can early exit.
17122       return;
17123     }
17124   } else {
17125     // The Microsoft ABI requires that we perform the destructor body
17126     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17127     // the deleting destructor is emitted with the vtable, not with the
17128     // destructor definition as in the Itanium ABI.
17129     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17130       CXXDestructorDecl *DD = Class->getDestructor();
17131       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17132         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17133           // If this is an out-of-line declaration, marking it referenced will
17134           // not do anything. Manually call CheckDestructor to look up operator
17135           // delete().
17136           ContextRAII SavedContext(*this, DD);
17137           CheckDestructor(DD);
17138         } else {
17139           MarkFunctionReferenced(Loc, Class->getDestructor());
17140         }
17141       }
17142     }
17143   }
17144 
17145   // Local classes need to have their virtual members marked
17146   // immediately. For all other classes, we mark their virtual members
17147   // at the end of the translation unit.
17148   if (Class->isLocalClass())
17149     MarkVirtualMembersReferenced(Loc, Class);
17150   else
17151     VTableUses.push_back(std::make_pair(Class, Loc));
17152 }
17153 
17154 bool Sema::DefineUsedVTables() {
17155   LoadExternalVTableUses();
17156   if (VTableUses.empty())
17157     return false;
17158 
17159   // Note: The VTableUses vector could grow as a result of marking
17160   // the members of a class as "used", so we check the size each
17161   // time through the loop and prefer indices (which are stable) to
17162   // iterators (which are not).
17163   bool DefinedAnything = false;
17164   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17165     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17166     if (!Class)
17167       continue;
17168     TemplateSpecializationKind ClassTSK =
17169         Class->getTemplateSpecializationKind();
17170 
17171     SourceLocation Loc = VTableUses[I].second;
17172 
17173     bool DefineVTable = true;
17174 
17175     // If this class has a key function, but that key function is
17176     // defined in another translation unit, we don't need to emit the
17177     // vtable even though we're using it.
17178     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17179     if (KeyFunction && !KeyFunction->hasBody()) {
17180       // The key function is in another translation unit.
17181       DefineVTable = false;
17182       TemplateSpecializationKind TSK =
17183           KeyFunction->getTemplateSpecializationKind();
17184       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17185              TSK != TSK_ImplicitInstantiation &&
17186              "Instantiations don't have key functions");
17187       (void)TSK;
17188     } else if (!KeyFunction) {
17189       // If we have a class with no key function that is the subject
17190       // of an explicit instantiation declaration, suppress the
17191       // vtable; it will live with the explicit instantiation
17192       // definition.
17193       bool IsExplicitInstantiationDeclaration =
17194           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17195       for (auto R : Class->redecls()) {
17196         TemplateSpecializationKind TSK
17197           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17198         if (TSK == TSK_ExplicitInstantiationDeclaration)
17199           IsExplicitInstantiationDeclaration = true;
17200         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17201           IsExplicitInstantiationDeclaration = false;
17202           break;
17203         }
17204       }
17205 
17206       if (IsExplicitInstantiationDeclaration)
17207         DefineVTable = false;
17208     }
17209 
17210     // The exception specifications for all virtual members may be needed even
17211     // if we are not providing an authoritative form of the vtable in this TU.
17212     // We may choose to emit it available_externally anyway.
17213     if (!DefineVTable) {
17214       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17215       continue;
17216     }
17217 
17218     // Mark all of the virtual members of this class as referenced, so
17219     // that we can build a vtable. Then, tell the AST consumer that a
17220     // vtable for this class is required.
17221     DefinedAnything = true;
17222     MarkVirtualMembersReferenced(Loc, Class);
17223     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17224     if (VTablesUsed[Canonical])
17225       Consumer.HandleVTable(Class);
17226 
17227     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17228     // no key function or the key function is inlined. Don't warn in C++ ABIs
17229     // that lack key functions, since the user won't be able to make one.
17230     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17231         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17232       const FunctionDecl *KeyFunctionDef = nullptr;
17233       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17234                            KeyFunctionDef->isInlined())) {
17235         Diag(Class->getLocation(),
17236              ClassTSK == TSK_ExplicitInstantiationDefinition
17237                  ? diag::warn_weak_template_vtable
17238                  : diag::warn_weak_vtable)
17239             << Class;
17240       }
17241     }
17242   }
17243   VTableUses.clear();
17244 
17245   return DefinedAnything;
17246 }
17247 
17248 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17249                                                  const CXXRecordDecl *RD) {
17250   for (const auto *I : RD->methods())
17251     if (I->isVirtual() && !I->isPure())
17252       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17253 }
17254 
17255 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17256                                         const CXXRecordDecl *RD,
17257                                         bool ConstexprOnly) {
17258   // Mark all functions which will appear in RD's vtable as used.
17259   CXXFinalOverriderMap FinalOverriders;
17260   RD->getFinalOverriders(FinalOverriders);
17261   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17262                                             E = FinalOverriders.end();
17263        I != E; ++I) {
17264     for (OverridingMethods::const_iterator OI = I->second.begin(),
17265                                            OE = I->second.end();
17266          OI != OE; ++OI) {
17267       assert(OI->second.size() > 0 && "no final overrider");
17268       CXXMethodDecl *Overrider = OI->second.front().Method;
17269 
17270       // C++ [basic.def.odr]p2:
17271       //   [...] A virtual member function is used if it is not pure. [...]
17272       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17273         MarkFunctionReferenced(Loc, Overrider);
17274     }
17275   }
17276 
17277   // Only classes that have virtual bases need a VTT.
17278   if (RD->getNumVBases() == 0)
17279     return;
17280 
17281   for (const auto &I : RD->bases()) {
17282     const auto *Base =
17283         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17284     if (Base->getNumVBases() == 0)
17285       continue;
17286     MarkVirtualMembersReferenced(Loc, Base);
17287   }
17288 }
17289 
17290 /// SetIvarInitializers - This routine builds initialization ASTs for the
17291 /// Objective-C implementation whose ivars need be initialized.
17292 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17293   if (!getLangOpts().CPlusPlus)
17294     return;
17295   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17296     SmallVector<ObjCIvarDecl*, 8> ivars;
17297     CollectIvarsToConstructOrDestruct(OID, ivars);
17298     if (ivars.empty())
17299       return;
17300     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17301     for (unsigned i = 0; i < ivars.size(); i++) {
17302       FieldDecl *Field = ivars[i];
17303       if (Field->isInvalidDecl())
17304         continue;
17305 
17306       CXXCtorInitializer *Member;
17307       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17308       InitializationKind InitKind =
17309         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17310 
17311       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17312       ExprResult MemberInit =
17313         InitSeq.Perform(*this, InitEntity, InitKind, None);
17314       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17315       // Note, MemberInit could actually come back empty if no initialization
17316       // is required (e.g., because it would call a trivial default constructor)
17317       if (!MemberInit.get() || MemberInit.isInvalid())
17318         continue;
17319 
17320       Member =
17321         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17322                                          SourceLocation(),
17323                                          MemberInit.getAs<Expr>(),
17324                                          SourceLocation());
17325       AllToInit.push_back(Member);
17326 
17327       // Be sure that the destructor is accessible and is marked as referenced.
17328       if (const RecordType *RecordTy =
17329               Context.getBaseElementType(Field->getType())
17330                   ->getAs<RecordType>()) {
17331         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17332         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17333           MarkFunctionReferenced(Field->getLocation(), Destructor);
17334           CheckDestructorAccess(Field->getLocation(), Destructor,
17335                             PDiag(diag::err_access_dtor_ivar)
17336                               << Context.getBaseElementType(Field->getType()));
17337         }
17338       }
17339     }
17340     ObjCImplementation->setIvarInitializers(Context,
17341                                             AllToInit.data(), AllToInit.size());
17342   }
17343 }
17344 
17345 static
17346 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17347                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17348                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17349                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17350                            Sema &S) {
17351   if (Ctor->isInvalidDecl())
17352     return;
17353 
17354   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17355 
17356   // Target may not be determinable yet, for instance if this is a dependent
17357   // call in an uninstantiated template.
17358   if (Target) {
17359     const FunctionDecl *FNTarget = nullptr;
17360     (void)Target->hasBody(FNTarget);
17361     Target = const_cast<CXXConstructorDecl*>(
17362       cast_or_null<CXXConstructorDecl>(FNTarget));
17363   }
17364 
17365   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17366                      // Avoid dereferencing a null pointer here.
17367                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17368 
17369   if (!Current.insert(Canonical).second)
17370     return;
17371 
17372   // We know that beyond here, we aren't chaining into a cycle.
17373   if (!Target || !Target->isDelegatingConstructor() ||
17374       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17375     Valid.insert(Current.begin(), Current.end());
17376     Current.clear();
17377   // We've hit a cycle.
17378   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17379              Current.count(TCanonical)) {
17380     // If we haven't diagnosed this cycle yet, do so now.
17381     if (!Invalid.count(TCanonical)) {
17382       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17383              diag::warn_delegating_ctor_cycle)
17384         << Ctor;
17385 
17386       // Don't add a note for a function delegating directly to itself.
17387       if (TCanonical != Canonical)
17388         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17389 
17390       CXXConstructorDecl *C = Target;
17391       while (C->getCanonicalDecl() != Canonical) {
17392         const FunctionDecl *FNTarget = nullptr;
17393         (void)C->getTargetConstructor()->hasBody(FNTarget);
17394         assert(FNTarget && "Ctor cycle through bodiless function");
17395 
17396         C = const_cast<CXXConstructorDecl*>(
17397           cast<CXXConstructorDecl>(FNTarget));
17398         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17399       }
17400     }
17401 
17402     Invalid.insert(Current.begin(), Current.end());
17403     Current.clear();
17404   } else {
17405     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17406   }
17407 }
17408 
17409 
17410 void Sema::CheckDelegatingCtorCycles() {
17411   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17412 
17413   for (DelegatingCtorDeclsType::iterator
17414          I = DelegatingCtorDecls.begin(ExternalSource),
17415          E = DelegatingCtorDecls.end();
17416        I != E; ++I)
17417     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17418 
17419   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17420     (*CI)->setInvalidDecl();
17421 }
17422 
17423 namespace {
17424   /// AST visitor that finds references to the 'this' expression.
17425   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17426     Sema &S;
17427 
17428   public:
17429     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17430 
17431     bool VisitCXXThisExpr(CXXThisExpr *E) {
17432       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17433         << E->isImplicit();
17434       return false;
17435     }
17436   };
17437 }
17438 
17439 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17440   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17441   if (!TSInfo)
17442     return false;
17443 
17444   TypeLoc TL = TSInfo->getTypeLoc();
17445   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17446   if (!ProtoTL)
17447     return false;
17448 
17449   // C++11 [expr.prim.general]p3:
17450   //   [The expression this] shall not appear before the optional
17451   //   cv-qualifier-seq and it shall not appear within the declaration of a
17452   //   static member function (although its type and value category are defined
17453   //   within a static member function as they are within a non-static member
17454   //   function). [ Note: this is because declaration matching does not occur
17455   //  until the complete declarator is known. - end note ]
17456   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17457   FindCXXThisExpr Finder(*this);
17458 
17459   // If the return type came after the cv-qualifier-seq, check it now.
17460   if (Proto->hasTrailingReturn() &&
17461       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17462     return true;
17463 
17464   // Check the exception specification.
17465   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17466     return true;
17467 
17468   // Check the trailing requires clause
17469   if (Expr *E = Method->getTrailingRequiresClause())
17470     if (!Finder.TraverseStmt(E))
17471       return true;
17472 
17473   return checkThisInStaticMemberFunctionAttributes(Method);
17474 }
17475 
17476 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17477   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17478   if (!TSInfo)
17479     return false;
17480 
17481   TypeLoc TL = TSInfo->getTypeLoc();
17482   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17483   if (!ProtoTL)
17484     return false;
17485 
17486   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17487   FindCXXThisExpr Finder(*this);
17488 
17489   switch (Proto->getExceptionSpecType()) {
17490   case EST_Unparsed:
17491   case EST_Uninstantiated:
17492   case EST_Unevaluated:
17493   case EST_BasicNoexcept:
17494   case EST_NoThrow:
17495   case EST_DynamicNone:
17496   case EST_MSAny:
17497   case EST_None:
17498     break;
17499 
17500   case EST_DependentNoexcept:
17501   case EST_NoexceptFalse:
17502   case EST_NoexceptTrue:
17503     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17504       return true;
17505     LLVM_FALLTHROUGH;
17506 
17507   case EST_Dynamic:
17508     for (const auto &E : Proto->exceptions()) {
17509       if (!Finder.TraverseType(E))
17510         return true;
17511     }
17512     break;
17513   }
17514 
17515   return false;
17516 }
17517 
17518 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17519   FindCXXThisExpr Finder(*this);
17520 
17521   // Check attributes.
17522   for (const auto *A : Method->attrs()) {
17523     // FIXME: This should be emitted by tblgen.
17524     Expr *Arg = nullptr;
17525     ArrayRef<Expr *> Args;
17526     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17527       Arg = G->getArg();
17528     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17529       Arg = G->getArg();
17530     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17531       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17532     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17533       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17534     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17535       Arg = ETLF->getSuccessValue();
17536       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17537     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17538       Arg = STLF->getSuccessValue();
17539       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17540     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17541       Arg = LR->getArg();
17542     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17543       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17544     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17545       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17546     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17547       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17548     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17549       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17550     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17551       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17552 
17553     if (Arg && !Finder.TraverseStmt(Arg))
17554       return true;
17555 
17556     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17557       if (!Finder.TraverseStmt(Args[I]))
17558         return true;
17559     }
17560   }
17561 
17562   return false;
17563 }
17564 
17565 void Sema::checkExceptionSpecification(
17566     bool IsTopLevel, ExceptionSpecificationType EST,
17567     ArrayRef<ParsedType> DynamicExceptions,
17568     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17569     SmallVectorImpl<QualType> &Exceptions,
17570     FunctionProtoType::ExceptionSpecInfo &ESI) {
17571   Exceptions.clear();
17572   ESI.Type = EST;
17573   if (EST == EST_Dynamic) {
17574     Exceptions.reserve(DynamicExceptions.size());
17575     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17576       // FIXME: Preserve type source info.
17577       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17578 
17579       if (IsTopLevel) {
17580         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17581         collectUnexpandedParameterPacks(ET, Unexpanded);
17582         if (!Unexpanded.empty()) {
17583           DiagnoseUnexpandedParameterPacks(
17584               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17585               Unexpanded);
17586           continue;
17587         }
17588       }
17589 
17590       // Check that the type is valid for an exception spec, and
17591       // drop it if not.
17592       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17593         Exceptions.push_back(ET);
17594     }
17595     ESI.Exceptions = Exceptions;
17596     return;
17597   }
17598 
17599   if (isComputedNoexcept(EST)) {
17600     assert((NoexceptExpr->isTypeDependent() ||
17601             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17602             Context.BoolTy) &&
17603            "Parser should have made sure that the expression is boolean");
17604     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17605       ESI.Type = EST_BasicNoexcept;
17606       return;
17607     }
17608 
17609     ESI.NoexceptExpr = NoexceptExpr;
17610     return;
17611   }
17612 }
17613 
17614 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17615              ExceptionSpecificationType EST,
17616              SourceRange SpecificationRange,
17617              ArrayRef<ParsedType> DynamicExceptions,
17618              ArrayRef<SourceRange> DynamicExceptionRanges,
17619              Expr *NoexceptExpr) {
17620   if (!MethodD)
17621     return;
17622 
17623   // Dig out the method we're referring to.
17624   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17625     MethodD = FunTmpl->getTemplatedDecl();
17626 
17627   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17628   if (!Method)
17629     return;
17630 
17631   // Check the exception specification.
17632   llvm::SmallVector<QualType, 4> Exceptions;
17633   FunctionProtoType::ExceptionSpecInfo ESI;
17634   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17635                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17636                               ESI);
17637 
17638   // Update the exception specification on the function type.
17639   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17640 
17641   if (Method->isStatic())
17642     checkThisInStaticMemberFunctionExceptionSpec(Method);
17643 
17644   if (Method->isVirtual()) {
17645     // Check overrides, which we previously had to delay.
17646     for (const CXXMethodDecl *O : Method->overridden_methods())
17647       CheckOverridingFunctionExceptionSpec(Method, O);
17648   }
17649 }
17650 
17651 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17652 ///
17653 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17654                                        SourceLocation DeclStart, Declarator &D,
17655                                        Expr *BitWidth,
17656                                        InClassInitStyle InitStyle,
17657                                        AccessSpecifier AS,
17658                                        const ParsedAttr &MSPropertyAttr) {
17659   IdentifierInfo *II = D.getIdentifier();
17660   if (!II) {
17661     Diag(DeclStart, diag::err_anonymous_property);
17662     return nullptr;
17663   }
17664   SourceLocation Loc = D.getIdentifierLoc();
17665 
17666   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17667   QualType T = TInfo->getType();
17668   if (getLangOpts().CPlusPlus) {
17669     CheckExtraCXXDefaultArguments(D);
17670 
17671     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17672                                         UPPC_DataMemberType)) {
17673       D.setInvalidType();
17674       T = Context.IntTy;
17675       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17676     }
17677   }
17678 
17679   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17680 
17681   if (D.getDeclSpec().isInlineSpecified())
17682     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17683         << getLangOpts().CPlusPlus17;
17684   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17685     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17686          diag::err_invalid_thread)
17687       << DeclSpec::getSpecifierName(TSCS);
17688 
17689   // Check to see if this name was declared as a member previously
17690   NamedDecl *PrevDecl = nullptr;
17691   LookupResult Previous(*this, II, Loc, LookupMemberName,
17692                         ForVisibleRedeclaration);
17693   LookupName(Previous, S);
17694   switch (Previous.getResultKind()) {
17695   case LookupResult::Found:
17696   case LookupResult::FoundUnresolvedValue:
17697     PrevDecl = Previous.getAsSingle<NamedDecl>();
17698     break;
17699 
17700   case LookupResult::FoundOverloaded:
17701     PrevDecl = Previous.getRepresentativeDecl();
17702     break;
17703 
17704   case LookupResult::NotFound:
17705   case LookupResult::NotFoundInCurrentInstantiation:
17706   case LookupResult::Ambiguous:
17707     break;
17708   }
17709 
17710   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17711     // Maybe we will complain about the shadowed template parameter.
17712     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17713     // Just pretend that we didn't see the previous declaration.
17714     PrevDecl = nullptr;
17715   }
17716 
17717   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17718     PrevDecl = nullptr;
17719 
17720   SourceLocation TSSL = D.getBeginLoc();
17721   MSPropertyDecl *NewPD =
17722       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17723                              MSPropertyAttr.getPropertyDataGetter(),
17724                              MSPropertyAttr.getPropertyDataSetter());
17725   ProcessDeclAttributes(TUScope, NewPD, D);
17726   NewPD->setAccess(AS);
17727 
17728   if (NewPD->isInvalidDecl())
17729     Record->setInvalidDecl();
17730 
17731   if (D.getDeclSpec().isModulePrivateSpecified())
17732     NewPD->setModulePrivate();
17733 
17734   if (NewPD->isInvalidDecl() && PrevDecl) {
17735     // Don't introduce NewFD into scope; there's already something
17736     // with the same name in the same scope.
17737   } else if (II) {
17738     PushOnScopeChains(NewPD, S);
17739   } else
17740     Record->addDecl(NewPD);
17741 
17742   return NewPD;
17743 }
17744 
17745 void Sema::ActOnStartFunctionDeclarationDeclarator(
17746     Declarator &Declarator, unsigned TemplateParameterDepth) {
17747   auto &Info = InventedParameterInfos.emplace_back();
17748   TemplateParameterList *ExplicitParams = nullptr;
17749   ArrayRef<TemplateParameterList *> ExplicitLists =
17750       Declarator.getTemplateParameterLists();
17751   if (!ExplicitLists.empty()) {
17752     bool IsMemberSpecialization, IsInvalid;
17753     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17754         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17755         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17756         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17757         /*SuppressDiagnostic=*/true);
17758   }
17759   if (ExplicitParams) {
17760     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17761     for (NamedDecl *Param : *ExplicitParams)
17762       Info.TemplateParams.push_back(Param);
17763     Info.NumExplicitTemplateParams = ExplicitParams->size();
17764   } else {
17765     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17766     Info.NumExplicitTemplateParams = 0;
17767   }
17768 }
17769 
17770 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17771   auto &FSI = InventedParameterInfos.back();
17772   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17773     if (FSI.NumExplicitTemplateParams != 0) {
17774       TemplateParameterList *ExplicitParams =
17775           Declarator.getTemplateParameterLists().back();
17776       Declarator.setInventedTemplateParameterList(
17777           TemplateParameterList::Create(
17778               Context, ExplicitParams->getTemplateLoc(),
17779               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17780               ExplicitParams->getRAngleLoc(),
17781               ExplicitParams->getRequiresClause()));
17782     } else {
17783       Declarator.setInventedTemplateParameterList(
17784           TemplateParameterList::Create(
17785               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17786               SourceLocation(), /*RequiresClause=*/nullptr));
17787     }
17788   }
17789   InventedParameterInfos.pop_back();
17790 }
17791