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 << static_cast<int>(New->getConstexprKind())
659         << static_cast<int>(Old->getConstexprKind());
660     Diag(Old->getLocation(), diag::note_previous_declaration);
661     Invalid = true;
662   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
663              Old->isDefined(Def) &&
664              // If a friend function is inlined but does not have 'inline'
665              // specifier, it is a definition. Do not report attribute conflict
666              // in this case, redefinition will be diagnosed later.
667              (New->isInlineSpecified() ||
668               New->getFriendObjectKind() == Decl::FOK_None)) {
669     // C++11 [dcl.fcn.spec]p4:
670     //   If the definition of a function appears in a translation unit before its
671     //   first declaration as inline, the program is ill-formed.
672     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
673     Diag(Def->getLocation(), diag::note_previous_definition);
674     Invalid = true;
675   }
676 
677   // C++17 [temp.deduct.guide]p3:
678   //   Two deduction guide declarations in the same translation unit
679   //   for the same class template shall not have equivalent
680   //   parameter-declaration-clauses.
681   if (isa<CXXDeductionGuideDecl>(New) &&
682       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
683     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
684     Diag(Old->getLocation(), diag::note_previous_declaration);
685   }
686 
687   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
688   // argument expression, that declaration shall be a definition and shall be
689   // the only declaration of the function or function template in the
690   // translation unit.
691   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
692       functionDeclHasDefaultArgument(Old)) {
693     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
694     Diag(Old->getLocation(), diag::note_previous_declaration);
695     Invalid = true;
696   }
697 
698   // C++11 [temp.friend]p4 (DR329):
699   //   When a function is defined in a friend function declaration in a class
700   //   template, the function is instantiated when the function is odr-used.
701   //   The same restrictions on multiple declarations and definitions that
702   //   apply to non-template function declarations and definitions also apply
703   //   to these implicit definitions.
704   const FunctionDecl *OldDefinition = nullptr;
705   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
706       Old->isDefined(OldDefinition, true))
707     CheckForFunctionRedefinition(New, OldDefinition);
708 
709   return Invalid;
710 }
711 
712 NamedDecl *
713 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
714                                    MultiTemplateParamsArg TemplateParamLists) {
715   assert(D.isDecompositionDeclarator());
716   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
717 
718   // The syntax only allows a decomposition declarator as a simple-declaration,
719   // a for-range-declaration, or a condition in Clang, but we parse it in more
720   // cases than that.
721   if (!D.mayHaveDecompositionDeclarator()) {
722     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
723       << Decomp.getSourceRange();
724     return nullptr;
725   }
726 
727   if (!TemplateParamLists.empty()) {
728     // FIXME: There's no rule against this, but there are also no rules that
729     // would actually make it usable, so we reject it for now.
730     Diag(TemplateParamLists.front()->getTemplateLoc(),
731          diag::err_decomp_decl_template);
732     return nullptr;
733   }
734 
735   Diag(Decomp.getLSquareLoc(),
736        !getLangOpts().CPlusPlus17
737            ? diag::ext_decomp_decl
738            : D.getContext() == DeclaratorContext::Condition
739                  ? diag::ext_decomp_decl_cond
740                  : diag::warn_cxx14_compat_decomp_decl)
741       << Decomp.getSourceRange();
742 
743   // The semantic context is always just the current context.
744   DeclContext *const DC = CurContext;
745 
746   // C++17 [dcl.dcl]/8:
747   //   The decl-specifier-seq shall contain only the type-specifier auto
748   //   and cv-qualifiers.
749   // C++2a [dcl.dcl]/8:
750   //   If decl-specifier-seq contains any decl-specifier other than static,
751   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
752   auto &DS = D.getDeclSpec();
753   {
754     SmallVector<StringRef, 8> BadSpecifiers;
755     SmallVector<SourceLocation, 8> BadSpecifierLocs;
756     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
757     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
758     if (auto SCS = DS.getStorageClassSpec()) {
759       if (SCS == DeclSpec::SCS_static) {
760         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
761         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762       } else {
763         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
764         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
765       }
766     }
767     if (auto TSCS = DS.getThreadStorageClassSpec()) {
768       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
769       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
770     }
771     if (DS.hasConstexprSpecifier()) {
772       BadSpecifiers.push_back(
773           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
774       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
775     }
776     if (DS.isInlineSpecified()) {
777       BadSpecifiers.push_back("inline");
778       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
779     }
780     if (!BadSpecifiers.empty()) {
781       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
782       Err << (int)BadSpecifiers.size()
783           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
784       // Don't add FixItHints to remove the specifiers; we do still respect
785       // them when building the underlying variable.
786       for (auto Loc : BadSpecifierLocs)
787         Err << SourceRange(Loc, Loc);
788     } else if (!CPlusPlus20Specifiers.empty()) {
789       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
790                          getLangOpts().CPlusPlus20
791                              ? diag::warn_cxx17_compat_decomp_decl_spec
792                              : diag::ext_decomp_decl_spec);
793       Warn << (int)CPlusPlus20Specifiers.size()
794            << llvm::join(CPlusPlus20Specifiers.begin(),
795                          CPlusPlus20Specifiers.end(), " ");
796       for (auto Loc : CPlusPlus20SpecifierLocs)
797         Warn << SourceRange(Loc, Loc);
798     }
799     // We can't recover from it being declared as a typedef.
800     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
801       return nullptr;
802   }
803 
804   // C++2a [dcl.struct.bind]p1:
805   //   A cv that includes volatile is deprecated
806   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
807       getLangOpts().CPlusPlus20)
808     Diag(DS.getVolatileSpecLoc(),
809          diag::warn_deprecated_volatile_structured_binding);
810 
811   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
812   QualType R = TInfo->getType();
813 
814   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
815                                       UPPC_DeclarationType))
816     D.setInvalidType();
817 
818   // The syntax only allows a single ref-qualifier prior to the decomposition
819   // declarator. No other declarator chunks are permitted. Also check the type
820   // specifier here.
821   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
822       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
823       (D.getNumTypeObjects() == 1 &&
824        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
825     Diag(Decomp.getLSquareLoc(),
826          (D.hasGroupingParens() ||
827           (D.getNumTypeObjects() &&
828            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
829              ? diag::err_decomp_decl_parens
830              : diag::err_decomp_decl_type)
831         << R;
832 
833     // In most cases, there's no actual problem with an explicitly-specified
834     // type, but a function type won't work here, and ActOnVariableDeclarator
835     // shouldn't be called for such a type.
836     if (R->isFunctionType())
837       D.setInvalidType();
838   }
839 
840   // Build the BindingDecls.
841   SmallVector<BindingDecl*, 8> Bindings;
842 
843   // Build the BindingDecls.
844   for (auto &B : D.getDecompositionDeclarator().bindings()) {
845     // Check for name conflicts.
846     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
847     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848                           ForVisibleRedeclaration);
849     LookupName(Previous, S,
850                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
851 
852     // It's not permitted to shadow a template parameter name.
853     if (Previous.isSingleResult() &&
854         Previous.getFoundDecl()->isTemplateParameter()) {
855       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
856                                       Previous.getFoundDecl());
857       Previous.clear();
858     }
859 
860     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
861 
862     // Find the shadowed declaration before filtering for scope.
863     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
864                                   ? getShadowedDeclaration(BD, Previous)
865                                   : nullptr;
866 
867     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
868                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
869     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
870                          /*AllowInlineNamespace*/false);
871 
872     if (!Previous.empty()) {
873       auto *Old = Previous.getRepresentativeDecl();
874       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
875       Diag(Old->getLocation(), diag::note_previous_definition);
876     } else if (ShadowedDecl && !D.isRedeclaration()) {
877       CheckShadow(BD, ShadowedDecl, Previous);
878     }
879     PushOnScopeChains(BD, S, true);
880     Bindings.push_back(BD);
881     ParsingInitForAutoVars.insert(BD);
882   }
883 
884   // There are no prior lookup results for the variable itself, because it
885   // is unnamed.
886   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
887                                Decomp.getLSquareLoc());
888   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
889                         ForVisibleRedeclaration);
890 
891   // Build the variable that holds the non-decomposed object.
892   bool AddToScope = true;
893   NamedDecl *New =
894       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
895                               MultiTemplateParamsArg(), AddToScope, Bindings);
896   if (AddToScope) {
897     S->AddDecl(New);
898     CurContext->addHiddenDecl(New);
899   }
900 
901   if (isInOpenMPDeclareTargetContext())
902     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
903 
904   return New;
905 }
906 
907 static bool checkSimpleDecomposition(
908     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
909     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
910     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
911   if ((int64_t)Bindings.size() != NumElems) {
912     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
913         << DecompType << (unsigned)Bindings.size()
914         << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10)
915         << (NumElems < Bindings.size());
916     return true;
917   }
918 
919   unsigned I = 0;
920   for (auto *B : Bindings) {
921     SourceLocation Loc = B->getLocation();
922     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
923     if (E.isInvalid())
924       return true;
925     E = GetInit(Loc, E.get(), I++);
926     if (E.isInvalid())
927       return true;
928     B->setBinding(ElemType, E.get());
929   }
930 
931   return false;
932 }
933 
934 static bool checkArrayLikeDecomposition(Sema &S,
935                                         ArrayRef<BindingDecl *> Bindings,
936                                         ValueDecl *Src, QualType DecompType,
937                                         const llvm::APSInt &NumElems,
938                                         QualType ElemType) {
939   return checkSimpleDecomposition(
940       S, Bindings, Src, DecompType, NumElems, ElemType,
941       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
942         ExprResult E = S.ActOnIntegerConstant(Loc, I);
943         if (E.isInvalid())
944           return ExprError();
945         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
946       });
947 }
948 
949 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
950                                     ValueDecl *Src, QualType DecompType,
951                                     const ConstantArrayType *CAT) {
952   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
953                                      llvm::APSInt(CAT->getSize()),
954                                      CAT->getElementType());
955 }
956 
957 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
958                                      ValueDecl *Src, QualType DecompType,
959                                      const VectorType *VT) {
960   return checkArrayLikeDecomposition(
961       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
962       S.Context.getQualifiedType(VT->getElementType(),
963                                  DecompType.getQualifiers()));
964 }
965 
966 static bool checkComplexDecomposition(Sema &S,
967                                       ArrayRef<BindingDecl *> Bindings,
968                                       ValueDecl *Src, QualType DecompType,
969                                       const ComplexType *CT) {
970   return checkSimpleDecomposition(
971       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
972       S.Context.getQualifiedType(CT->getElementType(),
973                                  DecompType.getQualifiers()),
974       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
975         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
976       });
977 }
978 
979 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
980                                      TemplateArgumentListInfo &Args) {
981   SmallString<128> SS;
982   llvm::raw_svector_ostream OS(SS);
983   bool First = true;
984   for (auto &Arg : Args.arguments()) {
985     if (!First)
986       OS << ", ";
987     Arg.getArgument().print(PrintingPolicy, OS);
988     First = false;
989   }
990   return std::string(OS.str());
991 }
992 
993 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
994                                      SourceLocation Loc, StringRef Trait,
995                                      TemplateArgumentListInfo &Args,
996                                      unsigned DiagID) {
997   auto DiagnoseMissing = [&] {
998     if (DiagID)
999       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1000                                                Args);
1001     return true;
1002   };
1003 
1004   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1005   NamespaceDecl *Std = S.getStdNamespace();
1006   if (!Std)
1007     return DiagnoseMissing();
1008 
1009   // Look up the trait itself, within namespace std. We can diagnose various
1010   // problems with this lookup even if we've been asked to not diagnose a
1011   // missing specialization, because this can only fail if the user has been
1012   // declaring their own names in namespace std or we don't support the
1013   // standard library implementation in use.
1014   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1015                       Loc, Sema::LookupOrdinaryName);
1016   if (!S.LookupQualifiedName(Result, Std))
1017     return DiagnoseMissing();
1018   if (Result.isAmbiguous())
1019     return true;
1020 
1021   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1022   if (!TraitTD) {
1023     Result.suppressDiagnostics();
1024     NamedDecl *Found = *Result.begin();
1025     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1026     S.Diag(Found->getLocation(), diag::note_declared_at);
1027     return true;
1028   }
1029 
1030   // Build the template-id.
1031   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1032   if (TraitTy.isNull())
1033     return true;
1034   if (!S.isCompleteType(Loc, TraitTy)) {
1035     if (DiagID)
1036       S.RequireCompleteType(
1037           Loc, TraitTy, DiagID,
1038           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1039     return true;
1040   }
1041 
1042   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1043   assert(RD && "specialization of class template is not a class?");
1044 
1045   // Look up the member of the trait type.
1046   S.LookupQualifiedName(TraitMemberLookup, RD);
1047   return TraitMemberLookup.isAmbiguous();
1048 }
1049 
1050 static TemplateArgumentLoc
1051 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1052                                    uint64_t I) {
1053   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1054   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1055 }
1056 
1057 static TemplateArgumentLoc
1058 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1059   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1060 }
1061 
1062 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1063 
1064 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1065                                llvm::APSInt &Size) {
1066   EnterExpressionEvaluationContext ContextRAII(
1067       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1068 
1069   DeclarationName Value = S.PP.getIdentifierInfo("value");
1070   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1071 
1072   // Form template argument list for tuple_size<T>.
1073   TemplateArgumentListInfo Args(Loc, Loc);
1074   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1075 
1076   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1077   // it's not tuple-like.
1078   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1079       R.empty())
1080     return IsTupleLike::NotTupleLike;
1081 
1082   // If we get this far, we've committed to the tuple interpretation, but
1083   // we can still fail if there actually isn't a usable ::value.
1084 
1085   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1086     LookupResult &R;
1087     TemplateArgumentListInfo &Args;
1088     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1089         : R(R), Args(Args) {}
1090     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1091                                                SourceLocation Loc) override {
1092       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1093           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1094     }
1095   } Diagnoser(R, Args);
1096 
1097   ExprResult E =
1098       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1099   if (E.isInvalid())
1100     return IsTupleLike::Error;
1101 
1102   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1103   if (E.isInvalid())
1104     return IsTupleLike::Error;
1105 
1106   return IsTupleLike::TupleLike;
1107 }
1108 
1109 /// \return std::tuple_element<I, T>::type.
1110 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1111                                         unsigned I, QualType T) {
1112   // Form template argument list for tuple_element<I, T>.
1113   TemplateArgumentListInfo Args(Loc, Loc);
1114   Args.addArgument(
1115       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1116   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1117 
1118   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1119   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1120   if (lookupStdTypeTraitMember(
1121           S, R, Loc, "tuple_element", Args,
1122           diag::err_decomp_decl_std_tuple_element_not_specialized))
1123     return QualType();
1124 
1125   auto *TD = R.getAsSingle<TypeDecl>();
1126   if (!TD) {
1127     R.suppressDiagnostics();
1128     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1129       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1130     if (!R.empty())
1131       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1132     return QualType();
1133   }
1134 
1135   return S.Context.getTypeDeclType(TD);
1136 }
1137 
1138 namespace {
1139 struct InitializingBinding {
1140   Sema &S;
1141   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1142     Sema::CodeSynthesisContext Ctx;
1143     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1144     Ctx.PointOfInstantiation = BD->getLocation();
1145     Ctx.Entity = BD;
1146     S.pushCodeSynthesisContext(Ctx);
1147   }
1148   ~InitializingBinding() {
1149     S.popCodeSynthesisContext();
1150   }
1151 };
1152 }
1153 
1154 static bool checkTupleLikeDecomposition(Sema &S,
1155                                         ArrayRef<BindingDecl *> Bindings,
1156                                         VarDecl *Src, QualType DecompType,
1157                                         const llvm::APSInt &TupleSize) {
1158   if ((int64_t)Bindings.size() != TupleSize) {
1159     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1160         << DecompType << (unsigned)Bindings.size()
1161         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1162         << TupleSize.toString(10) << (TupleSize < Bindings.size());
1163     return true;
1164   }
1165 
1166   if (Bindings.empty())
1167     return false;
1168 
1169   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1170 
1171   // [dcl.decomp]p3:
1172   //   The unqualified-id get is looked up in the scope of E by class member
1173   //   access lookup ...
1174   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1175   bool UseMemberGet = false;
1176   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1177     if (auto *RD = DecompType->getAsCXXRecordDecl())
1178       S.LookupQualifiedName(MemberGet, RD);
1179     if (MemberGet.isAmbiguous())
1180       return true;
1181     //   ... and if that finds at least one declaration that is a function
1182     //   template whose first template parameter is a non-type parameter ...
1183     for (NamedDecl *D : MemberGet) {
1184       if (FunctionTemplateDecl *FTD =
1185               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1186         TemplateParameterList *TPL = FTD->getTemplateParameters();
1187         if (TPL->size() != 0 &&
1188             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1189           //   ... the initializer is e.get<i>().
1190           UseMemberGet = true;
1191           break;
1192         }
1193       }
1194     }
1195   }
1196 
1197   unsigned I = 0;
1198   for (auto *B : Bindings) {
1199     InitializingBinding InitContext(S, B);
1200     SourceLocation Loc = B->getLocation();
1201 
1202     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1203     if (E.isInvalid())
1204       return true;
1205 
1206     //   e is an lvalue if the type of the entity is an lvalue reference and
1207     //   an xvalue otherwise
1208     if (!Src->getType()->isLValueReferenceType())
1209       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1210                                    E.get(), nullptr, VK_XValue,
1211                                    FPOptionsOverride());
1212 
1213     TemplateArgumentListInfo Args(Loc, Loc);
1214     Args.addArgument(
1215         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1216 
1217     if (UseMemberGet) {
1218       //   if [lookup of member get] finds at least one declaration, the
1219       //   initializer is e.get<i-1>().
1220       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1221                                      CXXScopeSpec(), SourceLocation(), nullptr,
1222                                      MemberGet, &Args, nullptr);
1223       if (E.isInvalid())
1224         return true;
1225 
1226       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1227     } else {
1228       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1229       //   in the associated namespaces.
1230       Expr *Get = UnresolvedLookupExpr::Create(
1231           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1232           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1233           UnresolvedSetIterator(), UnresolvedSetIterator());
1234 
1235       Expr *Arg = E.get();
1236       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1237     }
1238     if (E.isInvalid())
1239       return true;
1240     Expr *Init = E.get();
1241 
1242     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1243     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1244     if (T.isNull())
1245       return true;
1246 
1247     //   each vi is a variable of type "reference to T" initialized with the
1248     //   initializer, where the reference is an lvalue reference if the
1249     //   initializer is an lvalue and an rvalue reference otherwise
1250     QualType RefType =
1251         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1252     if (RefType.isNull())
1253       return true;
1254     auto *RefVD = VarDecl::Create(
1255         S.Context, Src->getDeclContext(), Loc, Loc,
1256         B->getDeclName().getAsIdentifierInfo(), RefType,
1257         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1258     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1259     RefVD->setTSCSpec(Src->getTSCSpec());
1260     RefVD->setImplicit();
1261     if (Src->isInlineSpecified())
1262       RefVD->setInlineSpecified();
1263     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1264 
1265     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1266     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1267     InitializationSequence Seq(S, Entity, Kind, Init);
1268     E = Seq.Perform(S, Entity, Kind, Init);
1269     if (E.isInvalid())
1270       return true;
1271     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1272     if (E.isInvalid())
1273       return true;
1274     RefVD->setInit(E.get());
1275     S.CheckCompleteVariableDeclaration(RefVD);
1276 
1277     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1278                                    DeclarationNameInfo(B->getDeclName(), Loc),
1279                                    RefVD);
1280     if (E.isInvalid())
1281       return true;
1282 
1283     B->setBinding(T, E.get());
1284     I++;
1285   }
1286 
1287   return false;
1288 }
1289 
1290 /// Find the base class to decompose in a built-in decomposition of a class type.
1291 /// This base class search is, unfortunately, not quite like any other that we
1292 /// perform anywhere else in C++.
1293 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1294                                                 const CXXRecordDecl *RD,
1295                                                 CXXCastPath &BasePath) {
1296   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1297                           CXXBasePath &Path) {
1298     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1299   };
1300 
1301   const CXXRecordDecl *ClassWithFields = nullptr;
1302   AccessSpecifier AS = AS_public;
1303   if (RD->hasDirectFields())
1304     // [dcl.decomp]p4:
1305     //   Otherwise, all of E's non-static data members shall be public direct
1306     //   members of E ...
1307     ClassWithFields = RD;
1308   else {
1309     //   ... or of ...
1310     CXXBasePaths Paths;
1311     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1312     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1313       // If no classes have fields, just decompose RD itself. (This will work
1314       // if and only if zero bindings were provided.)
1315       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1316     }
1317 
1318     CXXBasePath *BestPath = nullptr;
1319     for (auto &P : Paths) {
1320       if (!BestPath)
1321         BestPath = &P;
1322       else if (!S.Context.hasSameType(P.back().Base->getType(),
1323                                       BestPath->back().Base->getType())) {
1324         //   ... the same ...
1325         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1326           << false << RD << BestPath->back().Base->getType()
1327           << P.back().Base->getType();
1328         return DeclAccessPair();
1329       } else if (P.Access < BestPath->Access) {
1330         BestPath = &P;
1331       }
1332     }
1333 
1334     //   ... unambiguous ...
1335     QualType BaseType = BestPath->back().Base->getType();
1336     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1337       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1338         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1339       return DeclAccessPair();
1340     }
1341 
1342     //   ... [accessible, implied by other rules] base class of E.
1343     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1344                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1345     AS = BestPath->Access;
1346 
1347     ClassWithFields = BaseType->getAsCXXRecordDecl();
1348     S.BuildBasePathArray(Paths, BasePath);
1349   }
1350 
1351   // The above search did not check whether the selected class itself has base
1352   // classes with fields, so check that now.
1353   CXXBasePaths Paths;
1354   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1355     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1356       << (ClassWithFields == RD) << RD << ClassWithFields
1357       << Paths.front().back().Base->getType();
1358     return DeclAccessPair();
1359   }
1360 
1361   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1362 }
1363 
1364 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1365                                      ValueDecl *Src, QualType DecompType,
1366                                      const CXXRecordDecl *OrigRD) {
1367   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1368                             diag::err_incomplete_type))
1369     return true;
1370 
1371   CXXCastPath BasePath;
1372   DeclAccessPair BasePair =
1373       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1374   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1375   if (!RD)
1376     return true;
1377   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1378                                                  DecompType.getQualifiers());
1379 
1380   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1381     unsigned NumFields =
1382         std::count_if(RD->field_begin(), RD->field_end(),
1383                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1384     assert(Bindings.size() != NumFields);
1385     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1386         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1387         << (NumFields < Bindings.size());
1388     return true;
1389   };
1390 
1391   //   all of E's non-static data members shall be [...] well-formed
1392   //   when named as e.name in the context of the structured binding,
1393   //   E shall not have an anonymous union member, ...
1394   unsigned I = 0;
1395   for (auto *FD : RD->fields()) {
1396     if (FD->isUnnamedBitfield())
1397       continue;
1398 
1399     // All the non-static data members are required to be nameable, so they
1400     // must all have names.
1401     if (!FD->getDeclName()) {
1402       if (RD->isLambda()) {
1403         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1404         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1405         return true;
1406       }
1407 
1408       if (FD->isAnonymousStructOrUnion()) {
1409         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1410           << DecompType << FD->getType()->isUnionType();
1411         S.Diag(FD->getLocation(), diag::note_declared_at);
1412         return true;
1413       }
1414 
1415       // FIXME: Are there any other ways we could have an anonymous member?
1416     }
1417 
1418     // We have a real field to bind.
1419     if (I >= Bindings.size())
1420       return DiagnoseBadNumberOfBindings();
1421     auto *B = Bindings[I++];
1422     SourceLocation Loc = B->getLocation();
1423 
1424     // The field must be accessible in the context of the structured binding.
1425     // We already checked that the base class is accessible.
1426     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1427     // const_cast here.
1428     S.CheckStructuredBindingMemberAccess(
1429         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1430         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1431                                      BasePair.getAccess(), FD->getAccess())));
1432 
1433     // Initialize the binding to Src.FD.
1434     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1435     if (E.isInvalid())
1436       return true;
1437     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1438                             VK_LValue, &BasePath);
1439     if (E.isInvalid())
1440       return true;
1441     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1442                                   CXXScopeSpec(), FD,
1443                                   DeclAccessPair::make(FD, FD->getAccess()),
1444                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1445     if (E.isInvalid())
1446       return true;
1447 
1448     // If the type of the member is T, the referenced type is cv T, where cv is
1449     // the cv-qualification of the decomposition expression.
1450     //
1451     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1452     // 'const' to the type of the field.
1453     Qualifiers Q = DecompType.getQualifiers();
1454     if (FD->isMutable())
1455       Q.removeConst();
1456     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1457   }
1458 
1459   if (I != Bindings.size())
1460     return DiagnoseBadNumberOfBindings();
1461 
1462   return false;
1463 }
1464 
1465 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1466   QualType DecompType = DD->getType();
1467 
1468   // If the type of the decomposition is dependent, then so is the type of
1469   // each binding.
1470   if (DecompType->isDependentType()) {
1471     for (auto *B : DD->bindings())
1472       B->setType(Context.DependentTy);
1473     return;
1474   }
1475 
1476   DecompType = DecompType.getNonReferenceType();
1477   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1478 
1479   // C++1z [dcl.decomp]/2:
1480   //   If E is an array type [...]
1481   // As an extension, we also support decomposition of built-in complex and
1482   // vector types.
1483   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1484     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1485       DD->setInvalidDecl();
1486     return;
1487   }
1488   if (auto *VT = DecompType->getAs<VectorType>()) {
1489     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1490       DD->setInvalidDecl();
1491     return;
1492   }
1493   if (auto *CT = DecompType->getAs<ComplexType>()) {
1494     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1495       DD->setInvalidDecl();
1496     return;
1497   }
1498 
1499   // C++1z [dcl.decomp]/3:
1500   //   if the expression std::tuple_size<E>::value is a well-formed integral
1501   //   constant expression, [...]
1502   llvm::APSInt TupleSize(32);
1503   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1504   case IsTupleLike::Error:
1505     DD->setInvalidDecl();
1506     return;
1507 
1508   case IsTupleLike::TupleLike:
1509     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1510       DD->setInvalidDecl();
1511     return;
1512 
1513   case IsTupleLike::NotTupleLike:
1514     break;
1515   }
1516 
1517   // C++1z [dcl.dcl]/8:
1518   //   [E shall be of array or non-union class type]
1519   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1520   if (!RD || RD->isUnion()) {
1521     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1522         << DD << !RD << DecompType;
1523     DD->setInvalidDecl();
1524     return;
1525   }
1526 
1527   // C++1z [dcl.decomp]/4:
1528   //   all of E's non-static data members shall be [...] direct members of
1529   //   E or of the same unambiguous public base class of E, ...
1530   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1531     DD->setInvalidDecl();
1532 }
1533 
1534 /// Merge the exception specifications of two variable declarations.
1535 ///
1536 /// This is called when there's a redeclaration of a VarDecl. The function
1537 /// checks if the redeclaration might have an exception specification and
1538 /// validates compatibility and merges the specs if necessary.
1539 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1540   // Shortcut if exceptions are disabled.
1541   if (!getLangOpts().CXXExceptions)
1542     return;
1543 
1544   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1545          "Should only be called if types are otherwise the same.");
1546 
1547   QualType NewType = New->getType();
1548   QualType OldType = Old->getType();
1549 
1550   // We're only interested in pointers and references to functions, as well
1551   // as pointers to member functions.
1552   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1553     NewType = R->getPointeeType();
1554     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1555   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1556     NewType = P->getPointeeType();
1557     OldType = OldType->castAs<PointerType>()->getPointeeType();
1558   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1559     NewType = M->getPointeeType();
1560     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1561   }
1562 
1563   if (!NewType->isFunctionProtoType())
1564     return;
1565 
1566   // There's lots of special cases for functions. For function pointers, system
1567   // libraries are hopefully not as broken so that we don't need these
1568   // workarounds.
1569   if (CheckEquivalentExceptionSpec(
1570         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1571         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1572     New->setInvalidDecl();
1573   }
1574 }
1575 
1576 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1577 /// function declaration are well-formed according to C++
1578 /// [dcl.fct.default].
1579 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1580   unsigned NumParams = FD->getNumParams();
1581   unsigned ParamIdx = 0;
1582 
1583   // This checking doesn't make sense for explicit specializations; their
1584   // default arguments are determined by the declaration we're specializing,
1585   // not by FD.
1586   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1587     return;
1588   if (auto *FTD = FD->getDescribedFunctionTemplate())
1589     if (FTD->isMemberSpecialization())
1590       return;
1591 
1592   // Find first parameter with a default argument
1593   for (; ParamIdx < NumParams; ++ParamIdx) {
1594     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1595     if (Param->hasDefaultArg())
1596       break;
1597   }
1598 
1599   // C++20 [dcl.fct.default]p4:
1600   //   In a given function declaration, each parameter subsequent to a parameter
1601   //   with a default argument shall have a default argument supplied in this or
1602   //   a previous declaration, unless the parameter was expanded from a
1603   //   parameter pack, or shall be a function parameter pack.
1604   for (; ParamIdx < NumParams; ++ParamIdx) {
1605     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1606     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1607         !(CurrentInstantiationScope &&
1608           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1609       if (Param->isInvalidDecl())
1610         /* We already complained about this parameter. */;
1611       else if (Param->getIdentifier())
1612         Diag(Param->getLocation(),
1613              diag::err_param_default_argument_missing_name)
1614           << Param->getIdentifier();
1615       else
1616         Diag(Param->getLocation(),
1617              diag::err_param_default_argument_missing);
1618     }
1619   }
1620 }
1621 
1622 /// Check that the given type is a literal type. Issue a diagnostic if not,
1623 /// if Kind is Diagnose.
1624 /// \return \c true if a problem has been found (and optionally diagnosed).
1625 template <typename... Ts>
1626 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1627                              SourceLocation Loc, QualType T, unsigned DiagID,
1628                              Ts &&...DiagArgs) {
1629   if (T->isDependentType())
1630     return false;
1631 
1632   switch (Kind) {
1633   case Sema::CheckConstexprKind::Diagnose:
1634     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1635                                       std::forward<Ts>(DiagArgs)...);
1636 
1637   case Sema::CheckConstexprKind::CheckValid:
1638     return !T->isLiteralType(SemaRef.Context);
1639   }
1640 
1641   llvm_unreachable("unknown CheckConstexprKind");
1642 }
1643 
1644 /// Determine whether a destructor cannot be constexpr due to
1645 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1646                                                const CXXDestructorDecl *DD,
1647                                                Sema::CheckConstexprKind Kind) {
1648   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1649     const CXXRecordDecl *RD =
1650         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1651     if (!RD || RD->hasConstexprDestructor())
1652       return true;
1653 
1654     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1655       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1656           << static_cast<int>(DD->getConstexprKind()) << !FD
1657           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1658       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1659           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1660     }
1661     return false;
1662   };
1663 
1664   const CXXRecordDecl *RD = DD->getParent();
1665   for (const CXXBaseSpecifier &B : RD->bases())
1666     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1667       return false;
1668   for (const FieldDecl *FD : RD->fields())
1669     if (!Check(FD->getLocation(), FD->getType(), FD))
1670       return false;
1671   return true;
1672 }
1673 
1674 /// Check whether a function's parameter types are all literal types. If so,
1675 /// return true. If not, produce a suitable diagnostic and return false.
1676 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1677                                          const FunctionDecl *FD,
1678                                          Sema::CheckConstexprKind Kind) {
1679   unsigned ArgIndex = 0;
1680   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1681   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1682                                               e = FT->param_type_end();
1683        i != e; ++i, ++ArgIndex) {
1684     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1685     SourceLocation ParamLoc = PD->getLocation();
1686     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1687                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1688                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1689                          FD->isConsteval()))
1690       return false;
1691   }
1692   return true;
1693 }
1694 
1695 /// Check whether a function's return type is a literal type. If so, return
1696 /// true. If not, produce a suitable diagnostic and return false.
1697 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1698                                      Sema::CheckConstexprKind Kind) {
1699   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1700                        diag::err_constexpr_non_literal_return,
1701                        FD->isConsteval()))
1702     return false;
1703   return true;
1704 }
1705 
1706 /// Get diagnostic %select index for tag kind for
1707 /// record diagnostic message.
1708 /// WARNING: Indexes apply to particular diagnostics only!
1709 ///
1710 /// \returns diagnostic %select index.
1711 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1712   switch (Tag) {
1713   case TTK_Struct: return 0;
1714   case TTK_Interface: return 1;
1715   case TTK_Class:  return 2;
1716   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1717   }
1718 }
1719 
1720 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1721                                        Stmt *Body,
1722                                        Sema::CheckConstexprKind Kind);
1723 
1724 // Check whether a function declaration satisfies the requirements of a
1725 // constexpr function definition or a constexpr constructor definition. If so,
1726 // return true. If not, produce appropriate diagnostics (unless asked not to by
1727 // Kind) and return false.
1728 //
1729 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1730 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1731                                             CheckConstexprKind Kind) {
1732   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1733   if (MD && MD->isInstance()) {
1734     // C++11 [dcl.constexpr]p4:
1735     //  The definition of a constexpr constructor shall satisfy the following
1736     //  constraints:
1737     //  - the class shall not have any virtual base classes;
1738     //
1739     // FIXME: This only applies to constructors and destructors, not arbitrary
1740     // member functions.
1741     const CXXRecordDecl *RD = MD->getParent();
1742     if (RD->getNumVBases()) {
1743       if (Kind == CheckConstexprKind::CheckValid)
1744         return false;
1745 
1746       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1747         << isa<CXXConstructorDecl>(NewFD)
1748         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1749       for (const auto &I : RD->vbases())
1750         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1751             << I.getSourceRange();
1752       return false;
1753     }
1754   }
1755 
1756   if (!isa<CXXConstructorDecl>(NewFD)) {
1757     // C++11 [dcl.constexpr]p3:
1758     //  The definition of a constexpr function shall satisfy the following
1759     //  constraints:
1760     // - it shall not be virtual; (removed in C++20)
1761     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1762     if (Method && Method->isVirtual()) {
1763       if (getLangOpts().CPlusPlus20) {
1764         if (Kind == CheckConstexprKind::Diagnose)
1765           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1766       } else {
1767         if (Kind == CheckConstexprKind::CheckValid)
1768           return false;
1769 
1770         Method = Method->getCanonicalDecl();
1771         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1772 
1773         // If it's not obvious why this function is virtual, find an overridden
1774         // function which uses the 'virtual' keyword.
1775         const CXXMethodDecl *WrittenVirtual = Method;
1776         while (!WrittenVirtual->isVirtualAsWritten())
1777           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1778         if (WrittenVirtual != Method)
1779           Diag(WrittenVirtual->getLocation(),
1780                diag::note_overridden_virtual_function);
1781         return false;
1782       }
1783     }
1784 
1785     // - its return type shall be a literal type;
1786     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1787       return false;
1788   }
1789 
1790   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1791     // A destructor can be constexpr only if the defaulted destructor could be;
1792     // we don't need to check the members and bases if we already know they all
1793     // have constexpr destructors.
1794     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1795       if (Kind == CheckConstexprKind::CheckValid)
1796         return false;
1797       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1798         return false;
1799     }
1800   }
1801 
1802   // - each of its parameter types shall be a literal type;
1803   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1804     return false;
1805 
1806   Stmt *Body = NewFD->getBody();
1807   assert(Body &&
1808          "CheckConstexprFunctionDefinition called on function with no body");
1809   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1810 }
1811 
1812 /// Check the given declaration statement is legal within a constexpr function
1813 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1814 ///
1815 /// \return true if the body is OK (maybe only as an extension), false if we
1816 ///         have diagnosed a problem.
1817 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1818                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1819                                    Sema::CheckConstexprKind Kind) {
1820   // C++11 [dcl.constexpr]p3 and p4:
1821   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1822   //  contain only
1823   for (const auto *DclIt : DS->decls()) {
1824     switch (DclIt->getKind()) {
1825     case Decl::StaticAssert:
1826     case Decl::Using:
1827     case Decl::UsingShadow:
1828     case Decl::UsingDirective:
1829     case Decl::UnresolvedUsingTypename:
1830     case Decl::UnresolvedUsingValue:
1831       //   - static_assert-declarations
1832       //   - using-declarations,
1833       //   - using-directives,
1834       continue;
1835 
1836     case Decl::Typedef:
1837     case Decl::TypeAlias: {
1838       //   - typedef declarations and alias-declarations that do not define
1839       //     classes or enumerations,
1840       const auto *TN = cast<TypedefNameDecl>(DclIt);
1841       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1842         // Don't allow variably-modified types in constexpr functions.
1843         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1844           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1845           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1846             << TL.getSourceRange() << TL.getType()
1847             << isa<CXXConstructorDecl>(Dcl);
1848         }
1849         return false;
1850       }
1851       continue;
1852     }
1853 
1854     case Decl::Enum:
1855     case Decl::CXXRecord:
1856       // C++1y allows types to be defined, not just declared.
1857       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1858         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1859           SemaRef.Diag(DS->getBeginLoc(),
1860                        SemaRef.getLangOpts().CPlusPlus14
1861                            ? diag::warn_cxx11_compat_constexpr_type_definition
1862                            : diag::ext_constexpr_type_definition)
1863               << isa<CXXConstructorDecl>(Dcl);
1864         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1865           return false;
1866         }
1867       }
1868       continue;
1869 
1870     case Decl::EnumConstant:
1871     case Decl::IndirectField:
1872     case Decl::ParmVar:
1873       // These can only appear with other declarations which are banned in
1874       // C++11 and permitted in C++1y, so ignore them.
1875       continue;
1876 
1877     case Decl::Var:
1878     case Decl::Decomposition: {
1879       // C++1y [dcl.constexpr]p3 allows anything except:
1880       //   a definition of a variable of non-literal type or of static or
1881       //   thread storage duration or [before C++2a] for which no
1882       //   initialization is performed.
1883       const auto *VD = cast<VarDecl>(DclIt);
1884       if (VD->isThisDeclarationADefinition()) {
1885         if (VD->isStaticLocal()) {
1886           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1887             SemaRef.Diag(VD->getLocation(),
1888                          diag::err_constexpr_local_var_static)
1889               << isa<CXXConstructorDecl>(Dcl)
1890               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1891           }
1892           return false;
1893         }
1894         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1895                              diag::err_constexpr_local_var_non_literal_type,
1896                              isa<CXXConstructorDecl>(Dcl)))
1897           return false;
1898         if (!VD->getType()->isDependentType() &&
1899             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1900           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1901             SemaRef.Diag(
1902                 VD->getLocation(),
1903                 SemaRef.getLangOpts().CPlusPlus20
1904                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1905                     : diag::ext_constexpr_local_var_no_init)
1906                 << isa<CXXConstructorDecl>(Dcl);
1907           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1908             return false;
1909           }
1910           continue;
1911         }
1912       }
1913       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1914         SemaRef.Diag(VD->getLocation(),
1915                      SemaRef.getLangOpts().CPlusPlus14
1916                       ? diag::warn_cxx11_compat_constexpr_local_var
1917                       : diag::ext_constexpr_local_var)
1918           << isa<CXXConstructorDecl>(Dcl);
1919       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1920         return false;
1921       }
1922       continue;
1923     }
1924 
1925     case Decl::NamespaceAlias:
1926     case Decl::Function:
1927       // These are disallowed in C++11 and permitted in C++1y. Allow them
1928       // everywhere as an extension.
1929       if (!Cxx1yLoc.isValid())
1930         Cxx1yLoc = DS->getBeginLoc();
1931       continue;
1932 
1933     default:
1934       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1935         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1936             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1937       }
1938       return false;
1939     }
1940   }
1941 
1942   return true;
1943 }
1944 
1945 /// Check that the given field is initialized within a constexpr constructor.
1946 ///
1947 /// \param Dcl The constexpr constructor being checked.
1948 /// \param Field The field being checked. This may be a member of an anonymous
1949 ///        struct or union nested within the class being checked.
1950 /// \param Inits All declarations, including anonymous struct/union members and
1951 ///        indirect members, for which any initialization was provided.
1952 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1953 ///        multiple notes for different members to the same error.
1954 /// \param Kind Whether we're diagnosing a constructor as written or determining
1955 ///        whether the formal requirements are satisfied.
1956 /// \return \c false if we're checking for validity and the constructor does
1957 ///         not satisfy the requirements on a constexpr constructor.
1958 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1959                                           const FunctionDecl *Dcl,
1960                                           FieldDecl *Field,
1961                                           llvm::SmallSet<Decl*, 16> &Inits,
1962                                           bool &Diagnosed,
1963                                           Sema::CheckConstexprKind Kind) {
1964   // In C++20 onwards, there's nothing to check for validity.
1965   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1966       SemaRef.getLangOpts().CPlusPlus20)
1967     return true;
1968 
1969   if (Field->isInvalidDecl())
1970     return true;
1971 
1972   if (Field->isUnnamedBitfield())
1973     return true;
1974 
1975   // Anonymous unions with no variant members and empty anonymous structs do not
1976   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1977   // indirect fields don't need initializing.
1978   if (Field->isAnonymousStructOrUnion() &&
1979       (Field->getType()->isUnionType()
1980            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1981            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1982     return true;
1983 
1984   if (!Inits.count(Field)) {
1985     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1986       if (!Diagnosed) {
1987         SemaRef.Diag(Dcl->getLocation(),
1988                      SemaRef.getLangOpts().CPlusPlus20
1989                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1990                          : diag::ext_constexpr_ctor_missing_init);
1991         Diagnosed = true;
1992       }
1993       SemaRef.Diag(Field->getLocation(),
1994                    diag::note_constexpr_ctor_missing_init);
1995     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1996       return false;
1997     }
1998   } else if (Field->isAnonymousStructOrUnion()) {
1999     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2000     for (auto *I : RD->fields())
2001       // If an anonymous union contains an anonymous struct of which any member
2002       // is initialized, all members must be initialized.
2003       if (!RD->isUnion() || Inits.count(I))
2004         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2005                                            Kind))
2006           return false;
2007   }
2008   return true;
2009 }
2010 
2011 /// Check the provided statement is allowed in a constexpr function
2012 /// definition.
2013 static bool
2014 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2015                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2016                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2017                            Sema::CheckConstexprKind Kind) {
2018   // - its function-body shall be [...] a compound-statement that contains only
2019   switch (S->getStmtClass()) {
2020   case Stmt::NullStmtClass:
2021     //   - null statements,
2022     return true;
2023 
2024   case Stmt::DeclStmtClass:
2025     //   - static_assert-declarations
2026     //   - using-declarations,
2027     //   - using-directives,
2028     //   - typedef declarations and alias-declarations that do not define
2029     //     classes or enumerations,
2030     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2031       return false;
2032     return true;
2033 
2034   case Stmt::ReturnStmtClass:
2035     //   - and exactly one return statement;
2036     if (isa<CXXConstructorDecl>(Dcl)) {
2037       // C++1y allows return statements in constexpr constructors.
2038       if (!Cxx1yLoc.isValid())
2039         Cxx1yLoc = S->getBeginLoc();
2040       return true;
2041     }
2042 
2043     ReturnStmts.push_back(S->getBeginLoc());
2044     return true;
2045 
2046   case Stmt::CompoundStmtClass: {
2047     // C++1y allows compound-statements.
2048     if (!Cxx1yLoc.isValid())
2049       Cxx1yLoc = S->getBeginLoc();
2050 
2051     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2052     for (auto *BodyIt : CompStmt->body()) {
2053       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2054                                       Cxx1yLoc, Cxx2aLoc, Kind))
2055         return false;
2056     }
2057     return true;
2058   }
2059 
2060   case Stmt::AttributedStmtClass:
2061     if (!Cxx1yLoc.isValid())
2062       Cxx1yLoc = S->getBeginLoc();
2063     return true;
2064 
2065   case Stmt::IfStmtClass: {
2066     // C++1y allows if-statements.
2067     if (!Cxx1yLoc.isValid())
2068       Cxx1yLoc = S->getBeginLoc();
2069 
2070     IfStmt *If = cast<IfStmt>(S);
2071     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2072                                     Cxx1yLoc, Cxx2aLoc, Kind))
2073       return false;
2074     if (If->getElse() &&
2075         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2076                                     Cxx1yLoc, Cxx2aLoc, Kind))
2077       return false;
2078     return true;
2079   }
2080 
2081   case Stmt::WhileStmtClass:
2082   case Stmt::DoStmtClass:
2083   case Stmt::ForStmtClass:
2084   case Stmt::CXXForRangeStmtClass:
2085   case Stmt::ContinueStmtClass:
2086     // C++1y allows all of these. We don't allow them as extensions in C++11,
2087     // because they don't make sense without variable mutation.
2088     if (!SemaRef.getLangOpts().CPlusPlus14)
2089       break;
2090     if (!Cxx1yLoc.isValid())
2091       Cxx1yLoc = S->getBeginLoc();
2092     for (Stmt *SubStmt : S->children())
2093       if (SubStmt &&
2094           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2095                                       Cxx1yLoc, Cxx2aLoc, Kind))
2096         return false;
2097     return true;
2098 
2099   case Stmt::SwitchStmtClass:
2100   case Stmt::CaseStmtClass:
2101   case Stmt::DefaultStmtClass:
2102   case Stmt::BreakStmtClass:
2103     // C++1y allows switch-statements, and since they don't need variable
2104     // mutation, we can reasonably allow them in C++11 as an extension.
2105     if (!Cxx1yLoc.isValid())
2106       Cxx1yLoc = S->getBeginLoc();
2107     for (Stmt *SubStmt : S->children())
2108       if (SubStmt &&
2109           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2110                                       Cxx1yLoc, Cxx2aLoc, Kind))
2111         return false;
2112     return true;
2113 
2114   case Stmt::GCCAsmStmtClass:
2115   case Stmt::MSAsmStmtClass:
2116     // C++2a allows inline assembly statements.
2117   case Stmt::CXXTryStmtClass:
2118     if (Cxx2aLoc.isInvalid())
2119       Cxx2aLoc = S->getBeginLoc();
2120     for (Stmt *SubStmt : S->children()) {
2121       if (SubStmt &&
2122           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2123                                       Cxx1yLoc, Cxx2aLoc, Kind))
2124         return false;
2125     }
2126     return true;
2127 
2128   case Stmt::CXXCatchStmtClass:
2129     // Do not bother checking the language mode (already covered by the
2130     // try block check).
2131     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2132                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2133                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2134       return false;
2135     return true;
2136 
2137   default:
2138     if (!isa<Expr>(S))
2139       break;
2140 
2141     // C++1y allows expression-statements.
2142     if (!Cxx1yLoc.isValid())
2143       Cxx1yLoc = S->getBeginLoc();
2144     return true;
2145   }
2146 
2147   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2148     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2149         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2150   }
2151   return false;
2152 }
2153 
2154 /// Check the body for the given constexpr function declaration only contains
2155 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2156 ///
2157 /// \return true if the body is OK, false if we have found or diagnosed a
2158 /// problem.
2159 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2160                                        Stmt *Body,
2161                                        Sema::CheckConstexprKind Kind) {
2162   SmallVector<SourceLocation, 4> ReturnStmts;
2163 
2164   if (isa<CXXTryStmt>(Body)) {
2165     // C++11 [dcl.constexpr]p3:
2166     //  The definition of a constexpr function shall satisfy the following
2167     //  constraints: [...]
2168     // - its function-body shall be = delete, = default, or a
2169     //   compound-statement
2170     //
2171     // C++11 [dcl.constexpr]p4:
2172     //  In the definition of a constexpr constructor, [...]
2173     // - its function-body shall not be a function-try-block;
2174     //
2175     // This restriction is lifted in C++2a, as long as inner statements also
2176     // apply the general constexpr rules.
2177     switch (Kind) {
2178     case Sema::CheckConstexprKind::CheckValid:
2179       if (!SemaRef.getLangOpts().CPlusPlus20)
2180         return false;
2181       break;
2182 
2183     case Sema::CheckConstexprKind::Diagnose:
2184       SemaRef.Diag(Body->getBeginLoc(),
2185            !SemaRef.getLangOpts().CPlusPlus20
2186                ? diag::ext_constexpr_function_try_block_cxx20
2187                : diag::warn_cxx17_compat_constexpr_function_try_block)
2188           << isa<CXXConstructorDecl>(Dcl);
2189       break;
2190     }
2191   }
2192 
2193   // - its function-body shall be [...] a compound-statement that contains only
2194   //   [... list of cases ...]
2195   //
2196   // Note that walking the children here is enough to properly check for
2197   // CompoundStmt and CXXTryStmt body.
2198   SourceLocation Cxx1yLoc, Cxx2aLoc;
2199   for (Stmt *SubStmt : Body->children()) {
2200     if (SubStmt &&
2201         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2202                                     Cxx1yLoc, Cxx2aLoc, Kind))
2203       return false;
2204   }
2205 
2206   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2207     // If this is only valid as an extension, report that we don't satisfy the
2208     // constraints of the current language.
2209     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2210         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2211       return false;
2212   } else if (Cxx2aLoc.isValid()) {
2213     SemaRef.Diag(Cxx2aLoc,
2214          SemaRef.getLangOpts().CPlusPlus20
2215            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2216            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2217       << isa<CXXConstructorDecl>(Dcl);
2218   } else if (Cxx1yLoc.isValid()) {
2219     SemaRef.Diag(Cxx1yLoc,
2220          SemaRef.getLangOpts().CPlusPlus14
2221            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2222            : diag::ext_constexpr_body_invalid_stmt)
2223       << isa<CXXConstructorDecl>(Dcl);
2224   }
2225 
2226   if (const CXXConstructorDecl *Constructor
2227         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2228     const CXXRecordDecl *RD = Constructor->getParent();
2229     // DR1359:
2230     // - every non-variant non-static data member and base class sub-object
2231     //   shall be initialized;
2232     // DR1460:
2233     // - if the class is a union having variant members, exactly one of them
2234     //   shall be initialized;
2235     if (RD->isUnion()) {
2236       if (Constructor->getNumCtorInitializers() == 0 &&
2237           RD->hasVariantMembers()) {
2238         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2239           SemaRef.Diag(
2240               Dcl->getLocation(),
2241               SemaRef.getLangOpts().CPlusPlus20
2242                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2243                   : diag::ext_constexpr_union_ctor_no_init);
2244         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2245           return false;
2246         }
2247       }
2248     } else if (!Constructor->isDependentContext() &&
2249                !Constructor->isDelegatingConstructor()) {
2250       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2251 
2252       // Skip detailed checking if we have enough initializers, and we would
2253       // allow at most one initializer per member.
2254       bool AnyAnonStructUnionMembers = false;
2255       unsigned Fields = 0;
2256       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2257            E = RD->field_end(); I != E; ++I, ++Fields) {
2258         if (I->isAnonymousStructOrUnion()) {
2259           AnyAnonStructUnionMembers = true;
2260           break;
2261         }
2262       }
2263       // DR1460:
2264       // - if the class is a union-like class, but is not a union, for each of
2265       //   its anonymous union members having variant members, exactly one of
2266       //   them shall be initialized;
2267       if (AnyAnonStructUnionMembers ||
2268           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2269         // Check initialization of non-static data members. Base classes are
2270         // always initialized so do not need to be checked. Dependent bases
2271         // might not have initializers in the member initializer list.
2272         llvm::SmallSet<Decl*, 16> Inits;
2273         for (const auto *I: Constructor->inits()) {
2274           if (FieldDecl *FD = I->getMember())
2275             Inits.insert(FD);
2276           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2277             Inits.insert(ID->chain_begin(), ID->chain_end());
2278         }
2279 
2280         bool Diagnosed = false;
2281         for (auto *I : RD->fields())
2282           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2283                                              Kind))
2284             return false;
2285       }
2286     }
2287   } else {
2288     if (ReturnStmts.empty()) {
2289       // C++1y doesn't require constexpr functions to contain a 'return'
2290       // statement. We still do, unless the return type might be void, because
2291       // otherwise if there's no return statement, the function cannot
2292       // be used in a core constant expression.
2293       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2294                 (Dcl->getReturnType()->isVoidType() ||
2295                  Dcl->getReturnType()->isDependentType());
2296       switch (Kind) {
2297       case Sema::CheckConstexprKind::Diagnose:
2298         SemaRef.Diag(Dcl->getLocation(),
2299                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2300                         : diag::err_constexpr_body_no_return)
2301             << Dcl->isConsteval();
2302         if (!OK)
2303           return false;
2304         break;
2305 
2306       case Sema::CheckConstexprKind::CheckValid:
2307         // The formal requirements don't include this rule in C++14, even
2308         // though the "must be able to produce a constant expression" rules
2309         // still imply it in some cases.
2310         if (!SemaRef.getLangOpts().CPlusPlus14)
2311           return false;
2312         break;
2313       }
2314     } else if (ReturnStmts.size() > 1) {
2315       switch (Kind) {
2316       case Sema::CheckConstexprKind::Diagnose:
2317         SemaRef.Diag(
2318             ReturnStmts.back(),
2319             SemaRef.getLangOpts().CPlusPlus14
2320                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2321                 : diag::ext_constexpr_body_multiple_return);
2322         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2323           SemaRef.Diag(ReturnStmts[I],
2324                        diag::note_constexpr_body_previous_return);
2325         break;
2326 
2327       case Sema::CheckConstexprKind::CheckValid:
2328         if (!SemaRef.getLangOpts().CPlusPlus14)
2329           return false;
2330         break;
2331       }
2332     }
2333   }
2334 
2335   // C++11 [dcl.constexpr]p5:
2336   //   if no function argument values exist such that the function invocation
2337   //   substitution would produce a constant expression, the program is
2338   //   ill-formed; no diagnostic required.
2339   // C++11 [dcl.constexpr]p3:
2340   //   - every constructor call and implicit conversion used in initializing the
2341   //     return value shall be one of those allowed in a constant expression.
2342   // C++11 [dcl.constexpr]p4:
2343   //   - every constructor involved in initializing non-static data members and
2344   //     base class sub-objects shall be a constexpr constructor.
2345   //
2346   // Note that this rule is distinct from the "requirements for a constexpr
2347   // function", so is not checked in CheckValid mode.
2348   SmallVector<PartialDiagnosticAt, 8> Diags;
2349   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2350       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2351     SemaRef.Diag(Dcl->getLocation(),
2352                  diag::ext_constexpr_function_never_constant_expr)
2353         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2354     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2355       SemaRef.Diag(Diags[I].first, Diags[I].second);
2356     // Don't return false here: we allow this for compatibility in
2357     // system headers.
2358   }
2359 
2360   return true;
2361 }
2362 
2363 /// Get the class that is directly named by the current context. This is the
2364 /// class for which an unqualified-id in this scope could name a constructor
2365 /// or destructor.
2366 ///
2367 /// If the scope specifier denotes a class, this will be that class.
2368 /// If the scope specifier is empty, this will be the class whose
2369 /// member-specification we are currently within. Otherwise, there
2370 /// is no such class.
2371 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2372   assert(getLangOpts().CPlusPlus && "No class names in C!");
2373 
2374   if (SS && SS->isInvalid())
2375     return nullptr;
2376 
2377   if (SS && SS->isNotEmpty()) {
2378     DeclContext *DC = computeDeclContext(*SS, true);
2379     return dyn_cast_or_null<CXXRecordDecl>(DC);
2380   }
2381 
2382   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2383 }
2384 
2385 /// isCurrentClassName - Determine whether the identifier II is the
2386 /// name of the class type currently being defined. In the case of
2387 /// nested classes, this will only return true if II is the name of
2388 /// the innermost class.
2389 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2390                               const CXXScopeSpec *SS) {
2391   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2392   return CurDecl && &II == CurDecl->getIdentifier();
2393 }
2394 
2395 /// Determine whether the identifier II is a typo for the name of
2396 /// the class type currently being defined. If so, update it to the identifier
2397 /// that should have been used.
2398 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2399   assert(getLangOpts().CPlusPlus && "No class names in C!");
2400 
2401   if (!getLangOpts().SpellChecking)
2402     return false;
2403 
2404   CXXRecordDecl *CurDecl;
2405   if (SS && SS->isSet() && !SS->isInvalid()) {
2406     DeclContext *DC = computeDeclContext(*SS, true);
2407     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2408   } else
2409     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2410 
2411   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2412       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2413           < II->getLength()) {
2414     II = CurDecl->getIdentifier();
2415     return true;
2416   }
2417 
2418   return false;
2419 }
2420 
2421 /// Determine whether the given class is a base class of the given
2422 /// class, including looking at dependent bases.
2423 static bool findCircularInheritance(const CXXRecordDecl *Class,
2424                                     const CXXRecordDecl *Current) {
2425   SmallVector<const CXXRecordDecl*, 8> Queue;
2426 
2427   Class = Class->getCanonicalDecl();
2428   while (true) {
2429     for (const auto &I : Current->bases()) {
2430       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2431       if (!Base)
2432         continue;
2433 
2434       Base = Base->getDefinition();
2435       if (!Base)
2436         continue;
2437 
2438       if (Base->getCanonicalDecl() == Class)
2439         return true;
2440 
2441       Queue.push_back(Base);
2442     }
2443 
2444     if (Queue.empty())
2445       return false;
2446 
2447     Current = Queue.pop_back_val();
2448   }
2449 
2450   return false;
2451 }
2452 
2453 /// Check the validity of a C++ base class specifier.
2454 ///
2455 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2456 /// and returns NULL otherwise.
2457 CXXBaseSpecifier *
2458 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2459                          SourceRange SpecifierRange,
2460                          bool Virtual, AccessSpecifier Access,
2461                          TypeSourceInfo *TInfo,
2462                          SourceLocation EllipsisLoc) {
2463   QualType BaseType = TInfo->getType();
2464   if (BaseType->containsErrors()) {
2465     // Already emitted a diagnostic when parsing the error type.
2466     return nullptr;
2467   }
2468   // C++ [class.union]p1:
2469   //   A union shall not have base classes.
2470   if (Class->isUnion()) {
2471     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2472       << SpecifierRange;
2473     return nullptr;
2474   }
2475 
2476   if (EllipsisLoc.isValid() &&
2477       !TInfo->getType()->containsUnexpandedParameterPack()) {
2478     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2479       << TInfo->getTypeLoc().getSourceRange();
2480     EllipsisLoc = SourceLocation();
2481   }
2482 
2483   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2484 
2485   if (BaseType->isDependentType()) {
2486     // Make sure that we don't have circular inheritance among our dependent
2487     // bases. For non-dependent bases, the check for completeness below handles
2488     // this.
2489     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2490       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2491           ((BaseDecl = BaseDecl->getDefinition()) &&
2492            findCircularInheritance(Class, BaseDecl))) {
2493         Diag(BaseLoc, diag::err_circular_inheritance)
2494           << BaseType << Context.getTypeDeclType(Class);
2495 
2496         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2497           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2498             << BaseType;
2499 
2500         return nullptr;
2501       }
2502     }
2503 
2504     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2505                                           Class->getTagKind() == TTK_Class,
2506                                           Access, TInfo, EllipsisLoc);
2507   }
2508 
2509   // Base specifiers must be record types.
2510   if (!BaseType->isRecordType()) {
2511     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2512     return nullptr;
2513   }
2514 
2515   // C++ [class.union]p1:
2516   //   A union shall not be used as a base class.
2517   if (BaseType->isUnionType()) {
2518     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2519     return nullptr;
2520   }
2521 
2522   // For the MS ABI, propagate DLL attributes to base class templates.
2523   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2524     if (Attr *ClassAttr = getDLLAttr(Class)) {
2525       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2526               BaseType->getAsCXXRecordDecl())) {
2527         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2528                                             BaseLoc);
2529       }
2530     }
2531   }
2532 
2533   // C++ [class.derived]p2:
2534   //   The class-name in a base-specifier shall not be an incompletely
2535   //   defined class.
2536   if (RequireCompleteType(BaseLoc, BaseType,
2537                           diag::err_incomplete_base_class, SpecifierRange)) {
2538     Class->setInvalidDecl();
2539     return nullptr;
2540   }
2541 
2542   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2543   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2544   assert(BaseDecl && "Record type has no declaration");
2545   BaseDecl = BaseDecl->getDefinition();
2546   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2547   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2548   assert(CXXBaseDecl && "Base type is not a C++ type");
2549 
2550   // Microsoft docs say:
2551   // "If a base-class has a code_seg attribute, derived classes must have the
2552   // same attribute."
2553   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2554   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2555   if ((DerivedCSA || BaseCSA) &&
2556       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2557     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2558     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2559       << CXXBaseDecl;
2560     return nullptr;
2561   }
2562 
2563   // A class which contains a flexible array member is not suitable for use as a
2564   // base class:
2565   //   - If the layout determines that a base comes before another base,
2566   //     the flexible array member would index into the subsequent base.
2567   //   - If the layout determines that base comes before the derived class,
2568   //     the flexible array member would index into the derived class.
2569   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2570     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2571       << CXXBaseDecl->getDeclName();
2572     return nullptr;
2573   }
2574 
2575   // C++ [class]p3:
2576   //   If a class is marked final and it appears as a base-type-specifier in
2577   //   base-clause, the program is ill-formed.
2578   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2579     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2580       << CXXBaseDecl->getDeclName()
2581       << FA->isSpelledAsSealed();
2582     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2583         << CXXBaseDecl->getDeclName() << FA->getRange();
2584     return nullptr;
2585   }
2586 
2587   if (BaseDecl->isInvalidDecl())
2588     Class->setInvalidDecl();
2589 
2590   // Create the base specifier.
2591   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2592                                         Class->getTagKind() == TTK_Class,
2593                                         Access, TInfo, EllipsisLoc);
2594 }
2595 
2596 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2597 /// one entry in the base class list of a class specifier, for
2598 /// example:
2599 ///    class foo : public bar, virtual private baz {
2600 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2601 BaseResult
2602 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2603                          ParsedAttributes &Attributes,
2604                          bool Virtual, AccessSpecifier Access,
2605                          ParsedType basetype, SourceLocation BaseLoc,
2606                          SourceLocation EllipsisLoc) {
2607   if (!classdecl)
2608     return true;
2609 
2610   AdjustDeclIfTemplate(classdecl);
2611   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2612   if (!Class)
2613     return true;
2614 
2615   // We haven't yet attached the base specifiers.
2616   Class->setIsParsingBaseSpecifiers();
2617 
2618   // We do not support any C++11 attributes on base-specifiers yet.
2619   // Diagnose any attributes we see.
2620   for (const ParsedAttr &AL : Attributes) {
2621     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2622       continue;
2623     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2624                           ? (unsigned)diag::warn_unknown_attribute_ignored
2625                           : (unsigned)diag::err_base_specifier_attribute)
2626         << AL << AL.getRange();
2627   }
2628 
2629   TypeSourceInfo *TInfo = nullptr;
2630   GetTypeFromParser(basetype, &TInfo);
2631 
2632   if (EllipsisLoc.isInvalid() &&
2633       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2634                                       UPPC_BaseType))
2635     return true;
2636 
2637   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2638                                                       Virtual, Access, TInfo,
2639                                                       EllipsisLoc))
2640     return BaseSpec;
2641   else
2642     Class->setInvalidDecl();
2643 
2644   return true;
2645 }
2646 
2647 /// Use small set to collect indirect bases.  As this is only used
2648 /// locally, there's no need to abstract the small size parameter.
2649 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2650 
2651 /// Recursively add the bases of Type.  Don't add Type itself.
2652 static void
2653 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2654                   const QualType &Type)
2655 {
2656   // Even though the incoming type is a base, it might not be
2657   // a class -- it could be a template parm, for instance.
2658   if (auto Rec = Type->getAs<RecordType>()) {
2659     auto Decl = Rec->getAsCXXRecordDecl();
2660 
2661     // Iterate over its bases.
2662     for (const auto &BaseSpec : Decl->bases()) {
2663       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2664         .getUnqualifiedType();
2665       if (Set.insert(Base).second)
2666         // If we've not already seen it, recurse.
2667         NoteIndirectBases(Context, Set, Base);
2668     }
2669   }
2670 }
2671 
2672 /// Performs the actual work of attaching the given base class
2673 /// specifiers to a C++ class.
2674 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2675                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2676  if (Bases.empty())
2677     return false;
2678 
2679   // Used to keep track of which base types we have already seen, so
2680   // that we can properly diagnose redundant direct base types. Note
2681   // that the key is always the unqualified canonical type of the base
2682   // class.
2683   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2684 
2685   // Used to track indirect bases so we can see if a direct base is
2686   // ambiguous.
2687   IndirectBaseSet IndirectBaseTypes;
2688 
2689   // Copy non-redundant base specifiers into permanent storage.
2690   unsigned NumGoodBases = 0;
2691   bool Invalid = false;
2692   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2693     QualType NewBaseType
2694       = Context.getCanonicalType(Bases[idx]->getType());
2695     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2696 
2697     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2698     if (KnownBase) {
2699       // C++ [class.mi]p3:
2700       //   A class shall not be specified as a direct base class of a
2701       //   derived class more than once.
2702       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2703           << KnownBase->getType() << Bases[idx]->getSourceRange();
2704 
2705       // Delete the duplicate base class specifier; we're going to
2706       // overwrite its pointer later.
2707       Context.Deallocate(Bases[idx]);
2708 
2709       Invalid = true;
2710     } else {
2711       // Okay, add this new base class.
2712       KnownBase = Bases[idx];
2713       Bases[NumGoodBases++] = Bases[idx];
2714 
2715       // Note this base's direct & indirect bases, if there could be ambiguity.
2716       if (Bases.size() > 1)
2717         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2718 
2719       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2720         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2721         if (Class->isInterface() &&
2722               (!RD->isInterfaceLike() ||
2723                KnownBase->getAccessSpecifier() != AS_public)) {
2724           // The Microsoft extension __interface does not permit bases that
2725           // are not themselves public interfaces.
2726           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2727               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2728               << RD->getSourceRange();
2729           Invalid = true;
2730         }
2731         if (RD->hasAttr<WeakAttr>())
2732           Class->addAttr(WeakAttr::CreateImplicit(Context));
2733       }
2734     }
2735   }
2736 
2737   // Attach the remaining base class specifiers to the derived class.
2738   Class->setBases(Bases.data(), NumGoodBases);
2739 
2740   // Check that the only base classes that are duplicate are virtual.
2741   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2742     // Check whether this direct base is inaccessible due to ambiguity.
2743     QualType BaseType = Bases[idx]->getType();
2744 
2745     // Skip all dependent types in templates being used as base specifiers.
2746     // Checks below assume that the base specifier is a CXXRecord.
2747     if (BaseType->isDependentType())
2748       continue;
2749 
2750     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2751       .getUnqualifiedType();
2752 
2753     if (IndirectBaseTypes.count(CanonicalBase)) {
2754       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2755                          /*DetectVirtual=*/true);
2756       bool found
2757         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2758       assert(found);
2759       (void)found;
2760 
2761       if (Paths.isAmbiguous(CanonicalBase))
2762         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2763             << BaseType << getAmbiguousPathsDisplayString(Paths)
2764             << Bases[idx]->getSourceRange();
2765       else
2766         assert(Bases[idx]->isVirtual());
2767     }
2768 
2769     // Delete the base class specifier, since its data has been copied
2770     // into the CXXRecordDecl.
2771     Context.Deallocate(Bases[idx]);
2772   }
2773 
2774   return Invalid;
2775 }
2776 
2777 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2778 /// class, after checking whether there are any duplicate base
2779 /// classes.
2780 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2781                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2782   if (!ClassDecl || Bases.empty())
2783     return;
2784 
2785   AdjustDeclIfTemplate(ClassDecl);
2786   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2787 }
2788 
2789 /// Determine whether the type \p Derived is a C++ class that is
2790 /// derived from the type \p Base.
2791 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2792   if (!getLangOpts().CPlusPlus)
2793     return false;
2794 
2795   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2796   if (!DerivedRD)
2797     return false;
2798 
2799   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2800   if (!BaseRD)
2801     return false;
2802 
2803   // If either the base or the derived type is invalid, don't try to
2804   // check whether one is derived from the other.
2805   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2806     return false;
2807 
2808   // FIXME: In a modules build, do we need the entire path to be visible for us
2809   // to be able to use the inheritance relationship?
2810   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2811     return false;
2812 
2813   return DerivedRD->isDerivedFrom(BaseRD);
2814 }
2815 
2816 /// Determine whether the type \p Derived is a C++ class that is
2817 /// derived from the type \p Base.
2818 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2819                          CXXBasePaths &Paths) {
2820   if (!getLangOpts().CPlusPlus)
2821     return false;
2822 
2823   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2824   if (!DerivedRD)
2825     return false;
2826 
2827   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2828   if (!BaseRD)
2829     return false;
2830 
2831   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2832     return false;
2833 
2834   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2835 }
2836 
2837 static void BuildBasePathArray(const CXXBasePath &Path,
2838                                CXXCastPath &BasePathArray) {
2839   // We first go backward and check if we have a virtual base.
2840   // FIXME: It would be better if CXXBasePath had the base specifier for
2841   // the nearest virtual base.
2842   unsigned Start = 0;
2843   for (unsigned I = Path.size(); I != 0; --I) {
2844     if (Path[I - 1].Base->isVirtual()) {
2845       Start = I - 1;
2846       break;
2847     }
2848   }
2849 
2850   // Now add all bases.
2851   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2852     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2853 }
2854 
2855 
2856 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2857                               CXXCastPath &BasePathArray) {
2858   assert(BasePathArray.empty() && "Base path array must be empty!");
2859   assert(Paths.isRecordingPaths() && "Must record paths!");
2860   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2861 }
2862 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2863 /// conversion (where Derived and Base are class types) is
2864 /// well-formed, meaning that the conversion is unambiguous (and
2865 /// that all of the base classes are accessible). Returns true
2866 /// and emits a diagnostic if the code is ill-formed, returns false
2867 /// otherwise. Loc is the location where this routine should point to
2868 /// if there is an error, and Range is the source range to highlight
2869 /// if there is an error.
2870 ///
2871 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2872 /// diagnostic for the respective type of error will be suppressed, but the
2873 /// check for ill-formed code will still be performed.
2874 bool
2875 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2876                                    unsigned InaccessibleBaseID,
2877                                    unsigned AmbiguousBaseConvID,
2878                                    SourceLocation Loc, SourceRange Range,
2879                                    DeclarationName Name,
2880                                    CXXCastPath *BasePath,
2881                                    bool IgnoreAccess) {
2882   // First, determine whether the path from Derived to Base is
2883   // ambiguous. This is slightly more expensive than checking whether
2884   // the Derived to Base conversion exists, because here we need to
2885   // explore multiple paths to determine if there is an ambiguity.
2886   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2887                      /*DetectVirtual=*/false);
2888   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2889   if (!DerivationOkay)
2890     return true;
2891 
2892   const CXXBasePath *Path = nullptr;
2893   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2894     Path = &Paths.front();
2895 
2896   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2897   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2898   // user to access such bases.
2899   if (!Path && getLangOpts().MSVCCompat) {
2900     for (const CXXBasePath &PossiblePath : Paths) {
2901       if (PossiblePath.size() == 1) {
2902         Path = &PossiblePath;
2903         if (AmbiguousBaseConvID)
2904           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2905               << Base << Derived << Range;
2906         break;
2907       }
2908     }
2909   }
2910 
2911   if (Path) {
2912     if (!IgnoreAccess) {
2913       // Check that the base class can be accessed.
2914       switch (
2915           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2916       case AR_inaccessible:
2917         return true;
2918       case AR_accessible:
2919       case AR_dependent:
2920       case AR_delayed:
2921         break;
2922       }
2923     }
2924 
2925     // Build a base path if necessary.
2926     if (BasePath)
2927       ::BuildBasePathArray(*Path, *BasePath);
2928     return false;
2929   }
2930 
2931   if (AmbiguousBaseConvID) {
2932     // We know that the derived-to-base conversion is ambiguous, and
2933     // we're going to produce a diagnostic. Perform the derived-to-base
2934     // search just one more time to compute all of the possible paths so
2935     // that we can print them out. This is more expensive than any of
2936     // the previous derived-to-base checks we've done, but at this point
2937     // performance isn't as much of an issue.
2938     Paths.clear();
2939     Paths.setRecordingPaths(true);
2940     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2941     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2942     (void)StillOkay;
2943 
2944     // Build up a textual representation of the ambiguous paths, e.g.,
2945     // D -> B -> A, that will be used to illustrate the ambiguous
2946     // conversions in the diagnostic. We only print one of the paths
2947     // to each base class subobject.
2948     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2949 
2950     Diag(Loc, AmbiguousBaseConvID)
2951     << Derived << Base << PathDisplayStr << Range << Name;
2952   }
2953   return true;
2954 }
2955 
2956 bool
2957 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2958                                    SourceLocation Loc, SourceRange Range,
2959                                    CXXCastPath *BasePath,
2960                                    bool IgnoreAccess) {
2961   return CheckDerivedToBaseConversion(
2962       Derived, Base, diag::err_upcast_to_inaccessible_base,
2963       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2964       BasePath, IgnoreAccess);
2965 }
2966 
2967 
2968 /// Builds a string representing ambiguous paths from a
2969 /// specific derived class to different subobjects of the same base
2970 /// class.
2971 ///
2972 /// This function builds a string that can be used in error messages
2973 /// to show the different paths that one can take through the
2974 /// inheritance hierarchy to go from the derived class to different
2975 /// subobjects of a base class. The result looks something like this:
2976 /// @code
2977 /// struct D -> struct B -> struct A
2978 /// struct D -> struct C -> struct A
2979 /// @endcode
2980 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2981   std::string PathDisplayStr;
2982   std::set<unsigned> DisplayedPaths;
2983   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2984        Path != Paths.end(); ++Path) {
2985     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2986       // We haven't displayed a path to this particular base
2987       // class subobject yet.
2988       PathDisplayStr += "\n    ";
2989       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2990       for (CXXBasePath::const_iterator Element = Path->begin();
2991            Element != Path->end(); ++Element)
2992         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2993     }
2994   }
2995 
2996   return PathDisplayStr;
2997 }
2998 
2999 //===----------------------------------------------------------------------===//
3000 // C++ class member Handling
3001 //===----------------------------------------------------------------------===//
3002 
3003 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3004 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3005                                 SourceLocation ColonLoc,
3006                                 const ParsedAttributesView &Attrs) {
3007   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3008   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3009                                                   ASLoc, ColonLoc);
3010   CurContext->addHiddenDecl(ASDecl);
3011   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3012 }
3013 
3014 /// CheckOverrideControl - Check C++11 override control semantics.
3015 void Sema::CheckOverrideControl(NamedDecl *D) {
3016   if (D->isInvalidDecl())
3017     return;
3018 
3019   // We only care about "override" and "final" declarations.
3020   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3021     return;
3022 
3023   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3024 
3025   // We can't check dependent instance methods.
3026   if (MD && MD->isInstance() &&
3027       (MD->getParent()->hasAnyDependentBases() ||
3028        MD->getType()->isDependentType()))
3029     return;
3030 
3031   if (MD && !MD->isVirtual()) {
3032     // If we have a non-virtual method, check if if hides a virtual method.
3033     // (In that case, it's most likely the method has the wrong type.)
3034     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3035     FindHiddenVirtualMethods(MD, OverloadedMethods);
3036 
3037     if (!OverloadedMethods.empty()) {
3038       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3039         Diag(OA->getLocation(),
3040              diag::override_keyword_hides_virtual_member_function)
3041           << "override" << (OverloadedMethods.size() > 1);
3042       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3043         Diag(FA->getLocation(),
3044              diag::override_keyword_hides_virtual_member_function)
3045           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3046           << (OverloadedMethods.size() > 1);
3047       }
3048       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3049       MD->setInvalidDecl();
3050       return;
3051     }
3052     // Fall through into the general case diagnostic.
3053     // FIXME: We might want to attempt typo correction here.
3054   }
3055 
3056   if (!MD || !MD->isVirtual()) {
3057     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3058       Diag(OA->getLocation(),
3059            diag::override_keyword_only_allowed_on_virtual_member_functions)
3060         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3061       D->dropAttr<OverrideAttr>();
3062     }
3063     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3064       Diag(FA->getLocation(),
3065            diag::override_keyword_only_allowed_on_virtual_member_functions)
3066         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3067         << FixItHint::CreateRemoval(FA->getLocation());
3068       D->dropAttr<FinalAttr>();
3069     }
3070     return;
3071   }
3072 
3073   // C++11 [class.virtual]p5:
3074   //   If a function is marked with the virt-specifier override and
3075   //   does not override a member function of a base class, the program is
3076   //   ill-formed.
3077   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3078   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3079     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3080       << MD->getDeclName();
3081 }
3082 
3083 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3084   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3085     return;
3086   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3087   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3088     return;
3089 
3090   SourceLocation Loc = MD->getLocation();
3091   SourceLocation SpellingLoc = Loc;
3092   if (getSourceManager().isMacroArgExpansion(Loc))
3093     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3094   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3095   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3096       return;
3097 
3098   if (MD->size_overridden_methods() > 0) {
3099     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3100       unsigned DiagID =
3101           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3102               ? DiagInconsistent
3103               : DiagSuggest;
3104       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3105       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3106       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3107     };
3108     if (isa<CXXDestructorDecl>(MD))
3109       EmitDiag(
3110           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3111           diag::warn_suggest_destructor_marked_not_override_overriding);
3112     else
3113       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3114                diag::warn_suggest_function_marked_not_override_overriding);
3115   }
3116 }
3117 
3118 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3119 /// function overrides a virtual member function marked 'final', according to
3120 /// C++11 [class.virtual]p4.
3121 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3122                                                   const CXXMethodDecl *Old) {
3123   FinalAttr *FA = Old->getAttr<FinalAttr>();
3124   if (!FA)
3125     return false;
3126 
3127   Diag(New->getLocation(), diag::err_final_function_overridden)
3128     << New->getDeclName()
3129     << FA->isSpelledAsSealed();
3130   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3131   return true;
3132 }
3133 
3134 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3135   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3136   // FIXME: Destruction of ObjC lifetime types has side-effects.
3137   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3138     return !RD->isCompleteDefinition() ||
3139            !RD->hasTrivialDefaultConstructor() ||
3140            !RD->hasTrivialDestructor();
3141   return false;
3142 }
3143 
3144 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3145   ParsedAttributesView::const_iterator Itr =
3146       llvm::find_if(list, [](const ParsedAttr &AL) {
3147         return AL.isDeclspecPropertyAttribute();
3148       });
3149   if (Itr != list.end())
3150     return &*Itr;
3151   return nullptr;
3152 }
3153 
3154 // Check if there is a field shadowing.
3155 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3156                                       DeclarationName FieldName,
3157                                       const CXXRecordDecl *RD,
3158                                       bool DeclIsField) {
3159   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3160     return;
3161 
3162   // To record a shadowed field in a base
3163   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3164   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3165                            CXXBasePath &Path) {
3166     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3167     // Record an ambiguous path directly
3168     if (Bases.find(Base) != Bases.end())
3169       return true;
3170     for (const auto Field : Base->lookup(FieldName)) {
3171       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3172           Field->getAccess() != AS_private) {
3173         assert(Field->getAccess() != AS_none);
3174         assert(Bases.find(Base) == Bases.end());
3175         Bases[Base] = Field;
3176         return true;
3177       }
3178     }
3179     return false;
3180   };
3181 
3182   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3183                      /*DetectVirtual=*/true);
3184   if (!RD->lookupInBases(FieldShadowed, Paths))
3185     return;
3186 
3187   for (const auto &P : Paths) {
3188     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3189     auto It = Bases.find(Base);
3190     // Skip duplicated bases
3191     if (It == Bases.end())
3192       continue;
3193     auto BaseField = It->second;
3194     assert(BaseField->getAccess() != AS_private);
3195     if (AS_none !=
3196         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3197       Diag(Loc, diag::warn_shadow_field)
3198         << FieldName << RD << Base << DeclIsField;
3199       Diag(BaseField->getLocation(), diag::note_shadow_field);
3200       Bases.erase(It);
3201     }
3202   }
3203 }
3204 
3205 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3206 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3207 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3208 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3209 /// present (but parsing it has been deferred).
3210 NamedDecl *
3211 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3212                                MultiTemplateParamsArg TemplateParameterLists,
3213                                Expr *BW, const VirtSpecifiers &VS,
3214                                InClassInitStyle InitStyle) {
3215   const DeclSpec &DS = D.getDeclSpec();
3216   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3217   DeclarationName Name = NameInfo.getName();
3218   SourceLocation Loc = NameInfo.getLoc();
3219 
3220   // For anonymous bitfields, the location should point to the type.
3221   if (Loc.isInvalid())
3222     Loc = D.getBeginLoc();
3223 
3224   Expr *BitWidth = static_cast<Expr*>(BW);
3225 
3226   assert(isa<CXXRecordDecl>(CurContext));
3227   assert(!DS.isFriendSpecified());
3228 
3229   bool isFunc = D.isDeclarationOfFunction();
3230   const ParsedAttr *MSPropertyAttr =
3231       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3232 
3233   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3234     // The Microsoft extension __interface only permits public member functions
3235     // and prohibits constructors, destructors, operators, non-public member
3236     // functions, static methods and data members.
3237     unsigned InvalidDecl;
3238     bool ShowDeclName = true;
3239     if (!isFunc &&
3240         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3241       InvalidDecl = 0;
3242     else if (!isFunc)
3243       InvalidDecl = 1;
3244     else if (AS != AS_public)
3245       InvalidDecl = 2;
3246     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3247       InvalidDecl = 3;
3248     else switch (Name.getNameKind()) {
3249       case DeclarationName::CXXConstructorName:
3250         InvalidDecl = 4;
3251         ShowDeclName = false;
3252         break;
3253 
3254       case DeclarationName::CXXDestructorName:
3255         InvalidDecl = 5;
3256         ShowDeclName = false;
3257         break;
3258 
3259       case DeclarationName::CXXOperatorName:
3260       case DeclarationName::CXXConversionFunctionName:
3261         InvalidDecl = 6;
3262         break;
3263 
3264       default:
3265         InvalidDecl = 0;
3266         break;
3267     }
3268 
3269     if (InvalidDecl) {
3270       if (ShowDeclName)
3271         Diag(Loc, diag::err_invalid_member_in_interface)
3272           << (InvalidDecl-1) << Name;
3273       else
3274         Diag(Loc, diag::err_invalid_member_in_interface)
3275           << (InvalidDecl-1) << "";
3276       return nullptr;
3277     }
3278   }
3279 
3280   // C++ 9.2p6: A member shall not be declared to have automatic storage
3281   // duration (auto, register) or with the extern storage-class-specifier.
3282   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3283   // data members and cannot be applied to names declared const or static,
3284   // and cannot be applied to reference members.
3285   switch (DS.getStorageClassSpec()) {
3286   case DeclSpec::SCS_unspecified:
3287   case DeclSpec::SCS_typedef:
3288   case DeclSpec::SCS_static:
3289     break;
3290   case DeclSpec::SCS_mutable:
3291     if (isFunc) {
3292       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3293 
3294       // FIXME: It would be nicer if the keyword was ignored only for this
3295       // declarator. Otherwise we could get follow-up errors.
3296       D.getMutableDeclSpec().ClearStorageClassSpecs();
3297     }
3298     break;
3299   default:
3300     Diag(DS.getStorageClassSpecLoc(),
3301          diag::err_storageclass_invalid_for_member);
3302     D.getMutableDeclSpec().ClearStorageClassSpecs();
3303     break;
3304   }
3305 
3306   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3307                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3308                       !isFunc);
3309 
3310   if (DS.hasConstexprSpecifier() && isInstField) {
3311     SemaDiagnosticBuilder B =
3312         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3313     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3314     if (InitStyle == ICIS_NoInit) {
3315       B << 0 << 0;
3316       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3317         B << FixItHint::CreateRemoval(ConstexprLoc);
3318       else {
3319         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3320         D.getMutableDeclSpec().ClearConstexprSpec();
3321         const char *PrevSpec;
3322         unsigned DiagID;
3323         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3324             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3325         (void)Failed;
3326         assert(!Failed && "Making a constexpr member const shouldn't fail");
3327       }
3328     } else {
3329       B << 1;
3330       const char *PrevSpec;
3331       unsigned DiagID;
3332       if (D.getMutableDeclSpec().SetStorageClassSpec(
3333           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3334           Context.getPrintingPolicy())) {
3335         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3336                "This is the only DeclSpec that should fail to be applied");
3337         B << 1;
3338       } else {
3339         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3340         isInstField = false;
3341       }
3342     }
3343   }
3344 
3345   NamedDecl *Member;
3346   if (isInstField) {
3347     CXXScopeSpec &SS = D.getCXXScopeSpec();
3348 
3349     // Data members must have identifiers for names.
3350     if (!Name.isIdentifier()) {
3351       Diag(Loc, diag::err_bad_variable_name)
3352         << Name;
3353       return nullptr;
3354     }
3355 
3356     IdentifierInfo *II = Name.getAsIdentifierInfo();
3357 
3358     // Member field could not be with "template" keyword.
3359     // So TemplateParameterLists should be empty in this case.
3360     if (TemplateParameterLists.size()) {
3361       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3362       if (TemplateParams->size()) {
3363         // There is no such thing as a member field template.
3364         Diag(D.getIdentifierLoc(), diag::err_template_member)
3365             << II
3366             << SourceRange(TemplateParams->getTemplateLoc(),
3367                 TemplateParams->getRAngleLoc());
3368       } else {
3369         // There is an extraneous 'template<>' for this member.
3370         Diag(TemplateParams->getTemplateLoc(),
3371             diag::err_template_member_noparams)
3372             << II
3373             << SourceRange(TemplateParams->getTemplateLoc(),
3374                 TemplateParams->getRAngleLoc());
3375       }
3376       return nullptr;
3377     }
3378 
3379     if (SS.isSet() && !SS.isInvalid()) {
3380       // The user provided a superfluous scope specifier inside a class
3381       // definition:
3382       //
3383       // class X {
3384       //   int X::member;
3385       // };
3386       if (DeclContext *DC = computeDeclContext(SS, false))
3387         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3388                                      D.getName().getKind() ==
3389                                          UnqualifiedIdKind::IK_TemplateId);
3390       else
3391         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3392           << Name << SS.getRange();
3393 
3394       SS.clear();
3395     }
3396 
3397     if (MSPropertyAttr) {
3398       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3399                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3400       if (!Member)
3401         return nullptr;
3402       isInstField = false;
3403     } else {
3404       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3405                                 BitWidth, InitStyle, AS);
3406       if (!Member)
3407         return nullptr;
3408     }
3409 
3410     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3411   } else {
3412     Member = HandleDeclarator(S, D, TemplateParameterLists);
3413     if (!Member)
3414       return nullptr;
3415 
3416     // Non-instance-fields can't have a bitfield.
3417     if (BitWidth) {
3418       if (Member->isInvalidDecl()) {
3419         // don't emit another diagnostic.
3420       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3421         // C++ 9.6p3: A bit-field shall not be a static member.
3422         // "static member 'A' cannot be a bit-field"
3423         Diag(Loc, diag::err_static_not_bitfield)
3424           << Name << BitWidth->getSourceRange();
3425       } else if (isa<TypedefDecl>(Member)) {
3426         // "typedef member 'x' cannot be a bit-field"
3427         Diag(Loc, diag::err_typedef_not_bitfield)
3428           << Name << BitWidth->getSourceRange();
3429       } else {
3430         // A function typedef ("typedef int f(); f a;").
3431         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3432         Diag(Loc, diag::err_not_integral_type_bitfield)
3433           << Name << cast<ValueDecl>(Member)->getType()
3434           << BitWidth->getSourceRange();
3435       }
3436 
3437       BitWidth = nullptr;
3438       Member->setInvalidDecl();
3439     }
3440 
3441     NamedDecl *NonTemplateMember = Member;
3442     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3443       NonTemplateMember = FunTmpl->getTemplatedDecl();
3444     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3445       NonTemplateMember = VarTmpl->getTemplatedDecl();
3446 
3447     Member->setAccess(AS);
3448 
3449     // If we have declared a member function template or static data member
3450     // template, set the access of the templated declaration as well.
3451     if (NonTemplateMember != Member)
3452       NonTemplateMember->setAccess(AS);
3453 
3454     // C++ [temp.deduct.guide]p3:
3455     //   A deduction guide [...] for a member class template [shall be
3456     //   declared] with the same access [as the template].
3457     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3458       auto *TD = DG->getDeducedTemplate();
3459       // Access specifiers are only meaningful if both the template and the
3460       // deduction guide are from the same scope.
3461       if (AS != TD->getAccess() &&
3462           TD->getDeclContext()->getRedeclContext()->Equals(
3463               DG->getDeclContext()->getRedeclContext())) {
3464         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3465         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3466             << TD->getAccess();
3467         const AccessSpecDecl *LastAccessSpec = nullptr;
3468         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3469           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3470             LastAccessSpec = AccessSpec;
3471         }
3472         assert(LastAccessSpec && "differing access with no access specifier");
3473         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3474             << AS;
3475       }
3476     }
3477   }
3478 
3479   if (VS.isOverrideSpecified())
3480     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3481                                          AttributeCommonInfo::AS_Keyword));
3482   if (VS.isFinalSpecified())
3483     Member->addAttr(FinalAttr::Create(
3484         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3485         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3486 
3487   if (VS.getLastLocation().isValid()) {
3488     // Update the end location of a method that has a virt-specifiers.
3489     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3490       MD->setRangeEnd(VS.getLastLocation());
3491   }
3492 
3493   CheckOverrideControl(Member);
3494 
3495   assert((Name || isInstField) && "No identifier for non-field ?");
3496 
3497   if (isInstField) {
3498     FieldDecl *FD = cast<FieldDecl>(Member);
3499     FieldCollector->Add(FD);
3500 
3501     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3502       // Remember all explicit private FieldDecls that have a name, no side
3503       // effects and are not part of a dependent type declaration.
3504       if (!FD->isImplicit() && FD->getDeclName() &&
3505           FD->getAccess() == AS_private &&
3506           !FD->hasAttr<UnusedAttr>() &&
3507           !FD->getParent()->isDependentContext() &&
3508           !InitializationHasSideEffects(*FD))
3509         UnusedPrivateFields.insert(FD);
3510     }
3511   }
3512 
3513   return Member;
3514 }
3515 
3516 namespace {
3517   class UninitializedFieldVisitor
3518       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3519     Sema &S;
3520     // List of Decls to generate a warning on.  Also remove Decls that become
3521     // initialized.
3522     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3523     // List of base classes of the record.  Classes are removed after their
3524     // initializers.
3525     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3526     // Vector of decls to be removed from the Decl set prior to visiting the
3527     // nodes.  These Decls may have been initialized in the prior initializer.
3528     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3529     // If non-null, add a note to the warning pointing back to the constructor.
3530     const CXXConstructorDecl *Constructor;
3531     // Variables to hold state when processing an initializer list.  When
3532     // InitList is true, special case initialization of FieldDecls matching
3533     // InitListFieldDecl.
3534     bool InitList;
3535     FieldDecl *InitListFieldDecl;
3536     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3537 
3538   public:
3539     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3540     UninitializedFieldVisitor(Sema &S,
3541                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3542                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3543       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3544         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3545 
3546     // Returns true if the use of ME is not an uninitialized use.
3547     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3548                                          bool CheckReferenceOnly) {
3549       llvm::SmallVector<FieldDecl*, 4> Fields;
3550       bool ReferenceField = false;
3551       while (ME) {
3552         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3553         if (!FD)
3554           return false;
3555         Fields.push_back(FD);
3556         if (FD->getType()->isReferenceType())
3557           ReferenceField = true;
3558         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3559       }
3560 
3561       // Binding a reference to an uninitialized field is not an
3562       // uninitialized use.
3563       if (CheckReferenceOnly && !ReferenceField)
3564         return true;
3565 
3566       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3567       // Discard the first field since it is the field decl that is being
3568       // initialized.
3569       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3570         UsedFieldIndex.push_back((*I)->getFieldIndex());
3571       }
3572 
3573       for (auto UsedIter = UsedFieldIndex.begin(),
3574                 UsedEnd = UsedFieldIndex.end(),
3575                 OrigIter = InitFieldIndex.begin(),
3576                 OrigEnd = InitFieldIndex.end();
3577            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3578         if (*UsedIter < *OrigIter)
3579           return true;
3580         if (*UsedIter > *OrigIter)
3581           break;
3582       }
3583 
3584       return false;
3585     }
3586 
3587     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3588                           bool AddressOf) {
3589       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3590         return;
3591 
3592       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3593       // or union.
3594       MemberExpr *FieldME = ME;
3595 
3596       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3597 
3598       Expr *Base = ME;
3599       while (MemberExpr *SubME =
3600                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3601 
3602         if (isa<VarDecl>(SubME->getMemberDecl()))
3603           return;
3604 
3605         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3606           if (!FD->isAnonymousStructOrUnion())
3607             FieldME = SubME;
3608 
3609         if (!FieldME->getType().isPODType(S.Context))
3610           AllPODFields = false;
3611 
3612         Base = SubME->getBase();
3613       }
3614 
3615       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3616         Visit(Base);
3617         return;
3618       }
3619 
3620       if (AddressOf && AllPODFields)
3621         return;
3622 
3623       ValueDecl* FoundVD = FieldME->getMemberDecl();
3624 
3625       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3626         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3627           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3628         }
3629 
3630         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3631           QualType T = BaseCast->getType();
3632           if (T->isPointerType() &&
3633               BaseClasses.count(T->getPointeeType())) {
3634             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3635                 << T->getPointeeType() << FoundVD;
3636           }
3637         }
3638       }
3639 
3640       if (!Decls.count(FoundVD))
3641         return;
3642 
3643       const bool IsReference = FoundVD->getType()->isReferenceType();
3644 
3645       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3646         // Special checking for initializer lists.
3647         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3648           return;
3649         }
3650       } else {
3651         // Prevent double warnings on use of unbounded references.
3652         if (CheckReferenceOnly && !IsReference)
3653           return;
3654       }
3655 
3656       unsigned diag = IsReference
3657           ? diag::warn_reference_field_is_uninit
3658           : diag::warn_field_is_uninit;
3659       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3660       if (Constructor)
3661         S.Diag(Constructor->getLocation(),
3662                diag::note_uninit_in_this_constructor)
3663           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3664 
3665     }
3666 
3667     void HandleValue(Expr *E, bool AddressOf) {
3668       E = E->IgnoreParens();
3669 
3670       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3671         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3672                          AddressOf /*AddressOf*/);
3673         return;
3674       }
3675 
3676       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3677         Visit(CO->getCond());
3678         HandleValue(CO->getTrueExpr(), AddressOf);
3679         HandleValue(CO->getFalseExpr(), AddressOf);
3680         return;
3681       }
3682 
3683       if (BinaryConditionalOperator *BCO =
3684               dyn_cast<BinaryConditionalOperator>(E)) {
3685         Visit(BCO->getCond());
3686         HandleValue(BCO->getFalseExpr(), AddressOf);
3687         return;
3688       }
3689 
3690       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3691         HandleValue(OVE->getSourceExpr(), AddressOf);
3692         return;
3693       }
3694 
3695       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3696         switch (BO->getOpcode()) {
3697         default:
3698           break;
3699         case(BO_PtrMemD):
3700         case(BO_PtrMemI):
3701           HandleValue(BO->getLHS(), AddressOf);
3702           Visit(BO->getRHS());
3703           return;
3704         case(BO_Comma):
3705           Visit(BO->getLHS());
3706           HandleValue(BO->getRHS(), AddressOf);
3707           return;
3708         }
3709       }
3710 
3711       Visit(E);
3712     }
3713 
3714     void CheckInitListExpr(InitListExpr *ILE) {
3715       InitFieldIndex.push_back(0);
3716       for (auto Child : ILE->children()) {
3717         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3718           CheckInitListExpr(SubList);
3719         } else {
3720           Visit(Child);
3721         }
3722         ++InitFieldIndex.back();
3723       }
3724       InitFieldIndex.pop_back();
3725     }
3726 
3727     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3728                           FieldDecl *Field, const Type *BaseClass) {
3729       // Remove Decls that may have been initialized in the previous
3730       // initializer.
3731       for (ValueDecl* VD : DeclsToRemove)
3732         Decls.erase(VD);
3733       DeclsToRemove.clear();
3734 
3735       Constructor = FieldConstructor;
3736       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3737 
3738       if (ILE && Field) {
3739         InitList = true;
3740         InitListFieldDecl = Field;
3741         InitFieldIndex.clear();
3742         CheckInitListExpr(ILE);
3743       } else {
3744         InitList = false;
3745         Visit(E);
3746       }
3747 
3748       if (Field)
3749         Decls.erase(Field);
3750       if (BaseClass)
3751         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3752     }
3753 
3754     void VisitMemberExpr(MemberExpr *ME) {
3755       // All uses of unbounded reference fields will warn.
3756       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3757     }
3758 
3759     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3760       if (E->getCastKind() == CK_LValueToRValue) {
3761         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3762         return;
3763       }
3764 
3765       Inherited::VisitImplicitCastExpr(E);
3766     }
3767 
3768     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3769       if (E->getConstructor()->isCopyConstructor()) {
3770         Expr *ArgExpr = E->getArg(0);
3771         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3772           if (ILE->getNumInits() == 1)
3773             ArgExpr = ILE->getInit(0);
3774         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3775           if (ICE->getCastKind() == CK_NoOp)
3776             ArgExpr = ICE->getSubExpr();
3777         HandleValue(ArgExpr, false /*AddressOf*/);
3778         return;
3779       }
3780       Inherited::VisitCXXConstructExpr(E);
3781     }
3782 
3783     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3784       Expr *Callee = E->getCallee();
3785       if (isa<MemberExpr>(Callee)) {
3786         HandleValue(Callee, false /*AddressOf*/);
3787         for (auto Arg : E->arguments())
3788           Visit(Arg);
3789         return;
3790       }
3791 
3792       Inherited::VisitCXXMemberCallExpr(E);
3793     }
3794 
3795     void VisitCallExpr(CallExpr *E) {
3796       // Treat std::move as a use.
3797       if (E->isCallToStdMove()) {
3798         HandleValue(E->getArg(0), /*AddressOf=*/false);
3799         return;
3800       }
3801 
3802       Inherited::VisitCallExpr(E);
3803     }
3804 
3805     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3806       Expr *Callee = E->getCallee();
3807 
3808       if (isa<UnresolvedLookupExpr>(Callee))
3809         return Inherited::VisitCXXOperatorCallExpr(E);
3810 
3811       Visit(Callee);
3812       for (auto Arg : E->arguments())
3813         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3814     }
3815 
3816     void VisitBinaryOperator(BinaryOperator *E) {
3817       // If a field assignment is detected, remove the field from the
3818       // uninitiailized field set.
3819       if (E->getOpcode() == BO_Assign)
3820         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3821           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3822             if (!FD->getType()->isReferenceType())
3823               DeclsToRemove.push_back(FD);
3824 
3825       if (E->isCompoundAssignmentOp()) {
3826         HandleValue(E->getLHS(), false /*AddressOf*/);
3827         Visit(E->getRHS());
3828         return;
3829       }
3830 
3831       Inherited::VisitBinaryOperator(E);
3832     }
3833 
3834     void VisitUnaryOperator(UnaryOperator *E) {
3835       if (E->isIncrementDecrementOp()) {
3836         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3837         return;
3838       }
3839       if (E->getOpcode() == UO_AddrOf) {
3840         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3841           HandleValue(ME->getBase(), true /*AddressOf*/);
3842           return;
3843         }
3844       }
3845 
3846       Inherited::VisitUnaryOperator(E);
3847     }
3848   };
3849 
3850   // Diagnose value-uses of fields to initialize themselves, e.g.
3851   //   foo(foo)
3852   // where foo is not also a parameter to the constructor.
3853   // Also diagnose across field uninitialized use such as
3854   //   x(y), y(x)
3855   // TODO: implement -Wuninitialized and fold this into that framework.
3856   static void DiagnoseUninitializedFields(
3857       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3858 
3859     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3860                                            Constructor->getLocation())) {
3861       return;
3862     }
3863 
3864     if (Constructor->isInvalidDecl())
3865       return;
3866 
3867     const CXXRecordDecl *RD = Constructor->getParent();
3868 
3869     if (RD->isDependentContext())
3870       return;
3871 
3872     // Holds fields that are uninitialized.
3873     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3874 
3875     // At the beginning, all fields are uninitialized.
3876     for (auto *I : RD->decls()) {
3877       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3878         UninitializedFields.insert(FD);
3879       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3880         UninitializedFields.insert(IFD->getAnonField());
3881       }
3882     }
3883 
3884     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3885     for (auto I : RD->bases())
3886       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3887 
3888     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3889       return;
3890 
3891     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3892                                                    UninitializedFields,
3893                                                    UninitializedBaseClasses);
3894 
3895     for (const auto *FieldInit : Constructor->inits()) {
3896       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3897         break;
3898 
3899       Expr *InitExpr = FieldInit->getInit();
3900       if (!InitExpr)
3901         continue;
3902 
3903       if (CXXDefaultInitExpr *Default =
3904               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3905         InitExpr = Default->getExpr();
3906         if (!InitExpr)
3907           continue;
3908         // In class initializers will point to the constructor.
3909         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3910                                               FieldInit->getAnyMember(),
3911                                               FieldInit->getBaseClass());
3912       } else {
3913         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3914                                               FieldInit->getAnyMember(),
3915                                               FieldInit->getBaseClass());
3916       }
3917     }
3918   }
3919 } // namespace
3920 
3921 /// Enter a new C++ default initializer scope. After calling this, the
3922 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3923 /// parsing or instantiating the initializer failed.
3924 void Sema::ActOnStartCXXInClassMemberInitializer() {
3925   // Create a synthetic function scope to represent the call to the constructor
3926   // that notionally surrounds a use of this initializer.
3927   PushFunctionScope();
3928 }
3929 
3930 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3931   if (!D.isFunctionDeclarator())
3932     return;
3933   auto &FTI = D.getFunctionTypeInfo();
3934   if (!FTI.Params)
3935     return;
3936   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3937                                                           FTI.NumParams)) {
3938     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3939     if (ParamDecl->getDeclName())
3940       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3941   }
3942 }
3943 
3944 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3945   return ActOnRequiresClause(ConstraintExpr);
3946 }
3947 
3948 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3949   if (ConstraintExpr.isInvalid())
3950     return ExprError();
3951 
3952   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3953   if (ConstraintExpr.isInvalid())
3954     return ExprError();
3955 
3956   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3957                                       UPPC_RequiresClause))
3958     return ExprError();
3959 
3960   return ConstraintExpr;
3961 }
3962 
3963 /// This is invoked after parsing an in-class initializer for a
3964 /// non-static C++ class member, and after instantiating an in-class initializer
3965 /// in a class template. Such actions are deferred until the class is complete.
3966 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3967                                                   SourceLocation InitLoc,
3968                                                   Expr *InitExpr) {
3969   // Pop the notional constructor scope we created earlier.
3970   PopFunctionScopeInfo(nullptr, D);
3971 
3972   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3973   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3974          "must set init style when field is created");
3975 
3976   if (!InitExpr) {
3977     D->setInvalidDecl();
3978     if (FD)
3979       FD->removeInClassInitializer();
3980     return;
3981   }
3982 
3983   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3984     FD->setInvalidDecl();
3985     FD->removeInClassInitializer();
3986     return;
3987   }
3988 
3989   ExprResult Init = InitExpr;
3990   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3991     InitializedEntity Entity =
3992         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3993     InitializationKind Kind =
3994         FD->getInClassInitStyle() == ICIS_ListInit
3995             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3996                                                    InitExpr->getBeginLoc(),
3997                                                    InitExpr->getEndLoc())
3998             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3999     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4000     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4001     if (Init.isInvalid()) {
4002       FD->setInvalidDecl();
4003       return;
4004     }
4005   }
4006 
4007   // C++11 [class.base.init]p7:
4008   //   The initialization of each base and member constitutes a
4009   //   full-expression.
4010   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4011   if (Init.isInvalid()) {
4012     FD->setInvalidDecl();
4013     return;
4014   }
4015 
4016   InitExpr = Init.get();
4017 
4018   FD->setInClassInitializer(InitExpr);
4019 }
4020 
4021 /// Find the direct and/or virtual base specifiers that
4022 /// correspond to the given base type, for use in base initialization
4023 /// within a constructor.
4024 static bool FindBaseInitializer(Sema &SemaRef,
4025                                 CXXRecordDecl *ClassDecl,
4026                                 QualType BaseType,
4027                                 const CXXBaseSpecifier *&DirectBaseSpec,
4028                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4029   // First, check for a direct base class.
4030   DirectBaseSpec = nullptr;
4031   for (const auto &Base : ClassDecl->bases()) {
4032     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4033       // We found a direct base of this type. That's what we're
4034       // initializing.
4035       DirectBaseSpec = &Base;
4036       break;
4037     }
4038   }
4039 
4040   // Check for a virtual base class.
4041   // FIXME: We might be able to short-circuit this if we know in advance that
4042   // there are no virtual bases.
4043   VirtualBaseSpec = nullptr;
4044   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4045     // We haven't found a base yet; search the class hierarchy for a
4046     // virtual base class.
4047     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4048                        /*DetectVirtual=*/false);
4049     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4050                               SemaRef.Context.getTypeDeclType(ClassDecl),
4051                               BaseType, Paths)) {
4052       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4053            Path != Paths.end(); ++Path) {
4054         if (Path->back().Base->isVirtual()) {
4055           VirtualBaseSpec = Path->back().Base;
4056           break;
4057         }
4058       }
4059     }
4060   }
4061 
4062   return DirectBaseSpec || VirtualBaseSpec;
4063 }
4064 
4065 /// Handle a C++ member initializer using braced-init-list syntax.
4066 MemInitResult
4067 Sema::ActOnMemInitializer(Decl *ConstructorD,
4068                           Scope *S,
4069                           CXXScopeSpec &SS,
4070                           IdentifierInfo *MemberOrBase,
4071                           ParsedType TemplateTypeTy,
4072                           const DeclSpec &DS,
4073                           SourceLocation IdLoc,
4074                           Expr *InitList,
4075                           SourceLocation EllipsisLoc) {
4076   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4077                              DS, IdLoc, InitList,
4078                              EllipsisLoc);
4079 }
4080 
4081 /// Handle a C++ member initializer using parentheses syntax.
4082 MemInitResult
4083 Sema::ActOnMemInitializer(Decl *ConstructorD,
4084                           Scope *S,
4085                           CXXScopeSpec &SS,
4086                           IdentifierInfo *MemberOrBase,
4087                           ParsedType TemplateTypeTy,
4088                           const DeclSpec &DS,
4089                           SourceLocation IdLoc,
4090                           SourceLocation LParenLoc,
4091                           ArrayRef<Expr *> Args,
4092                           SourceLocation RParenLoc,
4093                           SourceLocation EllipsisLoc) {
4094   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4095   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4096                              DS, IdLoc, List, EllipsisLoc);
4097 }
4098 
4099 namespace {
4100 
4101 // Callback to only accept typo corrections that can be a valid C++ member
4102 // intializer: either a non-static field member or a base class.
4103 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4104 public:
4105   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4106       : ClassDecl(ClassDecl) {}
4107 
4108   bool ValidateCandidate(const TypoCorrection &candidate) override {
4109     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4110       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4111         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4112       return isa<TypeDecl>(ND);
4113     }
4114     return false;
4115   }
4116 
4117   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4118     return std::make_unique<MemInitializerValidatorCCC>(*this);
4119   }
4120 
4121 private:
4122   CXXRecordDecl *ClassDecl;
4123 };
4124 
4125 }
4126 
4127 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4128                                              CXXScopeSpec &SS,
4129                                              ParsedType TemplateTypeTy,
4130                                              IdentifierInfo *MemberOrBase) {
4131   if (SS.getScopeRep() || TemplateTypeTy)
4132     return nullptr;
4133   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4134   if (Result.empty())
4135     return nullptr;
4136   ValueDecl *Member;
4137   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4138       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4139     return Member;
4140   return nullptr;
4141 }
4142 
4143 /// Handle a C++ member initializer.
4144 MemInitResult
4145 Sema::BuildMemInitializer(Decl *ConstructorD,
4146                           Scope *S,
4147                           CXXScopeSpec &SS,
4148                           IdentifierInfo *MemberOrBase,
4149                           ParsedType TemplateTypeTy,
4150                           const DeclSpec &DS,
4151                           SourceLocation IdLoc,
4152                           Expr *Init,
4153                           SourceLocation EllipsisLoc) {
4154   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4155   if (!Res.isUsable())
4156     return true;
4157   Init = Res.get();
4158 
4159   if (!ConstructorD)
4160     return true;
4161 
4162   AdjustDeclIfTemplate(ConstructorD);
4163 
4164   CXXConstructorDecl *Constructor
4165     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4166   if (!Constructor) {
4167     // The user wrote a constructor initializer on a function that is
4168     // not a C++ constructor. Ignore the error for now, because we may
4169     // have more member initializers coming; we'll diagnose it just
4170     // once in ActOnMemInitializers.
4171     return true;
4172   }
4173 
4174   CXXRecordDecl *ClassDecl = Constructor->getParent();
4175 
4176   // C++ [class.base.init]p2:
4177   //   Names in a mem-initializer-id are looked up in the scope of the
4178   //   constructor's class and, if not found in that scope, are looked
4179   //   up in the scope containing the constructor's definition.
4180   //   [Note: if the constructor's class contains a member with the
4181   //   same name as a direct or virtual base class of the class, a
4182   //   mem-initializer-id naming the member or base class and composed
4183   //   of a single identifier refers to the class member. A
4184   //   mem-initializer-id for the hidden base class may be specified
4185   //   using a qualified name. ]
4186 
4187   // Look for a member, first.
4188   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4189           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4190     if (EllipsisLoc.isValid())
4191       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4192           << MemberOrBase
4193           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4194 
4195     return BuildMemberInitializer(Member, Init, IdLoc);
4196   }
4197   // It didn't name a member, so see if it names a class.
4198   QualType BaseType;
4199   TypeSourceInfo *TInfo = nullptr;
4200 
4201   if (TemplateTypeTy) {
4202     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4203     if (BaseType.isNull())
4204       return true;
4205   } else if (DS.getTypeSpecType() == TST_decltype) {
4206     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4207   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4208     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4209     return true;
4210   } else {
4211     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4212     LookupParsedName(R, S, &SS);
4213 
4214     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4215     if (!TyD) {
4216       if (R.isAmbiguous()) return true;
4217 
4218       // We don't want access-control diagnostics here.
4219       R.suppressDiagnostics();
4220 
4221       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4222         bool NotUnknownSpecialization = false;
4223         DeclContext *DC = computeDeclContext(SS, false);
4224         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4225           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4226 
4227         if (!NotUnknownSpecialization) {
4228           // When the scope specifier can refer to a member of an unknown
4229           // specialization, we take it as a type name.
4230           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4231                                        SS.getWithLocInContext(Context),
4232                                        *MemberOrBase, IdLoc);
4233           if (BaseType.isNull())
4234             return true;
4235 
4236           TInfo = Context.CreateTypeSourceInfo(BaseType);
4237           DependentNameTypeLoc TL =
4238               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4239           if (!TL.isNull()) {
4240             TL.setNameLoc(IdLoc);
4241             TL.setElaboratedKeywordLoc(SourceLocation());
4242             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4243           }
4244 
4245           R.clear();
4246           R.setLookupName(MemberOrBase);
4247         }
4248       }
4249 
4250       // If no results were found, try to correct typos.
4251       TypoCorrection Corr;
4252       MemInitializerValidatorCCC CCC(ClassDecl);
4253       if (R.empty() && BaseType.isNull() &&
4254           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4255                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4256         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4257           // We have found a non-static data member with a similar
4258           // name to what was typed; complain and initialize that
4259           // member.
4260           diagnoseTypo(Corr,
4261                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4262                          << MemberOrBase << true);
4263           return BuildMemberInitializer(Member, Init, IdLoc);
4264         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4265           const CXXBaseSpecifier *DirectBaseSpec;
4266           const CXXBaseSpecifier *VirtualBaseSpec;
4267           if (FindBaseInitializer(*this, ClassDecl,
4268                                   Context.getTypeDeclType(Type),
4269                                   DirectBaseSpec, VirtualBaseSpec)) {
4270             // We have found a direct or virtual base class with a
4271             // similar name to what was typed; complain and initialize
4272             // that base class.
4273             diagnoseTypo(Corr,
4274                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4275                            << MemberOrBase << false,
4276                          PDiag() /*Suppress note, we provide our own.*/);
4277 
4278             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4279                                                               : VirtualBaseSpec;
4280             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4281                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4282 
4283             TyD = Type;
4284           }
4285         }
4286       }
4287 
4288       if (!TyD && BaseType.isNull()) {
4289         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4290           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4291         return true;
4292       }
4293     }
4294 
4295     if (BaseType.isNull()) {
4296       BaseType = Context.getTypeDeclType(TyD);
4297       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4298       if (SS.isSet()) {
4299         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4300                                              BaseType);
4301         TInfo = Context.CreateTypeSourceInfo(BaseType);
4302         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4303         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4304         TL.setElaboratedKeywordLoc(SourceLocation());
4305         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4306       }
4307     }
4308   }
4309 
4310   if (!TInfo)
4311     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4312 
4313   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4314 }
4315 
4316 MemInitResult
4317 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4318                              SourceLocation IdLoc) {
4319   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4320   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4321   assert((DirectMember || IndirectMember) &&
4322          "Member must be a FieldDecl or IndirectFieldDecl");
4323 
4324   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4325     return true;
4326 
4327   if (Member->isInvalidDecl())
4328     return true;
4329 
4330   MultiExprArg Args;
4331   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4332     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4333   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4334     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4335   } else {
4336     // Template instantiation doesn't reconstruct ParenListExprs for us.
4337     Args = Init;
4338   }
4339 
4340   SourceRange InitRange = Init->getSourceRange();
4341 
4342   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4343     // Can't check initialization for a member of dependent type or when
4344     // any of the arguments are type-dependent expressions.
4345     DiscardCleanupsInEvaluationContext();
4346   } else {
4347     bool InitList = false;
4348     if (isa<InitListExpr>(Init)) {
4349       InitList = true;
4350       Args = Init;
4351     }
4352 
4353     // Initialize the member.
4354     InitializedEntity MemberEntity =
4355       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4356                    : InitializedEntity::InitializeMember(IndirectMember,
4357                                                          nullptr);
4358     InitializationKind Kind =
4359         InitList ? InitializationKind::CreateDirectList(
4360                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4361                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4362                                                     InitRange.getEnd());
4363 
4364     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4365     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4366                                             nullptr);
4367     if (MemberInit.isInvalid())
4368       return true;
4369 
4370     // C++11 [class.base.init]p7:
4371     //   The initialization of each base and member constitutes a
4372     //   full-expression.
4373     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4374                                      /*DiscardedValue*/ false);
4375     if (MemberInit.isInvalid())
4376       return true;
4377 
4378     Init = MemberInit.get();
4379   }
4380 
4381   if (DirectMember) {
4382     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4383                                             InitRange.getBegin(), Init,
4384                                             InitRange.getEnd());
4385   } else {
4386     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4387                                             InitRange.getBegin(), Init,
4388                                             InitRange.getEnd());
4389   }
4390 }
4391 
4392 MemInitResult
4393 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4394                                  CXXRecordDecl *ClassDecl) {
4395   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4396   if (!LangOpts.CPlusPlus11)
4397     return Diag(NameLoc, diag::err_delegating_ctor)
4398       << TInfo->getTypeLoc().getLocalSourceRange();
4399   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4400 
4401   bool InitList = true;
4402   MultiExprArg Args = Init;
4403   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4404     InitList = false;
4405     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4406   }
4407 
4408   SourceRange InitRange = Init->getSourceRange();
4409   // Initialize the object.
4410   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4411                                      QualType(ClassDecl->getTypeForDecl(), 0));
4412   InitializationKind Kind =
4413       InitList ? InitializationKind::CreateDirectList(
4414                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4415                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4416                                                   InitRange.getEnd());
4417   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4418   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4419                                               Args, nullptr);
4420   if (DelegationInit.isInvalid())
4421     return true;
4422 
4423   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4424          "Delegating constructor with no target?");
4425 
4426   // C++11 [class.base.init]p7:
4427   //   The initialization of each base and member constitutes a
4428   //   full-expression.
4429   DelegationInit = ActOnFinishFullExpr(
4430       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4431   if (DelegationInit.isInvalid())
4432     return true;
4433 
4434   // If we are in a dependent context, template instantiation will
4435   // perform this type-checking again. Just save the arguments that we
4436   // received in a ParenListExpr.
4437   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4438   // of the information that we have about the base
4439   // initializer. However, deconstructing the ASTs is a dicey process,
4440   // and this approach is far more likely to get the corner cases right.
4441   if (CurContext->isDependentContext())
4442     DelegationInit = Init;
4443 
4444   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4445                                           DelegationInit.getAs<Expr>(),
4446                                           InitRange.getEnd());
4447 }
4448 
4449 MemInitResult
4450 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4451                            Expr *Init, CXXRecordDecl *ClassDecl,
4452                            SourceLocation EllipsisLoc) {
4453   SourceLocation BaseLoc
4454     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4455 
4456   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4457     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4458              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4459 
4460   // C++ [class.base.init]p2:
4461   //   [...] Unless the mem-initializer-id names a nonstatic data
4462   //   member of the constructor's class or a direct or virtual base
4463   //   of that class, the mem-initializer is ill-formed. A
4464   //   mem-initializer-list can initialize a base class using any
4465   //   name that denotes that base class type.
4466   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4467 
4468   SourceRange InitRange = Init->getSourceRange();
4469   if (EllipsisLoc.isValid()) {
4470     // This is a pack expansion.
4471     if (!BaseType->containsUnexpandedParameterPack())  {
4472       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4473         << SourceRange(BaseLoc, InitRange.getEnd());
4474 
4475       EllipsisLoc = SourceLocation();
4476     }
4477   } else {
4478     // Check for any unexpanded parameter packs.
4479     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4480       return true;
4481 
4482     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4483       return true;
4484   }
4485 
4486   // Check for direct and virtual base classes.
4487   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4488   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4489   if (!Dependent) {
4490     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4491                                        BaseType))
4492       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4493 
4494     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4495                         VirtualBaseSpec);
4496 
4497     // C++ [base.class.init]p2:
4498     // Unless the mem-initializer-id names a nonstatic data member of the
4499     // constructor's class or a direct or virtual base of that class, the
4500     // mem-initializer is ill-formed.
4501     if (!DirectBaseSpec && !VirtualBaseSpec) {
4502       // If the class has any dependent bases, then it's possible that
4503       // one of those types will resolve to the same type as
4504       // BaseType. Therefore, just treat this as a dependent base
4505       // class initialization.  FIXME: Should we try to check the
4506       // initialization anyway? It seems odd.
4507       if (ClassDecl->hasAnyDependentBases())
4508         Dependent = true;
4509       else
4510         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4511           << BaseType << Context.getTypeDeclType(ClassDecl)
4512           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4513     }
4514   }
4515 
4516   if (Dependent) {
4517     DiscardCleanupsInEvaluationContext();
4518 
4519     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4520                                             /*IsVirtual=*/false,
4521                                             InitRange.getBegin(), Init,
4522                                             InitRange.getEnd(), EllipsisLoc);
4523   }
4524 
4525   // C++ [base.class.init]p2:
4526   //   If a mem-initializer-id is ambiguous because it designates both
4527   //   a direct non-virtual base class and an inherited virtual base
4528   //   class, the mem-initializer is ill-formed.
4529   if (DirectBaseSpec && VirtualBaseSpec)
4530     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4531       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4532 
4533   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4534   if (!BaseSpec)
4535     BaseSpec = VirtualBaseSpec;
4536 
4537   // Initialize the base.
4538   bool InitList = true;
4539   MultiExprArg Args = Init;
4540   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4541     InitList = false;
4542     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4543   }
4544 
4545   InitializedEntity BaseEntity =
4546     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4547   InitializationKind Kind =
4548       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4549                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4550                                                   InitRange.getEnd());
4551   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4552   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4553   if (BaseInit.isInvalid())
4554     return true;
4555 
4556   // C++11 [class.base.init]p7:
4557   //   The initialization of each base and member constitutes a
4558   //   full-expression.
4559   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4560                                  /*DiscardedValue*/ false);
4561   if (BaseInit.isInvalid())
4562     return true;
4563 
4564   // If we are in a dependent context, template instantiation will
4565   // perform this type-checking again. Just save the arguments that we
4566   // received in a ParenListExpr.
4567   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4568   // of the information that we have about the base
4569   // initializer. However, deconstructing the ASTs is a dicey process,
4570   // and this approach is far more likely to get the corner cases right.
4571   if (CurContext->isDependentContext())
4572     BaseInit = Init;
4573 
4574   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4575                                           BaseSpec->isVirtual(),
4576                                           InitRange.getBegin(),
4577                                           BaseInit.getAs<Expr>(),
4578                                           InitRange.getEnd(), EllipsisLoc);
4579 }
4580 
4581 // Create a static_cast\<T&&>(expr).
4582 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4583   if (T.isNull()) T = E->getType();
4584   QualType TargetType = SemaRef.BuildReferenceType(
4585       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4586   SourceLocation ExprLoc = E->getBeginLoc();
4587   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4588       TargetType, ExprLoc);
4589 
4590   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4591                                    SourceRange(ExprLoc, ExprLoc),
4592                                    E->getSourceRange()).get();
4593 }
4594 
4595 /// ImplicitInitializerKind - How an implicit base or member initializer should
4596 /// initialize its base or member.
4597 enum ImplicitInitializerKind {
4598   IIK_Default,
4599   IIK_Copy,
4600   IIK_Move,
4601   IIK_Inherit
4602 };
4603 
4604 static bool
4605 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4606                              ImplicitInitializerKind ImplicitInitKind,
4607                              CXXBaseSpecifier *BaseSpec,
4608                              bool IsInheritedVirtualBase,
4609                              CXXCtorInitializer *&CXXBaseInit) {
4610   InitializedEntity InitEntity
4611     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4612                                         IsInheritedVirtualBase);
4613 
4614   ExprResult BaseInit;
4615 
4616   switch (ImplicitInitKind) {
4617   case IIK_Inherit:
4618   case IIK_Default: {
4619     InitializationKind InitKind
4620       = InitializationKind::CreateDefault(Constructor->getLocation());
4621     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4622     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4623     break;
4624   }
4625 
4626   case IIK_Move:
4627   case IIK_Copy: {
4628     bool Moving = ImplicitInitKind == IIK_Move;
4629     ParmVarDecl *Param = Constructor->getParamDecl(0);
4630     QualType ParamType = Param->getType().getNonReferenceType();
4631 
4632     Expr *CopyCtorArg =
4633       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4634                           SourceLocation(), Param, false,
4635                           Constructor->getLocation(), ParamType,
4636                           VK_LValue, nullptr);
4637 
4638     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4639 
4640     // Cast to the base class to avoid ambiguities.
4641     QualType ArgTy =
4642       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4643                                        ParamType.getQualifiers());
4644 
4645     if (Moving) {
4646       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4647     }
4648 
4649     CXXCastPath BasePath;
4650     BasePath.push_back(BaseSpec);
4651     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4652                                             CK_UncheckedDerivedToBase,
4653                                             Moving ? VK_XValue : VK_LValue,
4654                                             &BasePath).get();
4655 
4656     InitializationKind InitKind
4657       = InitializationKind::CreateDirect(Constructor->getLocation(),
4658                                          SourceLocation(), SourceLocation());
4659     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4660     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4661     break;
4662   }
4663   }
4664 
4665   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4666   if (BaseInit.isInvalid())
4667     return true;
4668 
4669   CXXBaseInit =
4670     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4671                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4672                                                         SourceLocation()),
4673                                              BaseSpec->isVirtual(),
4674                                              SourceLocation(),
4675                                              BaseInit.getAs<Expr>(),
4676                                              SourceLocation(),
4677                                              SourceLocation());
4678 
4679   return false;
4680 }
4681 
4682 static bool RefersToRValueRef(Expr *MemRef) {
4683   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4684   return Referenced->getType()->isRValueReferenceType();
4685 }
4686 
4687 static bool
4688 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4689                                ImplicitInitializerKind ImplicitInitKind,
4690                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4691                                CXXCtorInitializer *&CXXMemberInit) {
4692   if (Field->isInvalidDecl())
4693     return true;
4694 
4695   SourceLocation Loc = Constructor->getLocation();
4696 
4697   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4698     bool Moving = ImplicitInitKind == IIK_Move;
4699     ParmVarDecl *Param = Constructor->getParamDecl(0);
4700     QualType ParamType = Param->getType().getNonReferenceType();
4701 
4702     // Suppress copying zero-width bitfields.
4703     if (Field->isZeroLengthBitField(SemaRef.Context))
4704       return false;
4705 
4706     Expr *MemberExprBase =
4707       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4708                           SourceLocation(), Param, false,
4709                           Loc, ParamType, VK_LValue, nullptr);
4710 
4711     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4712 
4713     if (Moving) {
4714       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4715     }
4716 
4717     // Build a reference to this field within the parameter.
4718     CXXScopeSpec SS;
4719     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4720                               Sema::LookupMemberName);
4721     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4722                                   : cast<ValueDecl>(Field), AS_public);
4723     MemberLookup.resolveKind();
4724     ExprResult CtorArg
4725       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4726                                          ParamType, Loc,
4727                                          /*IsArrow=*/false,
4728                                          SS,
4729                                          /*TemplateKWLoc=*/SourceLocation(),
4730                                          /*FirstQualifierInScope=*/nullptr,
4731                                          MemberLookup,
4732                                          /*TemplateArgs=*/nullptr,
4733                                          /*S*/nullptr);
4734     if (CtorArg.isInvalid())
4735       return true;
4736 
4737     // C++11 [class.copy]p15:
4738     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4739     //     with static_cast<T&&>(x.m);
4740     if (RefersToRValueRef(CtorArg.get())) {
4741       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4742     }
4743 
4744     InitializedEntity Entity =
4745         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4746                                                        /*Implicit*/ true)
4747                  : InitializedEntity::InitializeMember(Field, nullptr,
4748                                                        /*Implicit*/ true);
4749 
4750     // Direct-initialize to use the copy constructor.
4751     InitializationKind InitKind =
4752       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4753 
4754     Expr *CtorArgE = CtorArg.getAs<Expr>();
4755     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4756     ExprResult MemberInit =
4757         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4758     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4759     if (MemberInit.isInvalid())
4760       return true;
4761 
4762     if (Indirect)
4763       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4764           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4765     else
4766       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4767           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4768     return false;
4769   }
4770 
4771   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4772          "Unhandled implicit init kind!");
4773 
4774   QualType FieldBaseElementType =
4775     SemaRef.Context.getBaseElementType(Field->getType());
4776 
4777   if (FieldBaseElementType->isRecordType()) {
4778     InitializedEntity InitEntity =
4779         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4780                                                        /*Implicit*/ true)
4781                  : InitializedEntity::InitializeMember(Field, nullptr,
4782                                                        /*Implicit*/ true);
4783     InitializationKind InitKind =
4784       InitializationKind::CreateDefault(Loc);
4785 
4786     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4787     ExprResult MemberInit =
4788       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4789 
4790     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4791     if (MemberInit.isInvalid())
4792       return true;
4793 
4794     if (Indirect)
4795       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4796                                                                Indirect, Loc,
4797                                                                Loc,
4798                                                                MemberInit.get(),
4799                                                                Loc);
4800     else
4801       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4802                                                                Field, Loc, Loc,
4803                                                                MemberInit.get(),
4804                                                                Loc);
4805     return false;
4806   }
4807 
4808   if (!Field->getParent()->isUnion()) {
4809     if (FieldBaseElementType->isReferenceType()) {
4810       SemaRef.Diag(Constructor->getLocation(),
4811                    diag::err_uninitialized_member_in_ctor)
4812       << (int)Constructor->isImplicit()
4813       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4814       << 0 << Field->getDeclName();
4815       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4816       return true;
4817     }
4818 
4819     if (FieldBaseElementType.isConstQualified()) {
4820       SemaRef.Diag(Constructor->getLocation(),
4821                    diag::err_uninitialized_member_in_ctor)
4822       << (int)Constructor->isImplicit()
4823       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4824       << 1 << Field->getDeclName();
4825       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4826       return true;
4827     }
4828   }
4829 
4830   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4831     // ARC and Weak:
4832     //   Default-initialize Objective-C pointers to NULL.
4833     CXXMemberInit
4834       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4835                                                  Loc, Loc,
4836                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4837                                                  Loc);
4838     return false;
4839   }
4840 
4841   // Nothing to initialize.
4842   CXXMemberInit = nullptr;
4843   return false;
4844 }
4845 
4846 namespace {
4847 struct BaseAndFieldInfo {
4848   Sema &S;
4849   CXXConstructorDecl *Ctor;
4850   bool AnyErrorsInInits;
4851   ImplicitInitializerKind IIK;
4852   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4853   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4854   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4855 
4856   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4857     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4858     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4859     if (Ctor->getInheritedConstructor())
4860       IIK = IIK_Inherit;
4861     else if (Generated && Ctor->isCopyConstructor())
4862       IIK = IIK_Copy;
4863     else if (Generated && Ctor->isMoveConstructor())
4864       IIK = IIK_Move;
4865     else
4866       IIK = IIK_Default;
4867   }
4868 
4869   bool isImplicitCopyOrMove() const {
4870     switch (IIK) {
4871     case IIK_Copy:
4872     case IIK_Move:
4873       return true;
4874 
4875     case IIK_Default:
4876     case IIK_Inherit:
4877       return false;
4878     }
4879 
4880     llvm_unreachable("Invalid ImplicitInitializerKind!");
4881   }
4882 
4883   bool addFieldInitializer(CXXCtorInitializer *Init) {
4884     AllToInit.push_back(Init);
4885 
4886     // Check whether this initializer makes the field "used".
4887     if (Init->getInit()->HasSideEffects(S.Context))
4888       S.UnusedPrivateFields.remove(Init->getAnyMember());
4889 
4890     return false;
4891   }
4892 
4893   bool isInactiveUnionMember(FieldDecl *Field) {
4894     RecordDecl *Record = Field->getParent();
4895     if (!Record->isUnion())
4896       return false;
4897 
4898     if (FieldDecl *Active =
4899             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4900       return Active != Field->getCanonicalDecl();
4901 
4902     // In an implicit copy or move constructor, ignore any in-class initializer.
4903     if (isImplicitCopyOrMove())
4904       return true;
4905 
4906     // If there's no explicit initialization, the field is active only if it
4907     // has an in-class initializer...
4908     if (Field->hasInClassInitializer())
4909       return false;
4910     // ... or it's an anonymous struct or union whose class has an in-class
4911     // initializer.
4912     if (!Field->isAnonymousStructOrUnion())
4913       return true;
4914     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4915     return !FieldRD->hasInClassInitializer();
4916   }
4917 
4918   /// Determine whether the given field is, or is within, a union member
4919   /// that is inactive (because there was an initializer given for a different
4920   /// member of the union, or because the union was not initialized at all).
4921   bool isWithinInactiveUnionMember(FieldDecl *Field,
4922                                    IndirectFieldDecl *Indirect) {
4923     if (!Indirect)
4924       return isInactiveUnionMember(Field);
4925 
4926     for (auto *C : Indirect->chain()) {
4927       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4928       if (Field && isInactiveUnionMember(Field))
4929         return true;
4930     }
4931     return false;
4932   }
4933 };
4934 }
4935 
4936 /// Determine whether the given type is an incomplete or zero-lenfgth
4937 /// array type.
4938 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4939   if (T->isIncompleteArrayType())
4940     return true;
4941 
4942   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4943     if (!ArrayT->getSize())
4944       return true;
4945 
4946     T = ArrayT->getElementType();
4947   }
4948 
4949   return false;
4950 }
4951 
4952 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4953                                     FieldDecl *Field,
4954                                     IndirectFieldDecl *Indirect = nullptr) {
4955   if (Field->isInvalidDecl())
4956     return false;
4957 
4958   // Overwhelmingly common case: we have a direct initializer for this field.
4959   if (CXXCtorInitializer *Init =
4960           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4961     return Info.addFieldInitializer(Init);
4962 
4963   // C++11 [class.base.init]p8:
4964   //   if the entity is a non-static data member that has a
4965   //   brace-or-equal-initializer and either
4966   //   -- the constructor's class is a union and no other variant member of that
4967   //      union is designated by a mem-initializer-id or
4968   //   -- the constructor's class is not a union, and, if the entity is a member
4969   //      of an anonymous union, no other member of that union is designated by
4970   //      a mem-initializer-id,
4971   //   the entity is initialized as specified in [dcl.init].
4972   //
4973   // We also apply the same rules to handle anonymous structs within anonymous
4974   // unions.
4975   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4976     return false;
4977 
4978   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4979     ExprResult DIE =
4980         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4981     if (DIE.isInvalid())
4982       return true;
4983 
4984     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4985     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4986 
4987     CXXCtorInitializer *Init;
4988     if (Indirect)
4989       Init = new (SemaRef.Context)
4990           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4991                              SourceLocation(), DIE.get(), SourceLocation());
4992     else
4993       Init = new (SemaRef.Context)
4994           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4995                              SourceLocation(), DIE.get(), SourceLocation());
4996     return Info.addFieldInitializer(Init);
4997   }
4998 
4999   // Don't initialize incomplete or zero-length arrays.
5000   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5001     return false;
5002 
5003   // Don't try to build an implicit initializer if there were semantic
5004   // errors in any of the initializers (and therefore we might be
5005   // missing some that the user actually wrote).
5006   if (Info.AnyErrorsInInits)
5007     return false;
5008 
5009   CXXCtorInitializer *Init = nullptr;
5010   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5011                                      Indirect, Init))
5012     return true;
5013 
5014   if (!Init)
5015     return false;
5016 
5017   return Info.addFieldInitializer(Init);
5018 }
5019 
5020 bool
5021 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5022                                CXXCtorInitializer *Initializer) {
5023   assert(Initializer->isDelegatingInitializer());
5024   Constructor->setNumCtorInitializers(1);
5025   CXXCtorInitializer **initializer =
5026     new (Context) CXXCtorInitializer*[1];
5027   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5028   Constructor->setCtorInitializers(initializer);
5029 
5030   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5031     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5032     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5033   }
5034 
5035   DelegatingCtorDecls.push_back(Constructor);
5036 
5037   DiagnoseUninitializedFields(*this, Constructor);
5038 
5039   return false;
5040 }
5041 
5042 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5043                                ArrayRef<CXXCtorInitializer *> Initializers) {
5044   if (Constructor->isDependentContext()) {
5045     // Just store the initializers as written, they will be checked during
5046     // instantiation.
5047     if (!Initializers.empty()) {
5048       Constructor->setNumCtorInitializers(Initializers.size());
5049       CXXCtorInitializer **baseOrMemberInitializers =
5050         new (Context) CXXCtorInitializer*[Initializers.size()];
5051       memcpy(baseOrMemberInitializers, Initializers.data(),
5052              Initializers.size() * sizeof(CXXCtorInitializer*));
5053       Constructor->setCtorInitializers(baseOrMemberInitializers);
5054     }
5055 
5056     // Let template instantiation know whether we had errors.
5057     if (AnyErrors)
5058       Constructor->setInvalidDecl();
5059 
5060     return false;
5061   }
5062 
5063   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5064 
5065   // We need to build the initializer AST according to order of construction
5066   // and not what user specified in the Initializers list.
5067   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5068   if (!ClassDecl)
5069     return true;
5070 
5071   bool HadError = false;
5072 
5073   for (unsigned i = 0; i < Initializers.size(); i++) {
5074     CXXCtorInitializer *Member = Initializers[i];
5075 
5076     if (Member->isBaseInitializer())
5077       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5078     else {
5079       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5080 
5081       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5082         for (auto *C : F->chain()) {
5083           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5084           if (FD && FD->getParent()->isUnion())
5085             Info.ActiveUnionMember.insert(std::make_pair(
5086                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5087         }
5088       } else if (FieldDecl *FD = Member->getMember()) {
5089         if (FD->getParent()->isUnion())
5090           Info.ActiveUnionMember.insert(std::make_pair(
5091               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5092       }
5093     }
5094   }
5095 
5096   // Keep track of the direct virtual bases.
5097   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5098   for (auto &I : ClassDecl->bases()) {
5099     if (I.isVirtual())
5100       DirectVBases.insert(&I);
5101   }
5102 
5103   // Push virtual bases before others.
5104   for (auto &VBase : ClassDecl->vbases()) {
5105     if (CXXCtorInitializer *Value
5106         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5107       // [class.base.init]p7, per DR257:
5108       //   A mem-initializer where the mem-initializer-id names a virtual base
5109       //   class is ignored during execution of a constructor of any class that
5110       //   is not the most derived class.
5111       if (ClassDecl->isAbstract()) {
5112         // FIXME: Provide a fixit to remove the base specifier. This requires
5113         // tracking the location of the associated comma for a base specifier.
5114         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5115           << VBase.getType() << ClassDecl;
5116         DiagnoseAbstractType(ClassDecl);
5117       }
5118 
5119       Info.AllToInit.push_back(Value);
5120     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5121       // [class.base.init]p8, per DR257:
5122       //   If a given [...] base class is not named by a mem-initializer-id
5123       //   [...] and the entity is not a virtual base class of an abstract
5124       //   class, then [...] the entity is default-initialized.
5125       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5126       CXXCtorInitializer *CXXBaseInit;
5127       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5128                                        &VBase, IsInheritedVirtualBase,
5129                                        CXXBaseInit)) {
5130         HadError = true;
5131         continue;
5132       }
5133 
5134       Info.AllToInit.push_back(CXXBaseInit);
5135     }
5136   }
5137 
5138   // Non-virtual bases.
5139   for (auto &Base : ClassDecl->bases()) {
5140     // Virtuals are in the virtual base list and already constructed.
5141     if (Base.isVirtual())
5142       continue;
5143 
5144     if (CXXCtorInitializer *Value
5145           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5146       Info.AllToInit.push_back(Value);
5147     } else if (!AnyErrors) {
5148       CXXCtorInitializer *CXXBaseInit;
5149       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5150                                        &Base, /*IsInheritedVirtualBase=*/false,
5151                                        CXXBaseInit)) {
5152         HadError = true;
5153         continue;
5154       }
5155 
5156       Info.AllToInit.push_back(CXXBaseInit);
5157     }
5158   }
5159 
5160   // Fields.
5161   for (auto *Mem : ClassDecl->decls()) {
5162     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5163       // C++ [class.bit]p2:
5164       //   A declaration for a bit-field that omits the identifier declares an
5165       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5166       //   initialized.
5167       if (F->isUnnamedBitfield())
5168         continue;
5169 
5170       // If we're not generating the implicit copy/move constructor, then we'll
5171       // handle anonymous struct/union fields based on their individual
5172       // indirect fields.
5173       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5174         continue;
5175 
5176       if (CollectFieldInitializer(*this, Info, F))
5177         HadError = true;
5178       continue;
5179     }
5180 
5181     // Beyond this point, we only consider default initialization.
5182     if (Info.isImplicitCopyOrMove())
5183       continue;
5184 
5185     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5186       if (F->getType()->isIncompleteArrayType()) {
5187         assert(ClassDecl->hasFlexibleArrayMember() &&
5188                "Incomplete array type is not valid");
5189         continue;
5190       }
5191 
5192       // Initialize each field of an anonymous struct individually.
5193       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5194         HadError = true;
5195 
5196       continue;
5197     }
5198   }
5199 
5200   unsigned NumInitializers = Info.AllToInit.size();
5201   if (NumInitializers > 0) {
5202     Constructor->setNumCtorInitializers(NumInitializers);
5203     CXXCtorInitializer **baseOrMemberInitializers =
5204       new (Context) CXXCtorInitializer*[NumInitializers];
5205     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5206            NumInitializers * sizeof(CXXCtorInitializer*));
5207     Constructor->setCtorInitializers(baseOrMemberInitializers);
5208 
5209     // Constructors implicitly reference the base and member
5210     // destructors.
5211     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5212                                            Constructor->getParent());
5213   }
5214 
5215   return HadError;
5216 }
5217 
5218 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5219   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5220     const RecordDecl *RD = RT->getDecl();
5221     if (RD->isAnonymousStructOrUnion()) {
5222       for (auto *Field : RD->fields())
5223         PopulateKeysForFields(Field, IdealInits);
5224       return;
5225     }
5226   }
5227   IdealInits.push_back(Field->getCanonicalDecl());
5228 }
5229 
5230 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5231   return Context.getCanonicalType(BaseType).getTypePtr();
5232 }
5233 
5234 static const void *GetKeyForMember(ASTContext &Context,
5235                                    CXXCtorInitializer *Member) {
5236   if (!Member->isAnyMemberInitializer())
5237     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5238 
5239   return Member->getAnyMember()->getCanonicalDecl();
5240 }
5241 
5242 static void DiagnoseBaseOrMemInitializerOrder(
5243     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5244     ArrayRef<CXXCtorInitializer *> Inits) {
5245   if (Constructor->getDeclContext()->isDependentContext())
5246     return;
5247 
5248   // Don't check initializers order unless the warning is enabled at the
5249   // location of at least one initializer.
5250   bool ShouldCheckOrder = false;
5251   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5252     CXXCtorInitializer *Init = Inits[InitIndex];
5253     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5254                                  Init->getSourceLocation())) {
5255       ShouldCheckOrder = true;
5256       break;
5257     }
5258   }
5259   if (!ShouldCheckOrder)
5260     return;
5261 
5262   // Build the list of bases and members in the order that they'll
5263   // actually be initialized.  The explicit initializers should be in
5264   // this same order but may be missing things.
5265   SmallVector<const void*, 32> IdealInitKeys;
5266 
5267   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5268 
5269   // 1. Virtual bases.
5270   for (const auto &VBase : ClassDecl->vbases())
5271     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5272 
5273   // 2. Non-virtual bases.
5274   for (const auto &Base : ClassDecl->bases()) {
5275     if (Base.isVirtual())
5276       continue;
5277     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5278   }
5279 
5280   // 3. Direct fields.
5281   for (auto *Field : ClassDecl->fields()) {
5282     if (Field->isUnnamedBitfield())
5283       continue;
5284 
5285     PopulateKeysForFields(Field, IdealInitKeys);
5286   }
5287 
5288   unsigned NumIdealInits = IdealInitKeys.size();
5289   unsigned IdealIndex = 0;
5290 
5291   CXXCtorInitializer *PrevInit = nullptr;
5292   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5293     CXXCtorInitializer *Init = Inits[InitIndex];
5294     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5295 
5296     // Scan forward to try to find this initializer in the idealized
5297     // initializers list.
5298     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5299       if (InitKey == IdealInitKeys[IdealIndex])
5300         break;
5301 
5302     // If we didn't find this initializer, it must be because we
5303     // scanned past it on a previous iteration.  That can only
5304     // happen if we're out of order;  emit a warning.
5305     if (IdealIndex == NumIdealInits && PrevInit) {
5306       Sema::SemaDiagnosticBuilder D =
5307         SemaRef.Diag(PrevInit->getSourceLocation(),
5308                      diag::warn_initializer_out_of_order);
5309 
5310       if (PrevInit->isAnyMemberInitializer())
5311         D << 0 << PrevInit->getAnyMember()->getDeclName();
5312       else
5313         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5314 
5315       if (Init->isAnyMemberInitializer())
5316         D << 0 << Init->getAnyMember()->getDeclName();
5317       else
5318         D << 1 << Init->getTypeSourceInfo()->getType();
5319 
5320       // Move back to the initializer's location in the ideal list.
5321       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5322         if (InitKey == IdealInitKeys[IdealIndex])
5323           break;
5324 
5325       assert(IdealIndex < NumIdealInits &&
5326              "initializer not found in initializer list");
5327     }
5328 
5329     PrevInit = Init;
5330   }
5331 }
5332 
5333 namespace {
5334 bool CheckRedundantInit(Sema &S,
5335                         CXXCtorInitializer *Init,
5336                         CXXCtorInitializer *&PrevInit) {
5337   if (!PrevInit) {
5338     PrevInit = Init;
5339     return false;
5340   }
5341 
5342   if (FieldDecl *Field = Init->getAnyMember())
5343     S.Diag(Init->getSourceLocation(),
5344            diag::err_multiple_mem_initialization)
5345       << Field->getDeclName()
5346       << Init->getSourceRange();
5347   else {
5348     const Type *BaseClass = Init->getBaseClass();
5349     assert(BaseClass && "neither field nor base");
5350     S.Diag(Init->getSourceLocation(),
5351            diag::err_multiple_base_initialization)
5352       << QualType(BaseClass, 0)
5353       << Init->getSourceRange();
5354   }
5355   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5356     << 0 << PrevInit->getSourceRange();
5357 
5358   return true;
5359 }
5360 
5361 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5362 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5363 
5364 bool CheckRedundantUnionInit(Sema &S,
5365                              CXXCtorInitializer *Init,
5366                              RedundantUnionMap &Unions) {
5367   FieldDecl *Field = Init->getAnyMember();
5368   RecordDecl *Parent = Field->getParent();
5369   NamedDecl *Child = Field;
5370 
5371   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5372     if (Parent->isUnion()) {
5373       UnionEntry &En = Unions[Parent];
5374       if (En.first && En.first != Child) {
5375         S.Diag(Init->getSourceLocation(),
5376                diag::err_multiple_mem_union_initialization)
5377           << Field->getDeclName()
5378           << Init->getSourceRange();
5379         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5380           << 0 << En.second->getSourceRange();
5381         return true;
5382       }
5383       if (!En.first) {
5384         En.first = Child;
5385         En.second = Init;
5386       }
5387       if (!Parent->isAnonymousStructOrUnion())
5388         return false;
5389     }
5390 
5391     Child = Parent;
5392     Parent = cast<RecordDecl>(Parent->getDeclContext());
5393   }
5394 
5395   return false;
5396 }
5397 }
5398 
5399 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5400 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5401                                 SourceLocation ColonLoc,
5402                                 ArrayRef<CXXCtorInitializer*> MemInits,
5403                                 bool AnyErrors) {
5404   if (!ConstructorDecl)
5405     return;
5406 
5407   AdjustDeclIfTemplate(ConstructorDecl);
5408 
5409   CXXConstructorDecl *Constructor
5410     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5411 
5412   if (!Constructor) {
5413     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5414     return;
5415   }
5416 
5417   // Mapping for the duplicate initializers check.
5418   // For member initializers, this is keyed with a FieldDecl*.
5419   // For base initializers, this is keyed with a Type*.
5420   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5421 
5422   // Mapping for the inconsistent anonymous-union initializers check.
5423   RedundantUnionMap MemberUnions;
5424 
5425   bool HadError = false;
5426   for (unsigned i = 0; i < MemInits.size(); i++) {
5427     CXXCtorInitializer *Init = MemInits[i];
5428 
5429     // Set the source order index.
5430     Init->setSourceOrder(i);
5431 
5432     if (Init->isAnyMemberInitializer()) {
5433       const void *Key = GetKeyForMember(Context, Init);
5434       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5435           CheckRedundantUnionInit(*this, Init, MemberUnions))
5436         HadError = true;
5437     } else if (Init->isBaseInitializer()) {
5438       const void *Key = GetKeyForMember(Context, Init);
5439       if (CheckRedundantInit(*this, Init, Members[Key]))
5440         HadError = true;
5441     } else {
5442       assert(Init->isDelegatingInitializer());
5443       // This must be the only initializer
5444       if (MemInits.size() != 1) {
5445         Diag(Init->getSourceLocation(),
5446              diag::err_delegating_initializer_alone)
5447           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5448         // We will treat this as being the only initializer.
5449       }
5450       SetDelegatingInitializer(Constructor, MemInits[i]);
5451       // Return immediately as the initializer is set.
5452       return;
5453     }
5454   }
5455 
5456   if (HadError)
5457     return;
5458 
5459   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5460 
5461   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5462 
5463   DiagnoseUninitializedFields(*this, Constructor);
5464 }
5465 
5466 void
5467 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5468                                              CXXRecordDecl *ClassDecl) {
5469   // Ignore dependent contexts. Also ignore unions, since their members never
5470   // have destructors implicitly called.
5471   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5472     return;
5473 
5474   // FIXME: all the access-control diagnostics are positioned on the
5475   // field/base declaration.  That's probably good; that said, the
5476   // user might reasonably want to know why the destructor is being
5477   // emitted, and we currently don't say.
5478 
5479   // Non-static data members.
5480   for (auto *Field : ClassDecl->fields()) {
5481     if (Field->isInvalidDecl())
5482       continue;
5483 
5484     // Don't destroy incomplete or zero-length arrays.
5485     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5486       continue;
5487 
5488     QualType FieldType = Context.getBaseElementType(Field->getType());
5489 
5490     const RecordType* RT = FieldType->getAs<RecordType>();
5491     if (!RT)
5492       continue;
5493 
5494     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5495     if (FieldClassDecl->isInvalidDecl())
5496       continue;
5497     if (FieldClassDecl->hasIrrelevantDestructor())
5498       continue;
5499     // The destructor for an implicit anonymous union member is never invoked.
5500     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5501       continue;
5502 
5503     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5504     assert(Dtor && "No dtor found for FieldClassDecl!");
5505     CheckDestructorAccess(Field->getLocation(), Dtor,
5506                           PDiag(diag::err_access_dtor_field)
5507                             << Field->getDeclName()
5508                             << FieldType);
5509 
5510     MarkFunctionReferenced(Location, Dtor);
5511     DiagnoseUseOfDecl(Dtor, Location);
5512   }
5513 
5514   // We only potentially invoke the destructors of potentially constructed
5515   // subobjects.
5516   bool VisitVirtualBases = !ClassDecl->isAbstract();
5517 
5518   // If the destructor exists and has already been marked used in the MS ABI,
5519   // then virtual base destructors have already been checked and marked used.
5520   // Skip checking them again to avoid duplicate diagnostics.
5521   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5522     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5523     if (Dtor && Dtor->isUsed())
5524       VisitVirtualBases = false;
5525   }
5526 
5527   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5528 
5529   // Bases.
5530   for (const auto &Base : ClassDecl->bases()) {
5531     const RecordType *RT = Base.getType()->getAs<RecordType>();
5532     if (!RT)
5533       continue;
5534 
5535     // Remember direct virtual bases.
5536     if (Base.isVirtual()) {
5537       if (!VisitVirtualBases)
5538         continue;
5539       DirectVirtualBases.insert(RT);
5540     }
5541 
5542     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5543     // If our base class is invalid, we probably can't get its dtor anyway.
5544     if (BaseClassDecl->isInvalidDecl())
5545       continue;
5546     if (BaseClassDecl->hasIrrelevantDestructor())
5547       continue;
5548 
5549     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5550     assert(Dtor && "No dtor found for BaseClassDecl!");
5551 
5552     // FIXME: caret should be on the start of the class name
5553     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5554                           PDiag(diag::err_access_dtor_base)
5555                               << Base.getType() << Base.getSourceRange(),
5556                           Context.getTypeDeclType(ClassDecl));
5557 
5558     MarkFunctionReferenced(Location, Dtor);
5559     DiagnoseUseOfDecl(Dtor, Location);
5560   }
5561 
5562   if (VisitVirtualBases)
5563     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5564                                          &DirectVirtualBases);
5565 }
5566 
5567 void Sema::MarkVirtualBaseDestructorsReferenced(
5568     SourceLocation Location, CXXRecordDecl *ClassDecl,
5569     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5570   // Virtual bases.
5571   for (const auto &VBase : ClassDecl->vbases()) {
5572     // Bases are always records in a well-formed non-dependent class.
5573     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5574 
5575     // Ignore already visited direct virtual bases.
5576     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5577       continue;
5578 
5579     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5580     // If our base class is invalid, we probably can't get its dtor anyway.
5581     if (BaseClassDecl->isInvalidDecl())
5582       continue;
5583     if (BaseClassDecl->hasIrrelevantDestructor())
5584       continue;
5585 
5586     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5587     assert(Dtor && "No dtor found for BaseClassDecl!");
5588     if (CheckDestructorAccess(
5589             ClassDecl->getLocation(), Dtor,
5590             PDiag(diag::err_access_dtor_vbase)
5591                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5592             Context.getTypeDeclType(ClassDecl)) ==
5593         AR_accessible) {
5594       CheckDerivedToBaseConversion(
5595           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5596           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5597           SourceRange(), DeclarationName(), nullptr);
5598     }
5599 
5600     MarkFunctionReferenced(Location, Dtor);
5601     DiagnoseUseOfDecl(Dtor, Location);
5602   }
5603 }
5604 
5605 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5606   if (!CDtorDecl)
5607     return;
5608 
5609   if (CXXConstructorDecl *Constructor
5610       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5611     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5612     DiagnoseUninitializedFields(*this, Constructor);
5613   }
5614 }
5615 
5616 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5617   if (!getLangOpts().CPlusPlus)
5618     return false;
5619 
5620   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5621   if (!RD)
5622     return false;
5623 
5624   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5625   // class template specialization here, but doing so breaks a lot of code.
5626 
5627   // We can't answer whether something is abstract until it has a
5628   // definition. If it's currently being defined, we'll walk back
5629   // over all the declarations when we have a full definition.
5630   const CXXRecordDecl *Def = RD->getDefinition();
5631   if (!Def || Def->isBeingDefined())
5632     return false;
5633 
5634   return RD->isAbstract();
5635 }
5636 
5637 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5638                                   TypeDiagnoser &Diagnoser) {
5639   if (!isAbstractType(Loc, T))
5640     return false;
5641 
5642   T = Context.getBaseElementType(T);
5643   Diagnoser.diagnose(*this, Loc, T);
5644   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5645   return true;
5646 }
5647 
5648 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5649   // Check if we've already emitted the list of pure virtual functions
5650   // for this class.
5651   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5652     return;
5653 
5654   // If the diagnostic is suppressed, don't emit the notes. We're only
5655   // going to emit them once, so try to attach them to a diagnostic we're
5656   // actually going to show.
5657   if (Diags.isLastDiagnosticIgnored())
5658     return;
5659 
5660   CXXFinalOverriderMap FinalOverriders;
5661   RD->getFinalOverriders(FinalOverriders);
5662 
5663   // Keep a set of seen pure methods so we won't diagnose the same method
5664   // more than once.
5665   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5666 
5667   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5668                                    MEnd = FinalOverriders.end();
5669        M != MEnd;
5670        ++M) {
5671     for (OverridingMethods::iterator SO = M->second.begin(),
5672                                   SOEnd = M->second.end();
5673          SO != SOEnd; ++SO) {
5674       // C++ [class.abstract]p4:
5675       //   A class is abstract if it contains or inherits at least one
5676       //   pure virtual function for which the final overrider is pure
5677       //   virtual.
5678 
5679       //
5680       if (SO->second.size() != 1)
5681         continue;
5682 
5683       if (!SO->second.front().Method->isPure())
5684         continue;
5685 
5686       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5687         continue;
5688 
5689       Diag(SO->second.front().Method->getLocation(),
5690            diag::note_pure_virtual_function)
5691         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5692     }
5693   }
5694 
5695   if (!PureVirtualClassDiagSet)
5696     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5697   PureVirtualClassDiagSet->insert(RD);
5698 }
5699 
5700 namespace {
5701 struct AbstractUsageInfo {
5702   Sema &S;
5703   CXXRecordDecl *Record;
5704   CanQualType AbstractType;
5705   bool Invalid;
5706 
5707   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5708     : S(S), Record(Record),
5709       AbstractType(S.Context.getCanonicalType(
5710                    S.Context.getTypeDeclType(Record))),
5711       Invalid(false) {}
5712 
5713   void DiagnoseAbstractType() {
5714     if (Invalid) return;
5715     S.DiagnoseAbstractType(Record);
5716     Invalid = true;
5717   }
5718 
5719   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5720 };
5721 
5722 struct CheckAbstractUsage {
5723   AbstractUsageInfo &Info;
5724   const NamedDecl *Ctx;
5725 
5726   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5727     : Info(Info), Ctx(Ctx) {}
5728 
5729   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5730     switch (TL.getTypeLocClass()) {
5731 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5732 #define TYPELOC(CLASS, PARENT) \
5733     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5734 #include "clang/AST/TypeLocNodes.def"
5735     }
5736   }
5737 
5738   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5739     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5740     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5741       if (!TL.getParam(I))
5742         continue;
5743 
5744       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5745       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5746     }
5747   }
5748 
5749   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5750     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5751   }
5752 
5753   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5754     // Visit the type parameters from a permissive context.
5755     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5756       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5757       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5758         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5759           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5760       // TODO: other template argument types?
5761     }
5762   }
5763 
5764   // Visit pointee types from a permissive context.
5765 #define CheckPolymorphic(Type) \
5766   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5767     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5768   }
5769   CheckPolymorphic(PointerTypeLoc)
5770   CheckPolymorphic(ReferenceTypeLoc)
5771   CheckPolymorphic(MemberPointerTypeLoc)
5772   CheckPolymorphic(BlockPointerTypeLoc)
5773   CheckPolymorphic(AtomicTypeLoc)
5774 
5775   /// Handle all the types we haven't given a more specific
5776   /// implementation for above.
5777   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5778     // Every other kind of type that we haven't called out already
5779     // that has an inner type is either (1) sugar or (2) contains that
5780     // inner type in some way as a subobject.
5781     if (TypeLoc Next = TL.getNextTypeLoc())
5782       return Visit(Next, Sel);
5783 
5784     // If there's no inner type and we're in a permissive context,
5785     // don't diagnose.
5786     if (Sel == Sema::AbstractNone) return;
5787 
5788     // Check whether the type matches the abstract type.
5789     QualType T = TL.getType();
5790     if (T->isArrayType()) {
5791       Sel = Sema::AbstractArrayType;
5792       T = Info.S.Context.getBaseElementType(T);
5793     }
5794     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5795     if (CT != Info.AbstractType) return;
5796 
5797     // It matched; do some magic.
5798     if (Sel == Sema::AbstractArrayType) {
5799       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5800         << T << TL.getSourceRange();
5801     } else {
5802       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5803         << Sel << T << TL.getSourceRange();
5804     }
5805     Info.DiagnoseAbstractType();
5806   }
5807 };
5808 
5809 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5810                                   Sema::AbstractDiagSelID Sel) {
5811   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5812 }
5813 
5814 }
5815 
5816 /// Check for invalid uses of an abstract type in a method declaration.
5817 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5818                                     CXXMethodDecl *MD) {
5819   // No need to do the check on definitions, which require that
5820   // the return/param types be complete.
5821   if (MD->doesThisDeclarationHaveABody())
5822     return;
5823 
5824   // For safety's sake, just ignore it if we don't have type source
5825   // information.  This should never happen for non-implicit methods,
5826   // but...
5827   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5828     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5829 }
5830 
5831 /// Check for invalid uses of an abstract type within a class definition.
5832 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5833                                     CXXRecordDecl *RD) {
5834   for (auto *D : RD->decls()) {
5835     if (D->isImplicit()) continue;
5836 
5837     // Methods and method templates.
5838     if (isa<CXXMethodDecl>(D)) {
5839       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5840     } else if (isa<FunctionTemplateDecl>(D)) {
5841       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5842       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5843 
5844     // Fields and static variables.
5845     } else if (isa<FieldDecl>(D)) {
5846       FieldDecl *FD = cast<FieldDecl>(D);
5847       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5848         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5849     } else if (isa<VarDecl>(D)) {
5850       VarDecl *VD = cast<VarDecl>(D);
5851       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5852         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5853 
5854     // Nested classes and class templates.
5855     } else if (isa<CXXRecordDecl>(D)) {
5856       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5857     } else if (isa<ClassTemplateDecl>(D)) {
5858       CheckAbstractClassUsage(Info,
5859                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5860     }
5861   }
5862 }
5863 
5864 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5865   Attr *ClassAttr = getDLLAttr(Class);
5866   if (!ClassAttr)
5867     return;
5868 
5869   assert(ClassAttr->getKind() == attr::DLLExport);
5870 
5871   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5872 
5873   if (TSK == TSK_ExplicitInstantiationDeclaration)
5874     // Don't go any further if this is just an explicit instantiation
5875     // declaration.
5876     return;
5877 
5878   // Add a context note to explain how we got to any diagnostics produced below.
5879   struct MarkingClassDllexported {
5880     Sema &S;
5881     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5882                             SourceLocation AttrLoc)
5883         : S(S) {
5884       Sema::CodeSynthesisContext Ctx;
5885       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5886       Ctx.PointOfInstantiation = AttrLoc;
5887       Ctx.Entity = Class;
5888       S.pushCodeSynthesisContext(Ctx);
5889     }
5890     ~MarkingClassDllexported() {
5891       S.popCodeSynthesisContext();
5892     }
5893   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5894 
5895   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5896     S.MarkVTableUsed(Class->getLocation(), Class, true);
5897 
5898   for (Decl *Member : Class->decls()) {
5899     // Defined static variables that are members of an exported base
5900     // class must be marked export too.
5901     auto *VD = dyn_cast<VarDecl>(Member);
5902     if (VD && Member->getAttr<DLLExportAttr>() &&
5903         VD->getStorageClass() == SC_Static &&
5904         TSK == TSK_ImplicitInstantiation)
5905       S.MarkVariableReferenced(VD->getLocation(), VD);
5906 
5907     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5908     if (!MD)
5909       continue;
5910 
5911     if (Member->getAttr<DLLExportAttr>()) {
5912       if (MD->isUserProvided()) {
5913         // Instantiate non-default class member functions ...
5914 
5915         // .. except for certain kinds of template specializations.
5916         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5917           continue;
5918 
5919         S.MarkFunctionReferenced(Class->getLocation(), MD);
5920 
5921         // The function will be passed to the consumer when its definition is
5922         // encountered.
5923       } else if (MD->isExplicitlyDefaulted()) {
5924         // Synthesize and instantiate explicitly defaulted methods.
5925         S.MarkFunctionReferenced(Class->getLocation(), MD);
5926 
5927         if (TSK != TSK_ExplicitInstantiationDefinition) {
5928           // Except for explicit instantiation defs, we will not see the
5929           // definition again later, so pass it to the consumer now.
5930           S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5931         }
5932       } else if (!MD->isTrivial() ||
5933                  MD->isCopyAssignmentOperator() ||
5934                  MD->isMoveAssignmentOperator()) {
5935         // Synthesize and instantiate non-trivial implicit methods, and the copy
5936         // and move assignment operators. The latter are exported even if they
5937         // are trivial, because the address of an operator can be taken and
5938         // should compare equal across libraries.
5939         S.MarkFunctionReferenced(Class->getLocation(), MD);
5940 
5941         // There is no later point when we will see the definition of this
5942         // function, so pass it to the consumer now.
5943         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5944       }
5945     }
5946   }
5947 }
5948 
5949 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5950                                                         CXXRecordDecl *Class) {
5951   // Only the MS ABI has default constructor closures, so we don't need to do
5952   // this semantic checking anywhere else.
5953   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5954     return;
5955 
5956   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5957   for (Decl *Member : Class->decls()) {
5958     // Look for exported default constructors.
5959     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5960     if (!CD || !CD->isDefaultConstructor())
5961       continue;
5962     auto *Attr = CD->getAttr<DLLExportAttr>();
5963     if (!Attr)
5964       continue;
5965 
5966     // If the class is non-dependent, mark the default arguments as ODR-used so
5967     // that we can properly codegen the constructor closure.
5968     if (!Class->isDependentContext()) {
5969       for (ParmVarDecl *PD : CD->parameters()) {
5970         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5971         S.DiscardCleanupsInEvaluationContext();
5972       }
5973     }
5974 
5975     if (LastExportedDefaultCtor) {
5976       S.Diag(LastExportedDefaultCtor->getLocation(),
5977              diag::err_attribute_dll_ambiguous_default_ctor)
5978           << Class;
5979       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5980           << CD->getDeclName();
5981       return;
5982     }
5983     LastExportedDefaultCtor = CD;
5984   }
5985 }
5986 
5987 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5988                                                        CXXRecordDecl *Class) {
5989   bool ErrorReported = false;
5990   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5991                                                      ClassTemplateDecl *TD) {
5992     if (ErrorReported)
5993       return;
5994     S.Diag(TD->getLocation(),
5995            diag::err_cuda_device_builtin_surftex_cls_template)
5996         << /*surface*/ 0 << TD;
5997     ErrorReported = true;
5998   };
5999 
6000   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6001   if (!TD) {
6002     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6003     if (!SD) {
6004       S.Diag(Class->getLocation(),
6005              diag::err_cuda_device_builtin_surftex_ref_decl)
6006           << /*surface*/ 0 << Class;
6007       S.Diag(Class->getLocation(),
6008              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6009           << Class;
6010       return;
6011     }
6012     TD = SD->getSpecializedTemplate();
6013   }
6014 
6015   TemplateParameterList *Params = TD->getTemplateParameters();
6016   unsigned N = Params->size();
6017 
6018   if (N != 2) {
6019     reportIllegalClassTemplate(S, TD);
6020     S.Diag(TD->getLocation(),
6021            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6022         << TD << 2;
6023   }
6024   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6025     reportIllegalClassTemplate(S, TD);
6026     S.Diag(TD->getLocation(),
6027            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6028         << TD << /*1st*/ 0 << /*type*/ 0;
6029   }
6030   if (N > 1) {
6031     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6032     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6033       reportIllegalClassTemplate(S, TD);
6034       S.Diag(TD->getLocation(),
6035              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6036           << TD << /*2nd*/ 1 << /*integer*/ 1;
6037     }
6038   }
6039 }
6040 
6041 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6042                                                        CXXRecordDecl *Class) {
6043   bool ErrorReported = false;
6044   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6045                                                      ClassTemplateDecl *TD) {
6046     if (ErrorReported)
6047       return;
6048     S.Diag(TD->getLocation(),
6049            diag::err_cuda_device_builtin_surftex_cls_template)
6050         << /*texture*/ 1 << TD;
6051     ErrorReported = true;
6052   };
6053 
6054   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6055   if (!TD) {
6056     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6057     if (!SD) {
6058       S.Diag(Class->getLocation(),
6059              diag::err_cuda_device_builtin_surftex_ref_decl)
6060           << /*texture*/ 1 << Class;
6061       S.Diag(Class->getLocation(),
6062              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6063           << Class;
6064       return;
6065     }
6066     TD = SD->getSpecializedTemplate();
6067   }
6068 
6069   TemplateParameterList *Params = TD->getTemplateParameters();
6070   unsigned N = Params->size();
6071 
6072   if (N != 3) {
6073     reportIllegalClassTemplate(S, TD);
6074     S.Diag(TD->getLocation(),
6075            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6076         << TD << 3;
6077   }
6078   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6079     reportIllegalClassTemplate(S, TD);
6080     S.Diag(TD->getLocation(),
6081            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6082         << TD << /*1st*/ 0 << /*type*/ 0;
6083   }
6084   if (N > 1) {
6085     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6086     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6087       reportIllegalClassTemplate(S, TD);
6088       S.Diag(TD->getLocation(),
6089              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6090           << TD << /*2nd*/ 1 << /*integer*/ 1;
6091     }
6092   }
6093   if (N > 2) {
6094     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6095     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6096       reportIllegalClassTemplate(S, TD);
6097       S.Diag(TD->getLocation(),
6098              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6099           << TD << /*3rd*/ 2 << /*integer*/ 1;
6100     }
6101   }
6102 }
6103 
6104 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6105   // Mark any compiler-generated routines with the implicit code_seg attribute.
6106   for (auto *Method : Class->methods()) {
6107     if (Method->isUserProvided())
6108       continue;
6109     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6110       Method->addAttr(A);
6111   }
6112 }
6113 
6114 /// Check class-level dllimport/dllexport attribute.
6115 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6116   Attr *ClassAttr = getDLLAttr(Class);
6117 
6118   // MSVC inherits DLL attributes to partial class template specializations.
6119   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6120     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6121       if (Attr *TemplateAttr =
6122               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6123         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6124         A->setInherited(true);
6125         ClassAttr = A;
6126       }
6127     }
6128   }
6129 
6130   if (!ClassAttr)
6131     return;
6132 
6133   if (!Class->isExternallyVisible()) {
6134     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6135         << Class << ClassAttr;
6136     return;
6137   }
6138 
6139   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6140       !ClassAttr->isInherited()) {
6141     // Diagnose dll attributes on members of class with dll attribute.
6142     for (Decl *Member : Class->decls()) {
6143       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6144         continue;
6145       InheritableAttr *MemberAttr = getDLLAttr(Member);
6146       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6147         continue;
6148 
6149       Diag(MemberAttr->getLocation(),
6150              diag::err_attribute_dll_member_of_dll_class)
6151           << MemberAttr << ClassAttr;
6152       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6153       Member->setInvalidDecl();
6154     }
6155   }
6156 
6157   if (Class->getDescribedClassTemplate())
6158     // Don't inherit dll attribute until the template is instantiated.
6159     return;
6160 
6161   // The class is either imported or exported.
6162   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6163 
6164   // Check if this was a dllimport attribute propagated from a derived class to
6165   // a base class template specialization. We don't apply these attributes to
6166   // static data members.
6167   const bool PropagatedImport =
6168       !ClassExported &&
6169       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6170 
6171   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6172 
6173   // Ignore explicit dllexport on explicit class template instantiation
6174   // declarations, except in MinGW mode.
6175   if (ClassExported && !ClassAttr->isInherited() &&
6176       TSK == TSK_ExplicitInstantiationDeclaration &&
6177       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6178     Class->dropAttr<DLLExportAttr>();
6179     return;
6180   }
6181 
6182   // Force declaration of implicit members so they can inherit the attribute.
6183   ForceDeclarationOfImplicitMembers(Class);
6184 
6185   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6186   // seem to be true in practice?
6187 
6188   for (Decl *Member : Class->decls()) {
6189     VarDecl *VD = dyn_cast<VarDecl>(Member);
6190     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6191 
6192     // Only methods and static fields inherit the attributes.
6193     if (!VD && !MD)
6194       continue;
6195 
6196     if (MD) {
6197       // Don't process deleted methods.
6198       if (MD->isDeleted())
6199         continue;
6200 
6201       if (MD->isInlined()) {
6202         // MinGW does not import or export inline methods. But do it for
6203         // template instantiations.
6204         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6205             TSK != TSK_ExplicitInstantiationDeclaration &&
6206             TSK != TSK_ExplicitInstantiationDefinition)
6207           continue;
6208 
6209         // MSVC versions before 2015 don't export the move assignment operators
6210         // and move constructor, so don't attempt to import/export them if
6211         // we have a definition.
6212         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6213         if ((MD->isMoveAssignmentOperator() ||
6214              (Ctor && Ctor->isMoveConstructor())) &&
6215             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6216           continue;
6217 
6218         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6219         // operator is exported anyway.
6220         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6221             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6222           continue;
6223       }
6224     }
6225 
6226     // Don't apply dllimport attributes to static data members of class template
6227     // instantiations when the attribute is propagated from a derived class.
6228     if (VD && PropagatedImport)
6229       continue;
6230 
6231     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6232       continue;
6233 
6234     if (!getDLLAttr(Member)) {
6235       InheritableAttr *NewAttr = nullptr;
6236 
6237       // Do not export/import inline function when -fno-dllexport-inlines is
6238       // passed. But add attribute for later local static var check.
6239       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6240           TSK != TSK_ExplicitInstantiationDeclaration &&
6241           TSK != TSK_ExplicitInstantiationDefinition) {
6242         if (ClassExported) {
6243           NewAttr = ::new (getASTContext())
6244               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6245         } else {
6246           NewAttr = ::new (getASTContext())
6247               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6248         }
6249       } else {
6250         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6251       }
6252 
6253       NewAttr->setInherited(true);
6254       Member->addAttr(NewAttr);
6255 
6256       if (MD) {
6257         // Propagate DLLAttr to friend re-declarations of MD that have already
6258         // been constructed.
6259         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6260              FD = FD->getPreviousDecl()) {
6261           if (FD->getFriendObjectKind() == Decl::FOK_None)
6262             continue;
6263           assert(!getDLLAttr(FD) &&
6264                  "friend re-decl should not already have a DLLAttr");
6265           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6266           NewAttr->setInherited(true);
6267           FD->addAttr(NewAttr);
6268         }
6269       }
6270     }
6271   }
6272 
6273   if (ClassExported)
6274     DelayedDllExportClasses.push_back(Class);
6275 }
6276 
6277 /// Perform propagation of DLL attributes from a derived class to a
6278 /// templated base class for MS compatibility.
6279 void Sema::propagateDLLAttrToBaseClassTemplate(
6280     CXXRecordDecl *Class, Attr *ClassAttr,
6281     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6282   if (getDLLAttr(
6283           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6284     // If the base class template has a DLL attribute, don't try to change it.
6285     return;
6286   }
6287 
6288   auto TSK = BaseTemplateSpec->getSpecializationKind();
6289   if (!getDLLAttr(BaseTemplateSpec) &&
6290       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6291        TSK == TSK_ImplicitInstantiation)) {
6292     // The template hasn't been instantiated yet (or it has, but only as an
6293     // explicit instantiation declaration or implicit instantiation, which means
6294     // we haven't codegenned any members yet), so propagate the attribute.
6295     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6296     NewAttr->setInherited(true);
6297     BaseTemplateSpec->addAttr(NewAttr);
6298 
6299     // If this was an import, mark that we propagated it from a derived class to
6300     // a base class template specialization.
6301     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6302       ImportAttr->setPropagatedToBaseTemplate();
6303 
6304     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6305     // needs to be run again to work see the new attribute. Otherwise this will
6306     // get run whenever the template is instantiated.
6307     if (TSK != TSK_Undeclared)
6308       checkClassLevelDLLAttribute(BaseTemplateSpec);
6309 
6310     return;
6311   }
6312 
6313   if (getDLLAttr(BaseTemplateSpec)) {
6314     // The template has already been specialized or instantiated with an
6315     // attribute, explicitly or through propagation. We should not try to change
6316     // it.
6317     return;
6318   }
6319 
6320   // The template was previously instantiated or explicitly specialized without
6321   // a dll attribute, It's too late for us to add an attribute, so warn that
6322   // this is unsupported.
6323   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6324       << BaseTemplateSpec->isExplicitSpecialization();
6325   Diag(ClassAttr->getLocation(), diag::note_attribute);
6326   if (BaseTemplateSpec->isExplicitSpecialization()) {
6327     Diag(BaseTemplateSpec->getLocation(),
6328            diag::note_template_class_explicit_specialization_was_here)
6329         << BaseTemplateSpec;
6330   } else {
6331     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6332            diag::note_template_class_instantiation_was_here)
6333         << BaseTemplateSpec;
6334   }
6335 }
6336 
6337 /// Determine the kind of defaulting that would be done for a given function.
6338 ///
6339 /// If the function is both a default constructor and a copy / move constructor
6340 /// (due to having a default argument for the first parameter), this picks
6341 /// CXXDefaultConstructor.
6342 ///
6343 /// FIXME: Check that case is properly handled by all callers.
6344 Sema::DefaultedFunctionKind
6345 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6346   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6347     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6348       if (Ctor->isDefaultConstructor())
6349         return Sema::CXXDefaultConstructor;
6350 
6351       if (Ctor->isCopyConstructor())
6352         return Sema::CXXCopyConstructor;
6353 
6354       if (Ctor->isMoveConstructor())
6355         return Sema::CXXMoveConstructor;
6356     }
6357 
6358     if (MD->isCopyAssignmentOperator())
6359       return Sema::CXXCopyAssignment;
6360 
6361     if (MD->isMoveAssignmentOperator())
6362       return Sema::CXXMoveAssignment;
6363 
6364     if (isa<CXXDestructorDecl>(FD))
6365       return Sema::CXXDestructor;
6366   }
6367 
6368   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6369   case OO_EqualEqual:
6370     return DefaultedComparisonKind::Equal;
6371 
6372   case OO_ExclaimEqual:
6373     return DefaultedComparisonKind::NotEqual;
6374 
6375   case OO_Spaceship:
6376     // No point allowing this if <=> doesn't exist in the current language mode.
6377     if (!getLangOpts().CPlusPlus20)
6378       break;
6379     return DefaultedComparisonKind::ThreeWay;
6380 
6381   case OO_Less:
6382   case OO_LessEqual:
6383   case OO_Greater:
6384   case OO_GreaterEqual:
6385     // No point allowing this if <=> doesn't exist in the current language mode.
6386     if (!getLangOpts().CPlusPlus20)
6387       break;
6388     return DefaultedComparisonKind::Relational;
6389 
6390   default:
6391     break;
6392   }
6393 
6394   // Not defaultable.
6395   return DefaultedFunctionKind();
6396 }
6397 
6398 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6399                                     SourceLocation DefaultLoc) {
6400   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6401   if (DFK.isComparison())
6402     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6403 
6404   switch (DFK.asSpecialMember()) {
6405   case Sema::CXXDefaultConstructor:
6406     S.DefineImplicitDefaultConstructor(DefaultLoc,
6407                                        cast<CXXConstructorDecl>(FD));
6408     break;
6409   case Sema::CXXCopyConstructor:
6410     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6411     break;
6412   case Sema::CXXCopyAssignment:
6413     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6414     break;
6415   case Sema::CXXDestructor:
6416     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6417     break;
6418   case Sema::CXXMoveConstructor:
6419     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6420     break;
6421   case Sema::CXXMoveAssignment:
6422     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6423     break;
6424   case Sema::CXXInvalid:
6425     llvm_unreachable("Invalid special member.");
6426   }
6427 }
6428 
6429 /// Determine whether a type is permitted to be passed or returned in
6430 /// registers, per C++ [class.temporary]p3.
6431 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6432                                TargetInfo::CallingConvKind CCK) {
6433   if (D->isDependentType() || D->isInvalidDecl())
6434     return false;
6435 
6436   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6437   // The PS4 platform ABI follows the behavior of Clang 3.2.
6438   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6439     return !D->hasNonTrivialDestructorForCall() &&
6440            !D->hasNonTrivialCopyConstructorForCall();
6441 
6442   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6443     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6444     bool DtorIsTrivialForCall = false;
6445 
6446     // If a class has at least one non-deleted, trivial copy constructor, it
6447     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6448     //
6449     // Note: This permits classes with non-trivial copy or move ctors to be
6450     // passed in registers, so long as they *also* have a trivial copy ctor,
6451     // which is non-conforming.
6452     if (D->needsImplicitCopyConstructor()) {
6453       if (!D->defaultedCopyConstructorIsDeleted()) {
6454         if (D->hasTrivialCopyConstructor())
6455           CopyCtorIsTrivial = true;
6456         if (D->hasTrivialCopyConstructorForCall())
6457           CopyCtorIsTrivialForCall = true;
6458       }
6459     } else {
6460       for (const CXXConstructorDecl *CD : D->ctors()) {
6461         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6462           if (CD->isTrivial())
6463             CopyCtorIsTrivial = true;
6464           if (CD->isTrivialForCall())
6465             CopyCtorIsTrivialForCall = true;
6466         }
6467       }
6468     }
6469 
6470     if (D->needsImplicitDestructor()) {
6471       if (!D->defaultedDestructorIsDeleted() &&
6472           D->hasTrivialDestructorForCall())
6473         DtorIsTrivialForCall = true;
6474     } else if (const auto *DD = D->getDestructor()) {
6475       if (!DD->isDeleted() && DD->isTrivialForCall())
6476         DtorIsTrivialForCall = true;
6477     }
6478 
6479     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6480     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6481       return true;
6482 
6483     // If a class has a destructor, we'd really like to pass it indirectly
6484     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6485     // impossible for small types, which it will pass in a single register or
6486     // stack slot. Most objects with dtors are large-ish, so handle that early.
6487     // We can't call out all large objects as being indirect because there are
6488     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6489     // how we pass large POD types.
6490 
6491     // Note: This permits small classes with nontrivial destructors to be
6492     // passed in registers, which is non-conforming.
6493     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6494     uint64_t TypeSize = isAArch64 ? 128 : 64;
6495 
6496     if (CopyCtorIsTrivial &&
6497         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6498       return true;
6499     return false;
6500   }
6501 
6502   // Per C++ [class.temporary]p3, the relevant condition is:
6503   //   each copy constructor, move constructor, and destructor of X is
6504   //   either trivial or deleted, and X has at least one non-deleted copy
6505   //   or move constructor
6506   bool HasNonDeletedCopyOrMove = false;
6507 
6508   if (D->needsImplicitCopyConstructor() &&
6509       !D->defaultedCopyConstructorIsDeleted()) {
6510     if (!D->hasTrivialCopyConstructorForCall())
6511       return false;
6512     HasNonDeletedCopyOrMove = true;
6513   }
6514 
6515   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6516       !D->defaultedMoveConstructorIsDeleted()) {
6517     if (!D->hasTrivialMoveConstructorForCall())
6518       return false;
6519     HasNonDeletedCopyOrMove = true;
6520   }
6521 
6522   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6523       !D->hasTrivialDestructorForCall())
6524     return false;
6525 
6526   for (const CXXMethodDecl *MD : D->methods()) {
6527     if (MD->isDeleted())
6528       continue;
6529 
6530     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6531     if (CD && CD->isCopyOrMoveConstructor())
6532       HasNonDeletedCopyOrMove = true;
6533     else if (!isa<CXXDestructorDecl>(MD))
6534       continue;
6535 
6536     if (!MD->isTrivialForCall())
6537       return false;
6538   }
6539 
6540   return HasNonDeletedCopyOrMove;
6541 }
6542 
6543 /// Report an error regarding overriding, along with any relevant
6544 /// overridden methods.
6545 ///
6546 /// \param DiagID the primary error to report.
6547 /// \param MD the overriding method.
6548 static bool
6549 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6550                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6551   bool IssuedDiagnostic = false;
6552   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6553     if (Report(O)) {
6554       if (!IssuedDiagnostic) {
6555         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6556         IssuedDiagnostic = true;
6557       }
6558       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6559     }
6560   }
6561   return IssuedDiagnostic;
6562 }
6563 
6564 /// Perform semantic checks on a class definition that has been
6565 /// completing, introducing implicitly-declared members, checking for
6566 /// abstract types, etc.
6567 ///
6568 /// \param S The scope in which the class was parsed. Null if we didn't just
6569 ///        parse a class definition.
6570 /// \param Record The completed class.
6571 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6572   if (!Record)
6573     return;
6574 
6575   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6576     AbstractUsageInfo Info(*this, Record);
6577     CheckAbstractClassUsage(Info, Record);
6578   }
6579 
6580   // If this is not an aggregate type and has no user-declared constructor,
6581   // complain about any non-static data members of reference or const scalar
6582   // type, since they will never get initializers.
6583   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6584       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6585       !Record->isLambda()) {
6586     bool Complained = false;
6587     for (const auto *F : Record->fields()) {
6588       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6589         continue;
6590 
6591       if (F->getType()->isReferenceType() ||
6592           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6593         if (!Complained) {
6594           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6595             << Record->getTagKind() << Record;
6596           Complained = true;
6597         }
6598 
6599         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6600           << F->getType()->isReferenceType()
6601           << F->getDeclName();
6602       }
6603     }
6604   }
6605 
6606   if (Record->getIdentifier()) {
6607     // C++ [class.mem]p13:
6608     //   If T is the name of a class, then each of the following shall have a
6609     //   name different from T:
6610     //     - every member of every anonymous union that is a member of class T.
6611     //
6612     // C++ [class.mem]p14:
6613     //   In addition, if class T has a user-declared constructor (12.1), every
6614     //   non-static data member of class T shall have a name different from T.
6615     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6616     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6617          ++I) {
6618       NamedDecl *D = (*I)->getUnderlyingDecl();
6619       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6620            Record->hasUserDeclaredConstructor()) ||
6621           isa<IndirectFieldDecl>(D)) {
6622         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6623           << D->getDeclName();
6624         break;
6625       }
6626     }
6627   }
6628 
6629   // Warn if the class has virtual methods but non-virtual public destructor.
6630   if (Record->isPolymorphic() && !Record->isDependentType()) {
6631     CXXDestructorDecl *dtor = Record->getDestructor();
6632     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6633         !Record->hasAttr<FinalAttr>())
6634       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6635            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6636   }
6637 
6638   if (Record->isAbstract()) {
6639     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6640       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6641         << FA->isSpelledAsSealed();
6642       DiagnoseAbstractType(Record);
6643     }
6644   }
6645 
6646   // Warn if the class has a final destructor but is not itself marked final.
6647   if (!Record->hasAttr<FinalAttr>()) {
6648     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6649       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6650         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6651             << FA->isSpelledAsSealed()
6652             << FixItHint::CreateInsertion(
6653                    getLocForEndOfToken(Record->getLocation()),
6654                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6655         Diag(Record->getLocation(),
6656              diag::note_final_dtor_non_final_class_silence)
6657             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6658       }
6659     }
6660   }
6661 
6662   // See if trivial_abi has to be dropped.
6663   if (Record->hasAttr<TrivialABIAttr>())
6664     checkIllFormedTrivialABIStruct(*Record);
6665 
6666   // Set HasTrivialSpecialMemberForCall if the record has attribute
6667   // "trivial_abi".
6668   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6669 
6670   if (HasTrivialABI)
6671     Record->setHasTrivialSpecialMemberForCall();
6672 
6673   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6674   // We check these last because they can depend on the properties of the
6675   // primary comparison functions (==, <=>).
6676   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6677 
6678   // Perform checks that can't be done until we know all the properties of a
6679   // member function (whether it's defaulted, deleted, virtual, overriding,
6680   // ...).
6681   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6682     // A static function cannot override anything.
6683     if (MD->getStorageClass() == SC_Static) {
6684       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6685                           [](const CXXMethodDecl *) { return true; }))
6686         return;
6687     }
6688 
6689     // A deleted function cannot override a non-deleted function and vice
6690     // versa.
6691     if (ReportOverrides(*this,
6692                         MD->isDeleted() ? diag::err_deleted_override
6693                                         : diag::err_non_deleted_override,
6694                         MD, [&](const CXXMethodDecl *V) {
6695                           return MD->isDeleted() != V->isDeleted();
6696                         })) {
6697       if (MD->isDefaulted() && MD->isDeleted())
6698         // Explain why this defaulted function was deleted.
6699         DiagnoseDeletedDefaultedFunction(MD);
6700       return;
6701     }
6702 
6703     // A consteval function cannot override a non-consteval function and vice
6704     // versa.
6705     if (ReportOverrides(*this,
6706                         MD->isConsteval() ? diag::err_consteval_override
6707                                           : diag::err_non_consteval_override,
6708                         MD, [&](const CXXMethodDecl *V) {
6709                           return MD->isConsteval() != V->isConsteval();
6710                         })) {
6711       if (MD->isDefaulted() && MD->isDeleted())
6712         // Explain why this defaulted function was deleted.
6713         DiagnoseDeletedDefaultedFunction(MD);
6714       return;
6715     }
6716   };
6717 
6718   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6719     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6720       return false;
6721 
6722     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6723     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6724         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6725       DefaultedSecondaryComparisons.push_back(FD);
6726       return true;
6727     }
6728 
6729     CheckExplicitlyDefaultedFunction(S, FD);
6730     return false;
6731   };
6732 
6733   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6734     // Check whether the explicitly-defaulted members are valid.
6735     bool Incomplete = CheckForDefaultedFunction(M);
6736 
6737     // Skip the rest of the checks for a member of a dependent class.
6738     if (Record->isDependentType())
6739       return;
6740 
6741     // For an explicitly defaulted or deleted special member, we defer
6742     // determining triviality until the class is complete. That time is now!
6743     CXXSpecialMember CSM = getSpecialMember(M);
6744     if (!M->isImplicit() && !M->isUserProvided()) {
6745       if (CSM != CXXInvalid) {
6746         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6747         // Inform the class that we've finished declaring this member.
6748         Record->finishedDefaultedOrDeletedMember(M);
6749         M->setTrivialForCall(
6750             HasTrivialABI ||
6751             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6752         Record->setTrivialForCallFlags(M);
6753       }
6754     }
6755 
6756     // Set triviality for the purpose of calls if this is a user-provided
6757     // copy/move constructor or destructor.
6758     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6759          CSM == CXXDestructor) && M->isUserProvided()) {
6760       M->setTrivialForCall(HasTrivialABI);
6761       Record->setTrivialForCallFlags(M);
6762     }
6763 
6764     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6765         M->hasAttr<DLLExportAttr>()) {
6766       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6767           M->isTrivial() &&
6768           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6769            CSM == CXXDestructor))
6770         M->dropAttr<DLLExportAttr>();
6771 
6772       if (M->hasAttr<DLLExportAttr>()) {
6773         // Define after any fields with in-class initializers have been parsed.
6774         DelayedDllExportMemberFunctions.push_back(M);
6775       }
6776     }
6777 
6778     // Define defaulted constexpr virtual functions that override a base class
6779     // function right away.
6780     // FIXME: We can defer doing this until the vtable is marked as used.
6781     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6782       DefineDefaultedFunction(*this, M, M->getLocation());
6783 
6784     if (!Incomplete)
6785       CheckCompletedMemberFunction(M);
6786   };
6787 
6788   // Check the destructor before any other member function. We need to
6789   // determine whether it's trivial in order to determine whether the claas
6790   // type is a literal type, which is a prerequisite for determining whether
6791   // other special member functions are valid and whether they're implicitly
6792   // 'constexpr'.
6793   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6794     CompleteMemberFunction(Dtor);
6795 
6796   bool HasMethodWithOverrideControl = false,
6797        HasOverridingMethodWithoutOverrideControl = false;
6798   for (auto *D : Record->decls()) {
6799     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6800       // FIXME: We could do this check for dependent types with non-dependent
6801       // bases.
6802       if (!Record->isDependentType()) {
6803         // See if a method overloads virtual methods in a base
6804         // class without overriding any.
6805         if (!M->isStatic())
6806           DiagnoseHiddenVirtualMethods(M);
6807         if (M->hasAttr<OverrideAttr>())
6808           HasMethodWithOverrideControl = true;
6809         else if (M->size_overridden_methods() > 0)
6810           HasOverridingMethodWithoutOverrideControl = true;
6811       }
6812 
6813       if (!isa<CXXDestructorDecl>(M))
6814         CompleteMemberFunction(M);
6815     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6816       CheckForDefaultedFunction(
6817           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6818     }
6819   }
6820 
6821   if (HasOverridingMethodWithoutOverrideControl) {
6822     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6823     for (auto *M : Record->methods())
6824       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6825   }
6826 
6827   // Check the defaulted secondary comparisons after any other member functions.
6828   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6829     CheckExplicitlyDefaultedFunction(S, FD);
6830 
6831     // If this is a member function, we deferred checking it until now.
6832     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6833       CheckCompletedMemberFunction(MD);
6834   }
6835 
6836   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6837   // whether this class uses any C++ features that are implemented
6838   // completely differently in MSVC, and if so, emit a diagnostic.
6839   // That diagnostic defaults to an error, but we allow projects to
6840   // map it down to a warning (or ignore it).  It's a fairly common
6841   // practice among users of the ms_struct pragma to mass-annotate
6842   // headers, sweeping up a bunch of types that the project doesn't
6843   // really rely on MSVC-compatible layout for.  We must therefore
6844   // support "ms_struct except for C++ stuff" as a secondary ABI.
6845   // Don't emit this diagnostic if the feature was enabled as a
6846   // language option (as opposed to via a pragma or attribute), as
6847   // the option -mms-bitfields otherwise essentially makes it impossible
6848   // to build C++ code, unless this diagnostic is turned off.
6849   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6850       (Record->isPolymorphic() || Record->getNumBases())) {
6851     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6852   }
6853 
6854   checkClassLevelDLLAttribute(Record);
6855   checkClassLevelCodeSegAttribute(Record);
6856 
6857   bool ClangABICompat4 =
6858       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6859   TargetInfo::CallingConvKind CCK =
6860       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6861   bool CanPass = canPassInRegisters(*this, Record, CCK);
6862 
6863   // Do not change ArgPassingRestrictions if it has already been set to
6864   // APK_CanNeverPassInRegs.
6865   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6866     Record->setArgPassingRestrictions(CanPass
6867                                           ? RecordDecl::APK_CanPassInRegs
6868                                           : RecordDecl::APK_CannotPassInRegs);
6869 
6870   // If canPassInRegisters returns true despite the record having a non-trivial
6871   // destructor, the record is destructed in the callee. This happens only when
6872   // the record or one of its subobjects has a field annotated with trivial_abi
6873   // or a field qualified with ObjC __strong/__weak.
6874   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6875     Record->setParamDestroyedInCallee(true);
6876   else if (Record->hasNonTrivialDestructor())
6877     Record->setParamDestroyedInCallee(CanPass);
6878 
6879   if (getLangOpts().ForceEmitVTables) {
6880     // If we want to emit all the vtables, we need to mark it as used.  This
6881     // is especially required for cases like vtable assumption loads.
6882     MarkVTableUsed(Record->getInnerLocStart(), Record);
6883   }
6884 
6885   if (getLangOpts().CUDA) {
6886     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6887       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6888     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6889       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6890   }
6891 }
6892 
6893 /// Look up the special member function that would be called by a special
6894 /// member function for a subobject of class type.
6895 ///
6896 /// \param Class The class type of the subobject.
6897 /// \param CSM The kind of special member function.
6898 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6899 /// \param ConstRHS True if this is a copy operation with a const object
6900 ///        on its RHS, that is, if the argument to the outer special member
6901 ///        function is 'const' and this is not a field marked 'mutable'.
6902 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6903     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6904     unsigned FieldQuals, bool ConstRHS) {
6905   unsigned LHSQuals = 0;
6906   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6907     LHSQuals = FieldQuals;
6908 
6909   unsigned RHSQuals = FieldQuals;
6910   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6911     RHSQuals = 0;
6912   else if (ConstRHS)
6913     RHSQuals |= Qualifiers::Const;
6914 
6915   return S.LookupSpecialMember(Class, CSM,
6916                                RHSQuals & Qualifiers::Const,
6917                                RHSQuals & Qualifiers::Volatile,
6918                                false,
6919                                LHSQuals & Qualifiers::Const,
6920                                LHSQuals & Qualifiers::Volatile);
6921 }
6922 
6923 class Sema::InheritedConstructorInfo {
6924   Sema &S;
6925   SourceLocation UseLoc;
6926 
6927   /// A mapping from the base classes through which the constructor was
6928   /// inherited to the using shadow declaration in that base class (or a null
6929   /// pointer if the constructor was declared in that base class).
6930   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6931       InheritedFromBases;
6932 
6933 public:
6934   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6935                            ConstructorUsingShadowDecl *Shadow)
6936       : S(S), UseLoc(UseLoc) {
6937     bool DiagnosedMultipleConstructedBases = false;
6938     CXXRecordDecl *ConstructedBase = nullptr;
6939     UsingDecl *ConstructedBaseUsing = nullptr;
6940 
6941     // Find the set of such base class subobjects and check that there's a
6942     // unique constructed subobject.
6943     for (auto *D : Shadow->redecls()) {
6944       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6945       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6946       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6947 
6948       InheritedFromBases.insert(
6949           std::make_pair(DNominatedBase->getCanonicalDecl(),
6950                          DShadow->getNominatedBaseClassShadowDecl()));
6951       if (DShadow->constructsVirtualBase())
6952         InheritedFromBases.insert(
6953             std::make_pair(DConstructedBase->getCanonicalDecl(),
6954                            DShadow->getConstructedBaseClassShadowDecl()));
6955       else
6956         assert(DNominatedBase == DConstructedBase);
6957 
6958       // [class.inhctor.init]p2:
6959       //   If the constructor was inherited from multiple base class subobjects
6960       //   of type B, the program is ill-formed.
6961       if (!ConstructedBase) {
6962         ConstructedBase = DConstructedBase;
6963         ConstructedBaseUsing = D->getUsingDecl();
6964       } else if (ConstructedBase != DConstructedBase &&
6965                  !Shadow->isInvalidDecl()) {
6966         if (!DiagnosedMultipleConstructedBases) {
6967           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6968               << Shadow->getTargetDecl();
6969           S.Diag(ConstructedBaseUsing->getLocation(),
6970                diag::note_ambiguous_inherited_constructor_using)
6971               << ConstructedBase;
6972           DiagnosedMultipleConstructedBases = true;
6973         }
6974         S.Diag(D->getUsingDecl()->getLocation(),
6975                diag::note_ambiguous_inherited_constructor_using)
6976             << DConstructedBase;
6977       }
6978     }
6979 
6980     if (DiagnosedMultipleConstructedBases)
6981       Shadow->setInvalidDecl();
6982   }
6983 
6984   /// Find the constructor to use for inherited construction of a base class,
6985   /// and whether that base class constructor inherits the constructor from a
6986   /// virtual base class (in which case it won't actually invoke it).
6987   std::pair<CXXConstructorDecl *, bool>
6988   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6989     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6990     if (It == InheritedFromBases.end())
6991       return std::make_pair(nullptr, false);
6992 
6993     // This is an intermediary class.
6994     if (It->second)
6995       return std::make_pair(
6996           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6997           It->second->constructsVirtualBase());
6998 
6999     // This is the base class from which the constructor was inherited.
7000     return std::make_pair(Ctor, false);
7001   }
7002 };
7003 
7004 /// Is the special member function which would be selected to perform the
7005 /// specified operation on the specified class type a constexpr constructor?
7006 static bool
7007 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7008                          Sema::CXXSpecialMember CSM, unsigned Quals,
7009                          bool ConstRHS,
7010                          CXXConstructorDecl *InheritedCtor = nullptr,
7011                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7012   // If we're inheriting a constructor, see if we need to call it for this base
7013   // class.
7014   if (InheritedCtor) {
7015     assert(CSM == Sema::CXXDefaultConstructor);
7016     auto BaseCtor =
7017         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7018     if (BaseCtor)
7019       return BaseCtor->isConstexpr();
7020   }
7021 
7022   if (CSM == Sema::CXXDefaultConstructor)
7023     return ClassDecl->hasConstexprDefaultConstructor();
7024   if (CSM == Sema::CXXDestructor)
7025     return ClassDecl->hasConstexprDestructor();
7026 
7027   Sema::SpecialMemberOverloadResult SMOR =
7028       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7029   if (!SMOR.getMethod())
7030     // A constructor we wouldn't select can't be "involved in initializing"
7031     // anything.
7032     return true;
7033   return SMOR.getMethod()->isConstexpr();
7034 }
7035 
7036 /// Determine whether the specified special member function would be constexpr
7037 /// if it were implicitly defined.
7038 static bool defaultedSpecialMemberIsConstexpr(
7039     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7040     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7041     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7042   if (!S.getLangOpts().CPlusPlus11)
7043     return false;
7044 
7045   // C++11 [dcl.constexpr]p4:
7046   // In the definition of a constexpr constructor [...]
7047   bool Ctor = true;
7048   switch (CSM) {
7049   case Sema::CXXDefaultConstructor:
7050     if (Inherited)
7051       break;
7052     // Since default constructor lookup is essentially trivial (and cannot
7053     // involve, for instance, template instantiation), we compute whether a
7054     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7055     //
7056     // This is important for performance; we need to know whether the default
7057     // constructor is constexpr to determine whether the type is a literal type.
7058     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7059 
7060   case Sema::CXXCopyConstructor:
7061   case Sema::CXXMoveConstructor:
7062     // For copy or move constructors, we need to perform overload resolution.
7063     break;
7064 
7065   case Sema::CXXCopyAssignment:
7066   case Sema::CXXMoveAssignment:
7067     if (!S.getLangOpts().CPlusPlus14)
7068       return false;
7069     // In C++1y, we need to perform overload resolution.
7070     Ctor = false;
7071     break;
7072 
7073   case Sema::CXXDestructor:
7074     return ClassDecl->defaultedDestructorIsConstexpr();
7075 
7076   case Sema::CXXInvalid:
7077     return false;
7078   }
7079 
7080   //   -- if the class is a non-empty union, or for each non-empty anonymous
7081   //      union member of a non-union class, exactly one non-static data member
7082   //      shall be initialized; [DR1359]
7083   //
7084   // If we squint, this is guaranteed, since exactly one non-static data member
7085   // will be initialized (if the constructor isn't deleted), we just don't know
7086   // which one.
7087   if (Ctor && ClassDecl->isUnion())
7088     return CSM == Sema::CXXDefaultConstructor
7089                ? ClassDecl->hasInClassInitializer() ||
7090                      !ClassDecl->hasVariantMembers()
7091                : true;
7092 
7093   //   -- the class shall not have any virtual base classes;
7094   if (Ctor && ClassDecl->getNumVBases())
7095     return false;
7096 
7097   // C++1y [class.copy]p26:
7098   //   -- [the class] is a literal type, and
7099   if (!Ctor && !ClassDecl->isLiteral())
7100     return false;
7101 
7102   //   -- every constructor involved in initializing [...] base class
7103   //      sub-objects shall be a constexpr constructor;
7104   //   -- the assignment operator selected to copy/move each direct base
7105   //      class is a constexpr function, and
7106   for (const auto &B : ClassDecl->bases()) {
7107     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7108     if (!BaseType) continue;
7109 
7110     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7111     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7112                                   InheritedCtor, Inherited))
7113       return false;
7114   }
7115 
7116   //   -- every constructor involved in initializing non-static data members
7117   //      [...] shall be a constexpr constructor;
7118   //   -- every non-static data member and base class sub-object shall be
7119   //      initialized
7120   //   -- for each non-static data member of X that is of class type (or array
7121   //      thereof), the assignment operator selected to copy/move that member is
7122   //      a constexpr function
7123   for (const auto *F : ClassDecl->fields()) {
7124     if (F->isInvalidDecl())
7125       continue;
7126     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7127       continue;
7128     QualType BaseType = S.Context.getBaseElementType(F->getType());
7129     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7130       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7131       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7132                                     BaseType.getCVRQualifiers(),
7133                                     ConstArg && !F->isMutable()))
7134         return false;
7135     } else if (CSM == Sema::CXXDefaultConstructor) {
7136       return false;
7137     }
7138   }
7139 
7140   // All OK, it's constexpr!
7141   return true;
7142 }
7143 
7144 namespace {
7145 /// RAII object to register a defaulted function as having its exception
7146 /// specification computed.
7147 struct ComputingExceptionSpec {
7148   Sema &S;
7149 
7150   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7151       : S(S) {
7152     Sema::CodeSynthesisContext Ctx;
7153     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7154     Ctx.PointOfInstantiation = Loc;
7155     Ctx.Entity = FD;
7156     S.pushCodeSynthesisContext(Ctx);
7157   }
7158   ~ComputingExceptionSpec() {
7159     S.popCodeSynthesisContext();
7160   }
7161 };
7162 }
7163 
7164 static Sema::ImplicitExceptionSpecification
7165 ComputeDefaultedSpecialMemberExceptionSpec(
7166     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7167     Sema::InheritedConstructorInfo *ICI);
7168 
7169 static Sema::ImplicitExceptionSpecification
7170 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7171                                         FunctionDecl *FD,
7172                                         Sema::DefaultedComparisonKind DCK);
7173 
7174 static Sema::ImplicitExceptionSpecification
7175 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7176   auto DFK = S.getDefaultedFunctionKind(FD);
7177   if (DFK.isSpecialMember())
7178     return ComputeDefaultedSpecialMemberExceptionSpec(
7179         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7180   if (DFK.isComparison())
7181     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7182                                                    DFK.asComparison());
7183 
7184   auto *CD = cast<CXXConstructorDecl>(FD);
7185   assert(CD->getInheritedConstructor() &&
7186          "only defaulted functions and inherited constructors have implicit "
7187          "exception specs");
7188   Sema::InheritedConstructorInfo ICI(
7189       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7190   return ComputeDefaultedSpecialMemberExceptionSpec(
7191       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7192 }
7193 
7194 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7195                                                             CXXMethodDecl *MD) {
7196   FunctionProtoType::ExtProtoInfo EPI;
7197 
7198   // Build an exception specification pointing back at this member.
7199   EPI.ExceptionSpec.Type = EST_Unevaluated;
7200   EPI.ExceptionSpec.SourceDecl = MD;
7201 
7202   // Set the calling convention to the default for C++ instance methods.
7203   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7204       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7205                                             /*IsCXXMethod=*/true));
7206   return EPI;
7207 }
7208 
7209 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7210   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7211   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7212     return;
7213 
7214   // Evaluate the exception specification.
7215   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7216   auto ESI = IES.getExceptionSpec();
7217 
7218   // Update the type of the special member to use it.
7219   UpdateExceptionSpec(FD, ESI);
7220 }
7221 
7222 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7223   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7224 
7225   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7226   if (!DefKind) {
7227     assert(FD->getDeclContext()->isDependentContext());
7228     return;
7229   }
7230 
7231   if (DefKind.isSpecialMember()
7232           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7233                                                   DefKind.asSpecialMember())
7234           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7235     FD->setInvalidDecl();
7236 }
7237 
7238 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7239                                                  CXXSpecialMember CSM) {
7240   CXXRecordDecl *RD = MD->getParent();
7241 
7242   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7243          "not an explicitly-defaulted special member");
7244 
7245   // Defer all checking for special members of a dependent type.
7246   if (RD->isDependentType())
7247     return false;
7248 
7249   // Whether this was the first-declared instance of the constructor.
7250   // This affects whether we implicitly add an exception spec and constexpr.
7251   bool First = MD == MD->getCanonicalDecl();
7252 
7253   bool HadError = false;
7254 
7255   // C++11 [dcl.fct.def.default]p1:
7256   //   A function that is explicitly defaulted shall
7257   //     -- be a special member function [...] (checked elsewhere),
7258   //     -- have the same type (except for ref-qualifiers, and except that a
7259   //        copy operation can take a non-const reference) as an implicit
7260   //        declaration, and
7261   //     -- not have default arguments.
7262   // C++2a changes the second bullet to instead delete the function if it's
7263   // defaulted on its first declaration, unless it's "an assignment operator,
7264   // and its return type differs or its parameter type is not a reference".
7265   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7266   bool ShouldDeleteForTypeMismatch = false;
7267   unsigned ExpectedParams = 1;
7268   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7269     ExpectedParams = 0;
7270   if (MD->getNumParams() != ExpectedParams) {
7271     // This checks for default arguments: a copy or move constructor with a
7272     // default argument is classified as a default constructor, and assignment
7273     // operations and destructors can't have default arguments.
7274     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7275       << CSM << MD->getSourceRange();
7276     HadError = true;
7277   } else if (MD->isVariadic()) {
7278     if (DeleteOnTypeMismatch)
7279       ShouldDeleteForTypeMismatch = true;
7280     else {
7281       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7282         << CSM << MD->getSourceRange();
7283       HadError = true;
7284     }
7285   }
7286 
7287   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7288 
7289   bool CanHaveConstParam = false;
7290   if (CSM == CXXCopyConstructor)
7291     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7292   else if (CSM == CXXCopyAssignment)
7293     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7294 
7295   QualType ReturnType = Context.VoidTy;
7296   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7297     // Check for return type matching.
7298     ReturnType = Type->getReturnType();
7299 
7300     QualType DeclType = Context.getTypeDeclType(RD);
7301     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7302     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7303 
7304     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7305       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7306         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7307       HadError = true;
7308     }
7309 
7310     // A defaulted special member cannot have cv-qualifiers.
7311     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7312       if (DeleteOnTypeMismatch)
7313         ShouldDeleteForTypeMismatch = true;
7314       else {
7315         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7316           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7317         HadError = true;
7318       }
7319     }
7320   }
7321 
7322   // Check for parameter type matching.
7323   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7324   bool HasConstParam = false;
7325   if (ExpectedParams && ArgType->isReferenceType()) {
7326     // Argument must be reference to possibly-const T.
7327     QualType ReferentType = ArgType->getPointeeType();
7328     HasConstParam = ReferentType.isConstQualified();
7329 
7330     if (ReferentType.isVolatileQualified()) {
7331       if (DeleteOnTypeMismatch)
7332         ShouldDeleteForTypeMismatch = true;
7333       else {
7334         Diag(MD->getLocation(),
7335              diag::err_defaulted_special_member_volatile_param) << CSM;
7336         HadError = true;
7337       }
7338     }
7339 
7340     if (HasConstParam && !CanHaveConstParam) {
7341       if (DeleteOnTypeMismatch)
7342         ShouldDeleteForTypeMismatch = true;
7343       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7344         Diag(MD->getLocation(),
7345              diag::err_defaulted_special_member_copy_const_param)
7346           << (CSM == CXXCopyAssignment);
7347         // FIXME: Explain why this special member can't be const.
7348         HadError = true;
7349       } else {
7350         Diag(MD->getLocation(),
7351              diag::err_defaulted_special_member_move_const_param)
7352           << (CSM == CXXMoveAssignment);
7353         HadError = true;
7354       }
7355     }
7356   } else if (ExpectedParams) {
7357     // A copy assignment operator can take its argument by value, but a
7358     // defaulted one cannot.
7359     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7360     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7361     HadError = true;
7362   }
7363 
7364   // C++11 [dcl.fct.def.default]p2:
7365   //   An explicitly-defaulted function may be declared constexpr only if it
7366   //   would have been implicitly declared as constexpr,
7367   // Do not apply this rule to members of class templates, since core issue 1358
7368   // makes such functions always instantiate to constexpr functions. For
7369   // functions which cannot be constexpr (for non-constructors in C++11 and for
7370   // destructors in C++14 and C++17), this is checked elsewhere.
7371   //
7372   // FIXME: This should not apply if the member is deleted.
7373   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7374                                                      HasConstParam);
7375   if ((getLangOpts().CPlusPlus20 ||
7376        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7377                                   : isa<CXXConstructorDecl>(MD))) &&
7378       MD->isConstexpr() && !Constexpr &&
7379       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7380     Diag(MD->getBeginLoc(), MD->isConsteval()
7381                                 ? diag::err_incorrect_defaulted_consteval
7382                                 : diag::err_incorrect_defaulted_constexpr)
7383         << CSM;
7384     // FIXME: Explain why the special member can't be constexpr.
7385     HadError = true;
7386   }
7387 
7388   if (First) {
7389     // C++2a [dcl.fct.def.default]p3:
7390     //   If a function is explicitly defaulted on its first declaration, it is
7391     //   implicitly considered to be constexpr if the implicit declaration
7392     //   would be.
7393     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7394                                           ? ConstexprSpecKind::Consteval
7395                                           : ConstexprSpecKind::Constexpr)
7396                                    : ConstexprSpecKind::Unspecified);
7397 
7398     if (!Type->hasExceptionSpec()) {
7399       // C++2a [except.spec]p3:
7400       //   If a declaration of a function does not have a noexcept-specifier
7401       //   [and] is defaulted on its first declaration, [...] the exception
7402       //   specification is as specified below
7403       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7404       EPI.ExceptionSpec.Type = EST_Unevaluated;
7405       EPI.ExceptionSpec.SourceDecl = MD;
7406       MD->setType(Context.getFunctionType(ReturnType,
7407                                           llvm::makeArrayRef(&ArgType,
7408                                                              ExpectedParams),
7409                                           EPI));
7410     }
7411   }
7412 
7413   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7414     if (First) {
7415       SetDeclDeleted(MD, MD->getLocation());
7416       if (!inTemplateInstantiation() && !HadError) {
7417         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7418         if (ShouldDeleteForTypeMismatch) {
7419           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7420         } else {
7421           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7422         }
7423       }
7424       if (ShouldDeleteForTypeMismatch && !HadError) {
7425         Diag(MD->getLocation(),
7426              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7427       }
7428     } else {
7429       // C++11 [dcl.fct.def.default]p4:
7430       //   [For a] user-provided explicitly-defaulted function [...] if such a
7431       //   function is implicitly defined as deleted, the program is ill-formed.
7432       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7433       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7434       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7435       HadError = true;
7436     }
7437   }
7438 
7439   return HadError;
7440 }
7441 
7442 namespace {
7443 /// Helper class for building and checking a defaulted comparison.
7444 ///
7445 /// Defaulted functions are built in two phases:
7446 ///
7447 ///  * First, the set of operations that the function will perform are
7448 ///    identified, and some of them are checked. If any of the checked
7449 ///    operations is invalid in certain ways, the comparison function is
7450 ///    defined as deleted and no body is built.
7451 ///  * Then, if the function is not defined as deleted, the body is built.
7452 ///
7453 /// This is accomplished by performing two visitation steps over the eventual
7454 /// body of the function.
7455 template<typename Derived, typename ResultList, typename Result,
7456          typename Subobject>
7457 class DefaultedComparisonVisitor {
7458 public:
7459   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7460 
7461   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7462                              DefaultedComparisonKind DCK)
7463       : S(S), RD(RD), FD(FD), DCK(DCK) {
7464     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7465       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7466       // UnresolvedSet to avoid this copy.
7467       Fns.assign(Info->getUnqualifiedLookups().begin(),
7468                  Info->getUnqualifiedLookups().end());
7469     }
7470   }
7471 
7472   ResultList visit() {
7473     // The type of an lvalue naming a parameter of this function.
7474     QualType ParamLvalType =
7475         FD->getParamDecl(0)->getType().getNonReferenceType();
7476 
7477     ResultList Results;
7478 
7479     switch (DCK) {
7480     case DefaultedComparisonKind::None:
7481       llvm_unreachable("not a defaulted comparison");
7482 
7483     case DefaultedComparisonKind::Equal:
7484     case DefaultedComparisonKind::ThreeWay:
7485       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7486       return Results;
7487 
7488     case DefaultedComparisonKind::NotEqual:
7489     case DefaultedComparisonKind::Relational:
7490       Results.add(getDerived().visitExpandedSubobject(
7491           ParamLvalType, getDerived().getCompleteObject()));
7492       return Results;
7493     }
7494     llvm_unreachable("");
7495   }
7496 
7497 protected:
7498   Derived &getDerived() { return static_cast<Derived&>(*this); }
7499 
7500   /// Visit the expanded list of subobjects of the given type, as specified in
7501   /// C++2a [class.compare.default].
7502   ///
7503   /// \return \c true if the ResultList object said we're done, \c false if not.
7504   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7505                        Qualifiers Quals) {
7506     // C++2a [class.compare.default]p4:
7507     //   The direct base class subobjects of C
7508     for (CXXBaseSpecifier &Base : Record->bases())
7509       if (Results.add(getDerived().visitSubobject(
7510               S.Context.getQualifiedType(Base.getType(), Quals),
7511               getDerived().getBase(&Base))))
7512         return true;
7513 
7514     //   followed by the non-static data members of C
7515     for (FieldDecl *Field : Record->fields()) {
7516       // Recursively expand anonymous structs.
7517       if (Field->isAnonymousStructOrUnion()) {
7518         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7519                             Quals))
7520           return true;
7521         continue;
7522       }
7523 
7524       // Figure out the type of an lvalue denoting this field.
7525       Qualifiers FieldQuals = Quals;
7526       if (Field->isMutable())
7527         FieldQuals.removeConst();
7528       QualType FieldType =
7529           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7530 
7531       if (Results.add(getDerived().visitSubobject(
7532               FieldType, getDerived().getField(Field))))
7533         return true;
7534     }
7535 
7536     //   form a list of subobjects.
7537     return false;
7538   }
7539 
7540   Result visitSubobject(QualType Type, Subobject Subobj) {
7541     //   In that list, any subobject of array type is recursively expanded
7542     const ArrayType *AT = S.Context.getAsArrayType(Type);
7543     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7544       return getDerived().visitSubobjectArray(CAT->getElementType(),
7545                                               CAT->getSize(), Subobj);
7546     return getDerived().visitExpandedSubobject(Type, Subobj);
7547   }
7548 
7549   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7550                              Subobject Subobj) {
7551     return getDerived().visitSubobject(Type, Subobj);
7552   }
7553 
7554 protected:
7555   Sema &S;
7556   CXXRecordDecl *RD;
7557   FunctionDecl *FD;
7558   DefaultedComparisonKind DCK;
7559   UnresolvedSet<16> Fns;
7560 };
7561 
7562 /// Information about a defaulted comparison, as determined by
7563 /// DefaultedComparisonAnalyzer.
7564 struct DefaultedComparisonInfo {
7565   bool Deleted = false;
7566   bool Constexpr = true;
7567   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7568 
7569   static DefaultedComparisonInfo deleted() {
7570     DefaultedComparisonInfo Deleted;
7571     Deleted.Deleted = true;
7572     return Deleted;
7573   }
7574 
7575   bool add(const DefaultedComparisonInfo &R) {
7576     Deleted |= R.Deleted;
7577     Constexpr &= R.Constexpr;
7578     Category = commonComparisonType(Category, R.Category);
7579     return Deleted;
7580   }
7581 };
7582 
7583 /// An element in the expanded list of subobjects of a defaulted comparison, as
7584 /// specified in C++2a [class.compare.default]p4.
7585 struct DefaultedComparisonSubobject {
7586   enum { CompleteObject, Member, Base } Kind;
7587   NamedDecl *Decl;
7588   SourceLocation Loc;
7589 };
7590 
7591 /// A visitor over the notional body of a defaulted comparison that determines
7592 /// whether that body would be deleted or constexpr.
7593 class DefaultedComparisonAnalyzer
7594     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7595                                         DefaultedComparisonInfo,
7596                                         DefaultedComparisonInfo,
7597                                         DefaultedComparisonSubobject> {
7598 public:
7599   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7600 
7601 private:
7602   DiagnosticKind Diagnose;
7603 
7604 public:
7605   using Base = DefaultedComparisonVisitor;
7606   using Result = DefaultedComparisonInfo;
7607   using Subobject = DefaultedComparisonSubobject;
7608 
7609   friend Base;
7610 
7611   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7612                               DefaultedComparisonKind DCK,
7613                               DiagnosticKind Diagnose = NoDiagnostics)
7614       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7615 
7616   Result visit() {
7617     if ((DCK == DefaultedComparisonKind::Equal ||
7618          DCK == DefaultedComparisonKind::ThreeWay) &&
7619         RD->hasVariantMembers()) {
7620       // C++2a [class.compare.default]p2 [P2002R0]:
7621       //   A defaulted comparison operator function for class C is defined as
7622       //   deleted if [...] C has variant members.
7623       if (Diagnose == ExplainDeleted) {
7624         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7625           << FD << RD->isUnion() << RD;
7626       }
7627       return Result::deleted();
7628     }
7629 
7630     return Base::visit();
7631   }
7632 
7633 private:
7634   Subobject getCompleteObject() {
7635     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7636   }
7637 
7638   Subobject getBase(CXXBaseSpecifier *Base) {
7639     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7640                      Base->getBaseTypeLoc()};
7641   }
7642 
7643   Subobject getField(FieldDecl *Field) {
7644     return Subobject{Subobject::Member, Field, Field->getLocation()};
7645   }
7646 
7647   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7648     // C++2a [class.compare.default]p2 [P2002R0]:
7649     //   A defaulted <=> or == operator function for class C is defined as
7650     //   deleted if any non-static data member of C is of reference type
7651     if (Type->isReferenceType()) {
7652       if (Diagnose == ExplainDeleted) {
7653         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7654             << FD << RD;
7655       }
7656       return Result::deleted();
7657     }
7658 
7659     // [...] Let xi be an lvalue denoting the ith element [...]
7660     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7661     Expr *Args[] = {&Xi, &Xi};
7662 
7663     // All operators start by trying to apply that same operator recursively.
7664     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7665     assert(OO != OO_None && "not an overloaded operator!");
7666     return visitBinaryOperator(OO, Args, Subobj);
7667   }
7668 
7669   Result
7670   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7671                       Subobject Subobj,
7672                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7673     // Note that there is no need to consider rewritten candidates here if
7674     // we've already found there is no viable 'operator<=>' candidate (and are
7675     // considering synthesizing a '<=>' from '==' and '<').
7676     OverloadCandidateSet CandidateSet(
7677         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7678         OverloadCandidateSet::OperatorRewriteInfo(
7679             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7680 
7681     /// C++2a [class.compare.default]p1 [P2002R0]:
7682     ///   [...] the defaulted function itself is never a candidate for overload
7683     ///   resolution [...]
7684     CandidateSet.exclude(FD);
7685 
7686     if (Args[0]->getType()->isOverloadableType())
7687       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7688     else {
7689       // FIXME: We determine whether this is a valid expression by checking to
7690       // see if there's a viable builtin operator candidate for it. That isn't
7691       // really what the rules ask us to do, but should give the right results.
7692       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7693     }
7694 
7695     Result R;
7696 
7697     OverloadCandidateSet::iterator Best;
7698     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7699     case OR_Success: {
7700       // C++2a [class.compare.secondary]p2 [P2002R0]:
7701       //   The operator function [...] is defined as deleted if [...] the
7702       //   candidate selected by overload resolution is not a rewritten
7703       //   candidate.
7704       if ((DCK == DefaultedComparisonKind::NotEqual ||
7705            DCK == DefaultedComparisonKind::Relational) &&
7706           !Best->RewriteKind) {
7707         if (Diagnose == ExplainDeleted) {
7708           S.Diag(Best->Function->getLocation(),
7709                  diag::note_defaulted_comparison_not_rewritten_callee)
7710               << FD;
7711         }
7712         return Result::deleted();
7713       }
7714 
7715       // Throughout C++2a [class.compare]: if overload resolution does not
7716       // result in a usable function, the candidate function is defined as
7717       // deleted. This requires that we selected an accessible function.
7718       //
7719       // Note that this only considers the access of the function when named
7720       // within the type of the subobject, and not the access path for any
7721       // derived-to-base conversion.
7722       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7723       if (ArgClass && Best->FoundDecl.getDecl() &&
7724           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7725         QualType ObjectType = Subobj.Kind == Subobject::Member
7726                                   ? Args[0]->getType()
7727                                   : S.Context.getRecordType(RD);
7728         if (!S.isMemberAccessibleForDeletion(
7729                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7730                 Diagnose == ExplainDeleted
7731                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7732                           << FD << Subobj.Kind << Subobj.Decl
7733                     : S.PDiag()))
7734           return Result::deleted();
7735       }
7736 
7737       // C++2a [class.compare.default]p3 [P2002R0]:
7738       //   A defaulted comparison function is constexpr-compatible if [...]
7739       //   no overlod resolution performed [...] results in a non-constexpr
7740       //   function.
7741       if (FunctionDecl *BestFD = Best->Function) {
7742         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7743         // If it's not constexpr, explain why not.
7744         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7745           if (Subobj.Kind != Subobject::CompleteObject)
7746             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7747               << Subobj.Kind << Subobj.Decl;
7748           S.Diag(BestFD->getLocation(),
7749                  diag::note_defaulted_comparison_not_constexpr_here);
7750           // Bail out after explaining; we don't want any more notes.
7751           return Result::deleted();
7752         }
7753         R.Constexpr &= BestFD->isConstexpr();
7754       }
7755 
7756       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7757         if (auto *BestFD = Best->Function) {
7758           // If any callee has an undeduced return type, deduce it now.
7759           // FIXME: It's not clear how a failure here should be handled. For
7760           // now, we produce an eager diagnostic, because that is forward
7761           // compatible with most (all?) other reasonable options.
7762           if (BestFD->getReturnType()->isUndeducedType() &&
7763               S.DeduceReturnType(BestFD, FD->getLocation(),
7764                                  /*Diagnose=*/false)) {
7765             // Don't produce a duplicate error when asked to explain why the
7766             // comparison is deleted: we diagnosed that when initially checking
7767             // the defaulted operator.
7768             if (Diagnose == NoDiagnostics) {
7769               S.Diag(
7770                   FD->getLocation(),
7771                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7772                   << Subobj.Kind << Subobj.Decl;
7773               S.Diag(
7774                   Subobj.Loc,
7775                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7776                   << Subobj.Kind << Subobj.Decl;
7777               S.Diag(BestFD->getLocation(),
7778                      diag::note_defaulted_comparison_cannot_deduce_callee)
7779                   << Subobj.Kind << Subobj.Decl;
7780             }
7781             return Result::deleted();
7782           }
7783           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7784               BestFD->getCallResultType())) {
7785             R.Category = Info->Kind;
7786           } else {
7787             if (Diagnose == ExplainDeleted) {
7788               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7789                   << Subobj.Kind << Subobj.Decl
7790                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7791               S.Diag(BestFD->getLocation(),
7792                      diag::note_defaulted_comparison_cannot_deduce_callee)
7793                   << Subobj.Kind << Subobj.Decl;
7794             }
7795             return Result::deleted();
7796           }
7797         } else {
7798           Optional<ComparisonCategoryType> Cat =
7799               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7800           assert(Cat && "no category for builtin comparison?");
7801           R.Category = *Cat;
7802         }
7803       }
7804 
7805       // Note that we might be rewriting to a different operator. That call is
7806       // not considered until we come to actually build the comparison function.
7807       break;
7808     }
7809 
7810     case OR_Ambiguous:
7811       if (Diagnose == ExplainDeleted) {
7812         unsigned Kind = 0;
7813         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7814           Kind = OO == OO_EqualEqual ? 1 : 2;
7815         CandidateSet.NoteCandidates(
7816             PartialDiagnosticAt(
7817                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7818                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7819             S, OCD_AmbiguousCandidates, Args);
7820       }
7821       R = Result::deleted();
7822       break;
7823 
7824     case OR_Deleted:
7825       if (Diagnose == ExplainDeleted) {
7826         if ((DCK == DefaultedComparisonKind::NotEqual ||
7827              DCK == DefaultedComparisonKind::Relational) &&
7828             !Best->RewriteKind) {
7829           S.Diag(Best->Function->getLocation(),
7830                  diag::note_defaulted_comparison_not_rewritten_callee)
7831               << FD;
7832         } else {
7833           S.Diag(Subobj.Loc,
7834                  diag::note_defaulted_comparison_calls_deleted)
7835               << FD << Subobj.Kind << Subobj.Decl;
7836           S.NoteDeletedFunction(Best->Function);
7837         }
7838       }
7839       R = Result::deleted();
7840       break;
7841 
7842     case OR_No_Viable_Function:
7843       // If there's no usable candidate, we're done unless we can rewrite a
7844       // '<=>' in terms of '==' and '<'.
7845       if (OO == OO_Spaceship &&
7846           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7847         // For any kind of comparison category return type, we need a usable
7848         // '==' and a usable '<'.
7849         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7850                                        &CandidateSet)))
7851           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7852         break;
7853       }
7854 
7855       if (Diagnose == ExplainDeleted) {
7856         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7857             << FD << Subobj.Kind << Subobj.Decl;
7858 
7859         // For a three-way comparison, list both the candidates for the
7860         // original operator and the candidates for the synthesized operator.
7861         if (SpaceshipCandidates) {
7862           SpaceshipCandidates->NoteCandidates(
7863               S, Args,
7864               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7865                                                       Args, FD->getLocation()));
7866           S.Diag(Subobj.Loc,
7867                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7868               << (OO == OO_EqualEqual ? 0 : 1);
7869         }
7870 
7871         CandidateSet.NoteCandidates(
7872             S, Args,
7873             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7874                                             FD->getLocation()));
7875       }
7876       R = Result::deleted();
7877       break;
7878     }
7879 
7880     return R;
7881   }
7882 };
7883 
7884 /// A list of statements.
7885 struct StmtListResult {
7886   bool IsInvalid = false;
7887   llvm::SmallVector<Stmt*, 16> Stmts;
7888 
7889   bool add(const StmtResult &S) {
7890     IsInvalid |= S.isInvalid();
7891     if (IsInvalid)
7892       return true;
7893     Stmts.push_back(S.get());
7894     return false;
7895   }
7896 };
7897 
7898 /// A visitor over the notional body of a defaulted comparison that synthesizes
7899 /// the actual body.
7900 class DefaultedComparisonSynthesizer
7901     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7902                                         StmtListResult, StmtResult,
7903                                         std::pair<ExprResult, ExprResult>> {
7904   SourceLocation Loc;
7905   unsigned ArrayDepth = 0;
7906 
7907 public:
7908   using Base = DefaultedComparisonVisitor;
7909   using ExprPair = std::pair<ExprResult, ExprResult>;
7910 
7911   friend Base;
7912 
7913   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7914                                  DefaultedComparisonKind DCK,
7915                                  SourceLocation BodyLoc)
7916       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7917 
7918   /// Build a suitable function body for this defaulted comparison operator.
7919   StmtResult build() {
7920     Sema::CompoundScopeRAII CompoundScope(S);
7921 
7922     StmtListResult Stmts = visit();
7923     if (Stmts.IsInvalid)
7924       return StmtError();
7925 
7926     ExprResult RetVal;
7927     switch (DCK) {
7928     case DefaultedComparisonKind::None:
7929       llvm_unreachable("not a defaulted comparison");
7930 
7931     case DefaultedComparisonKind::Equal: {
7932       // C++2a [class.eq]p3:
7933       //   [...] compar[e] the corresponding elements [...] until the first
7934       //   index i where xi == yi yields [...] false. If no such index exists,
7935       //   V is true. Otherwise, V is false.
7936       //
7937       // Join the comparisons with '&&'s and return the result. Use a right
7938       // fold (traversing the conditions right-to-left), because that
7939       // short-circuits more naturally.
7940       auto OldStmts = std::move(Stmts.Stmts);
7941       Stmts.Stmts.clear();
7942       ExprResult CmpSoFar;
7943       // Finish a particular comparison chain.
7944       auto FinishCmp = [&] {
7945         if (Expr *Prior = CmpSoFar.get()) {
7946           // Convert the last expression to 'return ...;'
7947           if (RetVal.isUnset() && Stmts.Stmts.empty())
7948             RetVal = CmpSoFar;
7949           // Convert any prior comparison to 'if (!(...)) return false;'
7950           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7951             return true;
7952           CmpSoFar = ExprResult();
7953         }
7954         return false;
7955       };
7956       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7957         Expr *E = dyn_cast<Expr>(EAsStmt);
7958         if (!E) {
7959           // Found an array comparison.
7960           if (FinishCmp() || Stmts.add(EAsStmt))
7961             return StmtError();
7962           continue;
7963         }
7964 
7965         if (CmpSoFar.isUnset()) {
7966           CmpSoFar = E;
7967           continue;
7968         }
7969         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7970         if (CmpSoFar.isInvalid())
7971           return StmtError();
7972       }
7973       if (FinishCmp())
7974         return StmtError();
7975       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7976       //   If no such index exists, V is true.
7977       if (RetVal.isUnset())
7978         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7979       break;
7980     }
7981 
7982     case DefaultedComparisonKind::ThreeWay: {
7983       // Per C++2a [class.spaceship]p3, as a fallback add:
7984       // return static_cast<R>(std::strong_ordering::equal);
7985       QualType StrongOrdering = S.CheckComparisonCategoryType(
7986           ComparisonCategoryType::StrongOrdering, Loc,
7987           Sema::ComparisonCategoryUsage::DefaultedOperator);
7988       if (StrongOrdering.isNull())
7989         return StmtError();
7990       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7991                              .getValueInfo(ComparisonCategoryResult::Equal)
7992                              ->VD;
7993       RetVal = getDecl(EqualVD);
7994       if (RetVal.isInvalid())
7995         return StmtError();
7996       RetVal = buildStaticCastToR(RetVal.get());
7997       break;
7998     }
7999 
8000     case DefaultedComparisonKind::NotEqual:
8001     case DefaultedComparisonKind::Relational:
8002       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8003       break;
8004     }
8005 
8006     // Build the final return statement.
8007     if (RetVal.isInvalid())
8008       return StmtError();
8009     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8010     if (ReturnStmt.isInvalid())
8011       return StmtError();
8012     Stmts.Stmts.push_back(ReturnStmt.get());
8013 
8014     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8015   }
8016 
8017 private:
8018   ExprResult getDecl(ValueDecl *VD) {
8019     return S.BuildDeclarationNameExpr(
8020         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8021   }
8022 
8023   ExprResult getParam(unsigned I) {
8024     ParmVarDecl *PD = FD->getParamDecl(I);
8025     return getDecl(PD);
8026   }
8027 
8028   ExprPair getCompleteObject() {
8029     unsigned Param = 0;
8030     ExprResult LHS;
8031     if (isa<CXXMethodDecl>(FD)) {
8032       // LHS is '*this'.
8033       LHS = S.ActOnCXXThis(Loc);
8034       if (!LHS.isInvalid())
8035         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8036     } else {
8037       LHS = getParam(Param++);
8038     }
8039     ExprResult RHS = getParam(Param++);
8040     assert(Param == FD->getNumParams());
8041     return {LHS, RHS};
8042   }
8043 
8044   ExprPair getBase(CXXBaseSpecifier *Base) {
8045     ExprPair Obj = getCompleteObject();
8046     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8047       return {ExprError(), ExprError()};
8048     CXXCastPath Path = {Base};
8049     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8050                                 CK_DerivedToBase, VK_LValue, &Path),
8051             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8052                                 CK_DerivedToBase, VK_LValue, &Path)};
8053   }
8054 
8055   ExprPair getField(FieldDecl *Field) {
8056     ExprPair Obj = getCompleteObject();
8057     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8058       return {ExprError(), ExprError()};
8059 
8060     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8061     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8062     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8063                                       CXXScopeSpec(), Field, Found, NameInfo),
8064             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8065                                       CXXScopeSpec(), Field, Found, NameInfo)};
8066   }
8067 
8068   // FIXME: When expanding a subobject, register a note in the code synthesis
8069   // stack to say which subobject we're comparing.
8070 
8071   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8072     if (Cond.isInvalid())
8073       return StmtError();
8074 
8075     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8076     if (NotCond.isInvalid())
8077       return StmtError();
8078 
8079     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8080     assert(!False.isInvalid() && "should never fail");
8081     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8082     if (ReturnFalse.isInvalid())
8083       return StmtError();
8084 
8085     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8086                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8087                                           Sema::ConditionKind::Boolean),
8088                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8089   }
8090 
8091   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8092                                  ExprPair Subobj) {
8093     QualType SizeType = S.Context.getSizeType();
8094     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8095 
8096     // Build 'size_t i$n = 0'.
8097     IdentifierInfo *IterationVarName = nullptr;
8098     {
8099       SmallString<8> Str;
8100       llvm::raw_svector_ostream OS(Str);
8101       OS << "i" << ArrayDepth;
8102       IterationVarName = &S.Context.Idents.get(OS.str());
8103     }
8104     VarDecl *IterationVar = VarDecl::Create(
8105         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8106         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8107     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8108     IterationVar->setInit(
8109         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8110     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8111 
8112     auto IterRef = [&] {
8113       ExprResult Ref = S.BuildDeclarationNameExpr(
8114           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8115           IterationVar);
8116       assert(!Ref.isInvalid() && "can't reference our own variable?");
8117       return Ref.get();
8118     };
8119 
8120     // Build 'i$n != Size'.
8121     ExprResult Cond = S.CreateBuiltinBinOp(
8122         Loc, BO_NE, IterRef(),
8123         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8124     assert(!Cond.isInvalid() && "should never fail");
8125 
8126     // Build '++i$n'.
8127     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8128     assert(!Inc.isInvalid() && "should never fail");
8129 
8130     // Build 'a[i$n]' and 'b[i$n]'.
8131     auto Index = [&](ExprResult E) {
8132       if (E.isInvalid())
8133         return ExprError();
8134       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8135     };
8136     Subobj.first = Index(Subobj.first);
8137     Subobj.second = Index(Subobj.second);
8138 
8139     // Compare the array elements.
8140     ++ArrayDepth;
8141     StmtResult Substmt = visitSubobject(Type, Subobj);
8142     --ArrayDepth;
8143 
8144     if (Substmt.isInvalid())
8145       return StmtError();
8146 
8147     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8148     // For outer levels or for an 'operator<=>' we already have a suitable
8149     // statement that returns as necessary.
8150     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8151       assert(DCK == DefaultedComparisonKind::Equal &&
8152              "should have non-expression statement");
8153       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8154       if (Substmt.isInvalid())
8155         return StmtError();
8156     }
8157 
8158     // Build 'for (...) ...'
8159     return S.ActOnForStmt(Loc, Loc, Init,
8160                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8161                                            Sema::ConditionKind::Boolean),
8162                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8163                           Substmt.get());
8164   }
8165 
8166   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8167     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8168       return StmtError();
8169 
8170     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8171     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8172     ExprResult Op;
8173     if (Type->isOverloadableType())
8174       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8175                                    Obj.second.get(), /*PerformADL=*/true,
8176                                    /*AllowRewrittenCandidates=*/true, FD);
8177     else
8178       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8179     if (Op.isInvalid())
8180       return StmtError();
8181 
8182     switch (DCK) {
8183     case DefaultedComparisonKind::None:
8184       llvm_unreachable("not a defaulted comparison");
8185 
8186     case DefaultedComparisonKind::Equal:
8187       // Per C++2a [class.eq]p2, each comparison is individually contextually
8188       // converted to bool.
8189       Op = S.PerformContextuallyConvertToBool(Op.get());
8190       if (Op.isInvalid())
8191         return StmtError();
8192       return Op.get();
8193 
8194     case DefaultedComparisonKind::ThreeWay: {
8195       // Per C++2a [class.spaceship]p3, form:
8196       //   if (R cmp = static_cast<R>(op); cmp != 0)
8197       //     return cmp;
8198       QualType R = FD->getReturnType();
8199       Op = buildStaticCastToR(Op.get());
8200       if (Op.isInvalid())
8201         return StmtError();
8202 
8203       // R cmp = ...;
8204       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8205       VarDecl *VD =
8206           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8207                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8208       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8209       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8210 
8211       // cmp != 0
8212       ExprResult VDRef = getDecl(VD);
8213       if (VDRef.isInvalid())
8214         return StmtError();
8215       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8216       Expr *Zero =
8217           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8218       ExprResult Comp;
8219       if (VDRef.get()->getType()->isOverloadableType())
8220         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8221                                        true, FD);
8222       else
8223         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8224       if (Comp.isInvalid())
8225         return StmtError();
8226       Sema::ConditionResult Cond = S.ActOnCondition(
8227           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8228       if (Cond.isInvalid())
8229         return StmtError();
8230 
8231       // return cmp;
8232       VDRef = getDecl(VD);
8233       if (VDRef.isInvalid())
8234         return StmtError();
8235       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8236       if (ReturnStmt.isInvalid())
8237         return StmtError();
8238 
8239       // if (...)
8240       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8241                            ReturnStmt.get(),
8242                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8243     }
8244 
8245     case DefaultedComparisonKind::NotEqual:
8246     case DefaultedComparisonKind::Relational:
8247       // C++2a [class.compare.secondary]p2:
8248       //   Otherwise, the operator function yields x @ y.
8249       return Op.get();
8250     }
8251     llvm_unreachable("");
8252   }
8253 
8254   /// Build "static_cast<R>(E)".
8255   ExprResult buildStaticCastToR(Expr *E) {
8256     QualType R = FD->getReturnType();
8257     assert(!R->isUndeducedType() && "type should have been deduced already");
8258 
8259     // Don't bother forming a no-op cast in the common case.
8260     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8261       return E;
8262     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8263                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8264                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8265   }
8266 };
8267 }
8268 
8269 /// Perform the unqualified lookups that might be needed to form a defaulted
8270 /// comparison function for the given operator.
8271 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8272                                                   UnresolvedSetImpl &Operators,
8273                                                   OverloadedOperatorKind Op) {
8274   auto Lookup = [&](OverloadedOperatorKind OO) {
8275     Self.LookupOverloadedOperatorName(OO, S, Operators);
8276   };
8277 
8278   // Every defaulted operator looks up itself.
8279   Lookup(Op);
8280   // ... and the rewritten form of itself, if any.
8281   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8282     Lookup(ExtraOp);
8283 
8284   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8285   // synthesize a three-way comparison from '<' and '=='. In a dependent
8286   // context, we also need to look up '==' in case we implicitly declare a
8287   // defaulted 'operator=='.
8288   if (Op == OO_Spaceship) {
8289     Lookup(OO_ExclaimEqual);
8290     Lookup(OO_Less);
8291     Lookup(OO_EqualEqual);
8292   }
8293 }
8294 
8295 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8296                                               DefaultedComparisonKind DCK) {
8297   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8298 
8299   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8300   assert(RD && "defaulted comparison is not defaulted in a class");
8301 
8302   // Perform any unqualified lookups we're going to need to default this
8303   // function.
8304   if (S) {
8305     UnresolvedSet<32> Operators;
8306     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8307                                           FD->getOverloadedOperator());
8308     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8309         Context, Operators.pairs()));
8310   }
8311 
8312   // C++2a [class.compare.default]p1:
8313   //   A defaulted comparison operator function for some class C shall be a
8314   //   non-template function declared in the member-specification of C that is
8315   //    -- a non-static const member of C having one parameter of type
8316   //       const C&, or
8317   //    -- a friend of C having two parameters of type const C& or two
8318   //       parameters of type C.
8319   QualType ExpectedParmType1 = Context.getRecordType(RD);
8320   QualType ExpectedParmType2 =
8321       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8322   if (isa<CXXMethodDecl>(FD))
8323     ExpectedParmType1 = ExpectedParmType2;
8324   for (const ParmVarDecl *Param : FD->parameters()) {
8325     if (!Param->getType()->isDependentType() &&
8326         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8327         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8328       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8329       // corresponding defaulted 'operator<=>' already.
8330       if (!FD->isImplicit()) {
8331         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8332             << (int)DCK << Param->getType() << ExpectedParmType1
8333             << !isa<CXXMethodDecl>(FD)
8334             << ExpectedParmType2 << Param->getSourceRange();
8335       }
8336       return true;
8337     }
8338   }
8339   if (FD->getNumParams() == 2 &&
8340       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8341                            FD->getParamDecl(1)->getType())) {
8342     if (!FD->isImplicit()) {
8343       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8344           << (int)DCK
8345           << FD->getParamDecl(0)->getType()
8346           << FD->getParamDecl(0)->getSourceRange()
8347           << FD->getParamDecl(1)->getType()
8348           << FD->getParamDecl(1)->getSourceRange();
8349     }
8350     return true;
8351   }
8352 
8353   // ... non-static const member ...
8354   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8355     assert(!MD->isStatic() && "comparison function cannot be a static member");
8356     if (!MD->isConst()) {
8357       SourceLocation InsertLoc;
8358       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8359         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8360       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8361       // corresponding defaulted 'operator<=>' already.
8362       if (!MD->isImplicit()) {
8363         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8364           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8365       }
8366 
8367       // Add the 'const' to the type to recover.
8368       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8369       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8370       EPI.TypeQuals.addConst();
8371       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8372                                           FPT->getParamTypes(), EPI));
8373     }
8374   } else {
8375     // A non-member function declared in a class must be a friend.
8376     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8377   }
8378 
8379   // C++2a [class.eq]p1, [class.rel]p1:
8380   //   A [defaulted comparison other than <=>] shall have a declared return
8381   //   type bool.
8382   if (DCK != DefaultedComparisonKind::ThreeWay &&
8383       !FD->getDeclaredReturnType()->isDependentType() &&
8384       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8385     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8386         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8387         << FD->getReturnTypeSourceRange();
8388     return true;
8389   }
8390   // C++2a [class.spaceship]p2 [P2002R0]:
8391   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8392   //   R shall not contain a placeholder type.
8393   if (DCK == DefaultedComparisonKind::ThreeWay &&
8394       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8395       !Context.hasSameType(FD->getDeclaredReturnType(),
8396                            Context.getAutoDeductType())) {
8397     Diag(FD->getLocation(),
8398          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8399         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8400         << FD->getReturnTypeSourceRange();
8401     return true;
8402   }
8403 
8404   // For a defaulted function in a dependent class, defer all remaining checks
8405   // until instantiation.
8406   if (RD->isDependentType())
8407     return false;
8408 
8409   // Determine whether the function should be defined as deleted.
8410   DefaultedComparisonInfo Info =
8411       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8412 
8413   bool First = FD == FD->getCanonicalDecl();
8414 
8415   // If we want to delete the function, then do so; there's nothing else to
8416   // check in that case.
8417   if (Info.Deleted) {
8418     if (!First) {
8419       // C++11 [dcl.fct.def.default]p4:
8420       //   [For a] user-provided explicitly-defaulted function [...] if such a
8421       //   function is implicitly defined as deleted, the program is ill-formed.
8422       //
8423       // This is really just a consequence of the general rule that you can
8424       // only delete a function on its first declaration.
8425       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8426           << FD->isImplicit() << (int)DCK;
8427       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8428                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8429           .visit();
8430       return true;
8431     }
8432 
8433     SetDeclDeleted(FD, FD->getLocation());
8434     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8435       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8436           << (int)DCK;
8437       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8438                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8439           .visit();
8440     }
8441     return false;
8442   }
8443 
8444   // C++2a [class.spaceship]p2:
8445   //   The return type is deduced as the common comparison type of R0, R1, ...
8446   if (DCK == DefaultedComparisonKind::ThreeWay &&
8447       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8448     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8449     if (RetLoc.isInvalid())
8450       RetLoc = FD->getBeginLoc();
8451     // FIXME: Should we really care whether we have the complete type and the
8452     // 'enumerator' constants here? A forward declaration seems sufficient.
8453     QualType Cat = CheckComparisonCategoryType(
8454         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8455     if (Cat.isNull())
8456       return true;
8457     Context.adjustDeducedFunctionResultType(
8458         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8459   }
8460 
8461   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8462   //   An explicitly-defaulted function that is not defined as deleted may be
8463   //   declared constexpr or consteval only if it is constexpr-compatible.
8464   // C++2a [class.compare.default]p3 [P2002R0]:
8465   //   A defaulted comparison function is constexpr-compatible if it satisfies
8466   //   the requirements for a constexpr function [...]
8467   // The only relevant requirements are that the parameter and return types are
8468   // literal types. The remaining conditions are checked by the analyzer.
8469   if (FD->isConstexpr()) {
8470     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8471         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8472         !Info.Constexpr) {
8473       Diag(FD->getBeginLoc(),
8474            diag::err_incorrect_defaulted_comparison_constexpr)
8475           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8476       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8477                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8478           .visit();
8479     }
8480   }
8481 
8482   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8483   //   If a constexpr-compatible function is explicitly defaulted on its first
8484   //   declaration, it is implicitly considered to be constexpr.
8485   // FIXME: Only applying this to the first declaration seems problematic, as
8486   // simple reorderings can affect the meaning of the program.
8487   if (First && !FD->isConstexpr() && Info.Constexpr)
8488     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8489 
8490   // C++2a [except.spec]p3:
8491   //   If a declaration of a function does not have a noexcept-specifier
8492   //   [and] is defaulted on its first declaration, [...] the exception
8493   //   specification is as specified below
8494   if (FD->getExceptionSpecType() == EST_None) {
8495     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8496     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8497     EPI.ExceptionSpec.Type = EST_Unevaluated;
8498     EPI.ExceptionSpec.SourceDecl = FD;
8499     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8500                                         FPT->getParamTypes(), EPI));
8501   }
8502 
8503   return false;
8504 }
8505 
8506 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8507                                              FunctionDecl *Spaceship) {
8508   Sema::CodeSynthesisContext Ctx;
8509   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8510   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8511   Ctx.Entity = Spaceship;
8512   pushCodeSynthesisContext(Ctx);
8513 
8514   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8515     EqualEqual->setImplicit();
8516 
8517   popCodeSynthesisContext();
8518 }
8519 
8520 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8521                                      DefaultedComparisonKind DCK) {
8522   assert(FD->isDefaulted() && !FD->isDeleted() &&
8523          !FD->doesThisDeclarationHaveABody());
8524   if (FD->willHaveBody() || FD->isInvalidDecl())
8525     return;
8526 
8527   SynthesizedFunctionScope Scope(*this, FD);
8528 
8529   // Add a context note for diagnostics produced after this point.
8530   Scope.addContextNote(UseLoc);
8531 
8532   {
8533     // Build and set up the function body.
8534     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8535     SourceLocation BodyLoc =
8536         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8537     StmtResult Body =
8538         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8539     if (Body.isInvalid()) {
8540       FD->setInvalidDecl();
8541       return;
8542     }
8543     FD->setBody(Body.get());
8544     FD->markUsed(Context);
8545   }
8546 
8547   // The exception specification is needed because we are defining the
8548   // function. Note that this will reuse the body we just built.
8549   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8550 
8551   if (ASTMutationListener *L = getASTMutationListener())
8552     L->CompletedImplicitDefinition(FD);
8553 }
8554 
8555 static Sema::ImplicitExceptionSpecification
8556 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8557                                         FunctionDecl *FD,
8558                                         Sema::DefaultedComparisonKind DCK) {
8559   ComputingExceptionSpec CES(S, FD, Loc);
8560   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8561 
8562   if (FD->isInvalidDecl())
8563     return ExceptSpec;
8564 
8565   // The common case is that we just defined the comparison function. In that
8566   // case, just look at whether the body can throw.
8567   if (FD->hasBody()) {
8568     ExceptSpec.CalledStmt(FD->getBody());
8569   } else {
8570     // Otherwise, build a body so we can check it. This should ideally only
8571     // happen when we're not actually marking the function referenced. (This is
8572     // only really important for efficiency: we don't want to build and throw
8573     // away bodies for comparison functions more than we strictly need to.)
8574 
8575     // Pretend to synthesize the function body in an unevaluated context.
8576     // Note that we can't actually just go ahead and define the function here:
8577     // we are not permitted to mark its callees as referenced.
8578     Sema::SynthesizedFunctionScope Scope(S, FD);
8579     EnterExpressionEvaluationContext Context(
8580         S, Sema::ExpressionEvaluationContext::Unevaluated);
8581 
8582     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8583     SourceLocation BodyLoc =
8584         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8585     StmtResult Body =
8586         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8587     if (!Body.isInvalid())
8588       ExceptSpec.CalledStmt(Body.get());
8589 
8590     // FIXME: Can we hold onto this body and just transform it to potentially
8591     // evaluated when we're asked to define the function rather than rebuilding
8592     // it? Either that, or we should only build the bits of the body that we
8593     // need (the expressions, not the statements).
8594   }
8595 
8596   return ExceptSpec;
8597 }
8598 
8599 void Sema::CheckDelayedMemberExceptionSpecs() {
8600   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8601   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8602 
8603   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8604   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8605 
8606   // Perform any deferred checking of exception specifications for virtual
8607   // destructors.
8608   for (auto &Check : Overriding)
8609     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8610 
8611   // Perform any deferred checking of exception specifications for befriended
8612   // special members.
8613   for (auto &Check : Equivalent)
8614     CheckEquivalentExceptionSpec(Check.second, Check.first);
8615 }
8616 
8617 namespace {
8618 /// CRTP base class for visiting operations performed by a special member
8619 /// function (or inherited constructor).
8620 template<typename Derived>
8621 struct SpecialMemberVisitor {
8622   Sema &S;
8623   CXXMethodDecl *MD;
8624   Sema::CXXSpecialMember CSM;
8625   Sema::InheritedConstructorInfo *ICI;
8626 
8627   // Properties of the special member, computed for convenience.
8628   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8629 
8630   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8631                        Sema::InheritedConstructorInfo *ICI)
8632       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8633     switch (CSM) {
8634     case Sema::CXXDefaultConstructor:
8635     case Sema::CXXCopyConstructor:
8636     case Sema::CXXMoveConstructor:
8637       IsConstructor = true;
8638       break;
8639     case Sema::CXXCopyAssignment:
8640     case Sema::CXXMoveAssignment:
8641       IsAssignment = true;
8642       break;
8643     case Sema::CXXDestructor:
8644       break;
8645     case Sema::CXXInvalid:
8646       llvm_unreachable("invalid special member kind");
8647     }
8648 
8649     if (MD->getNumParams()) {
8650       if (const ReferenceType *RT =
8651               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8652         ConstArg = RT->getPointeeType().isConstQualified();
8653     }
8654   }
8655 
8656   Derived &getDerived() { return static_cast<Derived&>(*this); }
8657 
8658   /// Is this a "move" special member?
8659   bool isMove() const {
8660     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8661   }
8662 
8663   /// Look up the corresponding special member in the given class.
8664   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8665                                              unsigned Quals, bool IsMutable) {
8666     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8667                                        ConstArg && !IsMutable);
8668   }
8669 
8670   /// Look up the constructor for the specified base class to see if it's
8671   /// overridden due to this being an inherited constructor.
8672   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8673     if (!ICI)
8674       return {};
8675     assert(CSM == Sema::CXXDefaultConstructor);
8676     auto *BaseCtor =
8677       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8678     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8679       return MD;
8680     return {};
8681   }
8682 
8683   /// A base or member subobject.
8684   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8685 
8686   /// Get the location to use for a subobject in diagnostics.
8687   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8688     // FIXME: For an indirect virtual base, the direct base leading to
8689     // the indirect virtual base would be a more useful choice.
8690     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8691       return B->getBaseTypeLoc();
8692     else
8693       return Subobj.get<FieldDecl*>()->getLocation();
8694   }
8695 
8696   enum BasesToVisit {
8697     /// Visit all non-virtual (direct) bases.
8698     VisitNonVirtualBases,
8699     /// Visit all direct bases, virtual or not.
8700     VisitDirectBases,
8701     /// Visit all non-virtual bases, and all virtual bases if the class
8702     /// is not abstract.
8703     VisitPotentiallyConstructedBases,
8704     /// Visit all direct or virtual bases.
8705     VisitAllBases
8706   };
8707 
8708   // Visit the bases and members of the class.
8709   bool visit(BasesToVisit Bases) {
8710     CXXRecordDecl *RD = MD->getParent();
8711 
8712     if (Bases == VisitPotentiallyConstructedBases)
8713       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8714 
8715     for (auto &B : RD->bases())
8716       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8717           getDerived().visitBase(&B))
8718         return true;
8719 
8720     if (Bases == VisitAllBases)
8721       for (auto &B : RD->vbases())
8722         if (getDerived().visitBase(&B))
8723           return true;
8724 
8725     for (auto *F : RD->fields())
8726       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8727           getDerived().visitField(F))
8728         return true;
8729 
8730     return false;
8731   }
8732 };
8733 }
8734 
8735 namespace {
8736 struct SpecialMemberDeletionInfo
8737     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8738   bool Diagnose;
8739 
8740   SourceLocation Loc;
8741 
8742   bool AllFieldsAreConst;
8743 
8744   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8745                             Sema::CXXSpecialMember CSM,
8746                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8747       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8748         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8749 
8750   bool inUnion() const { return MD->getParent()->isUnion(); }
8751 
8752   Sema::CXXSpecialMember getEffectiveCSM() {
8753     return ICI ? Sema::CXXInvalid : CSM;
8754   }
8755 
8756   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8757 
8758   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8759   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8760 
8761   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8762   bool shouldDeleteForField(FieldDecl *FD);
8763   bool shouldDeleteForAllConstMembers();
8764 
8765   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8766                                      unsigned Quals);
8767   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8768                                     Sema::SpecialMemberOverloadResult SMOR,
8769                                     bool IsDtorCallInCtor);
8770 
8771   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8772 };
8773 }
8774 
8775 /// Is the given special member inaccessible when used on the given
8776 /// sub-object.
8777 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8778                                              CXXMethodDecl *target) {
8779   /// If we're operating on a base class, the object type is the
8780   /// type of this special member.
8781   QualType objectTy;
8782   AccessSpecifier access = target->getAccess();
8783   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8784     objectTy = S.Context.getTypeDeclType(MD->getParent());
8785     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8786 
8787   // If we're operating on a field, the object type is the type of the field.
8788   } else {
8789     objectTy = S.Context.getTypeDeclType(target->getParent());
8790   }
8791 
8792   return S.isMemberAccessibleForDeletion(
8793       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8794 }
8795 
8796 /// Check whether we should delete a special member due to the implicit
8797 /// definition containing a call to a special member of a subobject.
8798 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8799     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8800     bool IsDtorCallInCtor) {
8801   CXXMethodDecl *Decl = SMOR.getMethod();
8802   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8803 
8804   int DiagKind = -1;
8805 
8806   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8807     DiagKind = !Decl ? 0 : 1;
8808   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8809     DiagKind = 2;
8810   else if (!isAccessible(Subobj, Decl))
8811     DiagKind = 3;
8812   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8813            !Decl->isTrivial()) {
8814     // A member of a union must have a trivial corresponding special member.
8815     // As a weird special case, a destructor call from a union's constructor
8816     // must be accessible and non-deleted, but need not be trivial. Such a
8817     // destructor is never actually called, but is semantically checked as
8818     // if it were.
8819     DiagKind = 4;
8820   }
8821 
8822   if (DiagKind == -1)
8823     return false;
8824 
8825   if (Diagnose) {
8826     if (Field) {
8827       S.Diag(Field->getLocation(),
8828              diag::note_deleted_special_member_class_subobject)
8829         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8830         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8831     } else {
8832       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8833       S.Diag(Base->getBeginLoc(),
8834              diag::note_deleted_special_member_class_subobject)
8835           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8836           << Base->getType() << DiagKind << IsDtorCallInCtor
8837           << /*IsObjCPtr*/false;
8838     }
8839 
8840     if (DiagKind == 1)
8841       S.NoteDeletedFunction(Decl);
8842     // FIXME: Explain inaccessibility if DiagKind == 3.
8843   }
8844 
8845   return true;
8846 }
8847 
8848 /// Check whether we should delete a special member function due to having a
8849 /// direct or virtual base class or non-static data member of class type M.
8850 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8851     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8852   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8853   bool IsMutable = Field && Field->isMutable();
8854 
8855   // C++11 [class.ctor]p5:
8856   // -- any direct or virtual base class, or non-static data member with no
8857   //    brace-or-equal-initializer, has class type M (or array thereof) and
8858   //    either M has no default constructor or overload resolution as applied
8859   //    to M's default constructor results in an ambiguity or in a function
8860   //    that is deleted or inaccessible
8861   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8862   // -- a direct or virtual base class B that cannot be copied/moved because
8863   //    overload resolution, as applied to B's corresponding special member,
8864   //    results in an ambiguity or a function that is deleted or inaccessible
8865   //    from the defaulted special member
8866   // C++11 [class.dtor]p5:
8867   // -- any direct or virtual base class [...] has a type with a destructor
8868   //    that is deleted or inaccessible
8869   if (!(CSM == Sema::CXXDefaultConstructor &&
8870         Field && Field->hasInClassInitializer()) &&
8871       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8872                                    false))
8873     return true;
8874 
8875   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8876   // -- any direct or virtual base class or non-static data member has a
8877   //    type with a destructor that is deleted or inaccessible
8878   if (IsConstructor) {
8879     Sema::SpecialMemberOverloadResult SMOR =
8880         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8881                               false, false, false, false, false);
8882     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8883       return true;
8884   }
8885 
8886   return false;
8887 }
8888 
8889 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8890     FieldDecl *FD, QualType FieldType) {
8891   // The defaulted special functions are defined as deleted if this is a variant
8892   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8893   // type under ARC.
8894   if (!FieldType.hasNonTrivialObjCLifetime())
8895     return false;
8896 
8897   // Don't make the defaulted default constructor defined as deleted if the
8898   // member has an in-class initializer.
8899   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8900     return false;
8901 
8902   if (Diagnose) {
8903     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8904     S.Diag(FD->getLocation(),
8905            diag::note_deleted_special_member_class_subobject)
8906         << getEffectiveCSM() << ParentClass << /*IsField*/true
8907         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8908   }
8909 
8910   return true;
8911 }
8912 
8913 /// Check whether we should delete a special member function due to the class
8914 /// having a particular direct or virtual base class.
8915 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8916   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8917   // If program is correct, BaseClass cannot be null, but if it is, the error
8918   // must be reported elsewhere.
8919   if (!BaseClass)
8920     return false;
8921   // If we have an inheriting constructor, check whether we're calling an
8922   // inherited constructor instead of a default constructor.
8923   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8924   if (auto *BaseCtor = SMOR.getMethod()) {
8925     // Note that we do not check access along this path; other than that,
8926     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8927     // FIXME: Check that the base has a usable destructor! Sink this into
8928     // shouldDeleteForClassSubobject.
8929     if (BaseCtor->isDeleted() && Diagnose) {
8930       S.Diag(Base->getBeginLoc(),
8931              diag::note_deleted_special_member_class_subobject)
8932           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8933           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8934           << /*IsObjCPtr*/false;
8935       S.NoteDeletedFunction(BaseCtor);
8936     }
8937     return BaseCtor->isDeleted();
8938   }
8939   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8940 }
8941 
8942 /// Check whether we should delete a special member function due to the class
8943 /// having a particular non-static data member.
8944 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8945   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8946   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8947 
8948   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8949     return true;
8950 
8951   if (CSM == Sema::CXXDefaultConstructor) {
8952     // For a default constructor, all references must be initialized in-class
8953     // and, if a union, it must have a non-const member.
8954     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8955       if (Diagnose)
8956         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8957           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8958       return true;
8959     }
8960     // C++11 [class.ctor]p5: any non-variant non-static data member of
8961     // const-qualified type (or array thereof) with no
8962     // brace-or-equal-initializer does not have a user-provided default
8963     // constructor.
8964     if (!inUnion() && FieldType.isConstQualified() &&
8965         !FD->hasInClassInitializer() &&
8966         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8967       if (Diagnose)
8968         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8969           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8970       return true;
8971     }
8972 
8973     if (inUnion() && !FieldType.isConstQualified())
8974       AllFieldsAreConst = false;
8975   } else if (CSM == Sema::CXXCopyConstructor) {
8976     // For a copy constructor, data members must not be of rvalue reference
8977     // type.
8978     if (FieldType->isRValueReferenceType()) {
8979       if (Diagnose)
8980         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8981           << MD->getParent() << FD << FieldType;
8982       return true;
8983     }
8984   } else if (IsAssignment) {
8985     // For an assignment operator, data members must not be of reference type.
8986     if (FieldType->isReferenceType()) {
8987       if (Diagnose)
8988         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8989           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8990       return true;
8991     }
8992     if (!FieldRecord && FieldType.isConstQualified()) {
8993       // C++11 [class.copy]p23:
8994       // -- a non-static data member of const non-class type (or array thereof)
8995       if (Diagnose)
8996         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8997           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8998       return true;
8999     }
9000   }
9001 
9002   if (FieldRecord) {
9003     // Some additional restrictions exist on the variant members.
9004     if (!inUnion() && FieldRecord->isUnion() &&
9005         FieldRecord->isAnonymousStructOrUnion()) {
9006       bool AllVariantFieldsAreConst = true;
9007 
9008       // FIXME: Handle anonymous unions declared within anonymous unions.
9009       for (auto *UI : FieldRecord->fields()) {
9010         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9011 
9012         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9013           return true;
9014 
9015         if (!UnionFieldType.isConstQualified())
9016           AllVariantFieldsAreConst = false;
9017 
9018         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9019         if (UnionFieldRecord &&
9020             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9021                                           UnionFieldType.getCVRQualifiers()))
9022           return true;
9023       }
9024 
9025       // At least one member in each anonymous union must be non-const
9026       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9027           !FieldRecord->field_empty()) {
9028         if (Diagnose)
9029           S.Diag(FieldRecord->getLocation(),
9030                  diag::note_deleted_default_ctor_all_const)
9031             << !!ICI << MD->getParent() << /*anonymous union*/1;
9032         return true;
9033       }
9034 
9035       // Don't check the implicit member of the anonymous union type.
9036       // This is technically non-conformant, but sanity demands it.
9037       return false;
9038     }
9039 
9040     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9041                                       FieldType.getCVRQualifiers()))
9042       return true;
9043   }
9044 
9045   return false;
9046 }
9047 
9048 /// C++11 [class.ctor] p5:
9049 ///   A defaulted default constructor for a class X is defined as deleted if
9050 /// X is a union and all of its variant members are of const-qualified type.
9051 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9052   // This is a silly definition, because it gives an empty union a deleted
9053   // default constructor. Don't do that.
9054   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9055     bool AnyFields = false;
9056     for (auto *F : MD->getParent()->fields())
9057       if ((AnyFields = !F->isUnnamedBitfield()))
9058         break;
9059     if (!AnyFields)
9060       return false;
9061     if (Diagnose)
9062       S.Diag(MD->getParent()->getLocation(),
9063              diag::note_deleted_default_ctor_all_const)
9064         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9065     return true;
9066   }
9067   return false;
9068 }
9069 
9070 /// Determine whether a defaulted special member function should be defined as
9071 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9072 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9073 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9074                                      InheritedConstructorInfo *ICI,
9075                                      bool Diagnose) {
9076   if (MD->isInvalidDecl())
9077     return false;
9078   CXXRecordDecl *RD = MD->getParent();
9079   assert(!RD->isDependentType() && "do deletion after instantiation");
9080   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9081     return false;
9082 
9083   // C++11 [expr.lambda.prim]p19:
9084   //   The closure type associated with a lambda-expression has a
9085   //   deleted (8.4.3) default constructor and a deleted copy
9086   //   assignment operator.
9087   // C++2a adds back these operators if the lambda has no lambda-capture.
9088   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9089       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9090     if (Diagnose)
9091       Diag(RD->getLocation(), diag::note_lambda_decl);
9092     return true;
9093   }
9094 
9095   // For an anonymous struct or union, the copy and assignment special members
9096   // will never be used, so skip the check. For an anonymous union declared at
9097   // namespace scope, the constructor and destructor are used.
9098   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9099       RD->isAnonymousStructOrUnion())
9100     return false;
9101 
9102   // C++11 [class.copy]p7, p18:
9103   //   If the class definition declares a move constructor or move assignment
9104   //   operator, an implicitly declared copy constructor or copy assignment
9105   //   operator is defined as deleted.
9106   if (MD->isImplicit() &&
9107       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9108     CXXMethodDecl *UserDeclaredMove = nullptr;
9109 
9110     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9111     // deletion of the corresponding copy operation, not both copy operations.
9112     // MSVC 2015 has adopted the standards conforming behavior.
9113     bool DeletesOnlyMatchingCopy =
9114         getLangOpts().MSVCCompat &&
9115         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9116 
9117     if (RD->hasUserDeclaredMoveConstructor() &&
9118         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9119       if (!Diagnose) return true;
9120 
9121       // Find any user-declared move constructor.
9122       for (auto *I : RD->ctors()) {
9123         if (I->isMoveConstructor()) {
9124           UserDeclaredMove = I;
9125           break;
9126         }
9127       }
9128       assert(UserDeclaredMove);
9129     } else if (RD->hasUserDeclaredMoveAssignment() &&
9130                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9131       if (!Diagnose) return true;
9132 
9133       // Find any user-declared move assignment operator.
9134       for (auto *I : RD->methods()) {
9135         if (I->isMoveAssignmentOperator()) {
9136           UserDeclaredMove = I;
9137           break;
9138         }
9139       }
9140       assert(UserDeclaredMove);
9141     }
9142 
9143     if (UserDeclaredMove) {
9144       Diag(UserDeclaredMove->getLocation(),
9145            diag::note_deleted_copy_user_declared_move)
9146         << (CSM == CXXCopyAssignment) << RD
9147         << UserDeclaredMove->isMoveAssignmentOperator();
9148       return true;
9149     }
9150   }
9151 
9152   // Do access control from the special member function
9153   ContextRAII MethodContext(*this, MD);
9154 
9155   // C++11 [class.dtor]p5:
9156   // -- for a virtual destructor, lookup of the non-array deallocation function
9157   //    results in an ambiguity or in a function that is deleted or inaccessible
9158   if (CSM == CXXDestructor && MD->isVirtual()) {
9159     FunctionDecl *OperatorDelete = nullptr;
9160     DeclarationName Name =
9161       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9162     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9163                                  OperatorDelete, /*Diagnose*/false)) {
9164       if (Diagnose)
9165         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9166       return true;
9167     }
9168   }
9169 
9170   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9171 
9172   // Per DR1611, do not consider virtual bases of constructors of abstract
9173   // classes, since we are not going to construct them.
9174   // Per DR1658, do not consider virtual bases of destructors of abstract
9175   // classes either.
9176   // Per DR2180, for assignment operators we only assign (and thus only
9177   // consider) direct bases.
9178   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9179                                  : SMI.VisitPotentiallyConstructedBases))
9180     return true;
9181 
9182   if (SMI.shouldDeleteForAllConstMembers())
9183     return true;
9184 
9185   if (getLangOpts().CUDA) {
9186     // We should delete the special member in CUDA mode if target inference
9187     // failed.
9188     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9189     // is treated as certain special member, which may not reflect what special
9190     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9191     // expects CSM to match MD, therefore recalculate CSM.
9192     assert(ICI || CSM == getSpecialMember(MD));
9193     auto RealCSM = CSM;
9194     if (ICI)
9195       RealCSM = getSpecialMember(MD);
9196 
9197     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9198                                                    SMI.ConstArg, Diagnose);
9199   }
9200 
9201   return false;
9202 }
9203 
9204 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9205   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9206   assert(DFK && "not a defaultable function");
9207   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9208 
9209   if (DFK.isSpecialMember()) {
9210     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9211                               nullptr, /*Diagnose=*/true);
9212   } else {
9213     DefaultedComparisonAnalyzer(
9214         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9215         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9216         .visit();
9217   }
9218 }
9219 
9220 /// Perform lookup for a special member of the specified kind, and determine
9221 /// whether it is trivial. If the triviality can be determined without the
9222 /// lookup, skip it. This is intended for use when determining whether a
9223 /// special member of a containing object is trivial, and thus does not ever
9224 /// perform overload resolution for default constructors.
9225 ///
9226 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9227 /// member that was most likely to be intended to be trivial, if any.
9228 ///
9229 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9230 /// determine whether the special member is trivial.
9231 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9232                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9233                                      bool ConstRHS,
9234                                      Sema::TrivialABIHandling TAH,
9235                                      CXXMethodDecl **Selected) {
9236   if (Selected)
9237     *Selected = nullptr;
9238 
9239   switch (CSM) {
9240   case Sema::CXXInvalid:
9241     llvm_unreachable("not a special member");
9242 
9243   case Sema::CXXDefaultConstructor:
9244     // C++11 [class.ctor]p5:
9245     //   A default constructor is trivial if:
9246     //    - all the [direct subobjects] have trivial default constructors
9247     //
9248     // Note, no overload resolution is performed in this case.
9249     if (RD->hasTrivialDefaultConstructor())
9250       return true;
9251 
9252     if (Selected) {
9253       // If there's a default constructor which could have been trivial, dig it
9254       // out. Otherwise, if there's any user-provided default constructor, point
9255       // to that as an example of why there's not a trivial one.
9256       CXXConstructorDecl *DefCtor = nullptr;
9257       if (RD->needsImplicitDefaultConstructor())
9258         S.DeclareImplicitDefaultConstructor(RD);
9259       for (auto *CI : RD->ctors()) {
9260         if (!CI->isDefaultConstructor())
9261           continue;
9262         DefCtor = CI;
9263         if (!DefCtor->isUserProvided())
9264           break;
9265       }
9266 
9267       *Selected = DefCtor;
9268     }
9269 
9270     return false;
9271 
9272   case Sema::CXXDestructor:
9273     // C++11 [class.dtor]p5:
9274     //   A destructor is trivial if:
9275     //    - all the direct [subobjects] have trivial destructors
9276     if (RD->hasTrivialDestructor() ||
9277         (TAH == Sema::TAH_ConsiderTrivialABI &&
9278          RD->hasTrivialDestructorForCall()))
9279       return true;
9280 
9281     if (Selected) {
9282       if (RD->needsImplicitDestructor())
9283         S.DeclareImplicitDestructor(RD);
9284       *Selected = RD->getDestructor();
9285     }
9286 
9287     return false;
9288 
9289   case Sema::CXXCopyConstructor:
9290     // C++11 [class.copy]p12:
9291     //   A copy constructor is trivial if:
9292     //    - the constructor selected to copy each direct [subobject] is trivial
9293     if (RD->hasTrivialCopyConstructor() ||
9294         (TAH == Sema::TAH_ConsiderTrivialABI &&
9295          RD->hasTrivialCopyConstructorForCall())) {
9296       if (Quals == Qualifiers::Const)
9297         // We must either select the trivial copy constructor or reach an
9298         // ambiguity; no need to actually perform overload resolution.
9299         return true;
9300     } else if (!Selected) {
9301       return false;
9302     }
9303     // In C++98, we are not supposed to perform overload resolution here, but we
9304     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9305     // cases like B as having a non-trivial copy constructor:
9306     //   struct A { template<typename T> A(T&); };
9307     //   struct B { mutable A a; };
9308     goto NeedOverloadResolution;
9309 
9310   case Sema::CXXCopyAssignment:
9311     // C++11 [class.copy]p25:
9312     //   A copy assignment operator is trivial if:
9313     //    - the assignment operator selected to copy each direct [subobject] is
9314     //      trivial
9315     if (RD->hasTrivialCopyAssignment()) {
9316       if (Quals == Qualifiers::Const)
9317         return true;
9318     } else if (!Selected) {
9319       return false;
9320     }
9321     // In C++98, we are not supposed to perform overload resolution here, but we
9322     // treat that as a language defect.
9323     goto NeedOverloadResolution;
9324 
9325   case Sema::CXXMoveConstructor:
9326   case Sema::CXXMoveAssignment:
9327   NeedOverloadResolution:
9328     Sema::SpecialMemberOverloadResult SMOR =
9329         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9330 
9331     // The standard doesn't describe how to behave if the lookup is ambiguous.
9332     // We treat it as not making the member non-trivial, just like the standard
9333     // mandates for the default constructor. This should rarely matter, because
9334     // the member will also be deleted.
9335     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9336       return true;
9337 
9338     if (!SMOR.getMethod()) {
9339       assert(SMOR.getKind() ==
9340              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9341       return false;
9342     }
9343 
9344     // We deliberately don't check if we found a deleted special member. We're
9345     // not supposed to!
9346     if (Selected)
9347       *Selected = SMOR.getMethod();
9348 
9349     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9350         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9351       return SMOR.getMethod()->isTrivialForCall();
9352     return SMOR.getMethod()->isTrivial();
9353   }
9354 
9355   llvm_unreachable("unknown special method kind");
9356 }
9357 
9358 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9359   for (auto *CI : RD->ctors())
9360     if (!CI->isImplicit())
9361       return CI;
9362 
9363   // Look for constructor templates.
9364   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9365   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9366     if (CXXConstructorDecl *CD =
9367           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9368       return CD;
9369   }
9370 
9371   return nullptr;
9372 }
9373 
9374 /// The kind of subobject we are checking for triviality. The values of this
9375 /// enumeration are used in diagnostics.
9376 enum TrivialSubobjectKind {
9377   /// The subobject is a base class.
9378   TSK_BaseClass,
9379   /// The subobject is a non-static data member.
9380   TSK_Field,
9381   /// The object is actually the complete object.
9382   TSK_CompleteObject
9383 };
9384 
9385 /// Check whether the special member selected for a given type would be trivial.
9386 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9387                                       QualType SubType, bool ConstRHS,
9388                                       Sema::CXXSpecialMember CSM,
9389                                       TrivialSubobjectKind Kind,
9390                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9391   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9392   if (!SubRD)
9393     return true;
9394 
9395   CXXMethodDecl *Selected;
9396   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9397                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9398     return true;
9399 
9400   if (Diagnose) {
9401     if (ConstRHS)
9402       SubType.addConst();
9403 
9404     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9405       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9406         << Kind << SubType.getUnqualifiedType();
9407       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9408         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9409     } else if (!Selected)
9410       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9411         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9412     else if (Selected->isUserProvided()) {
9413       if (Kind == TSK_CompleteObject)
9414         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9415           << Kind << SubType.getUnqualifiedType() << CSM;
9416       else {
9417         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9418           << Kind << SubType.getUnqualifiedType() << CSM;
9419         S.Diag(Selected->getLocation(), diag::note_declared_at);
9420       }
9421     } else {
9422       if (Kind != TSK_CompleteObject)
9423         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9424           << Kind << SubType.getUnqualifiedType() << CSM;
9425 
9426       // Explain why the defaulted or deleted special member isn't trivial.
9427       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9428                                Diagnose);
9429     }
9430   }
9431 
9432   return false;
9433 }
9434 
9435 /// Check whether the members of a class type allow a special member to be
9436 /// trivial.
9437 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9438                                      Sema::CXXSpecialMember CSM,
9439                                      bool ConstArg,
9440                                      Sema::TrivialABIHandling TAH,
9441                                      bool Diagnose) {
9442   for (const auto *FI : RD->fields()) {
9443     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9444       continue;
9445 
9446     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9447 
9448     // Pretend anonymous struct or union members are members of this class.
9449     if (FI->isAnonymousStructOrUnion()) {
9450       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9451                                     CSM, ConstArg, TAH, Diagnose))
9452         return false;
9453       continue;
9454     }
9455 
9456     // C++11 [class.ctor]p5:
9457     //   A default constructor is trivial if [...]
9458     //    -- no non-static data member of its class has a
9459     //       brace-or-equal-initializer
9460     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9461       if (Diagnose)
9462         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9463             << FI;
9464       return false;
9465     }
9466 
9467     // Objective C ARC 4.3.5:
9468     //   [...] nontrivally ownership-qualified types are [...] not trivially
9469     //   default constructible, copy constructible, move constructible, copy
9470     //   assignable, move assignable, or destructible [...]
9471     if (FieldType.hasNonTrivialObjCLifetime()) {
9472       if (Diagnose)
9473         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9474           << RD << FieldType.getObjCLifetime();
9475       return false;
9476     }
9477 
9478     bool ConstRHS = ConstArg && !FI->isMutable();
9479     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9480                                    CSM, TSK_Field, TAH, Diagnose))
9481       return false;
9482   }
9483 
9484   return true;
9485 }
9486 
9487 /// Diagnose why the specified class does not have a trivial special member of
9488 /// the given kind.
9489 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9490   QualType Ty = Context.getRecordType(RD);
9491 
9492   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9493   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9494                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9495                             /*Diagnose*/true);
9496 }
9497 
9498 /// Determine whether a defaulted or deleted special member function is trivial,
9499 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9500 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9501 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9502                                   TrivialABIHandling TAH, bool Diagnose) {
9503   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9504 
9505   CXXRecordDecl *RD = MD->getParent();
9506 
9507   bool ConstArg = false;
9508 
9509   // C++11 [class.copy]p12, p25: [DR1593]
9510   //   A [special member] is trivial if [...] its parameter-type-list is
9511   //   equivalent to the parameter-type-list of an implicit declaration [...]
9512   switch (CSM) {
9513   case CXXDefaultConstructor:
9514   case CXXDestructor:
9515     // Trivial default constructors and destructors cannot have parameters.
9516     break;
9517 
9518   case CXXCopyConstructor:
9519   case CXXCopyAssignment: {
9520     // Trivial copy operations always have const, non-volatile parameter types.
9521     ConstArg = true;
9522     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9523     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9524     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9525       if (Diagnose)
9526         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9527           << Param0->getSourceRange() << Param0->getType()
9528           << Context.getLValueReferenceType(
9529                Context.getRecordType(RD).withConst());
9530       return false;
9531     }
9532     break;
9533   }
9534 
9535   case CXXMoveConstructor:
9536   case CXXMoveAssignment: {
9537     // Trivial move operations always have non-cv-qualified parameters.
9538     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9539     const RValueReferenceType *RT =
9540       Param0->getType()->getAs<RValueReferenceType>();
9541     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9542       if (Diagnose)
9543         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9544           << Param0->getSourceRange() << Param0->getType()
9545           << Context.getRValueReferenceType(Context.getRecordType(RD));
9546       return false;
9547     }
9548     break;
9549   }
9550 
9551   case CXXInvalid:
9552     llvm_unreachable("not a special member");
9553   }
9554 
9555   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9556     if (Diagnose)
9557       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9558            diag::note_nontrivial_default_arg)
9559         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9560     return false;
9561   }
9562   if (MD->isVariadic()) {
9563     if (Diagnose)
9564       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9565     return false;
9566   }
9567 
9568   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9569   //   A copy/move [constructor or assignment operator] is trivial if
9570   //    -- the [member] selected to copy/move each direct base class subobject
9571   //       is trivial
9572   //
9573   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9574   //   A [default constructor or destructor] is trivial if
9575   //    -- all the direct base classes have trivial [default constructors or
9576   //       destructors]
9577   for (const auto &BI : RD->bases())
9578     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9579                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9580       return false;
9581 
9582   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9583   //   A copy/move [constructor or assignment operator] for a class X is
9584   //   trivial if
9585   //    -- for each non-static data member of X that is of class type (or array
9586   //       thereof), the constructor selected to copy/move that member is
9587   //       trivial
9588   //
9589   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9590   //   A [default constructor or destructor] is trivial if
9591   //    -- for all of the non-static data members of its class that are of class
9592   //       type (or array thereof), each such class has a trivial [default
9593   //       constructor or destructor]
9594   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9595     return false;
9596 
9597   // C++11 [class.dtor]p5:
9598   //   A destructor is trivial if [...]
9599   //    -- the destructor is not virtual
9600   if (CSM == CXXDestructor && MD->isVirtual()) {
9601     if (Diagnose)
9602       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9603     return false;
9604   }
9605 
9606   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9607   //   A [special member] for class X is trivial if [...]
9608   //    -- class X has no virtual functions and no virtual base classes
9609   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9610     if (!Diagnose)
9611       return false;
9612 
9613     if (RD->getNumVBases()) {
9614       // Check for virtual bases. We already know that the corresponding
9615       // member in all bases is trivial, so vbases must all be direct.
9616       CXXBaseSpecifier &BS = *RD->vbases_begin();
9617       assert(BS.isVirtual());
9618       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9619       return false;
9620     }
9621 
9622     // Must have a virtual method.
9623     for (const auto *MI : RD->methods()) {
9624       if (MI->isVirtual()) {
9625         SourceLocation MLoc = MI->getBeginLoc();
9626         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9627         return false;
9628       }
9629     }
9630 
9631     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9632   }
9633 
9634   // Looks like it's trivial!
9635   return true;
9636 }
9637 
9638 namespace {
9639 struct FindHiddenVirtualMethod {
9640   Sema *S;
9641   CXXMethodDecl *Method;
9642   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9643   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9644 
9645 private:
9646   /// Check whether any most overridden method from MD in Methods
9647   static bool CheckMostOverridenMethods(
9648       const CXXMethodDecl *MD,
9649       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9650     if (MD->size_overridden_methods() == 0)
9651       return Methods.count(MD->getCanonicalDecl());
9652     for (const CXXMethodDecl *O : MD->overridden_methods())
9653       if (CheckMostOverridenMethods(O, Methods))
9654         return true;
9655     return false;
9656   }
9657 
9658 public:
9659   /// Member lookup function that determines whether a given C++
9660   /// method overloads virtual methods in a base class without overriding any,
9661   /// to be used with CXXRecordDecl::lookupInBases().
9662   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9663     RecordDecl *BaseRecord =
9664         Specifier->getType()->castAs<RecordType>()->getDecl();
9665 
9666     DeclarationName Name = Method->getDeclName();
9667     assert(Name.getNameKind() == DeclarationName::Identifier);
9668 
9669     bool foundSameNameMethod = false;
9670     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9671     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9672          Path.Decls = Path.Decls.slice(1)) {
9673       NamedDecl *D = Path.Decls.front();
9674       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9675         MD = MD->getCanonicalDecl();
9676         foundSameNameMethod = true;
9677         // Interested only in hidden virtual methods.
9678         if (!MD->isVirtual())
9679           continue;
9680         // If the method we are checking overrides a method from its base
9681         // don't warn about the other overloaded methods. Clang deviates from
9682         // GCC by only diagnosing overloads of inherited virtual functions that
9683         // do not override any other virtual functions in the base. GCC's
9684         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9685         // function from a base class. These cases may be better served by a
9686         // warning (not specific to virtual functions) on call sites when the
9687         // call would select a different function from the base class, were it
9688         // visible.
9689         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9690         if (!S->IsOverload(Method, MD, false))
9691           return true;
9692         // Collect the overload only if its hidden.
9693         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9694           overloadedMethods.push_back(MD);
9695       }
9696     }
9697 
9698     if (foundSameNameMethod)
9699       OverloadedMethods.append(overloadedMethods.begin(),
9700                                overloadedMethods.end());
9701     return foundSameNameMethod;
9702   }
9703 };
9704 } // end anonymous namespace
9705 
9706 /// Add the most overriden methods from MD to Methods
9707 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9708                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9709   if (MD->size_overridden_methods() == 0)
9710     Methods.insert(MD->getCanonicalDecl());
9711   else
9712     for (const CXXMethodDecl *O : MD->overridden_methods())
9713       AddMostOverridenMethods(O, Methods);
9714 }
9715 
9716 /// Check if a method overloads virtual methods in a base class without
9717 /// overriding any.
9718 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9719                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9720   if (!MD->getDeclName().isIdentifier())
9721     return;
9722 
9723   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9724                      /*bool RecordPaths=*/false,
9725                      /*bool DetectVirtual=*/false);
9726   FindHiddenVirtualMethod FHVM;
9727   FHVM.Method = MD;
9728   FHVM.S = this;
9729 
9730   // Keep the base methods that were overridden or introduced in the subclass
9731   // by 'using' in a set. A base method not in this set is hidden.
9732   CXXRecordDecl *DC = MD->getParent();
9733   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9734   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9735     NamedDecl *ND = *I;
9736     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9737       ND = shad->getTargetDecl();
9738     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9739       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9740   }
9741 
9742   if (DC->lookupInBases(FHVM, Paths))
9743     OverloadedMethods = FHVM.OverloadedMethods;
9744 }
9745 
9746 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9747                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9748   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9749     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9750     PartialDiagnostic PD = PDiag(
9751          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9752     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9753     Diag(overloadedMD->getLocation(), PD);
9754   }
9755 }
9756 
9757 /// Diagnose methods which overload virtual methods in a base class
9758 /// without overriding any.
9759 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9760   if (MD->isInvalidDecl())
9761     return;
9762 
9763   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9764     return;
9765 
9766   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9767   FindHiddenVirtualMethods(MD, OverloadedMethods);
9768   if (!OverloadedMethods.empty()) {
9769     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9770       << MD << (OverloadedMethods.size() > 1);
9771 
9772     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9773   }
9774 }
9775 
9776 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9777   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9778     // No diagnostics if this is a template instantiation.
9779     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9780       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9781            diag::ext_cannot_use_trivial_abi) << &RD;
9782       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9783            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9784     }
9785     RD.dropAttr<TrivialABIAttr>();
9786   };
9787 
9788   // Ill-formed if the copy and move constructors are deleted.
9789   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9790     // If the type is dependent, then assume it might have
9791     // implicit copy or move ctor because we won't know yet at this point.
9792     if (RD.isDependentType())
9793       return true;
9794     if (RD.needsImplicitCopyConstructor() &&
9795         !RD.defaultedCopyConstructorIsDeleted())
9796       return true;
9797     if (RD.needsImplicitMoveConstructor() &&
9798         !RD.defaultedMoveConstructorIsDeleted())
9799       return true;
9800     for (const CXXConstructorDecl *CD : RD.ctors())
9801       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9802         return true;
9803     return false;
9804   };
9805 
9806   if (!HasNonDeletedCopyOrMoveConstructor()) {
9807     PrintDiagAndRemoveAttr(0);
9808     return;
9809   }
9810 
9811   // Ill-formed if the struct has virtual functions.
9812   if (RD.isPolymorphic()) {
9813     PrintDiagAndRemoveAttr(1);
9814     return;
9815   }
9816 
9817   for (const auto &B : RD.bases()) {
9818     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9819     // virtual base.
9820     if (!B.getType()->isDependentType() &&
9821         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9822       PrintDiagAndRemoveAttr(2);
9823       return;
9824     }
9825 
9826     if (B.isVirtual()) {
9827       PrintDiagAndRemoveAttr(3);
9828       return;
9829     }
9830   }
9831 
9832   for (const auto *FD : RD.fields()) {
9833     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9834     // non-trivial for the purpose of calls.
9835     QualType FT = FD->getType();
9836     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9837       PrintDiagAndRemoveAttr(4);
9838       return;
9839     }
9840 
9841     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9842       if (!RT->isDependentType() &&
9843           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9844         PrintDiagAndRemoveAttr(5);
9845         return;
9846       }
9847   }
9848 }
9849 
9850 void Sema::ActOnFinishCXXMemberSpecification(
9851     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9852     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9853   if (!TagDecl)
9854     return;
9855 
9856   AdjustDeclIfTemplate(TagDecl);
9857 
9858   for (const ParsedAttr &AL : AttrList) {
9859     if (AL.getKind() != ParsedAttr::AT_Visibility)
9860       continue;
9861     AL.setInvalid();
9862     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9863   }
9864 
9865   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9866               // strict aliasing violation!
9867               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9868               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9869 
9870   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9871 }
9872 
9873 /// Find the equality comparison functions that should be implicitly declared
9874 /// in a given class definition, per C++2a [class.compare.default]p3.
9875 static void findImplicitlyDeclaredEqualityComparisons(
9876     ASTContext &Ctx, CXXRecordDecl *RD,
9877     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9878   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9879   if (!RD->lookup(EqEq).empty())
9880     // Member operator== explicitly declared: no implicit operator==s.
9881     return;
9882 
9883   // Traverse friends looking for an '==' or a '<=>'.
9884   for (FriendDecl *Friend : RD->friends()) {
9885     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9886     if (!FD) continue;
9887 
9888     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9889       // Friend operator== explicitly declared: no implicit operator==s.
9890       Spaceships.clear();
9891       return;
9892     }
9893 
9894     if (FD->getOverloadedOperator() == OO_Spaceship &&
9895         FD->isExplicitlyDefaulted())
9896       Spaceships.push_back(FD);
9897   }
9898 
9899   // Look for members named 'operator<=>'.
9900   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9901   for (NamedDecl *ND : RD->lookup(Cmp)) {
9902     // Note that we could find a non-function here (either a function template
9903     // or a using-declaration). Neither case results in an implicit
9904     // 'operator=='.
9905     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9906       if (FD->isExplicitlyDefaulted())
9907         Spaceships.push_back(FD);
9908   }
9909 }
9910 
9911 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9912 /// special functions, such as the default constructor, copy
9913 /// constructor, or destructor, to the given C++ class (C++
9914 /// [special]p1).  This routine can only be executed just before the
9915 /// definition of the class is complete.
9916 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9917   // Don't add implicit special members to templated classes.
9918   // FIXME: This means unqualified lookups for 'operator=' within a class
9919   // template don't work properly.
9920   if (!ClassDecl->isDependentType()) {
9921     if (ClassDecl->needsImplicitDefaultConstructor()) {
9922       ++getASTContext().NumImplicitDefaultConstructors;
9923 
9924       if (ClassDecl->hasInheritedConstructor())
9925         DeclareImplicitDefaultConstructor(ClassDecl);
9926     }
9927 
9928     if (ClassDecl->needsImplicitCopyConstructor()) {
9929       ++getASTContext().NumImplicitCopyConstructors;
9930 
9931       // If the properties or semantics of the copy constructor couldn't be
9932       // determined while the class was being declared, force a declaration
9933       // of it now.
9934       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9935           ClassDecl->hasInheritedConstructor())
9936         DeclareImplicitCopyConstructor(ClassDecl);
9937       // For the MS ABI we need to know whether the copy ctor is deleted. A
9938       // prerequisite for deleting the implicit copy ctor is that the class has
9939       // a move ctor or move assignment that is either user-declared or whose
9940       // semantics are inherited from a subobject. FIXME: We should provide a
9941       // more direct way for CodeGen to ask whether the constructor was deleted.
9942       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9943                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9944                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9945                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9946                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9947         DeclareImplicitCopyConstructor(ClassDecl);
9948     }
9949 
9950     if (getLangOpts().CPlusPlus11 &&
9951         ClassDecl->needsImplicitMoveConstructor()) {
9952       ++getASTContext().NumImplicitMoveConstructors;
9953 
9954       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9955           ClassDecl->hasInheritedConstructor())
9956         DeclareImplicitMoveConstructor(ClassDecl);
9957     }
9958 
9959     if (ClassDecl->needsImplicitCopyAssignment()) {
9960       ++getASTContext().NumImplicitCopyAssignmentOperators;
9961 
9962       // If we have a dynamic class, then the copy assignment operator may be
9963       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9964       // it shows up in the right place in the vtable and that we diagnose
9965       // problems with the implicit exception specification.
9966       if (ClassDecl->isDynamicClass() ||
9967           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9968           ClassDecl->hasInheritedAssignment())
9969         DeclareImplicitCopyAssignment(ClassDecl);
9970     }
9971 
9972     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9973       ++getASTContext().NumImplicitMoveAssignmentOperators;
9974 
9975       // Likewise for the move assignment operator.
9976       if (ClassDecl->isDynamicClass() ||
9977           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9978           ClassDecl->hasInheritedAssignment())
9979         DeclareImplicitMoveAssignment(ClassDecl);
9980     }
9981 
9982     if (ClassDecl->needsImplicitDestructor()) {
9983       ++getASTContext().NumImplicitDestructors;
9984 
9985       // If we have a dynamic class, then the destructor may be virtual, so we
9986       // have to declare the destructor immediately. This ensures that, e.g., it
9987       // shows up in the right place in the vtable and that we diagnose problems
9988       // with the implicit exception specification.
9989       if (ClassDecl->isDynamicClass() ||
9990           ClassDecl->needsOverloadResolutionForDestructor())
9991         DeclareImplicitDestructor(ClassDecl);
9992     }
9993   }
9994 
9995   // C++2a [class.compare.default]p3:
9996   //   If the member-specification does not explicitly declare any member or
9997   //   friend named operator==, an == operator function is declared implicitly
9998   //   for each defaulted three-way comparison operator function defined in
9999   //   the member-specification
10000   // FIXME: Consider doing this lazily.
10001   // We do this during the initial parse for a class template, not during
10002   // instantiation, so that we can handle unqualified lookups for 'operator=='
10003   // when parsing the template.
10004   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10005     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10006     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10007                                               DefaultedSpaceships);
10008     for (auto *FD : DefaultedSpaceships)
10009       DeclareImplicitEqualityComparison(ClassDecl, FD);
10010   }
10011 }
10012 
10013 unsigned
10014 Sema::ActOnReenterTemplateScope(Decl *D,
10015                                 llvm::function_ref<Scope *()> EnterScope) {
10016   if (!D)
10017     return 0;
10018   AdjustDeclIfTemplate(D);
10019 
10020   // In order to get name lookup right, reenter template scopes in order from
10021   // outermost to innermost.
10022   SmallVector<TemplateParameterList *, 4> ParameterLists;
10023   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10024 
10025   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10026     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10027       ParameterLists.push_back(DD->getTemplateParameterList(i));
10028 
10029     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10030       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10031         ParameterLists.push_back(FTD->getTemplateParameters());
10032     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10033       LookupDC = VD->getDeclContext();
10034 
10035       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10036         ParameterLists.push_back(VTD->getTemplateParameters());
10037       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10038         ParameterLists.push_back(PSD->getTemplateParameters());
10039     }
10040   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10041     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10042       ParameterLists.push_back(TD->getTemplateParameterList(i));
10043 
10044     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10045       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10046         ParameterLists.push_back(CTD->getTemplateParameters());
10047       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10048         ParameterLists.push_back(PSD->getTemplateParameters());
10049     }
10050   }
10051   // FIXME: Alias declarations and concepts.
10052 
10053   unsigned Count = 0;
10054   Scope *InnermostTemplateScope = nullptr;
10055   for (TemplateParameterList *Params : ParameterLists) {
10056     // Ignore explicit specializations; they don't contribute to the template
10057     // depth.
10058     if (Params->size() == 0)
10059       continue;
10060 
10061     InnermostTemplateScope = EnterScope();
10062     for (NamedDecl *Param : *Params) {
10063       if (Param->getDeclName()) {
10064         InnermostTemplateScope->AddDecl(Param);
10065         IdResolver.AddDecl(Param);
10066       }
10067     }
10068     ++Count;
10069   }
10070 
10071   // Associate the new template scopes with the corresponding entities.
10072   if (InnermostTemplateScope) {
10073     assert(LookupDC && "no enclosing DeclContext for template lookup");
10074     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10075   }
10076 
10077   return Count;
10078 }
10079 
10080 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10081   if (!RecordD) return;
10082   AdjustDeclIfTemplate(RecordD);
10083   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10084   PushDeclContext(S, Record);
10085 }
10086 
10087 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10088   if (!RecordD) return;
10089   PopDeclContext();
10090 }
10091 
10092 /// This is used to implement the constant expression evaluation part of the
10093 /// attribute enable_if extension. There is nothing in standard C++ which would
10094 /// require reentering parameters.
10095 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10096   if (!Param)
10097     return;
10098 
10099   S->AddDecl(Param);
10100   if (Param->getDeclName())
10101     IdResolver.AddDecl(Param);
10102 }
10103 
10104 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10105 /// parsing a top-level (non-nested) C++ class, and we are now
10106 /// parsing those parts of the given Method declaration that could
10107 /// not be parsed earlier (C++ [class.mem]p2), such as default
10108 /// arguments. This action should enter the scope of the given
10109 /// Method declaration as if we had just parsed the qualified method
10110 /// name. However, it should not bring the parameters into scope;
10111 /// that will be performed by ActOnDelayedCXXMethodParameter.
10112 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10113 }
10114 
10115 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10116 /// C++ method declaration. We're (re-)introducing the given
10117 /// function parameter into scope for use in parsing later parts of
10118 /// the method declaration. For example, we could see an
10119 /// ActOnParamDefaultArgument event for this parameter.
10120 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10121   if (!ParamD)
10122     return;
10123 
10124   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10125 
10126   S->AddDecl(Param);
10127   if (Param->getDeclName())
10128     IdResolver.AddDecl(Param);
10129 }
10130 
10131 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10132 /// processing the delayed method declaration for Method. The method
10133 /// declaration is now considered finished. There may be a separate
10134 /// ActOnStartOfFunctionDef action later (not necessarily
10135 /// immediately!) for this method, if it was also defined inside the
10136 /// class body.
10137 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10138   if (!MethodD)
10139     return;
10140 
10141   AdjustDeclIfTemplate(MethodD);
10142 
10143   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10144 
10145   // Now that we have our default arguments, check the constructor
10146   // again. It could produce additional diagnostics or affect whether
10147   // the class has implicitly-declared destructors, among other
10148   // things.
10149   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10150     CheckConstructor(Constructor);
10151 
10152   // Check the default arguments, which we may have added.
10153   if (!Method->isInvalidDecl())
10154     CheckCXXDefaultArguments(Method);
10155 }
10156 
10157 // Emit the given diagnostic for each non-address-space qualifier.
10158 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10159 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10160   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10161   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10162     bool DiagOccured = false;
10163     FTI.MethodQualifiers->forEachQualifier(
10164         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10165                                    SourceLocation SL) {
10166           // This diagnostic should be emitted on any qualifier except an addr
10167           // space qualifier. However, forEachQualifier currently doesn't visit
10168           // addr space qualifiers, so there's no way to write this condition
10169           // right now; we just diagnose on everything.
10170           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10171           DiagOccured = true;
10172         });
10173     if (DiagOccured)
10174       D.setInvalidType();
10175   }
10176 }
10177 
10178 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10179 /// the well-formedness of the constructor declarator @p D with type @p
10180 /// R. If there are any errors in the declarator, this routine will
10181 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10182 /// will be updated to reflect a well-formed type for the constructor and
10183 /// returned.
10184 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10185                                           StorageClass &SC) {
10186   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10187 
10188   // C++ [class.ctor]p3:
10189   //   A constructor shall not be virtual (10.3) or static (9.4). A
10190   //   constructor can be invoked for a const, volatile or const
10191   //   volatile object. A constructor shall not be declared const,
10192   //   volatile, or const volatile (9.3.2).
10193   if (isVirtual) {
10194     if (!D.isInvalidType())
10195       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10196         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10197         << SourceRange(D.getIdentifierLoc());
10198     D.setInvalidType();
10199   }
10200   if (SC == SC_Static) {
10201     if (!D.isInvalidType())
10202       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10203         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10204         << SourceRange(D.getIdentifierLoc());
10205     D.setInvalidType();
10206     SC = SC_None;
10207   }
10208 
10209   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10210     diagnoseIgnoredQualifiers(
10211         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10212         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10213         D.getDeclSpec().getRestrictSpecLoc(),
10214         D.getDeclSpec().getAtomicSpecLoc());
10215     D.setInvalidType();
10216   }
10217 
10218   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10219 
10220   // C++0x [class.ctor]p4:
10221   //   A constructor shall not be declared with a ref-qualifier.
10222   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10223   if (FTI.hasRefQualifier()) {
10224     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10225       << FTI.RefQualifierIsLValueRef
10226       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10227     D.setInvalidType();
10228   }
10229 
10230   // Rebuild the function type "R" without any type qualifiers (in
10231   // case any of the errors above fired) and with "void" as the
10232   // return type, since constructors don't have return types.
10233   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10234   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10235     return R;
10236 
10237   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10238   EPI.TypeQuals = Qualifiers();
10239   EPI.RefQualifier = RQ_None;
10240 
10241   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10242 }
10243 
10244 /// CheckConstructor - Checks a fully-formed constructor for
10245 /// well-formedness, issuing any diagnostics required. Returns true if
10246 /// the constructor declarator is invalid.
10247 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10248   CXXRecordDecl *ClassDecl
10249     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10250   if (!ClassDecl)
10251     return Constructor->setInvalidDecl();
10252 
10253   // C++ [class.copy]p3:
10254   //   A declaration of a constructor for a class X is ill-formed if
10255   //   its first parameter is of type (optionally cv-qualified) X and
10256   //   either there are no other parameters or else all other
10257   //   parameters have default arguments.
10258   if (!Constructor->isInvalidDecl() &&
10259       Constructor->hasOneParamOrDefaultArgs() &&
10260       Constructor->getTemplateSpecializationKind() !=
10261           TSK_ImplicitInstantiation) {
10262     QualType ParamType = Constructor->getParamDecl(0)->getType();
10263     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10264     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10265       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10266       const char *ConstRef
10267         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10268                                                         : " const &";
10269       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10270         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10271 
10272       // FIXME: Rather that making the constructor invalid, we should endeavor
10273       // to fix the type.
10274       Constructor->setInvalidDecl();
10275     }
10276   }
10277 }
10278 
10279 /// CheckDestructor - Checks a fully-formed destructor definition for
10280 /// well-formedness, issuing any diagnostics required.  Returns true
10281 /// on error.
10282 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10283   CXXRecordDecl *RD = Destructor->getParent();
10284 
10285   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10286     SourceLocation Loc;
10287 
10288     if (!Destructor->isImplicit())
10289       Loc = Destructor->getLocation();
10290     else
10291       Loc = RD->getLocation();
10292 
10293     // If we have a virtual destructor, look up the deallocation function
10294     if (FunctionDecl *OperatorDelete =
10295             FindDeallocationFunctionForDestructor(Loc, RD)) {
10296       Expr *ThisArg = nullptr;
10297 
10298       // If the notional 'delete this' expression requires a non-trivial
10299       // conversion from 'this' to the type of a destroying operator delete's
10300       // first parameter, perform that conversion now.
10301       if (OperatorDelete->isDestroyingOperatorDelete()) {
10302         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10303         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10304           // C++ [class.dtor]p13:
10305           //   ... as if for the expression 'delete this' appearing in a
10306           //   non-virtual destructor of the destructor's class.
10307           ContextRAII SwitchContext(*this, Destructor);
10308           ExprResult This =
10309               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10310           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10311           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10312           if (This.isInvalid()) {
10313             // FIXME: Register this as a context note so that it comes out
10314             // in the right order.
10315             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10316             return true;
10317           }
10318           ThisArg = This.get();
10319         }
10320       }
10321 
10322       DiagnoseUseOfDecl(OperatorDelete, Loc);
10323       MarkFunctionReferenced(Loc, OperatorDelete);
10324       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10325     }
10326   }
10327 
10328   return false;
10329 }
10330 
10331 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10332 /// the well-formednes of the destructor declarator @p D with type @p
10333 /// R. If there are any errors in the declarator, this routine will
10334 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10335 /// will be updated to reflect a well-formed type for the destructor and
10336 /// returned.
10337 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10338                                          StorageClass& SC) {
10339   // C++ [class.dtor]p1:
10340   //   [...] A typedef-name that names a class is a class-name
10341   //   (7.1.3); however, a typedef-name that names a class shall not
10342   //   be used as the identifier in the declarator for a destructor
10343   //   declaration.
10344   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10345   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10346     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10347       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10348   else if (const TemplateSpecializationType *TST =
10349              DeclaratorType->getAs<TemplateSpecializationType>())
10350     if (TST->isTypeAlias())
10351       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10352         << DeclaratorType << 1;
10353 
10354   // C++ [class.dtor]p2:
10355   //   A destructor is used to destroy objects of its class type. A
10356   //   destructor takes no parameters, and no return type can be
10357   //   specified for it (not even void). The address of a destructor
10358   //   shall not be taken. A destructor shall not be static. A
10359   //   destructor can be invoked for a const, volatile or const
10360   //   volatile object. A destructor shall not be declared const,
10361   //   volatile or const volatile (9.3.2).
10362   if (SC == SC_Static) {
10363     if (!D.isInvalidType())
10364       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10365         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10366         << SourceRange(D.getIdentifierLoc())
10367         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10368 
10369     SC = SC_None;
10370   }
10371   if (!D.isInvalidType()) {
10372     // Destructors don't have return types, but the parser will
10373     // happily parse something like:
10374     //
10375     //   class X {
10376     //     float ~X();
10377     //   };
10378     //
10379     // The return type will be eliminated later.
10380     if (D.getDeclSpec().hasTypeSpecifier())
10381       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10382         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10383         << SourceRange(D.getIdentifierLoc());
10384     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10385       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10386                                 SourceLocation(),
10387                                 D.getDeclSpec().getConstSpecLoc(),
10388                                 D.getDeclSpec().getVolatileSpecLoc(),
10389                                 D.getDeclSpec().getRestrictSpecLoc(),
10390                                 D.getDeclSpec().getAtomicSpecLoc());
10391       D.setInvalidType();
10392     }
10393   }
10394 
10395   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10396 
10397   // C++0x [class.dtor]p2:
10398   //   A destructor shall not be declared with a ref-qualifier.
10399   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10400   if (FTI.hasRefQualifier()) {
10401     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10402       << FTI.RefQualifierIsLValueRef
10403       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10404     D.setInvalidType();
10405   }
10406 
10407   // Make sure we don't have any parameters.
10408   if (FTIHasNonVoidParameters(FTI)) {
10409     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10410 
10411     // Delete the parameters.
10412     FTI.freeParams();
10413     D.setInvalidType();
10414   }
10415 
10416   // Make sure the destructor isn't variadic.
10417   if (FTI.isVariadic) {
10418     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10419     D.setInvalidType();
10420   }
10421 
10422   // Rebuild the function type "R" without any type qualifiers or
10423   // parameters (in case any of the errors above fired) and with
10424   // "void" as the return type, since destructors don't have return
10425   // types.
10426   if (!D.isInvalidType())
10427     return R;
10428 
10429   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10430   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10431   EPI.Variadic = false;
10432   EPI.TypeQuals = Qualifiers();
10433   EPI.RefQualifier = RQ_None;
10434   return Context.getFunctionType(Context.VoidTy, None, EPI);
10435 }
10436 
10437 static void extendLeft(SourceRange &R, SourceRange Before) {
10438   if (Before.isInvalid())
10439     return;
10440   R.setBegin(Before.getBegin());
10441   if (R.getEnd().isInvalid())
10442     R.setEnd(Before.getEnd());
10443 }
10444 
10445 static void extendRight(SourceRange &R, SourceRange After) {
10446   if (After.isInvalid())
10447     return;
10448   if (R.getBegin().isInvalid())
10449     R.setBegin(After.getBegin());
10450   R.setEnd(After.getEnd());
10451 }
10452 
10453 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10454 /// well-formednes of the conversion function declarator @p D with
10455 /// type @p R. If there are any errors in the declarator, this routine
10456 /// will emit diagnostics and return true. Otherwise, it will return
10457 /// false. Either way, the type @p R will be updated to reflect a
10458 /// well-formed type for the conversion operator.
10459 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10460                                      StorageClass& SC) {
10461   // C++ [class.conv.fct]p1:
10462   //   Neither parameter types nor return type can be specified. The
10463   //   type of a conversion function (8.3.5) is "function taking no
10464   //   parameter returning conversion-type-id."
10465   if (SC == SC_Static) {
10466     if (!D.isInvalidType())
10467       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10468         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10469         << D.getName().getSourceRange();
10470     D.setInvalidType();
10471     SC = SC_None;
10472   }
10473 
10474   TypeSourceInfo *ConvTSI = nullptr;
10475   QualType ConvType =
10476       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10477 
10478   const DeclSpec &DS = D.getDeclSpec();
10479   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10480     // Conversion functions don't have return types, but the parser will
10481     // happily parse something like:
10482     //
10483     //   class X {
10484     //     float operator bool();
10485     //   };
10486     //
10487     // The return type will be changed later anyway.
10488     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10489       << SourceRange(DS.getTypeSpecTypeLoc())
10490       << SourceRange(D.getIdentifierLoc());
10491     D.setInvalidType();
10492   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10493     // It's also plausible that the user writes type qualifiers in the wrong
10494     // place, such as:
10495     //   struct S { const operator int(); };
10496     // FIXME: we could provide a fixit to move the qualifiers onto the
10497     // conversion type.
10498     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10499         << SourceRange(D.getIdentifierLoc()) << 0;
10500     D.setInvalidType();
10501   }
10502 
10503   const auto *Proto = R->castAs<FunctionProtoType>();
10504 
10505   // Make sure we don't have any parameters.
10506   if (Proto->getNumParams() > 0) {
10507     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10508 
10509     // Delete the parameters.
10510     D.getFunctionTypeInfo().freeParams();
10511     D.setInvalidType();
10512   } else if (Proto->isVariadic()) {
10513     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10514     D.setInvalidType();
10515   }
10516 
10517   // Diagnose "&operator bool()" and other such nonsense.  This
10518   // is actually a gcc extension which we don't support.
10519   if (Proto->getReturnType() != ConvType) {
10520     bool NeedsTypedef = false;
10521     SourceRange Before, After;
10522 
10523     // Walk the chunks and extract information on them for our diagnostic.
10524     bool PastFunctionChunk = false;
10525     for (auto &Chunk : D.type_objects()) {
10526       switch (Chunk.Kind) {
10527       case DeclaratorChunk::Function:
10528         if (!PastFunctionChunk) {
10529           if (Chunk.Fun.HasTrailingReturnType) {
10530             TypeSourceInfo *TRT = nullptr;
10531             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10532             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10533           }
10534           PastFunctionChunk = true;
10535           break;
10536         }
10537         LLVM_FALLTHROUGH;
10538       case DeclaratorChunk::Array:
10539         NeedsTypedef = true;
10540         extendRight(After, Chunk.getSourceRange());
10541         break;
10542 
10543       case DeclaratorChunk::Pointer:
10544       case DeclaratorChunk::BlockPointer:
10545       case DeclaratorChunk::Reference:
10546       case DeclaratorChunk::MemberPointer:
10547       case DeclaratorChunk::Pipe:
10548         extendLeft(Before, Chunk.getSourceRange());
10549         break;
10550 
10551       case DeclaratorChunk::Paren:
10552         extendLeft(Before, Chunk.Loc);
10553         extendRight(After, Chunk.EndLoc);
10554         break;
10555       }
10556     }
10557 
10558     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10559                          After.isValid()  ? After.getBegin() :
10560                                             D.getIdentifierLoc();
10561     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10562     DB << Before << After;
10563 
10564     if (!NeedsTypedef) {
10565       DB << /*don't need a typedef*/0;
10566 
10567       // If we can provide a correct fix-it hint, do so.
10568       if (After.isInvalid() && ConvTSI) {
10569         SourceLocation InsertLoc =
10570             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10571         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10572            << FixItHint::CreateInsertionFromRange(
10573                   InsertLoc, CharSourceRange::getTokenRange(Before))
10574            << FixItHint::CreateRemoval(Before);
10575       }
10576     } else if (!Proto->getReturnType()->isDependentType()) {
10577       DB << /*typedef*/1 << Proto->getReturnType();
10578     } else if (getLangOpts().CPlusPlus11) {
10579       DB << /*alias template*/2 << Proto->getReturnType();
10580     } else {
10581       DB << /*might not be fixable*/3;
10582     }
10583 
10584     // Recover by incorporating the other type chunks into the result type.
10585     // Note, this does *not* change the name of the function. This is compatible
10586     // with the GCC extension:
10587     //   struct S { &operator int(); } s;
10588     //   int &r = s.operator int(); // ok in GCC
10589     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10590     ConvType = Proto->getReturnType();
10591   }
10592 
10593   // C++ [class.conv.fct]p4:
10594   //   The conversion-type-id shall not represent a function type nor
10595   //   an array type.
10596   if (ConvType->isArrayType()) {
10597     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10598     ConvType = Context.getPointerType(ConvType);
10599     D.setInvalidType();
10600   } else if (ConvType->isFunctionType()) {
10601     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10602     ConvType = Context.getPointerType(ConvType);
10603     D.setInvalidType();
10604   }
10605 
10606   // Rebuild the function type "R" without any parameters (in case any
10607   // of the errors above fired) and with the conversion type as the
10608   // return type.
10609   if (D.isInvalidType())
10610     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10611 
10612   // C++0x explicit conversion operators.
10613   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10614     Diag(DS.getExplicitSpecLoc(),
10615          getLangOpts().CPlusPlus11
10616              ? diag::warn_cxx98_compat_explicit_conversion_functions
10617              : diag::ext_explicit_conversion_functions)
10618         << SourceRange(DS.getExplicitSpecRange());
10619 }
10620 
10621 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10622 /// the declaration of the given C++ conversion function. This routine
10623 /// is responsible for recording the conversion function in the C++
10624 /// class, if possible.
10625 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10626   assert(Conversion && "Expected to receive a conversion function declaration");
10627 
10628   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10629 
10630   // Make sure we aren't redeclaring the conversion function.
10631   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10632   // C++ [class.conv.fct]p1:
10633   //   [...] A conversion function is never used to convert a
10634   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10635   //   same object type (or a reference to it), to a (possibly
10636   //   cv-qualified) base class of that type (or a reference to it),
10637   //   or to (possibly cv-qualified) void.
10638   QualType ClassType
10639     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10640   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10641     ConvType = ConvTypeRef->getPointeeType();
10642   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10643       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10644     /* Suppress diagnostics for instantiations. */;
10645   else if (Conversion->size_overridden_methods() != 0)
10646     /* Suppress diagnostics for overriding virtual function in a base class. */;
10647   else if (ConvType->isRecordType()) {
10648     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10649     if (ConvType == ClassType)
10650       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10651         << ClassType;
10652     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10653       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10654         <<  ClassType << ConvType;
10655   } else if (ConvType->isVoidType()) {
10656     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10657       << ClassType << ConvType;
10658   }
10659 
10660   if (FunctionTemplateDecl *ConversionTemplate
10661                                 = Conversion->getDescribedFunctionTemplate())
10662     return ConversionTemplate;
10663 
10664   return Conversion;
10665 }
10666 
10667 namespace {
10668 /// Utility class to accumulate and print a diagnostic listing the invalid
10669 /// specifier(s) on a declaration.
10670 struct BadSpecifierDiagnoser {
10671   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10672       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10673   ~BadSpecifierDiagnoser() {
10674     Diagnostic << Specifiers;
10675   }
10676 
10677   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10678     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10679   }
10680   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10681     return check(SpecLoc,
10682                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10683   }
10684   void check(SourceLocation SpecLoc, const char *Spec) {
10685     if (SpecLoc.isInvalid()) return;
10686     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10687     if (!Specifiers.empty()) Specifiers += " ";
10688     Specifiers += Spec;
10689   }
10690 
10691   Sema &S;
10692   Sema::SemaDiagnosticBuilder Diagnostic;
10693   std::string Specifiers;
10694 };
10695 }
10696 
10697 /// Check the validity of a declarator that we parsed for a deduction-guide.
10698 /// These aren't actually declarators in the grammar, so we need to check that
10699 /// the user didn't specify any pieces that are not part of the deduction-guide
10700 /// grammar.
10701 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10702                                          StorageClass &SC) {
10703   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10704   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10705   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10706 
10707   // C++ [temp.deduct.guide]p3:
10708   //   A deduction-gide shall be declared in the same scope as the
10709   //   corresponding class template.
10710   if (!CurContext->getRedeclContext()->Equals(
10711           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10712     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10713       << GuidedTemplateDecl;
10714     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10715   }
10716 
10717   auto &DS = D.getMutableDeclSpec();
10718   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10719   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10720       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10721       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10722     BadSpecifierDiagnoser Diagnoser(
10723         *this, D.getIdentifierLoc(),
10724         diag::err_deduction_guide_invalid_specifier);
10725 
10726     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10727     DS.ClearStorageClassSpecs();
10728     SC = SC_None;
10729 
10730     // 'explicit' is permitted.
10731     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10732     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10733     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10734     DS.ClearConstexprSpec();
10735 
10736     Diagnoser.check(DS.getConstSpecLoc(), "const");
10737     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10738     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10739     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10740     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10741     DS.ClearTypeQualifiers();
10742 
10743     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10744     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10745     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10746     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10747     DS.ClearTypeSpecType();
10748   }
10749 
10750   if (D.isInvalidType())
10751     return;
10752 
10753   // Check the declarator is simple enough.
10754   bool FoundFunction = false;
10755   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10756     if (Chunk.Kind == DeclaratorChunk::Paren)
10757       continue;
10758     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10759       Diag(D.getDeclSpec().getBeginLoc(),
10760            diag::err_deduction_guide_with_complex_decl)
10761           << D.getSourceRange();
10762       break;
10763     }
10764     if (!Chunk.Fun.hasTrailingReturnType()) {
10765       Diag(D.getName().getBeginLoc(),
10766            diag::err_deduction_guide_no_trailing_return_type);
10767       break;
10768     }
10769 
10770     // Check that the return type is written as a specialization of
10771     // the template specified as the deduction-guide's name.
10772     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10773     TypeSourceInfo *TSI = nullptr;
10774     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10775     assert(TSI && "deduction guide has valid type but invalid return type?");
10776     bool AcceptableReturnType = false;
10777     bool MightInstantiateToSpecialization = false;
10778     if (auto RetTST =
10779             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10780       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10781       bool TemplateMatches =
10782           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10783       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10784         AcceptableReturnType = true;
10785       else {
10786         // This could still instantiate to the right type, unless we know it
10787         // names the wrong class template.
10788         auto *TD = SpecifiedName.getAsTemplateDecl();
10789         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10790                                              !TemplateMatches);
10791       }
10792     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10793       MightInstantiateToSpecialization = true;
10794     }
10795 
10796     if (!AcceptableReturnType) {
10797       Diag(TSI->getTypeLoc().getBeginLoc(),
10798            diag::err_deduction_guide_bad_trailing_return_type)
10799           << GuidedTemplate << TSI->getType()
10800           << MightInstantiateToSpecialization
10801           << TSI->getTypeLoc().getSourceRange();
10802     }
10803 
10804     // Keep going to check that we don't have any inner declarator pieces (we
10805     // could still have a function returning a pointer to a function).
10806     FoundFunction = true;
10807   }
10808 
10809   if (D.isFunctionDefinition())
10810     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10811 }
10812 
10813 //===----------------------------------------------------------------------===//
10814 // Namespace Handling
10815 //===----------------------------------------------------------------------===//
10816 
10817 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10818 /// reopened.
10819 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10820                                             SourceLocation Loc,
10821                                             IdentifierInfo *II, bool *IsInline,
10822                                             NamespaceDecl *PrevNS) {
10823   assert(*IsInline != PrevNS->isInline());
10824 
10825   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10826   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10827   // inline namespaces, with the intention of bringing names into namespace std.
10828   //
10829   // We support this just well enough to get that case working; this is not
10830   // sufficient to support reopening namespaces as inline in general.
10831   if (*IsInline && II && II->getName().startswith("__atomic") &&
10832       S.getSourceManager().isInSystemHeader(Loc)) {
10833     // Mark all prior declarations of the namespace as inline.
10834     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10835          NS = NS->getPreviousDecl())
10836       NS->setInline(*IsInline);
10837     // Patch up the lookup table for the containing namespace. This isn't really
10838     // correct, but it's good enough for this particular case.
10839     for (auto *I : PrevNS->decls())
10840       if (auto *ND = dyn_cast<NamedDecl>(I))
10841         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10842     return;
10843   }
10844 
10845   if (PrevNS->isInline())
10846     // The user probably just forgot the 'inline', so suggest that it
10847     // be added back.
10848     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10849       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10850   else
10851     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10852 
10853   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10854   *IsInline = PrevNS->isInline();
10855 }
10856 
10857 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10858 /// definition.
10859 Decl *Sema::ActOnStartNamespaceDef(
10860     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10861     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10862     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10863   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10864   // For anonymous namespace, take the location of the left brace.
10865   SourceLocation Loc = II ? IdentLoc : LBrace;
10866   bool IsInline = InlineLoc.isValid();
10867   bool IsInvalid = false;
10868   bool IsStd = false;
10869   bool AddToKnown = false;
10870   Scope *DeclRegionScope = NamespcScope->getParent();
10871 
10872   NamespaceDecl *PrevNS = nullptr;
10873   if (II) {
10874     // C++ [namespace.def]p2:
10875     //   The identifier in an original-namespace-definition shall not
10876     //   have been previously defined in the declarative region in
10877     //   which the original-namespace-definition appears. The
10878     //   identifier in an original-namespace-definition is the name of
10879     //   the namespace. Subsequently in that declarative region, it is
10880     //   treated as an original-namespace-name.
10881     //
10882     // Since namespace names are unique in their scope, and we don't
10883     // look through using directives, just look for any ordinary names
10884     // as if by qualified name lookup.
10885     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10886                    ForExternalRedeclaration);
10887     LookupQualifiedName(R, CurContext->getRedeclContext());
10888     NamedDecl *PrevDecl =
10889         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10890     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10891 
10892     if (PrevNS) {
10893       // This is an extended namespace definition.
10894       if (IsInline != PrevNS->isInline())
10895         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10896                                         &IsInline, PrevNS);
10897     } else if (PrevDecl) {
10898       // This is an invalid name redefinition.
10899       Diag(Loc, diag::err_redefinition_different_kind)
10900         << II;
10901       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10902       IsInvalid = true;
10903       // Continue on to push Namespc as current DeclContext and return it.
10904     } else if (II->isStr("std") &&
10905                CurContext->getRedeclContext()->isTranslationUnit()) {
10906       // This is the first "real" definition of the namespace "std", so update
10907       // our cache of the "std" namespace to point at this definition.
10908       PrevNS = getStdNamespace();
10909       IsStd = true;
10910       AddToKnown = !IsInline;
10911     } else {
10912       // We've seen this namespace for the first time.
10913       AddToKnown = !IsInline;
10914     }
10915   } else {
10916     // Anonymous namespaces.
10917 
10918     // Determine whether the parent already has an anonymous namespace.
10919     DeclContext *Parent = CurContext->getRedeclContext();
10920     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10921       PrevNS = TU->getAnonymousNamespace();
10922     } else {
10923       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10924       PrevNS = ND->getAnonymousNamespace();
10925     }
10926 
10927     if (PrevNS && IsInline != PrevNS->isInline())
10928       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10929                                       &IsInline, PrevNS);
10930   }
10931 
10932   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10933                                                  StartLoc, Loc, II, PrevNS);
10934   if (IsInvalid)
10935     Namespc->setInvalidDecl();
10936 
10937   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10938   AddPragmaAttributes(DeclRegionScope, Namespc);
10939 
10940   // FIXME: Should we be merging attributes?
10941   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10942     PushNamespaceVisibilityAttr(Attr, Loc);
10943 
10944   if (IsStd)
10945     StdNamespace = Namespc;
10946   if (AddToKnown)
10947     KnownNamespaces[Namespc] = false;
10948 
10949   if (II) {
10950     PushOnScopeChains(Namespc, DeclRegionScope);
10951   } else {
10952     // Link the anonymous namespace into its parent.
10953     DeclContext *Parent = CurContext->getRedeclContext();
10954     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10955       TU->setAnonymousNamespace(Namespc);
10956     } else {
10957       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10958     }
10959 
10960     CurContext->addDecl(Namespc);
10961 
10962     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10963     //   behaves as if it were replaced by
10964     //     namespace unique { /* empty body */ }
10965     //     using namespace unique;
10966     //     namespace unique { namespace-body }
10967     //   where all occurrences of 'unique' in a translation unit are
10968     //   replaced by the same identifier and this identifier differs
10969     //   from all other identifiers in the entire program.
10970 
10971     // We just create the namespace with an empty name and then add an
10972     // implicit using declaration, just like the standard suggests.
10973     //
10974     // CodeGen enforces the "universally unique" aspect by giving all
10975     // declarations semantically contained within an anonymous
10976     // namespace internal linkage.
10977 
10978     if (!PrevNS) {
10979       UD = UsingDirectiveDecl::Create(Context, Parent,
10980                                       /* 'using' */ LBrace,
10981                                       /* 'namespace' */ SourceLocation(),
10982                                       /* qualifier */ NestedNameSpecifierLoc(),
10983                                       /* identifier */ SourceLocation(),
10984                                       Namespc,
10985                                       /* Ancestor */ Parent);
10986       UD->setImplicit();
10987       Parent->addDecl(UD);
10988     }
10989   }
10990 
10991   ActOnDocumentableDecl(Namespc);
10992 
10993   // Although we could have an invalid decl (i.e. the namespace name is a
10994   // redefinition), push it as current DeclContext and try to continue parsing.
10995   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10996   // for the namespace has the declarations that showed up in that particular
10997   // namespace definition.
10998   PushDeclContext(NamespcScope, Namespc);
10999   return Namespc;
11000 }
11001 
11002 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11003 /// is a namespace alias, returns the namespace it points to.
11004 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11005   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11006     return AD->getNamespace();
11007   return dyn_cast_or_null<NamespaceDecl>(D);
11008 }
11009 
11010 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11011 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11012 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11013   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11014   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11015   Namespc->setRBraceLoc(RBrace);
11016   PopDeclContext();
11017   if (Namespc->hasAttr<VisibilityAttr>())
11018     PopPragmaVisibility(true, RBrace);
11019   // If this namespace contains an export-declaration, export it now.
11020   if (DeferredExportedNamespaces.erase(Namespc))
11021     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11022 }
11023 
11024 CXXRecordDecl *Sema::getStdBadAlloc() const {
11025   return cast_or_null<CXXRecordDecl>(
11026                                   StdBadAlloc.get(Context.getExternalSource()));
11027 }
11028 
11029 EnumDecl *Sema::getStdAlignValT() const {
11030   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11031 }
11032 
11033 NamespaceDecl *Sema::getStdNamespace() const {
11034   return cast_or_null<NamespaceDecl>(
11035                                  StdNamespace.get(Context.getExternalSource()));
11036 }
11037 
11038 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11039   if (!StdExperimentalNamespaceCache) {
11040     if (auto Std = getStdNamespace()) {
11041       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11042                           SourceLocation(), LookupNamespaceName);
11043       if (!LookupQualifiedName(Result, Std) ||
11044           !(StdExperimentalNamespaceCache =
11045                 Result.getAsSingle<NamespaceDecl>()))
11046         Result.suppressDiagnostics();
11047     }
11048   }
11049   return StdExperimentalNamespaceCache;
11050 }
11051 
11052 namespace {
11053 
11054 enum UnsupportedSTLSelect {
11055   USS_InvalidMember,
11056   USS_MissingMember,
11057   USS_NonTrivial,
11058   USS_Other
11059 };
11060 
11061 struct InvalidSTLDiagnoser {
11062   Sema &S;
11063   SourceLocation Loc;
11064   QualType TyForDiags;
11065 
11066   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11067                       const VarDecl *VD = nullptr) {
11068     {
11069       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11070                << TyForDiags << ((int)Sel);
11071       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11072         assert(!Name.empty());
11073         D << Name;
11074       }
11075     }
11076     if (Sel == USS_InvalidMember) {
11077       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11078           << VD << VD->getSourceRange();
11079     }
11080     return QualType();
11081   }
11082 };
11083 } // namespace
11084 
11085 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11086                                            SourceLocation Loc,
11087                                            ComparisonCategoryUsage Usage) {
11088   assert(getLangOpts().CPlusPlus &&
11089          "Looking for comparison category type outside of C++.");
11090 
11091   // Use an elaborated type for diagnostics which has a name containing the
11092   // prepended 'std' namespace but not any inline namespace names.
11093   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11094     auto *NNS =
11095         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11096     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11097   };
11098 
11099   // Check if we've already successfully checked the comparison category type
11100   // before. If so, skip checking it again.
11101   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11102   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11103     // The only thing we need to check is that the type has a reachable
11104     // definition in the current context.
11105     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11106       return QualType();
11107 
11108     return Info->getType();
11109   }
11110 
11111   // If lookup failed
11112   if (!Info) {
11113     std::string NameForDiags = "std::";
11114     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11115     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11116         << NameForDiags << (int)Usage;
11117     return QualType();
11118   }
11119 
11120   assert(Info->Kind == Kind);
11121   assert(Info->Record);
11122 
11123   // Update the Record decl in case we encountered a forward declaration on our
11124   // first pass. FIXME: This is a bit of a hack.
11125   if (Info->Record->hasDefinition())
11126     Info->Record = Info->Record->getDefinition();
11127 
11128   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11129     return QualType();
11130 
11131   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11132 
11133   if (!Info->Record->isTriviallyCopyable())
11134     return UnsupportedSTLError(USS_NonTrivial);
11135 
11136   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11137     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11138     // Tolerate empty base classes.
11139     if (Base->isEmpty())
11140       continue;
11141     // Reject STL implementations which have at least one non-empty base.
11142     return UnsupportedSTLError();
11143   }
11144 
11145   // Check that the STL has implemented the types using a single integer field.
11146   // This expectation allows better codegen for builtin operators. We require:
11147   //   (1) The class has exactly one field.
11148   //   (2) The field is an integral or enumeration type.
11149   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11150   if (std::distance(FIt, FEnd) != 1 ||
11151       !FIt->getType()->isIntegralOrEnumerationType()) {
11152     return UnsupportedSTLError();
11153   }
11154 
11155   // Build each of the require values and store them in Info.
11156   for (ComparisonCategoryResult CCR :
11157        ComparisonCategories::getPossibleResultsForType(Kind)) {
11158     StringRef MemName = ComparisonCategories::getResultString(CCR);
11159     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11160 
11161     if (!ValInfo)
11162       return UnsupportedSTLError(USS_MissingMember, MemName);
11163 
11164     VarDecl *VD = ValInfo->VD;
11165     assert(VD && "should not be null!");
11166 
11167     // Attempt to diagnose reasons why the STL definition of this type
11168     // might be foobar, including it failing to be a constant expression.
11169     // TODO Handle more ways the lookup or result can be invalid.
11170     if (!VD->isStaticDataMember() ||
11171         !VD->isUsableInConstantExpressions(Context))
11172       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11173 
11174     // Attempt to evaluate the var decl as a constant expression and extract
11175     // the value of its first field as a ICE. If this fails, the STL
11176     // implementation is not supported.
11177     if (!ValInfo->hasValidIntValue())
11178       return UnsupportedSTLError();
11179 
11180     MarkVariableReferenced(Loc, VD);
11181   }
11182 
11183   // We've successfully built the required types and expressions. Update
11184   // the cache and return the newly cached value.
11185   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11186   return Info->getType();
11187 }
11188 
11189 /// Retrieve the special "std" namespace, which may require us to
11190 /// implicitly define the namespace.
11191 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11192   if (!StdNamespace) {
11193     // The "std" namespace has not yet been defined, so build one implicitly.
11194     StdNamespace = NamespaceDecl::Create(Context,
11195                                          Context.getTranslationUnitDecl(),
11196                                          /*Inline=*/false,
11197                                          SourceLocation(), SourceLocation(),
11198                                          &PP.getIdentifierTable().get("std"),
11199                                          /*PrevDecl=*/nullptr);
11200     getStdNamespace()->setImplicit(true);
11201   }
11202 
11203   return getStdNamespace();
11204 }
11205 
11206 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11207   assert(getLangOpts().CPlusPlus &&
11208          "Looking for std::initializer_list outside of C++.");
11209 
11210   // We're looking for implicit instantiations of
11211   // template <typename E> class std::initializer_list.
11212 
11213   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11214     return false;
11215 
11216   ClassTemplateDecl *Template = nullptr;
11217   const TemplateArgument *Arguments = nullptr;
11218 
11219   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11220 
11221     ClassTemplateSpecializationDecl *Specialization =
11222         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11223     if (!Specialization)
11224       return false;
11225 
11226     Template = Specialization->getSpecializedTemplate();
11227     Arguments = Specialization->getTemplateArgs().data();
11228   } else if (const TemplateSpecializationType *TST =
11229                  Ty->getAs<TemplateSpecializationType>()) {
11230     Template = dyn_cast_or_null<ClassTemplateDecl>(
11231         TST->getTemplateName().getAsTemplateDecl());
11232     Arguments = TST->getArgs();
11233   }
11234   if (!Template)
11235     return false;
11236 
11237   if (!StdInitializerList) {
11238     // Haven't recognized std::initializer_list yet, maybe this is it.
11239     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11240     if (TemplateClass->getIdentifier() !=
11241             &PP.getIdentifierTable().get("initializer_list") ||
11242         !getStdNamespace()->InEnclosingNamespaceSetOf(
11243             TemplateClass->getDeclContext()))
11244       return false;
11245     // This is a template called std::initializer_list, but is it the right
11246     // template?
11247     TemplateParameterList *Params = Template->getTemplateParameters();
11248     if (Params->getMinRequiredArguments() != 1)
11249       return false;
11250     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11251       return false;
11252 
11253     // It's the right template.
11254     StdInitializerList = Template;
11255   }
11256 
11257   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11258     return false;
11259 
11260   // This is an instance of std::initializer_list. Find the argument type.
11261   if (Element)
11262     *Element = Arguments[0].getAsType();
11263   return true;
11264 }
11265 
11266 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11267   NamespaceDecl *Std = S.getStdNamespace();
11268   if (!Std) {
11269     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11270     return nullptr;
11271   }
11272 
11273   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11274                       Loc, Sema::LookupOrdinaryName);
11275   if (!S.LookupQualifiedName(Result, Std)) {
11276     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11277     return nullptr;
11278   }
11279   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11280   if (!Template) {
11281     Result.suppressDiagnostics();
11282     // We found something weird. Complain about the first thing we found.
11283     NamedDecl *Found = *Result.begin();
11284     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11285     return nullptr;
11286   }
11287 
11288   // We found some template called std::initializer_list. Now verify that it's
11289   // correct.
11290   TemplateParameterList *Params = Template->getTemplateParameters();
11291   if (Params->getMinRequiredArguments() != 1 ||
11292       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11293     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11294     return nullptr;
11295   }
11296 
11297   return Template;
11298 }
11299 
11300 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11301   if (!StdInitializerList) {
11302     StdInitializerList = LookupStdInitializerList(*this, Loc);
11303     if (!StdInitializerList)
11304       return QualType();
11305   }
11306 
11307   TemplateArgumentListInfo Args(Loc, Loc);
11308   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11309                                        Context.getTrivialTypeSourceInfo(Element,
11310                                                                         Loc)));
11311   return Context.getCanonicalType(
11312       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11313 }
11314 
11315 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11316   // C++ [dcl.init.list]p2:
11317   //   A constructor is an initializer-list constructor if its first parameter
11318   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11319   //   std::initializer_list<E> for some type E, and either there are no other
11320   //   parameters or else all other parameters have default arguments.
11321   if (!Ctor->hasOneParamOrDefaultArgs())
11322     return false;
11323 
11324   QualType ArgType = Ctor->getParamDecl(0)->getType();
11325   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11326     ArgType = RT->getPointeeType().getUnqualifiedType();
11327 
11328   return isStdInitializerList(ArgType, nullptr);
11329 }
11330 
11331 /// Determine whether a using statement is in a context where it will be
11332 /// apply in all contexts.
11333 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11334   switch (CurContext->getDeclKind()) {
11335     case Decl::TranslationUnit:
11336       return true;
11337     case Decl::LinkageSpec:
11338       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11339     default:
11340       return false;
11341   }
11342 }
11343 
11344 namespace {
11345 
11346 // Callback to only accept typo corrections that are namespaces.
11347 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11348 public:
11349   bool ValidateCandidate(const TypoCorrection &candidate) override {
11350     if (NamedDecl *ND = candidate.getCorrectionDecl())
11351       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11352     return false;
11353   }
11354 
11355   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11356     return std::make_unique<NamespaceValidatorCCC>(*this);
11357   }
11358 };
11359 
11360 }
11361 
11362 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11363                                        CXXScopeSpec &SS,
11364                                        SourceLocation IdentLoc,
11365                                        IdentifierInfo *Ident) {
11366   R.clear();
11367   NamespaceValidatorCCC CCC{};
11368   if (TypoCorrection Corrected =
11369           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11370                         Sema::CTK_ErrorRecovery)) {
11371     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11372       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11373       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11374                               Ident->getName().equals(CorrectedStr);
11375       S.diagnoseTypo(Corrected,
11376                      S.PDiag(diag::err_using_directive_member_suggest)
11377                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11378                      S.PDiag(diag::note_namespace_defined_here));
11379     } else {
11380       S.diagnoseTypo(Corrected,
11381                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11382                      S.PDiag(diag::note_namespace_defined_here));
11383     }
11384     R.addDecl(Corrected.getFoundDecl());
11385     return true;
11386   }
11387   return false;
11388 }
11389 
11390 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11391                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11392                                 SourceLocation IdentLoc,
11393                                 IdentifierInfo *NamespcName,
11394                                 const ParsedAttributesView &AttrList) {
11395   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11396   assert(NamespcName && "Invalid NamespcName.");
11397   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11398 
11399   // This can only happen along a recovery path.
11400   while (S->isTemplateParamScope())
11401     S = S->getParent();
11402   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11403 
11404   UsingDirectiveDecl *UDir = nullptr;
11405   NestedNameSpecifier *Qualifier = nullptr;
11406   if (SS.isSet())
11407     Qualifier = SS.getScopeRep();
11408 
11409   // Lookup namespace name.
11410   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11411   LookupParsedName(R, S, &SS);
11412   if (R.isAmbiguous())
11413     return nullptr;
11414 
11415   if (R.empty()) {
11416     R.clear();
11417     // Allow "using namespace std;" or "using namespace ::std;" even if
11418     // "std" hasn't been defined yet, for GCC compatibility.
11419     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11420         NamespcName->isStr("std")) {
11421       Diag(IdentLoc, diag::ext_using_undefined_std);
11422       R.addDecl(getOrCreateStdNamespace());
11423       R.resolveKind();
11424     }
11425     // Otherwise, attempt typo correction.
11426     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11427   }
11428 
11429   if (!R.empty()) {
11430     NamedDecl *Named = R.getRepresentativeDecl();
11431     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11432     assert(NS && "expected namespace decl");
11433 
11434     // The use of a nested name specifier may trigger deprecation warnings.
11435     DiagnoseUseOfDecl(Named, IdentLoc);
11436 
11437     // C++ [namespace.udir]p1:
11438     //   A using-directive specifies that the names in the nominated
11439     //   namespace can be used in the scope in which the
11440     //   using-directive appears after the using-directive. During
11441     //   unqualified name lookup (3.4.1), the names appear as if they
11442     //   were declared in the nearest enclosing namespace which
11443     //   contains both the using-directive and the nominated
11444     //   namespace. [Note: in this context, "contains" means "contains
11445     //   directly or indirectly". ]
11446 
11447     // Find enclosing context containing both using-directive and
11448     // nominated namespace.
11449     DeclContext *CommonAncestor = NS;
11450     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11451       CommonAncestor = CommonAncestor->getParent();
11452 
11453     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11454                                       SS.getWithLocInContext(Context),
11455                                       IdentLoc, Named, CommonAncestor);
11456 
11457     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11458         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11459       Diag(IdentLoc, diag::warn_using_directive_in_header);
11460     }
11461 
11462     PushUsingDirective(S, UDir);
11463   } else {
11464     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11465   }
11466 
11467   if (UDir)
11468     ProcessDeclAttributeList(S, UDir, AttrList);
11469 
11470   return UDir;
11471 }
11472 
11473 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11474   // If the scope has an associated entity and the using directive is at
11475   // namespace or translation unit scope, add the UsingDirectiveDecl into
11476   // its lookup structure so qualified name lookup can find it.
11477   DeclContext *Ctx = S->getEntity();
11478   if (Ctx && !Ctx->isFunctionOrMethod())
11479     Ctx->addDecl(UDir);
11480   else
11481     // Otherwise, it is at block scope. The using-directives will affect lookup
11482     // only to the end of the scope.
11483     S->PushUsingDirective(UDir);
11484 }
11485 
11486 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11487                                   SourceLocation UsingLoc,
11488                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11489                                   UnqualifiedId &Name,
11490                                   SourceLocation EllipsisLoc,
11491                                   const ParsedAttributesView &AttrList) {
11492   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11493 
11494   if (SS.isEmpty()) {
11495     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11496     return nullptr;
11497   }
11498 
11499   switch (Name.getKind()) {
11500   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11501   case UnqualifiedIdKind::IK_Identifier:
11502   case UnqualifiedIdKind::IK_OperatorFunctionId:
11503   case UnqualifiedIdKind::IK_LiteralOperatorId:
11504   case UnqualifiedIdKind::IK_ConversionFunctionId:
11505     break;
11506 
11507   case UnqualifiedIdKind::IK_ConstructorName:
11508   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11509     // C++11 inheriting constructors.
11510     Diag(Name.getBeginLoc(),
11511          getLangOpts().CPlusPlus11
11512              ? diag::warn_cxx98_compat_using_decl_constructor
11513              : diag::err_using_decl_constructor)
11514         << SS.getRange();
11515 
11516     if (getLangOpts().CPlusPlus11) break;
11517 
11518     return nullptr;
11519 
11520   case UnqualifiedIdKind::IK_DestructorName:
11521     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11522     return nullptr;
11523 
11524   case UnqualifiedIdKind::IK_TemplateId:
11525     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11526         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11527     return nullptr;
11528 
11529   case UnqualifiedIdKind::IK_DeductionGuideName:
11530     llvm_unreachable("cannot parse qualified deduction guide name");
11531   }
11532 
11533   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11534   DeclarationName TargetName = TargetNameInfo.getName();
11535   if (!TargetName)
11536     return nullptr;
11537 
11538   // Warn about access declarations.
11539   if (UsingLoc.isInvalid()) {
11540     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11541                                  ? diag::err_access_decl
11542                                  : diag::warn_access_decl_deprecated)
11543         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11544   }
11545 
11546   if (EllipsisLoc.isInvalid()) {
11547     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11548         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11549       return nullptr;
11550   } else {
11551     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11552         !TargetNameInfo.containsUnexpandedParameterPack()) {
11553       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11554         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11555       EllipsisLoc = SourceLocation();
11556     }
11557   }
11558 
11559   NamedDecl *UD =
11560       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11561                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11562                             /*IsInstantiation*/false);
11563   if (UD)
11564     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11565 
11566   return UD;
11567 }
11568 
11569 /// Determine whether a using declaration considers the given
11570 /// declarations as "equivalent", e.g., if they are redeclarations of
11571 /// the same entity or are both typedefs of the same type.
11572 static bool
11573 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11574   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11575     return true;
11576 
11577   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11578     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11579       return Context.hasSameType(TD1->getUnderlyingType(),
11580                                  TD2->getUnderlyingType());
11581 
11582   return false;
11583 }
11584 
11585 
11586 /// Determines whether to create a using shadow decl for a particular
11587 /// decl, given the set of decls existing prior to this using lookup.
11588 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11589                                 const LookupResult &Previous,
11590                                 UsingShadowDecl *&PrevShadow) {
11591   // Diagnose finding a decl which is not from a base class of the
11592   // current class.  We do this now because there are cases where this
11593   // function will silently decide not to build a shadow decl, which
11594   // will pre-empt further diagnostics.
11595   //
11596   // We don't need to do this in C++11 because we do the check once on
11597   // the qualifier.
11598   //
11599   // FIXME: diagnose the following if we care enough:
11600   //   struct A { int foo; };
11601   //   struct B : A { using A::foo; };
11602   //   template <class T> struct C : A {};
11603   //   template <class T> struct D : C<T> { using B::foo; } // <---
11604   // This is invalid (during instantiation) in C++03 because B::foo
11605   // resolves to the using decl in B, which is not a base class of D<T>.
11606   // We can't diagnose it immediately because C<T> is an unknown
11607   // specialization.  The UsingShadowDecl in D<T> then points directly
11608   // to A::foo, which will look well-formed when we instantiate.
11609   // The right solution is to not collapse the shadow-decl chain.
11610   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11611     DeclContext *OrigDC = Orig->getDeclContext();
11612 
11613     // Handle enums and anonymous structs.
11614     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11615     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11616     while (OrigRec->isAnonymousStructOrUnion())
11617       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11618 
11619     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11620       if (OrigDC == CurContext) {
11621         Diag(Using->getLocation(),
11622              diag::err_using_decl_nested_name_specifier_is_current_class)
11623           << Using->getQualifierLoc().getSourceRange();
11624         Diag(Orig->getLocation(), diag::note_using_decl_target);
11625         Using->setInvalidDecl();
11626         return true;
11627       }
11628 
11629       Diag(Using->getQualifierLoc().getBeginLoc(),
11630            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11631         << Using->getQualifier()
11632         << cast<CXXRecordDecl>(CurContext)
11633         << Using->getQualifierLoc().getSourceRange();
11634       Diag(Orig->getLocation(), diag::note_using_decl_target);
11635       Using->setInvalidDecl();
11636       return true;
11637     }
11638   }
11639 
11640   if (Previous.empty()) return false;
11641 
11642   NamedDecl *Target = Orig;
11643   if (isa<UsingShadowDecl>(Target))
11644     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11645 
11646   // If the target happens to be one of the previous declarations, we
11647   // don't have a conflict.
11648   //
11649   // FIXME: but we might be increasing its access, in which case we
11650   // should redeclare it.
11651   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11652   bool FoundEquivalentDecl = false;
11653   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11654          I != E; ++I) {
11655     NamedDecl *D = (*I)->getUnderlyingDecl();
11656     // We can have UsingDecls in our Previous results because we use the same
11657     // LookupResult for checking whether the UsingDecl itself is a valid
11658     // redeclaration.
11659     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11660       continue;
11661 
11662     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11663       // C++ [class.mem]p19:
11664       //   If T is the name of a class, then [every named member other than
11665       //   a non-static data member] shall have a name different from T
11666       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11667           !isa<IndirectFieldDecl>(Target) &&
11668           !isa<UnresolvedUsingValueDecl>(Target) &&
11669           DiagnoseClassNameShadow(
11670               CurContext,
11671               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11672         return true;
11673     }
11674 
11675     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11676       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11677         PrevShadow = Shadow;
11678       FoundEquivalentDecl = true;
11679     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11680       // We don't conflict with an existing using shadow decl of an equivalent
11681       // declaration, but we're not a redeclaration of it.
11682       FoundEquivalentDecl = true;
11683     }
11684 
11685     if (isVisible(D))
11686       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11687   }
11688 
11689   if (FoundEquivalentDecl)
11690     return false;
11691 
11692   if (FunctionDecl *FD = Target->getAsFunction()) {
11693     NamedDecl *OldDecl = nullptr;
11694     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11695                           /*IsForUsingDecl*/ true)) {
11696     case Ovl_Overload:
11697       return false;
11698 
11699     case Ovl_NonFunction:
11700       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11701       break;
11702 
11703     // We found a decl with the exact signature.
11704     case Ovl_Match:
11705       // If we're in a record, we want to hide the target, so we
11706       // return true (without a diagnostic) to tell the caller not to
11707       // build a shadow decl.
11708       if (CurContext->isRecord())
11709         return true;
11710 
11711       // If we're not in a record, this is an error.
11712       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11713       break;
11714     }
11715 
11716     Diag(Target->getLocation(), diag::note_using_decl_target);
11717     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11718     Using->setInvalidDecl();
11719     return true;
11720   }
11721 
11722   // Target is not a function.
11723 
11724   if (isa<TagDecl>(Target)) {
11725     // No conflict between a tag and a non-tag.
11726     if (!Tag) return false;
11727 
11728     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11729     Diag(Target->getLocation(), diag::note_using_decl_target);
11730     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11731     Using->setInvalidDecl();
11732     return true;
11733   }
11734 
11735   // No conflict between a tag and a non-tag.
11736   if (!NonTag) return false;
11737 
11738   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11739   Diag(Target->getLocation(), diag::note_using_decl_target);
11740   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11741   Using->setInvalidDecl();
11742   return true;
11743 }
11744 
11745 /// Determine whether a direct base class is a virtual base class.
11746 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11747   if (!Derived->getNumVBases())
11748     return false;
11749   for (auto &B : Derived->bases())
11750     if (B.getType()->getAsCXXRecordDecl() == Base)
11751       return B.isVirtual();
11752   llvm_unreachable("not a direct base class");
11753 }
11754 
11755 /// Builds a shadow declaration corresponding to a 'using' declaration.
11756 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11757                                             UsingDecl *UD,
11758                                             NamedDecl *Orig,
11759                                             UsingShadowDecl *PrevDecl) {
11760   // If we resolved to another shadow declaration, just coalesce them.
11761   NamedDecl *Target = Orig;
11762   if (isa<UsingShadowDecl>(Target)) {
11763     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11764     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11765   }
11766 
11767   NamedDecl *NonTemplateTarget = Target;
11768   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11769     NonTemplateTarget = TargetTD->getTemplatedDecl();
11770 
11771   UsingShadowDecl *Shadow;
11772   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11773     bool IsVirtualBase =
11774         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11775                             UD->getQualifier()->getAsRecordDecl());
11776     Shadow = ConstructorUsingShadowDecl::Create(
11777         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11778   } else {
11779     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11780                                      Target);
11781   }
11782   UD->addShadowDecl(Shadow);
11783 
11784   Shadow->setAccess(UD->getAccess());
11785   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11786     Shadow->setInvalidDecl();
11787 
11788   Shadow->setPreviousDecl(PrevDecl);
11789 
11790   if (S)
11791     PushOnScopeChains(Shadow, S);
11792   else
11793     CurContext->addDecl(Shadow);
11794 
11795 
11796   return Shadow;
11797 }
11798 
11799 /// Hides a using shadow declaration.  This is required by the current
11800 /// using-decl implementation when a resolvable using declaration in a
11801 /// class is followed by a declaration which would hide or override
11802 /// one or more of the using decl's targets; for example:
11803 ///
11804 ///   struct Base { void foo(int); };
11805 ///   struct Derived : Base {
11806 ///     using Base::foo;
11807 ///     void foo(int);
11808 ///   };
11809 ///
11810 /// The governing language is C++03 [namespace.udecl]p12:
11811 ///
11812 ///   When a using-declaration brings names from a base class into a
11813 ///   derived class scope, member functions in the derived class
11814 ///   override and/or hide member functions with the same name and
11815 ///   parameter types in a base class (rather than conflicting).
11816 ///
11817 /// There are two ways to implement this:
11818 ///   (1) optimistically create shadow decls when they're not hidden
11819 ///       by existing declarations, or
11820 ///   (2) don't create any shadow decls (or at least don't make them
11821 ///       visible) until we've fully parsed/instantiated the class.
11822 /// The problem with (1) is that we might have to retroactively remove
11823 /// a shadow decl, which requires several O(n) operations because the
11824 /// decl structures are (very reasonably) not designed for removal.
11825 /// (2) avoids this but is very fiddly and phase-dependent.
11826 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11827   if (Shadow->getDeclName().getNameKind() ==
11828         DeclarationName::CXXConversionFunctionName)
11829     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11830 
11831   // Remove it from the DeclContext...
11832   Shadow->getDeclContext()->removeDecl(Shadow);
11833 
11834   // ...and the scope, if applicable...
11835   if (S) {
11836     S->RemoveDecl(Shadow);
11837     IdResolver.RemoveDecl(Shadow);
11838   }
11839 
11840   // ...and the using decl.
11841   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11842 
11843   // TODO: complain somehow if Shadow was used.  It shouldn't
11844   // be possible for this to happen, because...?
11845 }
11846 
11847 /// Find the base specifier for a base class with the given type.
11848 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11849                                                 QualType DesiredBase,
11850                                                 bool &AnyDependentBases) {
11851   // Check whether the named type is a direct base class.
11852   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11853     .getUnqualifiedType();
11854   for (auto &Base : Derived->bases()) {
11855     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11856     if (CanonicalDesiredBase == BaseType)
11857       return &Base;
11858     if (BaseType->isDependentType())
11859       AnyDependentBases = true;
11860   }
11861   return nullptr;
11862 }
11863 
11864 namespace {
11865 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11866 public:
11867   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11868                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11869       : HasTypenameKeyword(HasTypenameKeyword),
11870         IsInstantiation(IsInstantiation), OldNNS(NNS),
11871         RequireMemberOf(RequireMemberOf) {}
11872 
11873   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11874     NamedDecl *ND = Candidate.getCorrectionDecl();
11875 
11876     // Keywords are not valid here.
11877     if (!ND || isa<NamespaceDecl>(ND))
11878       return false;
11879 
11880     // Completely unqualified names are invalid for a 'using' declaration.
11881     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11882       return false;
11883 
11884     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11885     // reject.
11886 
11887     if (RequireMemberOf) {
11888       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11889       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11890         // No-one ever wants a using-declaration to name an injected-class-name
11891         // of a base class, unless they're declaring an inheriting constructor.
11892         ASTContext &Ctx = ND->getASTContext();
11893         if (!Ctx.getLangOpts().CPlusPlus11)
11894           return false;
11895         QualType FoundType = Ctx.getRecordType(FoundRecord);
11896 
11897         // Check that the injected-class-name is named as a member of its own
11898         // type; we don't want to suggest 'using Derived::Base;', since that
11899         // means something else.
11900         NestedNameSpecifier *Specifier =
11901             Candidate.WillReplaceSpecifier()
11902                 ? Candidate.getCorrectionSpecifier()
11903                 : OldNNS;
11904         if (!Specifier->getAsType() ||
11905             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11906           return false;
11907 
11908         // Check that this inheriting constructor declaration actually names a
11909         // direct base class of the current class.
11910         bool AnyDependentBases = false;
11911         if (!findDirectBaseWithType(RequireMemberOf,
11912                                     Ctx.getRecordType(FoundRecord),
11913                                     AnyDependentBases) &&
11914             !AnyDependentBases)
11915           return false;
11916       } else {
11917         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11918         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11919           return false;
11920 
11921         // FIXME: Check that the base class member is accessible?
11922       }
11923     } else {
11924       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11925       if (FoundRecord && FoundRecord->isInjectedClassName())
11926         return false;
11927     }
11928 
11929     if (isa<TypeDecl>(ND))
11930       return HasTypenameKeyword || !IsInstantiation;
11931 
11932     return !HasTypenameKeyword;
11933   }
11934 
11935   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11936     return std::make_unique<UsingValidatorCCC>(*this);
11937   }
11938 
11939 private:
11940   bool HasTypenameKeyword;
11941   bool IsInstantiation;
11942   NestedNameSpecifier *OldNNS;
11943   CXXRecordDecl *RequireMemberOf;
11944 };
11945 } // end anonymous namespace
11946 
11947 /// Builds a using declaration.
11948 ///
11949 /// \param IsInstantiation - Whether this call arises from an
11950 ///   instantiation of an unresolved using declaration.  We treat
11951 ///   the lookup differently for these declarations.
11952 NamedDecl *Sema::BuildUsingDeclaration(
11953     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11954     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11955     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11956     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11957   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11958   SourceLocation IdentLoc = NameInfo.getLoc();
11959   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11960 
11961   // FIXME: We ignore attributes for now.
11962 
11963   // For an inheriting constructor declaration, the name of the using
11964   // declaration is the name of a constructor in this class, not in the
11965   // base class.
11966   DeclarationNameInfo UsingName = NameInfo;
11967   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11968     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11969       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11970           Context.getCanonicalType(Context.getRecordType(RD))));
11971 
11972   // Do the redeclaration lookup in the current scope.
11973   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11974                         ForVisibleRedeclaration);
11975   Previous.setHideTags(false);
11976   if (S) {
11977     LookupName(Previous, S);
11978 
11979     // It is really dumb that we have to do this.
11980     LookupResult::Filter F = Previous.makeFilter();
11981     while (F.hasNext()) {
11982       NamedDecl *D = F.next();
11983       if (!isDeclInScope(D, CurContext, S))
11984         F.erase();
11985       // If we found a local extern declaration that's not ordinarily visible,
11986       // and this declaration is being added to a non-block scope, ignore it.
11987       // We're only checking for scope conflicts here, not also for violations
11988       // of the linkage rules.
11989       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11990                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11991         F.erase();
11992     }
11993     F.done();
11994   } else {
11995     assert(IsInstantiation && "no scope in non-instantiation");
11996     if (CurContext->isRecord())
11997       LookupQualifiedName(Previous, CurContext);
11998     else {
11999       // No redeclaration check is needed here; in non-member contexts we
12000       // diagnosed all possible conflicts with other using-declarations when
12001       // building the template:
12002       //
12003       // For a dependent non-type using declaration, the only valid case is
12004       // if we instantiate to a single enumerator. We check for conflicts
12005       // between shadow declarations we introduce, and we check in the template
12006       // definition for conflicts between a non-type using declaration and any
12007       // other declaration, which together covers all cases.
12008       //
12009       // A dependent typename using declaration will never successfully
12010       // instantiate, since it will always name a class member, so we reject
12011       // that in the template definition.
12012     }
12013   }
12014 
12015   // Check for invalid redeclarations.
12016   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12017                                   SS, IdentLoc, Previous))
12018     return nullptr;
12019 
12020   // Check for bad qualifiers.
12021   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12022                               IdentLoc))
12023     return nullptr;
12024 
12025   DeclContext *LookupContext = computeDeclContext(SS);
12026   NamedDecl *D;
12027   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12028   if (!LookupContext || EllipsisLoc.isValid()) {
12029     if (HasTypenameKeyword) {
12030       // FIXME: not all declaration name kinds are legal here
12031       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12032                                               UsingLoc, TypenameLoc,
12033                                               QualifierLoc,
12034                                               IdentLoc, NameInfo.getName(),
12035                                               EllipsisLoc);
12036     } else {
12037       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12038                                            QualifierLoc, NameInfo, EllipsisLoc);
12039     }
12040     D->setAccess(AS);
12041     CurContext->addDecl(D);
12042     return D;
12043   }
12044 
12045   auto Build = [&](bool Invalid) {
12046     UsingDecl *UD =
12047         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12048                           UsingName, HasTypenameKeyword);
12049     UD->setAccess(AS);
12050     CurContext->addDecl(UD);
12051     UD->setInvalidDecl(Invalid);
12052     return UD;
12053   };
12054   auto BuildInvalid = [&]{ return Build(true); };
12055   auto BuildValid = [&]{ return Build(false); };
12056 
12057   if (RequireCompleteDeclContext(SS, LookupContext))
12058     return BuildInvalid();
12059 
12060   // Look up the target name.
12061   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12062 
12063   // Unlike most lookups, we don't always want to hide tag
12064   // declarations: tag names are visible through the using declaration
12065   // even if hidden by ordinary names, *except* in a dependent context
12066   // where it's important for the sanity of two-phase lookup.
12067   if (!IsInstantiation)
12068     R.setHideTags(false);
12069 
12070   // For the purposes of this lookup, we have a base object type
12071   // equal to that of the current context.
12072   if (CurContext->isRecord()) {
12073     R.setBaseObjectType(
12074                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12075   }
12076 
12077   LookupQualifiedName(R, LookupContext);
12078 
12079   // Try to correct typos if possible. If constructor name lookup finds no
12080   // results, that means the named class has no explicit constructors, and we
12081   // suppressed declaring implicit ones (probably because it's dependent or
12082   // invalid).
12083   if (R.empty() &&
12084       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12085     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12086     // it will believe that glibc provides a ::gets in cases where it does not,
12087     // and will try to pull it into namespace std with a using-declaration.
12088     // Just ignore the using-declaration in that case.
12089     auto *II = NameInfo.getName().getAsIdentifierInfo();
12090     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12091         CurContext->isStdNamespace() &&
12092         isa<TranslationUnitDecl>(LookupContext) &&
12093         getSourceManager().isInSystemHeader(UsingLoc))
12094       return nullptr;
12095     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12096                           dyn_cast<CXXRecordDecl>(CurContext));
12097     if (TypoCorrection Corrected =
12098             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12099                         CTK_ErrorRecovery)) {
12100       // We reject candidates where DroppedSpecifier == true, hence the
12101       // literal '0' below.
12102       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12103                                 << NameInfo.getName() << LookupContext << 0
12104                                 << SS.getRange());
12105 
12106       // If we picked a correction with no attached Decl we can't do anything
12107       // useful with it, bail out.
12108       NamedDecl *ND = Corrected.getCorrectionDecl();
12109       if (!ND)
12110         return BuildInvalid();
12111 
12112       // If we corrected to an inheriting constructor, handle it as one.
12113       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12114       if (RD && RD->isInjectedClassName()) {
12115         // The parent of the injected class name is the class itself.
12116         RD = cast<CXXRecordDecl>(RD->getParent());
12117 
12118         // Fix up the information we'll use to build the using declaration.
12119         if (Corrected.WillReplaceSpecifier()) {
12120           NestedNameSpecifierLocBuilder Builder;
12121           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12122                               QualifierLoc.getSourceRange());
12123           QualifierLoc = Builder.getWithLocInContext(Context);
12124         }
12125 
12126         // In this case, the name we introduce is the name of a derived class
12127         // constructor.
12128         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12129         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12130             Context.getCanonicalType(Context.getRecordType(CurClass))));
12131         UsingName.setNamedTypeInfo(nullptr);
12132         for (auto *Ctor : LookupConstructors(RD))
12133           R.addDecl(Ctor);
12134         R.resolveKind();
12135       } else {
12136         // FIXME: Pick up all the declarations if we found an overloaded
12137         // function.
12138         UsingName.setName(ND->getDeclName());
12139         R.addDecl(ND);
12140       }
12141     } else {
12142       Diag(IdentLoc, diag::err_no_member)
12143         << NameInfo.getName() << LookupContext << SS.getRange();
12144       return BuildInvalid();
12145     }
12146   }
12147 
12148   if (R.isAmbiguous())
12149     return BuildInvalid();
12150 
12151   if (HasTypenameKeyword) {
12152     // If we asked for a typename and got a non-type decl, error out.
12153     if (!R.getAsSingle<TypeDecl>()) {
12154       Diag(IdentLoc, diag::err_using_typename_non_type);
12155       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12156         Diag((*I)->getUnderlyingDecl()->getLocation(),
12157              diag::note_using_decl_target);
12158       return BuildInvalid();
12159     }
12160   } else {
12161     // If we asked for a non-typename and we got a type, error out,
12162     // but only if this is an instantiation of an unresolved using
12163     // decl.  Otherwise just silently find the type name.
12164     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12165       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12166       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12167       return BuildInvalid();
12168     }
12169   }
12170 
12171   // C++14 [namespace.udecl]p6:
12172   // A using-declaration shall not name a namespace.
12173   if (R.getAsSingle<NamespaceDecl>()) {
12174     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12175       << SS.getRange();
12176     return BuildInvalid();
12177   }
12178 
12179   // C++14 [namespace.udecl]p7:
12180   // A using-declaration shall not name a scoped enumerator.
12181   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12182     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12183       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12184         << SS.getRange();
12185       return BuildInvalid();
12186     }
12187   }
12188 
12189   UsingDecl *UD = BuildValid();
12190 
12191   // Some additional rules apply to inheriting constructors.
12192   if (UsingName.getName().getNameKind() ==
12193         DeclarationName::CXXConstructorName) {
12194     // Suppress access diagnostics; the access check is instead performed at the
12195     // point of use for an inheriting constructor.
12196     R.suppressDiagnostics();
12197     if (CheckInheritingConstructorUsingDecl(UD))
12198       return UD;
12199   }
12200 
12201   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12202     UsingShadowDecl *PrevDecl = nullptr;
12203     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12204       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12205   }
12206 
12207   return UD;
12208 }
12209 
12210 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12211                                     ArrayRef<NamedDecl *> Expansions) {
12212   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12213          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12214          isa<UsingPackDecl>(InstantiatedFrom));
12215 
12216   auto *UPD =
12217       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12218   UPD->setAccess(InstantiatedFrom->getAccess());
12219   CurContext->addDecl(UPD);
12220   return UPD;
12221 }
12222 
12223 /// Additional checks for a using declaration referring to a constructor name.
12224 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12225   assert(!UD->hasTypename() && "expecting a constructor name");
12226 
12227   const Type *SourceType = UD->getQualifier()->getAsType();
12228   assert(SourceType &&
12229          "Using decl naming constructor doesn't have type in scope spec.");
12230   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12231 
12232   // Check whether the named type is a direct base class.
12233   bool AnyDependentBases = false;
12234   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12235                                       AnyDependentBases);
12236   if (!Base && !AnyDependentBases) {
12237     Diag(UD->getUsingLoc(),
12238          diag::err_using_decl_constructor_not_in_direct_base)
12239       << UD->getNameInfo().getSourceRange()
12240       << QualType(SourceType, 0) << TargetClass;
12241     UD->setInvalidDecl();
12242     return true;
12243   }
12244 
12245   if (Base)
12246     Base->setInheritConstructors();
12247 
12248   return false;
12249 }
12250 
12251 /// Checks that the given using declaration is not an invalid
12252 /// redeclaration.  Note that this is checking only for the using decl
12253 /// itself, not for any ill-formedness among the UsingShadowDecls.
12254 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12255                                        bool HasTypenameKeyword,
12256                                        const CXXScopeSpec &SS,
12257                                        SourceLocation NameLoc,
12258                                        const LookupResult &Prev) {
12259   NestedNameSpecifier *Qual = SS.getScopeRep();
12260 
12261   // C++03 [namespace.udecl]p8:
12262   // C++0x [namespace.udecl]p10:
12263   //   A using-declaration is a declaration and can therefore be used
12264   //   repeatedly where (and only where) multiple declarations are
12265   //   allowed.
12266   //
12267   // That's in non-member contexts.
12268   if (!CurContext->getRedeclContext()->isRecord()) {
12269     // A dependent qualifier outside a class can only ever resolve to an
12270     // enumeration type. Therefore it conflicts with any other non-type
12271     // declaration in the same scope.
12272     // FIXME: How should we check for dependent type-type conflicts at block
12273     // scope?
12274     if (Qual->isDependent() && !HasTypenameKeyword) {
12275       for (auto *D : Prev) {
12276         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12277           bool OldCouldBeEnumerator =
12278               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12279           Diag(NameLoc,
12280                OldCouldBeEnumerator ? diag::err_redefinition
12281                                     : diag::err_redefinition_different_kind)
12282               << Prev.getLookupName();
12283           Diag(D->getLocation(), diag::note_previous_definition);
12284           return true;
12285         }
12286       }
12287     }
12288     return false;
12289   }
12290 
12291   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12292     NamedDecl *D = *I;
12293 
12294     bool DTypename;
12295     NestedNameSpecifier *DQual;
12296     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12297       DTypename = UD->hasTypename();
12298       DQual = UD->getQualifier();
12299     } else if (UnresolvedUsingValueDecl *UD
12300                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12301       DTypename = false;
12302       DQual = UD->getQualifier();
12303     } else if (UnresolvedUsingTypenameDecl *UD
12304                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12305       DTypename = true;
12306       DQual = UD->getQualifier();
12307     } else continue;
12308 
12309     // using decls differ if one says 'typename' and the other doesn't.
12310     // FIXME: non-dependent using decls?
12311     if (HasTypenameKeyword != DTypename) continue;
12312 
12313     // using decls differ if they name different scopes (but note that
12314     // template instantiation can cause this check to trigger when it
12315     // didn't before instantiation).
12316     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12317         Context.getCanonicalNestedNameSpecifier(DQual))
12318       continue;
12319 
12320     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12321     Diag(D->getLocation(), diag::note_using_decl) << 1;
12322     return true;
12323   }
12324 
12325   return false;
12326 }
12327 
12328 
12329 /// Checks that the given nested-name qualifier used in a using decl
12330 /// in the current context is appropriately related to the current
12331 /// scope.  If an error is found, diagnoses it and returns true.
12332 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12333                                    bool HasTypename,
12334                                    const CXXScopeSpec &SS,
12335                                    const DeclarationNameInfo &NameInfo,
12336                                    SourceLocation NameLoc) {
12337   DeclContext *NamedContext = computeDeclContext(SS);
12338 
12339   if (!CurContext->isRecord()) {
12340     // C++03 [namespace.udecl]p3:
12341     // C++0x [namespace.udecl]p8:
12342     //   A using-declaration for a class member shall be a member-declaration.
12343 
12344     // If we weren't able to compute a valid scope, it might validly be a
12345     // dependent class scope or a dependent enumeration unscoped scope. If
12346     // we have a 'typename' keyword, the scope must resolve to a class type.
12347     if ((HasTypename && !NamedContext) ||
12348         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12349       auto *RD = NamedContext
12350                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12351                      : nullptr;
12352       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12353         RD = nullptr;
12354 
12355       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12356         << SS.getRange();
12357 
12358       // If we have a complete, non-dependent source type, try to suggest a
12359       // way to get the same effect.
12360       if (!RD)
12361         return true;
12362 
12363       // Find what this using-declaration was referring to.
12364       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12365       R.setHideTags(false);
12366       R.suppressDiagnostics();
12367       LookupQualifiedName(R, RD);
12368 
12369       if (R.getAsSingle<TypeDecl>()) {
12370         if (getLangOpts().CPlusPlus11) {
12371           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12372           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12373             << 0 // alias declaration
12374             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12375                                           NameInfo.getName().getAsString() +
12376                                               " = ");
12377         } else {
12378           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12379           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12380           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12381             << 1 // typedef declaration
12382             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12383             << FixItHint::CreateInsertion(
12384                    InsertLoc, " " + NameInfo.getName().getAsString());
12385         }
12386       } else if (R.getAsSingle<VarDecl>()) {
12387         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12388         // repeating the type of the static data member here.
12389         FixItHint FixIt;
12390         if (getLangOpts().CPlusPlus11) {
12391           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12392           FixIt = FixItHint::CreateReplacement(
12393               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12394         }
12395 
12396         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12397           << 2 // reference declaration
12398           << FixIt;
12399       } else if (R.getAsSingle<EnumConstantDecl>()) {
12400         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12401         // repeating the type of the enumeration here, and we can't do so if
12402         // the type is anonymous.
12403         FixItHint FixIt;
12404         if (getLangOpts().CPlusPlus11) {
12405           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12406           FixIt = FixItHint::CreateReplacement(
12407               UsingLoc,
12408               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12409         }
12410 
12411         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12412           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12413           << FixIt;
12414       }
12415       return true;
12416     }
12417 
12418     // Otherwise, this might be valid.
12419     return false;
12420   }
12421 
12422   // The current scope is a record.
12423 
12424   // If the named context is dependent, we can't decide much.
12425   if (!NamedContext) {
12426     // FIXME: in C++0x, we can diagnose if we can prove that the
12427     // nested-name-specifier does not refer to a base class, which is
12428     // still possible in some cases.
12429 
12430     // Otherwise we have to conservatively report that things might be
12431     // okay.
12432     return false;
12433   }
12434 
12435   if (!NamedContext->isRecord()) {
12436     // Ideally this would point at the last name in the specifier,
12437     // but we don't have that level of source info.
12438     Diag(SS.getRange().getBegin(),
12439          diag::err_using_decl_nested_name_specifier_is_not_class)
12440       << SS.getScopeRep() << SS.getRange();
12441     return true;
12442   }
12443 
12444   if (!NamedContext->isDependentContext() &&
12445       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12446     return true;
12447 
12448   if (getLangOpts().CPlusPlus11) {
12449     // C++11 [namespace.udecl]p3:
12450     //   In a using-declaration used as a member-declaration, the
12451     //   nested-name-specifier shall name a base class of the class
12452     //   being defined.
12453 
12454     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12455                                  cast<CXXRecordDecl>(NamedContext))) {
12456       if (CurContext == NamedContext) {
12457         Diag(NameLoc,
12458              diag::err_using_decl_nested_name_specifier_is_current_class)
12459           << SS.getRange();
12460         return true;
12461       }
12462 
12463       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12464         Diag(SS.getRange().getBegin(),
12465              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12466           << SS.getScopeRep()
12467           << cast<CXXRecordDecl>(CurContext)
12468           << SS.getRange();
12469       }
12470       return true;
12471     }
12472 
12473     return false;
12474   }
12475 
12476   // C++03 [namespace.udecl]p4:
12477   //   A using-declaration used as a member-declaration shall refer
12478   //   to a member of a base class of the class being defined [etc.].
12479 
12480   // Salient point: SS doesn't have to name a base class as long as
12481   // lookup only finds members from base classes.  Therefore we can
12482   // diagnose here only if we can prove that that can't happen,
12483   // i.e. if the class hierarchies provably don't intersect.
12484 
12485   // TODO: it would be nice if "definitely valid" results were cached
12486   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12487   // need to be repeated.
12488 
12489   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12490   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12491     Bases.insert(Base);
12492     return true;
12493   };
12494 
12495   // Collect all bases. Return false if we find a dependent base.
12496   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12497     return false;
12498 
12499   // Returns true if the base is dependent or is one of the accumulated base
12500   // classes.
12501   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12502     return !Bases.count(Base);
12503   };
12504 
12505   // Return false if the class has a dependent base or if it or one
12506   // of its bases is present in the base set of the current context.
12507   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12508       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12509     return false;
12510 
12511   Diag(SS.getRange().getBegin(),
12512        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12513     << SS.getScopeRep()
12514     << cast<CXXRecordDecl>(CurContext)
12515     << SS.getRange();
12516 
12517   return true;
12518 }
12519 
12520 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12521                                   MultiTemplateParamsArg TemplateParamLists,
12522                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12523                                   const ParsedAttributesView &AttrList,
12524                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12525   // Skip up to the relevant declaration scope.
12526   while (S->isTemplateParamScope())
12527     S = S->getParent();
12528   assert((S->getFlags() & Scope::DeclScope) &&
12529          "got alias-declaration outside of declaration scope");
12530 
12531   if (Type.isInvalid())
12532     return nullptr;
12533 
12534   bool Invalid = false;
12535   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12536   TypeSourceInfo *TInfo = nullptr;
12537   GetTypeFromParser(Type.get(), &TInfo);
12538 
12539   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12540     return nullptr;
12541 
12542   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12543                                       UPPC_DeclarationType)) {
12544     Invalid = true;
12545     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12546                                              TInfo->getTypeLoc().getBeginLoc());
12547   }
12548 
12549   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12550                         TemplateParamLists.size()
12551                             ? forRedeclarationInCurContext()
12552                             : ForVisibleRedeclaration);
12553   LookupName(Previous, S);
12554 
12555   // Warn about shadowing the name of a template parameter.
12556   if (Previous.isSingleResult() &&
12557       Previous.getFoundDecl()->isTemplateParameter()) {
12558     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12559     Previous.clear();
12560   }
12561 
12562   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12563          "name in alias declaration must be an identifier");
12564   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12565                                                Name.StartLocation,
12566                                                Name.Identifier, TInfo);
12567 
12568   NewTD->setAccess(AS);
12569 
12570   if (Invalid)
12571     NewTD->setInvalidDecl();
12572 
12573   ProcessDeclAttributeList(S, NewTD, AttrList);
12574   AddPragmaAttributes(S, NewTD);
12575 
12576   CheckTypedefForVariablyModifiedType(S, NewTD);
12577   Invalid |= NewTD->isInvalidDecl();
12578 
12579   bool Redeclaration = false;
12580 
12581   NamedDecl *NewND;
12582   if (TemplateParamLists.size()) {
12583     TypeAliasTemplateDecl *OldDecl = nullptr;
12584     TemplateParameterList *OldTemplateParams = nullptr;
12585 
12586     if (TemplateParamLists.size() != 1) {
12587       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12588         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12589          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12590     }
12591     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12592 
12593     // Check that we can declare a template here.
12594     if (CheckTemplateDeclScope(S, TemplateParams))
12595       return nullptr;
12596 
12597     // Only consider previous declarations in the same scope.
12598     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12599                          /*ExplicitInstantiationOrSpecialization*/false);
12600     if (!Previous.empty()) {
12601       Redeclaration = true;
12602 
12603       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12604       if (!OldDecl && !Invalid) {
12605         Diag(UsingLoc, diag::err_redefinition_different_kind)
12606           << Name.Identifier;
12607 
12608         NamedDecl *OldD = Previous.getRepresentativeDecl();
12609         if (OldD->getLocation().isValid())
12610           Diag(OldD->getLocation(), diag::note_previous_definition);
12611 
12612         Invalid = true;
12613       }
12614 
12615       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12616         if (TemplateParameterListsAreEqual(TemplateParams,
12617                                            OldDecl->getTemplateParameters(),
12618                                            /*Complain=*/true,
12619                                            TPL_TemplateMatch))
12620           OldTemplateParams =
12621               OldDecl->getMostRecentDecl()->getTemplateParameters();
12622         else
12623           Invalid = true;
12624 
12625         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12626         if (!Invalid &&
12627             !Context.hasSameType(OldTD->getUnderlyingType(),
12628                                  NewTD->getUnderlyingType())) {
12629           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12630           // but we can't reasonably accept it.
12631           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12632             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12633           if (OldTD->getLocation().isValid())
12634             Diag(OldTD->getLocation(), diag::note_previous_definition);
12635           Invalid = true;
12636         }
12637       }
12638     }
12639 
12640     // Merge any previous default template arguments into our parameters,
12641     // and check the parameter list.
12642     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12643                                    TPC_TypeAliasTemplate))
12644       return nullptr;
12645 
12646     TypeAliasTemplateDecl *NewDecl =
12647       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12648                                     Name.Identifier, TemplateParams,
12649                                     NewTD);
12650     NewTD->setDescribedAliasTemplate(NewDecl);
12651 
12652     NewDecl->setAccess(AS);
12653 
12654     if (Invalid)
12655       NewDecl->setInvalidDecl();
12656     else if (OldDecl) {
12657       NewDecl->setPreviousDecl(OldDecl);
12658       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12659     }
12660 
12661     NewND = NewDecl;
12662   } else {
12663     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12664       setTagNameForLinkagePurposes(TD, NewTD);
12665       handleTagNumbering(TD, S);
12666     }
12667     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12668     NewND = NewTD;
12669   }
12670 
12671   PushOnScopeChains(NewND, S);
12672   ActOnDocumentableDecl(NewND);
12673   return NewND;
12674 }
12675 
12676 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12677                                    SourceLocation AliasLoc,
12678                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12679                                    SourceLocation IdentLoc,
12680                                    IdentifierInfo *Ident) {
12681 
12682   // Lookup the namespace name.
12683   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12684   LookupParsedName(R, S, &SS);
12685 
12686   if (R.isAmbiguous())
12687     return nullptr;
12688 
12689   if (R.empty()) {
12690     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12691       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12692       return nullptr;
12693     }
12694   }
12695   assert(!R.isAmbiguous() && !R.empty());
12696   NamedDecl *ND = R.getRepresentativeDecl();
12697 
12698   // Check if we have a previous declaration with the same name.
12699   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12700                      ForVisibleRedeclaration);
12701   LookupName(PrevR, S);
12702 
12703   // Check we're not shadowing a template parameter.
12704   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12705     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12706     PrevR.clear();
12707   }
12708 
12709   // Filter out any other lookup result from an enclosing scope.
12710   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12711                        /*AllowInlineNamespace*/false);
12712 
12713   // Find the previous declaration and check that we can redeclare it.
12714   NamespaceAliasDecl *Prev = nullptr;
12715   if (PrevR.isSingleResult()) {
12716     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12717     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12718       // We already have an alias with the same name that points to the same
12719       // namespace; check that it matches.
12720       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12721         Prev = AD;
12722       } else if (isVisible(PrevDecl)) {
12723         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12724           << Alias;
12725         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12726           << AD->getNamespace();
12727         return nullptr;
12728       }
12729     } else if (isVisible(PrevDecl)) {
12730       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12731                             ? diag::err_redefinition
12732                             : diag::err_redefinition_different_kind;
12733       Diag(AliasLoc, DiagID) << Alias;
12734       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12735       return nullptr;
12736     }
12737   }
12738 
12739   // The use of a nested name specifier may trigger deprecation warnings.
12740   DiagnoseUseOfDecl(ND, IdentLoc);
12741 
12742   NamespaceAliasDecl *AliasDecl =
12743     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12744                                Alias, SS.getWithLocInContext(Context),
12745                                IdentLoc, ND);
12746   if (Prev)
12747     AliasDecl->setPreviousDecl(Prev);
12748 
12749   PushOnScopeChains(AliasDecl, S);
12750   return AliasDecl;
12751 }
12752 
12753 namespace {
12754 struct SpecialMemberExceptionSpecInfo
12755     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12756   SourceLocation Loc;
12757   Sema::ImplicitExceptionSpecification ExceptSpec;
12758 
12759   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12760                                  Sema::CXXSpecialMember CSM,
12761                                  Sema::InheritedConstructorInfo *ICI,
12762                                  SourceLocation Loc)
12763       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12764 
12765   bool visitBase(CXXBaseSpecifier *Base);
12766   bool visitField(FieldDecl *FD);
12767 
12768   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12769                            unsigned Quals);
12770 
12771   void visitSubobjectCall(Subobject Subobj,
12772                           Sema::SpecialMemberOverloadResult SMOR);
12773 };
12774 }
12775 
12776 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12777   auto *RT = Base->getType()->getAs<RecordType>();
12778   if (!RT)
12779     return false;
12780 
12781   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12782   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12783   if (auto *BaseCtor = SMOR.getMethod()) {
12784     visitSubobjectCall(Base, BaseCtor);
12785     return false;
12786   }
12787 
12788   visitClassSubobject(BaseClass, Base, 0);
12789   return false;
12790 }
12791 
12792 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12793   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12794     Expr *E = FD->getInClassInitializer();
12795     if (!E)
12796       // FIXME: It's a little wasteful to build and throw away a
12797       // CXXDefaultInitExpr here.
12798       // FIXME: We should have a single context note pointing at Loc, and
12799       // this location should be MD->getLocation() instead, since that's
12800       // the location where we actually use the default init expression.
12801       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12802     if (E)
12803       ExceptSpec.CalledExpr(E);
12804   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12805                             ->getAs<RecordType>()) {
12806     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12807                         FD->getType().getCVRQualifiers());
12808   }
12809   return false;
12810 }
12811 
12812 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12813                                                          Subobject Subobj,
12814                                                          unsigned Quals) {
12815   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12816   bool IsMutable = Field && Field->isMutable();
12817   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12818 }
12819 
12820 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12821     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12822   // Note, if lookup fails, it doesn't matter what exception specification we
12823   // choose because the special member will be deleted.
12824   if (CXXMethodDecl *MD = SMOR.getMethod())
12825     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12826 }
12827 
12828 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12829   llvm::APSInt Result;
12830   ExprResult Converted = CheckConvertedConstantExpression(
12831       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12832   ExplicitSpec.setExpr(Converted.get());
12833   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12834     ExplicitSpec.setKind(Result.getBoolValue()
12835                              ? ExplicitSpecKind::ResolvedTrue
12836                              : ExplicitSpecKind::ResolvedFalse);
12837     return true;
12838   }
12839   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12840   return false;
12841 }
12842 
12843 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12844   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12845   if (!ExplicitExpr->isTypeDependent())
12846     tryResolveExplicitSpecifier(ES);
12847   return ES;
12848 }
12849 
12850 static Sema::ImplicitExceptionSpecification
12851 ComputeDefaultedSpecialMemberExceptionSpec(
12852     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12853     Sema::InheritedConstructorInfo *ICI) {
12854   ComputingExceptionSpec CES(S, MD, Loc);
12855 
12856   CXXRecordDecl *ClassDecl = MD->getParent();
12857 
12858   // C++ [except.spec]p14:
12859   //   An implicitly declared special member function (Clause 12) shall have an
12860   //   exception-specification. [...]
12861   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12862   if (ClassDecl->isInvalidDecl())
12863     return Info.ExceptSpec;
12864 
12865   // FIXME: If this diagnostic fires, we're probably missing a check for
12866   // attempting to resolve an exception specification before it's known
12867   // at a higher level.
12868   if (S.RequireCompleteType(MD->getLocation(),
12869                             S.Context.getRecordType(ClassDecl),
12870                             diag::err_exception_spec_incomplete_type))
12871     return Info.ExceptSpec;
12872 
12873   // C++1z [except.spec]p7:
12874   //   [Look for exceptions thrown by] a constructor selected [...] to
12875   //   initialize a potentially constructed subobject,
12876   // C++1z [except.spec]p8:
12877   //   The exception specification for an implicitly-declared destructor, or a
12878   //   destructor without a noexcept-specifier, is potentially-throwing if and
12879   //   only if any of the destructors for any of its potentially constructed
12880   //   subojects is potentially throwing.
12881   // FIXME: We respect the first rule but ignore the "potentially constructed"
12882   // in the second rule to resolve a core issue (no number yet) that would have
12883   // us reject:
12884   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12885   //   struct B : A {};
12886   //   struct C : B { void f(); };
12887   // ... due to giving B::~B() a non-throwing exception specification.
12888   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12889                                 : Info.VisitAllBases);
12890 
12891   return Info.ExceptSpec;
12892 }
12893 
12894 namespace {
12895 /// RAII object to register a special member as being currently declared.
12896 struct DeclaringSpecialMember {
12897   Sema &S;
12898   Sema::SpecialMemberDecl D;
12899   Sema::ContextRAII SavedContext;
12900   bool WasAlreadyBeingDeclared;
12901 
12902   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12903       : S(S), D(RD, CSM), SavedContext(S, RD) {
12904     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12905     if (WasAlreadyBeingDeclared)
12906       // This almost never happens, but if it does, ensure that our cache
12907       // doesn't contain a stale result.
12908       S.SpecialMemberCache.clear();
12909     else {
12910       // Register a note to be produced if we encounter an error while
12911       // declaring the special member.
12912       Sema::CodeSynthesisContext Ctx;
12913       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12914       // FIXME: We don't have a location to use here. Using the class's
12915       // location maintains the fiction that we declare all special members
12916       // with the class, but (1) it's not clear that lying about that helps our
12917       // users understand what's going on, and (2) there may be outer contexts
12918       // on the stack (some of which are relevant) and printing them exposes
12919       // our lies.
12920       Ctx.PointOfInstantiation = RD->getLocation();
12921       Ctx.Entity = RD;
12922       Ctx.SpecialMember = CSM;
12923       S.pushCodeSynthesisContext(Ctx);
12924     }
12925   }
12926   ~DeclaringSpecialMember() {
12927     if (!WasAlreadyBeingDeclared) {
12928       S.SpecialMembersBeingDeclared.erase(D);
12929       S.popCodeSynthesisContext();
12930     }
12931   }
12932 
12933   /// Are we already trying to declare this special member?
12934   bool isAlreadyBeingDeclared() const {
12935     return WasAlreadyBeingDeclared;
12936   }
12937 };
12938 }
12939 
12940 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12941   // Look up any existing declarations, but don't trigger declaration of all
12942   // implicit special members with this name.
12943   DeclarationName Name = FD->getDeclName();
12944   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12945                  ForExternalRedeclaration);
12946   for (auto *D : FD->getParent()->lookup(Name))
12947     if (auto *Acceptable = R.getAcceptableDecl(D))
12948       R.addDecl(Acceptable);
12949   R.resolveKind();
12950   R.suppressDiagnostics();
12951 
12952   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12953 }
12954 
12955 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12956                                           QualType ResultTy,
12957                                           ArrayRef<QualType> Args) {
12958   // Build an exception specification pointing back at this constructor.
12959   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12960 
12961   LangAS AS = getDefaultCXXMethodAddrSpace();
12962   if (AS != LangAS::Default) {
12963     EPI.TypeQuals.addAddressSpace(AS);
12964   }
12965 
12966   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12967   SpecialMem->setType(QT);
12968 }
12969 
12970 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12971                                                      CXXRecordDecl *ClassDecl) {
12972   // C++ [class.ctor]p5:
12973   //   A default constructor for a class X is a constructor of class X
12974   //   that can be called without an argument. If there is no
12975   //   user-declared constructor for class X, a default constructor is
12976   //   implicitly declared. An implicitly-declared default constructor
12977   //   is an inline public member of its class.
12978   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12979          "Should not build implicit default constructor!");
12980 
12981   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12982   if (DSM.isAlreadyBeingDeclared())
12983     return nullptr;
12984 
12985   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12986                                                      CXXDefaultConstructor,
12987                                                      false);
12988 
12989   // Create the actual constructor declaration.
12990   CanQualType ClassType
12991     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12992   SourceLocation ClassLoc = ClassDecl->getLocation();
12993   DeclarationName Name
12994     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12995   DeclarationNameInfo NameInfo(Name, ClassLoc);
12996   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12997       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12998       /*TInfo=*/nullptr, ExplicitSpecifier(),
12999       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13000       Constexpr ? ConstexprSpecKind::Constexpr
13001                 : ConstexprSpecKind::Unspecified);
13002   DefaultCon->setAccess(AS_public);
13003   DefaultCon->setDefaulted();
13004 
13005   if (getLangOpts().CUDA) {
13006     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13007                                             DefaultCon,
13008                                             /* ConstRHS */ false,
13009                                             /* Diagnose */ false);
13010   }
13011 
13012   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13013 
13014   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13015   // constructors is easy to compute.
13016   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13017 
13018   // Note that we have declared this constructor.
13019   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13020 
13021   Scope *S = getScopeForContext(ClassDecl);
13022   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13023 
13024   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13025     SetDeclDeleted(DefaultCon, ClassLoc);
13026 
13027   if (S)
13028     PushOnScopeChains(DefaultCon, S, false);
13029   ClassDecl->addDecl(DefaultCon);
13030 
13031   return DefaultCon;
13032 }
13033 
13034 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13035                                             CXXConstructorDecl *Constructor) {
13036   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13037           !Constructor->doesThisDeclarationHaveABody() &&
13038           !Constructor->isDeleted()) &&
13039     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13040   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13041     return;
13042 
13043   CXXRecordDecl *ClassDecl = Constructor->getParent();
13044   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13045 
13046   SynthesizedFunctionScope Scope(*this, Constructor);
13047 
13048   // The exception specification is needed because we are defining the
13049   // function.
13050   ResolveExceptionSpec(CurrentLocation,
13051                        Constructor->getType()->castAs<FunctionProtoType>());
13052   MarkVTableUsed(CurrentLocation, ClassDecl);
13053 
13054   // Add a context note for diagnostics produced after this point.
13055   Scope.addContextNote(CurrentLocation);
13056 
13057   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13058     Constructor->setInvalidDecl();
13059     return;
13060   }
13061 
13062   SourceLocation Loc = Constructor->getEndLoc().isValid()
13063                            ? Constructor->getEndLoc()
13064                            : Constructor->getLocation();
13065   Constructor->setBody(new (Context) CompoundStmt(Loc));
13066   Constructor->markUsed(Context);
13067 
13068   if (ASTMutationListener *L = getASTMutationListener()) {
13069     L->CompletedImplicitDefinition(Constructor);
13070   }
13071 
13072   DiagnoseUninitializedFields(*this, Constructor);
13073 }
13074 
13075 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13076   // Perform any delayed checks on exception specifications.
13077   CheckDelayedMemberExceptionSpecs();
13078 }
13079 
13080 /// Find or create the fake constructor we synthesize to model constructing an
13081 /// object of a derived class via a constructor of a base class.
13082 CXXConstructorDecl *
13083 Sema::findInheritingConstructor(SourceLocation Loc,
13084                                 CXXConstructorDecl *BaseCtor,
13085                                 ConstructorUsingShadowDecl *Shadow) {
13086   CXXRecordDecl *Derived = Shadow->getParent();
13087   SourceLocation UsingLoc = Shadow->getLocation();
13088 
13089   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13090   // For now we use the name of the base class constructor as a member of the
13091   // derived class to indicate a (fake) inherited constructor name.
13092   DeclarationName Name = BaseCtor->getDeclName();
13093 
13094   // Check to see if we already have a fake constructor for this inherited
13095   // constructor call.
13096   for (NamedDecl *Ctor : Derived->lookup(Name))
13097     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13098                                ->getInheritedConstructor()
13099                                .getConstructor(),
13100                            BaseCtor))
13101       return cast<CXXConstructorDecl>(Ctor);
13102 
13103   DeclarationNameInfo NameInfo(Name, UsingLoc);
13104   TypeSourceInfo *TInfo =
13105       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13106   FunctionProtoTypeLoc ProtoLoc =
13107       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13108 
13109   // Check the inherited constructor is valid and find the list of base classes
13110   // from which it was inherited.
13111   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13112 
13113   bool Constexpr =
13114       BaseCtor->isConstexpr() &&
13115       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13116                                         false, BaseCtor, &ICI);
13117 
13118   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13119       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13120       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13121       /*isImplicitlyDeclared=*/true,
13122       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13123       InheritedConstructor(Shadow, BaseCtor),
13124       BaseCtor->getTrailingRequiresClause());
13125   if (Shadow->isInvalidDecl())
13126     DerivedCtor->setInvalidDecl();
13127 
13128   // Build an unevaluated exception specification for this fake constructor.
13129   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13130   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13131   EPI.ExceptionSpec.Type = EST_Unevaluated;
13132   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13133   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13134                                                FPT->getParamTypes(), EPI));
13135 
13136   // Build the parameter declarations.
13137   SmallVector<ParmVarDecl *, 16> ParamDecls;
13138   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13139     TypeSourceInfo *TInfo =
13140         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13141     ParmVarDecl *PD = ParmVarDecl::Create(
13142         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13143         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13144     PD->setScopeInfo(0, I);
13145     PD->setImplicit();
13146     // Ensure attributes are propagated onto parameters (this matters for
13147     // format, pass_object_size, ...).
13148     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13149     ParamDecls.push_back(PD);
13150     ProtoLoc.setParam(I, PD);
13151   }
13152 
13153   // Set up the new constructor.
13154   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13155   DerivedCtor->setAccess(BaseCtor->getAccess());
13156   DerivedCtor->setParams(ParamDecls);
13157   Derived->addDecl(DerivedCtor);
13158 
13159   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13160     SetDeclDeleted(DerivedCtor, UsingLoc);
13161 
13162   return DerivedCtor;
13163 }
13164 
13165 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13166   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13167                                Ctor->getInheritedConstructor().getShadowDecl());
13168   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13169                             /*Diagnose*/true);
13170 }
13171 
13172 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13173                                        CXXConstructorDecl *Constructor) {
13174   CXXRecordDecl *ClassDecl = Constructor->getParent();
13175   assert(Constructor->getInheritedConstructor() &&
13176          !Constructor->doesThisDeclarationHaveABody() &&
13177          !Constructor->isDeleted());
13178   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13179     return;
13180 
13181   // Initializations are performed "as if by a defaulted default constructor",
13182   // so enter the appropriate scope.
13183   SynthesizedFunctionScope Scope(*this, Constructor);
13184 
13185   // The exception specification is needed because we are defining the
13186   // function.
13187   ResolveExceptionSpec(CurrentLocation,
13188                        Constructor->getType()->castAs<FunctionProtoType>());
13189   MarkVTableUsed(CurrentLocation, ClassDecl);
13190 
13191   // Add a context note for diagnostics produced after this point.
13192   Scope.addContextNote(CurrentLocation);
13193 
13194   ConstructorUsingShadowDecl *Shadow =
13195       Constructor->getInheritedConstructor().getShadowDecl();
13196   CXXConstructorDecl *InheritedCtor =
13197       Constructor->getInheritedConstructor().getConstructor();
13198 
13199   // [class.inhctor.init]p1:
13200   //   initialization proceeds as if a defaulted default constructor is used to
13201   //   initialize the D object and each base class subobject from which the
13202   //   constructor was inherited
13203 
13204   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13205   CXXRecordDecl *RD = Shadow->getParent();
13206   SourceLocation InitLoc = Shadow->getLocation();
13207 
13208   // Build explicit initializers for all base classes from which the
13209   // constructor was inherited.
13210   SmallVector<CXXCtorInitializer*, 8> Inits;
13211   for (bool VBase : {false, true}) {
13212     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13213       if (B.isVirtual() != VBase)
13214         continue;
13215 
13216       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13217       if (!BaseRD)
13218         continue;
13219 
13220       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13221       if (!BaseCtor.first)
13222         continue;
13223 
13224       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13225       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13226           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13227 
13228       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13229       Inits.push_back(new (Context) CXXCtorInitializer(
13230           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13231           SourceLocation()));
13232     }
13233   }
13234 
13235   // We now proceed as if for a defaulted default constructor, with the relevant
13236   // initializers replaced.
13237 
13238   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13239     Constructor->setInvalidDecl();
13240     return;
13241   }
13242 
13243   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13244   Constructor->markUsed(Context);
13245 
13246   if (ASTMutationListener *L = getASTMutationListener()) {
13247     L->CompletedImplicitDefinition(Constructor);
13248   }
13249 
13250   DiagnoseUninitializedFields(*this, Constructor);
13251 }
13252 
13253 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13254   // C++ [class.dtor]p2:
13255   //   If a class has no user-declared destructor, a destructor is
13256   //   declared implicitly. An implicitly-declared destructor is an
13257   //   inline public member of its class.
13258   assert(ClassDecl->needsImplicitDestructor());
13259 
13260   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13261   if (DSM.isAlreadyBeingDeclared())
13262     return nullptr;
13263 
13264   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13265                                                      CXXDestructor,
13266                                                      false);
13267 
13268   // Create the actual destructor declaration.
13269   CanQualType ClassType
13270     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13271   SourceLocation ClassLoc = ClassDecl->getLocation();
13272   DeclarationName Name
13273     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13274   DeclarationNameInfo NameInfo(Name, ClassLoc);
13275   CXXDestructorDecl *Destructor =
13276       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13277                                 QualType(), nullptr, /*isInline=*/true,
13278                                 /*isImplicitlyDeclared=*/true,
13279                                 Constexpr ? ConstexprSpecKind::Constexpr
13280                                           : ConstexprSpecKind::Unspecified);
13281   Destructor->setAccess(AS_public);
13282   Destructor->setDefaulted();
13283 
13284   if (getLangOpts().CUDA) {
13285     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13286                                             Destructor,
13287                                             /* ConstRHS */ false,
13288                                             /* Diagnose */ false);
13289   }
13290 
13291   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13292 
13293   // We don't need to use SpecialMemberIsTrivial here; triviality for
13294   // destructors is easy to compute.
13295   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13296   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13297                                 ClassDecl->hasTrivialDestructorForCall());
13298 
13299   // Note that we have declared this destructor.
13300   ++getASTContext().NumImplicitDestructorsDeclared;
13301 
13302   Scope *S = getScopeForContext(ClassDecl);
13303   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13304 
13305   // We can't check whether an implicit destructor is deleted before we complete
13306   // the definition of the class, because its validity depends on the alignment
13307   // of the class. We'll check this from ActOnFields once the class is complete.
13308   if (ClassDecl->isCompleteDefinition() &&
13309       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13310     SetDeclDeleted(Destructor, ClassLoc);
13311 
13312   // Introduce this destructor into its scope.
13313   if (S)
13314     PushOnScopeChains(Destructor, S, false);
13315   ClassDecl->addDecl(Destructor);
13316 
13317   return Destructor;
13318 }
13319 
13320 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13321                                     CXXDestructorDecl *Destructor) {
13322   assert((Destructor->isDefaulted() &&
13323           !Destructor->doesThisDeclarationHaveABody() &&
13324           !Destructor->isDeleted()) &&
13325          "DefineImplicitDestructor - call it for implicit default dtor");
13326   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13327     return;
13328 
13329   CXXRecordDecl *ClassDecl = Destructor->getParent();
13330   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13331 
13332   SynthesizedFunctionScope Scope(*this, Destructor);
13333 
13334   // The exception specification is needed because we are defining the
13335   // function.
13336   ResolveExceptionSpec(CurrentLocation,
13337                        Destructor->getType()->castAs<FunctionProtoType>());
13338   MarkVTableUsed(CurrentLocation, ClassDecl);
13339 
13340   // Add a context note for diagnostics produced after this point.
13341   Scope.addContextNote(CurrentLocation);
13342 
13343   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13344                                          Destructor->getParent());
13345 
13346   if (CheckDestructor(Destructor)) {
13347     Destructor->setInvalidDecl();
13348     return;
13349   }
13350 
13351   SourceLocation Loc = Destructor->getEndLoc().isValid()
13352                            ? Destructor->getEndLoc()
13353                            : Destructor->getLocation();
13354   Destructor->setBody(new (Context) CompoundStmt(Loc));
13355   Destructor->markUsed(Context);
13356 
13357   if (ASTMutationListener *L = getASTMutationListener()) {
13358     L->CompletedImplicitDefinition(Destructor);
13359   }
13360 }
13361 
13362 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13363                                           CXXDestructorDecl *Destructor) {
13364   if (Destructor->isInvalidDecl())
13365     return;
13366 
13367   CXXRecordDecl *ClassDecl = Destructor->getParent();
13368   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13369          "implicit complete dtors unneeded outside MS ABI");
13370   assert(ClassDecl->getNumVBases() > 0 &&
13371          "complete dtor only exists for classes with vbases");
13372 
13373   SynthesizedFunctionScope Scope(*this, Destructor);
13374 
13375   // Add a context note for diagnostics produced after this point.
13376   Scope.addContextNote(CurrentLocation);
13377 
13378   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13379 }
13380 
13381 /// Perform any semantic analysis which needs to be delayed until all
13382 /// pending class member declarations have been parsed.
13383 void Sema::ActOnFinishCXXMemberDecls() {
13384   // If the context is an invalid C++ class, just suppress these checks.
13385   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13386     if (Record->isInvalidDecl()) {
13387       DelayedOverridingExceptionSpecChecks.clear();
13388       DelayedEquivalentExceptionSpecChecks.clear();
13389       return;
13390     }
13391     checkForMultipleExportedDefaultConstructors(*this, Record);
13392   }
13393 }
13394 
13395 void Sema::ActOnFinishCXXNonNestedClass() {
13396   referenceDLLExportedClassMethods();
13397 
13398   if (!DelayedDllExportMemberFunctions.empty()) {
13399     SmallVector<CXXMethodDecl*, 4> WorkList;
13400     std::swap(DelayedDllExportMemberFunctions, WorkList);
13401     for (CXXMethodDecl *M : WorkList) {
13402       DefineDefaultedFunction(*this, M, M->getLocation());
13403 
13404       // Pass the method to the consumer to get emitted. This is not necessary
13405       // for explicit instantiation definitions, as they will get emitted
13406       // anyway.
13407       if (M->getParent()->getTemplateSpecializationKind() !=
13408           TSK_ExplicitInstantiationDefinition)
13409         ActOnFinishInlineFunctionDef(M);
13410     }
13411   }
13412 }
13413 
13414 void Sema::referenceDLLExportedClassMethods() {
13415   if (!DelayedDllExportClasses.empty()) {
13416     // Calling ReferenceDllExportedMembers might cause the current function to
13417     // be called again, so use a local copy of DelayedDllExportClasses.
13418     SmallVector<CXXRecordDecl *, 4> WorkList;
13419     std::swap(DelayedDllExportClasses, WorkList);
13420     for (CXXRecordDecl *Class : WorkList)
13421       ReferenceDllExportedMembers(*this, Class);
13422   }
13423 }
13424 
13425 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13426   assert(getLangOpts().CPlusPlus11 &&
13427          "adjusting dtor exception specs was introduced in c++11");
13428 
13429   if (Destructor->isDependentContext())
13430     return;
13431 
13432   // C++11 [class.dtor]p3:
13433   //   A declaration of a destructor that does not have an exception-
13434   //   specification is implicitly considered to have the same exception-
13435   //   specification as an implicit declaration.
13436   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13437   if (DtorType->hasExceptionSpec())
13438     return;
13439 
13440   // Replace the destructor's type, building off the existing one. Fortunately,
13441   // the only thing of interest in the destructor type is its extended info.
13442   // The return and arguments are fixed.
13443   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13444   EPI.ExceptionSpec.Type = EST_Unevaluated;
13445   EPI.ExceptionSpec.SourceDecl = Destructor;
13446   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13447 
13448   // FIXME: If the destructor has a body that could throw, and the newly created
13449   // spec doesn't allow exceptions, we should emit a warning, because this
13450   // change in behavior can break conforming C++03 programs at runtime.
13451   // However, we don't have a body or an exception specification yet, so it
13452   // needs to be done somewhere else.
13453 }
13454 
13455 namespace {
13456 /// An abstract base class for all helper classes used in building the
13457 //  copy/move operators. These classes serve as factory functions and help us
13458 //  avoid using the same Expr* in the AST twice.
13459 class ExprBuilder {
13460   ExprBuilder(const ExprBuilder&) = delete;
13461   ExprBuilder &operator=(const ExprBuilder&) = delete;
13462 
13463 protected:
13464   static Expr *assertNotNull(Expr *E) {
13465     assert(E && "Expression construction must not fail.");
13466     return E;
13467   }
13468 
13469 public:
13470   ExprBuilder() {}
13471   virtual ~ExprBuilder() {}
13472 
13473   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13474 };
13475 
13476 class RefBuilder: public ExprBuilder {
13477   VarDecl *Var;
13478   QualType VarType;
13479 
13480 public:
13481   Expr *build(Sema &S, SourceLocation Loc) const override {
13482     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13483   }
13484 
13485   RefBuilder(VarDecl *Var, QualType VarType)
13486       : Var(Var), VarType(VarType) {}
13487 };
13488 
13489 class ThisBuilder: public ExprBuilder {
13490 public:
13491   Expr *build(Sema &S, SourceLocation Loc) const override {
13492     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13493   }
13494 };
13495 
13496 class CastBuilder: public ExprBuilder {
13497   const ExprBuilder &Builder;
13498   QualType Type;
13499   ExprValueKind Kind;
13500   const CXXCastPath &Path;
13501 
13502 public:
13503   Expr *build(Sema &S, SourceLocation Loc) const override {
13504     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13505                                              CK_UncheckedDerivedToBase, Kind,
13506                                              &Path).get());
13507   }
13508 
13509   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13510               const CXXCastPath &Path)
13511       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13512 };
13513 
13514 class DerefBuilder: public ExprBuilder {
13515   const ExprBuilder &Builder;
13516 
13517 public:
13518   Expr *build(Sema &S, SourceLocation Loc) const override {
13519     return assertNotNull(
13520         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13521   }
13522 
13523   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13524 };
13525 
13526 class MemberBuilder: public ExprBuilder {
13527   const ExprBuilder &Builder;
13528   QualType Type;
13529   CXXScopeSpec SS;
13530   bool IsArrow;
13531   LookupResult &MemberLookup;
13532 
13533 public:
13534   Expr *build(Sema &S, SourceLocation Loc) const override {
13535     return assertNotNull(S.BuildMemberReferenceExpr(
13536         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13537         nullptr, MemberLookup, nullptr, nullptr).get());
13538   }
13539 
13540   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13541                 LookupResult &MemberLookup)
13542       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13543         MemberLookup(MemberLookup) {}
13544 };
13545 
13546 class MoveCastBuilder: public ExprBuilder {
13547   const ExprBuilder &Builder;
13548 
13549 public:
13550   Expr *build(Sema &S, SourceLocation Loc) const override {
13551     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13552   }
13553 
13554   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13555 };
13556 
13557 class LvalueConvBuilder: public ExprBuilder {
13558   const ExprBuilder &Builder;
13559 
13560 public:
13561   Expr *build(Sema &S, SourceLocation Loc) const override {
13562     return assertNotNull(
13563         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13564   }
13565 
13566   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13567 };
13568 
13569 class SubscriptBuilder: public ExprBuilder {
13570   const ExprBuilder &Base;
13571   const ExprBuilder &Index;
13572 
13573 public:
13574   Expr *build(Sema &S, SourceLocation Loc) const override {
13575     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13576         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13577   }
13578 
13579   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13580       : Base(Base), Index(Index) {}
13581 };
13582 
13583 } // end anonymous namespace
13584 
13585 /// When generating a defaulted copy or move assignment operator, if a field
13586 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13587 /// do so. This optimization only applies for arrays of scalars, and for arrays
13588 /// of class type where the selected copy/move-assignment operator is trivial.
13589 static StmtResult
13590 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13591                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13592   // Compute the size of the memory buffer to be copied.
13593   QualType SizeType = S.Context.getSizeType();
13594   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13595                    S.Context.getTypeSizeInChars(T).getQuantity());
13596 
13597   // Take the address of the field references for "from" and "to". We
13598   // directly construct UnaryOperators here because semantic analysis
13599   // does not permit us to take the address of an xvalue.
13600   Expr *From = FromB.build(S, Loc);
13601   From = UnaryOperator::Create(
13602       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13603       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13604   Expr *To = ToB.build(S, Loc);
13605   To = UnaryOperator::Create(
13606       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13607       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13608 
13609   const Type *E = T->getBaseElementTypeUnsafe();
13610   bool NeedsCollectableMemCpy =
13611       E->isRecordType() &&
13612       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13613 
13614   // Create a reference to the __builtin_objc_memmove_collectable function
13615   StringRef MemCpyName = NeedsCollectableMemCpy ?
13616     "__builtin_objc_memmove_collectable" :
13617     "__builtin_memcpy";
13618   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13619                  Sema::LookupOrdinaryName);
13620   S.LookupName(R, S.TUScope, true);
13621 
13622   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13623   if (!MemCpy)
13624     // Something went horribly wrong earlier, and we will have complained
13625     // about it.
13626     return StmtError();
13627 
13628   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13629                                             VK_RValue, Loc, nullptr);
13630   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13631 
13632   Expr *CallArgs[] = {
13633     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13634   };
13635   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13636                                     Loc, CallArgs, Loc);
13637 
13638   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13639   return Call.getAs<Stmt>();
13640 }
13641 
13642 /// Builds a statement that copies/moves the given entity from \p From to
13643 /// \c To.
13644 ///
13645 /// This routine is used to copy/move the members of a class with an
13646 /// implicitly-declared copy/move assignment operator. When the entities being
13647 /// copied are arrays, this routine builds for loops to copy them.
13648 ///
13649 /// \param S The Sema object used for type-checking.
13650 ///
13651 /// \param Loc The location where the implicit copy/move is being generated.
13652 ///
13653 /// \param T The type of the expressions being copied/moved. Both expressions
13654 /// must have this type.
13655 ///
13656 /// \param To The expression we are copying/moving to.
13657 ///
13658 /// \param From The expression we are copying/moving from.
13659 ///
13660 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13661 /// Otherwise, it's a non-static member subobject.
13662 ///
13663 /// \param Copying Whether we're copying or moving.
13664 ///
13665 /// \param Depth Internal parameter recording the depth of the recursion.
13666 ///
13667 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13668 /// if a memcpy should be used instead.
13669 static StmtResult
13670 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13671                                  const ExprBuilder &To, const ExprBuilder &From,
13672                                  bool CopyingBaseSubobject, bool Copying,
13673                                  unsigned Depth = 0) {
13674   // C++11 [class.copy]p28:
13675   //   Each subobject is assigned in the manner appropriate to its type:
13676   //
13677   //     - if the subobject is of class type, as if by a call to operator= with
13678   //       the subobject as the object expression and the corresponding
13679   //       subobject of x as a single function argument (as if by explicit
13680   //       qualification; that is, ignoring any possible virtual overriding
13681   //       functions in more derived classes);
13682   //
13683   // C++03 [class.copy]p13:
13684   //     - if the subobject is of class type, the copy assignment operator for
13685   //       the class is used (as if by explicit qualification; that is,
13686   //       ignoring any possible virtual overriding functions in more derived
13687   //       classes);
13688   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13689     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13690 
13691     // Look for operator=.
13692     DeclarationName Name
13693       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13694     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13695     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13696 
13697     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13698     // operator.
13699     if (!S.getLangOpts().CPlusPlus11) {
13700       LookupResult::Filter F = OpLookup.makeFilter();
13701       while (F.hasNext()) {
13702         NamedDecl *D = F.next();
13703         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13704           if (Method->isCopyAssignmentOperator() ||
13705               (!Copying && Method->isMoveAssignmentOperator()))
13706             continue;
13707 
13708         F.erase();
13709       }
13710       F.done();
13711     }
13712 
13713     // Suppress the protected check (C++ [class.protected]) for each of the
13714     // assignment operators we found. This strange dance is required when
13715     // we're assigning via a base classes's copy-assignment operator. To
13716     // ensure that we're getting the right base class subobject (without
13717     // ambiguities), we need to cast "this" to that subobject type; to
13718     // ensure that we don't go through the virtual call mechanism, we need
13719     // to qualify the operator= name with the base class (see below). However,
13720     // this means that if the base class has a protected copy assignment
13721     // operator, the protected member access check will fail. So, we
13722     // rewrite "protected" access to "public" access in this case, since we
13723     // know by construction that we're calling from a derived class.
13724     if (CopyingBaseSubobject) {
13725       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13726            L != LEnd; ++L) {
13727         if (L.getAccess() == AS_protected)
13728           L.setAccess(AS_public);
13729       }
13730     }
13731 
13732     // Create the nested-name-specifier that will be used to qualify the
13733     // reference to operator=; this is required to suppress the virtual
13734     // call mechanism.
13735     CXXScopeSpec SS;
13736     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13737     SS.MakeTrivial(S.Context,
13738                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13739                                                CanonicalT),
13740                    Loc);
13741 
13742     // Create the reference to operator=.
13743     ExprResult OpEqualRef
13744       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13745                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13746                                    /*FirstQualifierInScope=*/nullptr,
13747                                    OpLookup,
13748                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13749                                    /*SuppressQualifierCheck=*/true);
13750     if (OpEqualRef.isInvalid())
13751       return StmtError();
13752 
13753     // Build the call to the assignment operator.
13754 
13755     Expr *FromInst = From.build(S, Loc);
13756     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13757                                                   OpEqualRef.getAs<Expr>(),
13758                                                   Loc, FromInst, Loc);
13759     if (Call.isInvalid())
13760       return StmtError();
13761 
13762     // If we built a call to a trivial 'operator=' while copying an array,
13763     // bail out. We'll replace the whole shebang with a memcpy.
13764     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13765     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13766       return StmtResult((Stmt*)nullptr);
13767 
13768     // Convert to an expression-statement, and clean up any produced
13769     // temporaries.
13770     return S.ActOnExprStmt(Call);
13771   }
13772 
13773   //     - if the subobject is of scalar type, the built-in assignment
13774   //       operator is used.
13775   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13776   if (!ArrayTy) {
13777     ExprResult Assignment = S.CreateBuiltinBinOp(
13778         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13779     if (Assignment.isInvalid())
13780       return StmtError();
13781     return S.ActOnExprStmt(Assignment);
13782   }
13783 
13784   //     - if the subobject is an array, each element is assigned, in the
13785   //       manner appropriate to the element type;
13786 
13787   // Construct a loop over the array bounds, e.g.,
13788   //
13789   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13790   //
13791   // that will copy each of the array elements.
13792   QualType SizeType = S.Context.getSizeType();
13793 
13794   // Create the iteration variable.
13795   IdentifierInfo *IterationVarName = nullptr;
13796   {
13797     SmallString<8> Str;
13798     llvm::raw_svector_ostream OS(Str);
13799     OS << "__i" << Depth;
13800     IterationVarName = &S.Context.Idents.get(OS.str());
13801   }
13802   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13803                                           IterationVarName, SizeType,
13804                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13805                                           SC_None);
13806 
13807   // Initialize the iteration variable to zero.
13808   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13809   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13810 
13811   // Creates a reference to the iteration variable.
13812   RefBuilder IterationVarRef(IterationVar, SizeType);
13813   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13814 
13815   // Create the DeclStmt that holds the iteration variable.
13816   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13817 
13818   // Subscript the "from" and "to" expressions with the iteration variable.
13819   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13820   MoveCastBuilder FromIndexMove(FromIndexCopy);
13821   const ExprBuilder *FromIndex;
13822   if (Copying)
13823     FromIndex = &FromIndexCopy;
13824   else
13825     FromIndex = &FromIndexMove;
13826 
13827   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13828 
13829   // Build the copy/move for an individual element of the array.
13830   StmtResult Copy =
13831     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13832                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13833                                      Copying, Depth + 1);
13834   // Bail out if copying fails or if we determined that we should use memcpy.
13835   if (Copy.isInvalid() || !Copy.get())
13836     return Copy;
13837 
13838   // Create the comparison against the array bound.
13839   llvm::APInt Upper
13840     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13841   Expr *Comparison = BinaryOperator::Create(
13842       S.Context, IterationVarRefRVal.build(S, Loc),
13843       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13844       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13845 
13846   // Create the pre-increment of the iteration variable. We can determine
13847   // whether the increment will overflow based on the value of the array
13848   // bound.
13849   Expr *Increment = UnaryOperator::Create(
13850       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13851       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13852 
13853   // Construct the loop that copies all elements of this array.
13854   return S.ActOnForStmt(
13855       Loc, Loc, InitStmt,
13856       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13857       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13858 }
13859 
13860 static StmtResult
13861 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13862                       const ExprBuilder &To, const ExprBuilder &From,
13863                       bool CopyingBaseSubobject, bool Copying) {
13864   // Maybe we should use a memcpy?
13865   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13866       T.isTriviallyCopyableType(S.Context))
13867     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13868 
13869   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13870                                                      CopyingBaseSubobject,
13871                                                      Copying, 0));
13872 
13873   // If we ended up picking a trivial assignment operator for an array of a
13874   // non-trivially-copyable class type, just emit a memcpy.
13875   if (!Result.isInvalid() && !Result.get())
13876     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13877 
13878   return Result;
13879 }
13880 
13881 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13882   // Note: The following rules are largely analoguous to the copy
13883   // constructor rules. Note that virtual bases are not taken into account
13884   // for determining the argument type of the operator. Note also that
13885   // operators taking an object instead of a reference are allowed.
13886   assert(ClassDecl->needsImplicitCopyAssignment());
13887 
13888   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13889   if (DSM.isAlreadyBeingDeclared())
13890     return nullptr;
13891 
13892   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13893   LangAS AS = getDefaultCXXMethodAddrSpace();
13894   if (AS != LangAS::Default)
13895     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13896   QualType RetType = Context.getLValueReferenceType(ArgType);
13897   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13898   if (Const)
13899     ArgType = ArgType.withConst();
13900 
13901   ArgType = Context.getLValueReferenceType(ArgType);
13902 
13903   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13904                                                      CXXCopyAssignment,
13905                                                      Const);
13906 
13907   //   An implicitly-declared copy assignment operator is an inline public
13908   //   member of its class.
13909   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13910   SourceLocation ClassLoc = ClassDecl->getLocation();
13911   DeclarationNameInfo NameInfo(Name, ClassLoc);
13912   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13913       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13914       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13915       /*isInline=*/true,
13916       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
13917       SourceLocation());
13918   CopyAssignment->setAccess(AS_public);
13919   CopyAssignment->setDefaulted();
13920   CopyAssignment->setImplicit();
13921 
13922   if (getLangOpts().CUDA) {
13923     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13924                                             CopyAssignment,
13925                                             /* ConstRHS */ Const,
13926                                             /* Diagnose */ false);
13927   }
13928 
13929   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13930 
13931   // Add the parameter to the operator.
13932   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13933                                                ClassLoc, ClassLoc,
13934                                                /*Id=*/nullptr, ArgType,
13935                                                /*TInfo=*/nullptr, SC_None,
13936                                                nullptr);
13937   CopyAssignment->setParams(FromParam);
13938 
13939   CopyAssignment->setTrivial(
13940     ClassDecl->needsOverloadResolutionForCopyAssignment()
13941       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13942       : ClassDecl->hasTrivialCopyAssignment());
13943 
13944   // Note that we have added this copy-assignment operator.
13945   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13946 
13947   Scope *S = getScopeForContext(ClassDecl);
13948   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13949 
13950   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13951     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13952     SetDeclDeleted(CopyAssignment, ClassLoc);
13953   }
13954 
13955   if (S)
13956     PushOnScopeChains(CopyAssignment, S, false);
13957   ClassDecl->addDecl(CopyAssignment);
13958 
13959   return CopyAssignment;
13960 }
13961 
13962 /// Diagnose an implicit copy operation for a class which is odr-used, but
13963 /// which is deprecated because the class has a user-declared copy constructor,
13964 /// copy assignment operator, or destructor.
13965 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13966   assert(CopyOp->isImplicit());
13967 
13968   CXXRecordDecl *RD = CopyOp->getParent();
13969   CXXMethodDecl *UserDeclaredOperation = nullptr;
13970 
13971   // In Microsoft mode, assignment operations don't affect constructors and
13972   // vice versa.
13973   if (RD->hasUserDeclaredDestructor()) {
13974     UserDeclaredOperation = RD->getDestructor();
13975   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13976              RD->hasUserDeclaredCopyConstructor() &&
13977              !S.getLangOpts().MSVCCompat) {
13978     // Find any user-declared copy constructor.
13979     for (auto *I : RD->ctors()) {
13980       if (I->isCopyConstructor()) {
13981         UserDeclaredOperation = I;
13982         break;
13983       }
13984     }
13985     assert(UserDeclaredOperation);
13986   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13987              RD->hasUserDeclaredCopyAssignment() &&
13988              !S.getLangOpts().MSVCCompat) {
13989     // Find any user-declared move assignment operator.
13990     for (auto *I : RD->methods()) {
13991       if (I->isCopyAssignmentOperator()) {
13992         UserDeclaredOperation = I;
13993         break;
13994       }
13995     }
13996     assert(UserDeclaredOperation);
13997   }
13998 
13999   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
14000     S.Diag(UserDeclaredOperation->getLocation(),
14001            isa<CXXDestructorDecl>(UserDeclaredOperation)
14002                ? diag::warn_deprecated_copy_dtor_operation
14003                : diag::warn_deprecated_copy_operation)
14004         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
14005   }
14006 }
14007 
14008 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14009                                         CXXMethodDecl *CopyAssignOperator) {
14010   assert((CopyAssignOperator->isDefaulted() &&
14011           CopyAssignOperator->isOverloadedOperator() &&
14012           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14013           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14014           !CopyAssignOperator->isDeleted()) &&
14015          "DefineImplicitCopyAssignment called for wrong function");
14016   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14017     return;
14018 
14019   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14020   if (ClassDecl->isInvalidDecl()) {
14021     CopyAssignOperator->setInvalidDecl();
14022     return;
14023   }
14024 
14025   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14026 
14027   // The exception specification is needed because we are defining the
14028   // function.
14029   ResolveExceptionSpec(CurrentLocation,
14030                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14031 
14032   // Add a context note for diagnostics produced after this point.
14033   Scope.addContextNote(CurrentLocation);
14034 
14035   // C++11 [class.copy]p18:
14036   //   The [definition of an implicitly declared copy assignment operator] is
14037   //   deprecated if the class has a user-declared copy constructor or a
14038   //   user-declared destructor.
14039   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14040     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14041 
14042   // C++0x [class.copy]p30:
14043   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14044   //   for a non-union class X performs memberwise copy assignment of its
14045   //   subobjects. The direct base classes of X are assigned first, in the
14046   //   order of their declaration in the base-specifier-list, and then the
14047   //   immediate non-static data members of X are assigned, in the order in
14048   //   which they were declared in the class definition.
14049 
14050   // The statements that form the synthesized function body.
14051   SmallVector<Stmt*, 8> Statements;
14052 
14053   // The parameter for the "other" object, which we are copying from.
14054   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14055   Qualifiers OtherQuals = Other->getType().getQualifiers();
14056   QualType OtherRefType = Other->getType();
14057   if (const LValueReferenceType *OtherRef
14058                                 = OtherRefType->getAs<LValueReferenceType>()) {
14059     OtherRefType = OtherRef->getPointeeType();
14060     OtherQuals = OtherRefType.getQualifiers();
14061   }
14062 
14063   // Our location for everything implicitly-generated.
14064   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14065                            ? CopyAssignOperator->getEndLoc()
14066                            : CopyAssignOperator->getLocation();
14067 
14068   // Builds a DeclRefExpr for the "other" object.
14069   RefBuilder OtherRef(Other, OtherRefType);
14070 
14071   // Builds the "this" pointer.
14072   ThisBuilder This;
14073 
14074   // Assign base classes.
14075   bool Invalid = false;
14076   for (auto &Base : ClassDecl->bases()) {
14077     // Form the assignment:
14078     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14079     QualType BaseType = Base.getType().getUnqualifiedType();
14080     if (!BaseType->isRecordType()) {
14081       Invalid = true;
14082       continue;
14083     }
14084 
14085     CXXCastPath BasePath;
14086     BasePath.push_back(&Base);
14087 
14088     // Construct the "from" expression, which is an implicit cast to the
14089     // appropriately-qualified base type.
14090     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14091                      VK_LValue, BasePath);
14092 
14093     // Dereference "this".
14094     DerefBuilder DerefThis(This);
14095     CastBuilder To(DerefThis,
14096                    Context.getQualifiedType(
14097                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14098                    VK_LValue, BasePath);
14099 
14100     // Build the copy.
14101     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14102                                             To, From,
14103                                             /*CopyingBaseSubobject=*/true,
14104                                             /*Copying=*/true);
14105     if (Copy.isInvalid()) {
14106       CopyAssignOperator->setInvalidDecl();
14107       return;
14108     }
14109 
14110     // Success! Record the copy.
14111     Statements.push_back(Copy.getAs<Expr>());
14112   }
14113 
14114   // Assign non-static members.
14115   for (auto *Field : ClassDecl->fields()) {
14116     // FIXME: We should form some kind of AST representation for the implied
14117     // memcpy in a union copy operation.
14118     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14119       continue;
14120 
14121     if (Field->isInvalidDecl()) {
14122       Invalid = true;
14123       continue;
14124     }
14125 
14126     // Check for members of reference type; we can't copy those.
14127     if (Field->getType()->isReferenceType()) {
14128       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14129         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14130       Diag(Field->getLocation(), diag::note_declared_at);
14131       Invalid = true;
14132       continue;
14133     }
14134 
14135     // Check for members of const-qualified, non-class type.
14136     QualType BaseType = Context.getBaseElementType(Field->getType());
14137     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14138       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14139         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14140       Diag(Field->getLocation(), diag::note_declared_at);
14141       Invalid = true;
14142       continue;
14143     }
14144 
14145     // Suppress assigning zero-width bitfields.
14146     if (Field->isZeroLengthBitField(Context))
14147       continue;
14148 
14149     QualType FieldType = Field->getType().getNonReferenceType();
14150     if (FieldType->isIncompleteArrayType()) {
14151       assert(ClassDecl->hasFlexibleArrayMember() &&
14152              "Incomplete array type is not valid");
14153       continue;
14154     }
14155 
14156     // Build references to the field in the object we're copying from and to.
14157     CXXScopeSpec SS; // Intentionally empty
14158     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14159                               LookupMemberName);
14160     MemberLookup.addDecl(Field);
14161     MemberLookup.resolveKind();
14162 
14163     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14164 
14165     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14166 
14167     // Build the copy of this field.
14168     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14169                                             To, From,
14170                                             /*CopyingBaseSubobject=*/false,
14171                                             /*Copying=*/true);
14172     if (Copy.isInvalid()) {
14173       CopyAssignOperator->setInvalidDecl();
14174       return;
14175     }
14176 
14177     // Success! Record the copy.
14178     Statements.push_back(Copy.getAs<Stmt>());
14179   }
14180 
14181   if (!Invalid) {
14182     // Add a "return *this;"
14183     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14184 
14185     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14186     if (Return.isInvalid())
14187       Invalid = true;
14188     else
14189       Statements.push_back(Return.getAs<Stmt>());
14190   }
14191 
14192   if (Invalid) {
14193     CopyAssignOperator->setInvalidDecl();
14194     return;
14195   }
14196 
14197   StmtResult Body;
14198   {
14199     CompoundScopeRAII CompoundScope(*this);
14200     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14201                              /*isStmtExpr=*/false);
14202     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14203   }
14204   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14205   CopyAssignOperator->markUsed(Context);
14206 
14207   if (ASTMutationListener *L = getASTMutationListener()) {
14208     L->CompletedImplicitDefinition(CopyAssignOperator);
14209   }
14210 }
14211 
14212 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14213   assert(ClassDecl->needsImplicitMoveAssignment());
14214 
14215   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14216   if (DSM.isAlreadyBeingDeclared())
14217     return nullptr;
14218 
14219   // Note: The following rules are largely analoguous to the move
14220   // constructor rules.
14221 
14222   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14223   LangAS AS = getDefaultCXXMethodAddrSpace();
14224   if (AS != LangAS::Default)
14225     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14226   QualType RetType = Context.getLValueReferenceType(ArgType);
14227   ArgType = Context.getRValueReferenceType(ArgType);
14228 
14229   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14230                                                      CXXMoveAssignment,
14231                                                      false);
14232 
14233   //   An implicitly-declared move assignment operator is an inline public
14234   //   member of its class.
14235   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14236   SourceLocation ClassLoc = ClassDecl->getLocation();
14237   DeclarationNameInfo NameInfo(Name, ClassLoc);
14238   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14239       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14240       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14241       /*isInline=*/true,
14242       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14243       SourceLocation());
14244   MoveAssignment->setAccess(AS_public);
14245   MoveAssignment->setDefaulted();
14246   MoveAssignment->setImplicit();
14247 
14248   if (getLangOpts().CUDA) {
14249     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14250                                             MoveAssignment,
14251                                             /* ConstRHS */ false,
14252                                             /* Diagnose */ false);
14253   }
14254 
14255   // Build an exception specification pointing back at this member.
14256   FunctionProtoType::ExtProtoInfo EPI =
14257       getImplicitMethodEPI(*this, MoveAssignment);
14258   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14259 
14260   // Add the parameter to the operator.
14261   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14262                                                ClassLoc, ClassLoc,
14263                                                /*Id=*/nullptr, ArgType,
14264                                                /*TInfo=*/nullptr, SC_None,
14265                                                nullptr);
14266   MoveAssignment->setParams(FromParam);
14267 
14268   MoveAssignment->setTrivial(
14269     ClassDecl->needsOverloadResolutionForMoveAssignment()
14270       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14271       : ClassDecl->hasTrivialMoveAssignment());
14272 
14273   // Note that we have added this copy-assignment operator.
14274   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14275 
14276   Scope *S = getScopeForContext(ClassDecl);
14277   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14278 
14279   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14280     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14281     SetDeclDeleted(MoveAssignment, ClassLoc);
14282   }
14283 
14284   if (S)
14285     PushOnScopeChains(MoveAssignment, S, false);
14286   ClassDecl->addDecl(MoveAssignment);
14287 
14288   return MoveAssignment;
14289 }
14290 
14291 /// Check if we're implicitly defining a move assignment operator for a class
14292 /// with virtual bases. Such a move assignment might move-assign the virtual
14293 /// base multiple times.
14294 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14295                                                SourceLocation CurrentLocation) {
14296   assert(!Class->isDependentContext() && "should not define dependent move");
14297 
14298   // Only a virtual base could get implicitly move-assigned multiple times.
14299   // Only a non-trivial move assignment can observe this. We only want to
14300   // diagnose if we implicitly define an assignment operator that assigns
14301   // two base classes, both of which move-assign the same virtual base.
14302   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14303       Class->getNumBases() < 2)
14304     return;
14305 
14306   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14307   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14308   VBaseMap VBases;
14309 
14310   for (auto &BI : Class->bases()) {
14311     Worklist.push_back(&BI);
14312     while (!Worklist.empty()) {
14313       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14314       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14315 
14316       // If the base has no non-trivial move assignment operators,
14317       // we don't care about moves from it.
14318       if (!Base->hasNonTrivialMoveAssignment())
14319         continue;
14320 
14321       // If there's nothing virtual here, skip it.
14322       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14323         continue;
14324 
14325       // If we're not actually going to call a move assignment for this base,
14326       // or the selected move assignment is trivial, skip it.
14327       Sema::SpecialMemberOverloadResult SMOR =
14328         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14329                               /*ConstArg*/false, /*VolatileArg*/false,
14330                               /*RValueThis*/true, /*ConstThis*/false,
14331                               /*VolatileThis*/false);
14332       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14333           !SMOR.getMethod()->isMoveAssignmentOperator())
14334         continue;
14335 
14336       if (BaseSpec->isVirtual()) {
14337         // We're going to move-assign this virtual base, and its move
14338         // assignment operator is not trivial. If this can happen for
14339         // multiple distinct direct bases of Class, diagnose it. (If it
14340         // only happens in one base, we'll diagnose it when synthesizing
14341         // that base class's move assignment operator.)
14342         CXXBaseSpecifier *&Existing =
14343             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14344                 .first->second;
14345         if (Existing && Existing != &BI) {
14346           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14347             << Class << Base;
14348           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14349               << (Base->getCanonicalDecl() ==
14350                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14351               << Base << Existing->getType() << Existing->getSourceRange();
14352           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14353               << (Base->getCanonicalDecl() ==
14354                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14355               << Base << BI.getType() << BaseSpec->getSourceRange();
14356 
14357           // Only diagnose each vbase once.
14358           Existing = nullptr;
14359         }
14360       } else {
14361         // Only walk over bases that have defaulted move assignment operators.
14362         // We assume that any user-provided move assignment operator handles
14363         // the multiple-moves-of-vbase case itself somehow.
14364         if (!SMOR.getMethod()->isDefaulted())
14365           continue;
14366 
14367         // We're going to move the base classes of Base. Add them to the list.
14368         for (auto &BI : Base->bases())
14369           Worklist.push_back(&BI);
14370       }
14371     }
14372   }
14373 }
14374 
14375 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14376                                         CXXMethodDecl *MoveAssignOperator) {
14377   assert((MoveAssignOperator->isDefaulted() &&
14378           MoveAssignOperator->isOverloadedOperator() &&
14379           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14380           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14381           !MoveAssignOperator->isDeleted()) &&
14382          "DefineImplicitMoveAssignment called for wrong function");
14383   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14384     return;
14385 
14386   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14387   if (ClassDecl->isInvalidDecl()) {
14388     MoveAssignOperator->setInvalidDecl();
14389     return;
14390   }
14391 
14392   // C++0x [class.copy]p28:
14393   //   The implicitly-defined or move assignment operator for a non-union class
14394   //   X performs memberwise move assignment of its subobjects. The direct base
14395   //   classes of X are assigned first, in the order of their declaration in the
14396   //   base-specifier-list, and then the immediate non-static data members of X
14397   //   are assigned, in the order in which they were declared in the class
14398   //   definition.
14399 
14400   // Issue a warning if our implicit move assignment operator will move
14401   // from a virtual base more than once.
14402   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14403 
14404   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14405 
14406   // The exception specification is needed because we are defining the
14407   // function.
14408   ResolveExceptionSpec(CurrentLocation,
14409                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14410 
14411   // Add a context note for diagnostics produced after this point.
14412   Scope.addContextNote(CurrentLocation);
14413 
14414   // The statements that form the synthesized function body.
14415   SmallVector<Stmt*, 8> Statements;
14416 
14417   // The parameter for the "other" object, which we are move from.
14418   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14419   QualType OtherRefType =
14420       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14421 
14422   // Our location for everything implicitly-generated.
14423   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14424                            ? MoveAssignOperator->getEndLoc()
14425                            : MoveAssignOperator->getLocation();
14426 
14427   // Builds a reference to the "other" object.
14428   RefBuilder OtherRef(Other, OtherRefType);
14429   // Cast to rvalue.
14430   MoveCastBuilder MoveOther(OtherRef);
14431 
14432   // Builds the "this" pointer.
14433   ThisBuilder This;
14434 
14435   // Assign base classes.
14436   bool Invalid = false;
14437   for (auto &Base : ClassDecl->bases()) {
14438     // C++11 [class.copy]p28:
14439     //   It is unspecified whether subobjects representing virtual base classes
14440     //   are assigned more than once by the implicitly-defined copy assignment
14441     //   operator.
14442     // FIXME: Do not assign to a vbase that will be assigned by some other base
14443     // class. For a move-assignment, this can result in the vbase being moved
14444     // multiple times.
14445 
14446     // Form the assignment:
14447     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14448     QualType BaseType = Base.getType().getUnqualifiedType();
14449     if (!BaseType->isRecordType()) {
14450       Invalid = true;
14451       continue;
14452     }
14453 
14454     CXXCastPath BasePath;
14455     BasePath.push_back(&Base);
14456 
14457     // Construct the "from" expression, which is an implicit cast to the
14458     // appropriately-qualified base type.
14459     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14460 
14461     // Dereference "this".
14462     DerefBuilder DerefThis(This);
14463 
14464     // Implicitly cast "this" to the appropriately-qualified base type.
14465     CastBuilder To(DerefThis,
14466                    Context.getQualifiedType(
14467                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14468                    VK_LValue, BasePath);
14469 
14470     // Build the move.
14471     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14472                                             To, From,
14473                                             /*CopyingBaseSubobject=*/true,
14474                                             /*Copying=*/false);
14475     if (Move.isInvalid()) {
14476       MoveAssignOperator->setInvalidDecl();
14477       return;
14478     }
14479 
14480     // Success! Record the move.
14481     Statements.push_back(Move.getAs<Expr>());
14482   }
14483 
14484   // Assign non-static members.
14485   for (auto *Field : ClassDecl->fields()) {
14486     // FIXME: We should form some kind of AST representation for the implied
14487     // memcpy in a union copy operation.
14488     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14489       continue;
14490 
14491     if (Field->isInvalidDecl()) {
14492       Invalid = true;
14493       continue;
14494     }
14495 
14496     // Check for members of reference type; we can't move those.
14497     if (Field->getType()->isReferenceType()) {
14498       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14499         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14500       Diag(Field->getLocation(), diag::note_declared_at);
14501       Invalid = true;
14502       continue;
14503     }
14504 
14505     // Check for members of const-qualified, non-class type.
14506     QualType BaseType = Context.getBaseElementType(Field->getType());
14507     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14508       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14509         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14510       Diag(Field->getLocation(), diag::note_declared_at);
14511       Invalid = true;
14512       continue;
14513     }
14514 
14515     // Suppress assigning zero-width bitfields.
14516     if (Field->isZeroLengthBitField(Context))
14517       continue;
14518 
14519     QualType FieldType = Field->getType().getNonReferenceType();
14520     if (FieldType->isIncompleteArrayType()) {
14521       assert(ClassDecl->hasFlexibleArrayMember() &&
14522              "Incomplete array type is not valid");
14523       continue;
14524     }
14525 
14526     // Build references to the field in the object we're copying from and to.
14527     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14528                               LookupMemberName);
14529     MemberLookup.addDecl(Field);
14530     MemberLookup.resolveKind();
14531     MemberBuilder From(MoveOther, OtherRefType,
14532                        /*IsArrow=*/false, MemberLookup);
14533     MemberBuilder To(This, getCurrentThisType(),
14534                      /*IsArrow=*/true, MemberLookup);
14535 
14536     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14537         "Member reference with rvalue base must be rvalue except for reference "
14538         "members, which aren't allowed for move assignment.");
14539 
14540     // Build the move of this field.
14541     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14542                                             To, From,
14543                                             /*CopyingBaseSubobject=*/false,
14544                                             /*Copying=*/false);
14545     if (Move.isInvalid()) {
14546       MoveAssignOperator->setInvalidDecl();
14547       return;
14548     }
14549 
14550     // Success! Record the copy.
14551     Statements.push_back(Move.getAs<Stmt>());
14552   }
14553 
14554   if (!Invalid) {
14555     // Add a "return *this;"
14556     ExprResult ThisObj =
14557         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14558 
14559     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14560     if (Return.isInvalid())
14561       Invalid = true;
14562     else
14563       Statements.push_back(Return.getAs<Stmt>());
14564   }
14565 
14566   if (Invalid) {
14567     MoveAssignOperator->setInvalidDecl();
14568     return;
14569   }
14570 
14571   StmtResult Body;
14572   {
14573     CompoundScopeRAII CompoundScope(*this);
14574     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14575                              /*isStmtExpr=*/false);
14576     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14577   }
14578   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14579   MoveAssignOperator->markUsed(Context);
14580 
14581   if (ASTMutationListener *L = getASTMutationListener()) {
14582     L->CompletedImplicitDefinition(MoveAssignOperator);
14583   }
14584 }
14585 
14586 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14587                                                     CXXRecordDecl *ClassDecl) {
14588   // C++ [class.copy]p4:
14589   //   If the class definition does not explicitly declare a copy
14590   //   constructor, one is declared implicitly.
14591   assert(ClassDecl->needsImplicitCopyConstructor());
14592 
14593   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14594   if (DSM.isAlreadyBeingDeclared())
14595     return nullptr;
14596 
14597   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14598   QualType ArgType = ClassType;
14599   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14600   if (Const)
14601     ArgType = ArgType.withConst();
14602 
14603   LangAS AS = getDefaultCXXMethodAddrSpace();
14604   if (AS != LangAS::Default)
14605     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14606 
14607   ArgType = Context.getLValueReferenceType(ArgType);
14608 
14609   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14610                                                      CXXCopyConstructor,
14611                                                      Const);
14612 
14613   DeclarationName Name
14614     = Context.DeclarationNames.getCXXConstructorName(
14615                                            Context.getCanonicalType(ClassType));
14616   SourceLocation ClassLoc = ClassDecl->getLocation();
14617   DeclarationNameInfo NameInfo(Name, ClassLoc);
14618 
14619   //   An implicitly-declared copy constructor is an inline public
14620   //   member of its class.
14621   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14622       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14623       ExplicitSpecifier(),
14624       /*isInline=*/true,
14625       /*isImplicitlyDeclared=*/true,
14626       Constexpr ? ConstexprSpecKind::Constexpr
14627                 : ConstexprSpecKind::Unspecified);
14628   CopyConstructor->setAccess(AS_public);
14629   CopyConstructor->setDefaulted();
14630 
14631   if (getLangOpts().CUDA) {
14632     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14633                                             CopyConstructor,
14634                                             /* ConstRHS */ Const,
14635                                             /* Diagnose */ false);
14636   }
14637 
14638   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14639 
14640   // Add the parameter to the constructor.
14641   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14642                                                ClassLoc, ClassLoc,
14643                                                /*IdentifierInfo=*/nullptr,
14644                                                ArgType, /*TInfo=*/nullptr,
14645                                                SC_None, nullptr);
14646   CopyConstructor->setParams(FromParam);
14647 
14648   CopyConstructor->setTrivial(
14649       ClassDecl->needsOverloadResolutionForCopyConstructor()
14650           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14651           : ClassDecl->hasTrivialCopyConstructor());
14652 
14653   CopyConstructor->setTrivialForCall(
14654       ClassDecl->hasAttr<TrivialABIAttr>() ||
14655       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14656            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14657              TAH_ConsiderTrivialABI)
14658            : ClassDecl->hasTrivialCopyConstructorForCall()));
14659 
14660   // Note that we have declared this constructor.
14661   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14662 
14663   Scope *S = getScopeForContext(ClassDecl);
14664   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14665 
14666   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14667     ClassDecl->setImplicitCopyConstructorIsDeleted();
14668     SetDeclDeleted(CopyConstructor, ClassLoc);
14669   }
14670 
14671   if (S)
14672     PushOnScopeChains(CopyConstructor, S, false);
14673   ClassDecl->addDecl(CopyConstructor);
14674 
14675   return CopyConstructor;
14676 }
14677 
14678 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14679                                          CXXConstructorDecl *CopyConstructor) {
14680   assert((CopyConstructor->isDefaulted() &&
14681           CopyConstructor->isCopyConstructor() &&
14682           !CopyConstructor->doesThisDeclarationHaveABody() &&
14683           !CopyConstructor->isDeleted()) &&
14684          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14685   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14686     return;
14687 
14688   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14689   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14690 
14691   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14692 
14693   // The exception specification is needed because we are defining the
14694   // function.
14695   ResolveExceptionSpec(CurrentLocation,
14696                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14697   MarkVTableUsed(CurrentLocation, ClassDecl);
14698 
14699   // Add a context note for diagnostics produced after this point.
14700   Scope.addContextNote(CurrentLocation);
14701 
14702   // C++11 [class.copy]p7:
14703   //   The [definition of an implicitly declared copy constructor] is
14704   //   deprecated if the class has a user-declared copy assignment operator
14705   //   or a user-declared destructor.
14706   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14707     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14708 
14709   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14710     CopyConstructor->setInvalidDecl();
14711   }  else {
14712     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14713                              ? CopyConstructor->getEndLoc()
14714                              : CopyConstructor->getLocation();
14715     Sema::CompoundScopeRAII CompoundScope(*this);
14716     CopyConstructor->setBody(
14717         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14718     CopyConstructor->markUsed(Context);
14719   }
14720 
14721   if (ASTMutationListener *L = getASTMutationListener()) {
14722     L->CompletedImplicitDefinition(CopyConstructor);
14723   }
14724 }
14725 
14726 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14727                                                     CXXRecordDecl *ClassDecl) {
14728   assert(ClassDecl->needsImplicitMoveConstructor());
14729 
14730   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14731   if (DSM.isAlreadyBeingDeclared())
14732     return nullptr;
14733 
14734   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14735 
14736   QualType ArgType = ClassType;
14737   LangAS AS = getDefaultCXXMethodAddrSpace();
14738   if (AS != LangAS::Default)
14739     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14740   ArgType = Context.getRValueReferenceType(ArgType);
14741 
14742   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14743                                                      CXXMoveConstructor,
14744                                                      false);
14745 
14746   DeclarationName Name
14747     = Context.DeclarationNames.getCXXConstructorName(
14748                                            Context.getCanonicalType(ClassType));
14749   SourceLocation ClassLoc = ClassDecl->getLocation();
14750   DeclarationNameInfo NameInfo(Name, ClassLoc);
14751 
14752   // C++11 [class.copy]p11:
14753   //   An implicitly-declared copy/move constructor is an inline public
14754   //   member of its class.
14755   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14756       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14757       ExplicitSpecifier(),
14758       /*isInline=*/true,
14759       /*isImplicitlyDeclared=*/true,
14760       Constexpr ? ConstexprSpecKind::Constexpr
14761                 : ConstexprSpecKind::Unspecified);
14762   MoveConstructor->setAccess(AS_public);
14763   MoveConstructor->setDefaulted();
14764 
14765   if (getLangOpts().CUDA) {
14766     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14767                                             MoveConstructor,
14768                                             /* ConstRHS */ false,
14769                                             /* Diagnose */ false);
14770   }
14771 
14772   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14773 
14774   // Add the parameter to the constructor.
14775   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14776                                                ClassLoc, ClassLoc,
14777                                                /*IdentifierInfo=*/nullptr,
14778                                                ArgType, /*TInfo=*/nullptr,
14779                                                SC_None, nullptr);
14780   MoveConstructor->setParams(FromParam);
14781 
14782   MoveConstructor->setTrivial(
14783       ClassDecl->needsOverloadResolutionForMoveConstructor()
14784           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14785           : ClassDecl->hasTrivialMoveConstructor());
14786 
14787   MoveConstructor->setTrivialForCall(
14788       ClassDecl->hasAttr<TrivialABIAttr>() ||
14789       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14790            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14791                                     TAH_ConsiderTrivialABI)
14792            : ClassDecl->hasTrivialMoveConstructorForCall()));
14793 
14794   // Note that we have declared this constructor.
14795   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14796 
14797   Scope *S = getScopeForContext(ClassDecl);
14798   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14799 
14800   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14801     ClassDecl->setImplicitMoveConstructorIsDeleted();
14802     SetDeclDeleted(MoveConstructor, ClassLoc);
14803   }
14804 
14805   if (S)
14806     PushOnScopeChains(MoveConstructor, S, false);
14807   ClassDecl->addDecl(MoveConstructor);
14808 
14809   return MoveConstructor;
14810 }
14811 
14812 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14813                                          CXXConstructorDecl *MoveConstructor) {
14814   assert((MoveConstructor->isDefaulted() &&
14815           MoveConstructor->isMoveConstructor() &&
14816           !MoveConstructor->doesThisDeclarationHaveABody() &&
14817           !MoveConstructor->isDeleted()) &&
14818          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14819   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14820     return;
14821 
14822   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14823   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14824 
14825   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14826 
14827   // The exception specification is needed because we are defining the
14828   // function.
14829   ResolveExceptionSpec(CurrentLocation,
14830                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14831   MarkVTableUsed(CurrentLocation, ClassDecl);
14832 
14833   // Add a context note for diagnostics produced after this point.
14834   Scope.addContextNote(CurrentLocation);
14835 
14836   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14837     MoveConstructor->setInvalidDecl();
14838   } else {
14839     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14840                              ? MoveConstructor->getEndLoc()
14841                              : MoveConstructor->getLocation();
14842     Sema::CompoundScopeRAII CompoundScope(*this);
14843     MoveConstructor->setBody(ActOnCompoundStmt(
14844         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14845     MoveConstructor->markUsed(Context);
14846   }
14847 
14848   if (ASTMutationListener *L = getASTMutationListener()) {
14849     L->CompletedImplicitDefinition(MoveConstructor);
14850   }
14851 }
14852 
14853 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14854   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14855 }
14856 
14857 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14858                             SourceLocation CurrentLocation,
14859                             CXXConversionDecl *Conv) {
14860   SynthesizedFunctionScope Scope(*this, Conv);
14861   assert(!Conv->getReturnType()->isUndeducedType());
14862 
14863   QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType();
14864   CallingConv CC =
14865       ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv();
14866 
14867   CXXRecordDecl *Lambda = Conv->getParent();
14868   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14869   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14870 
14871   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14872     CallOp = InstantiateFunctionDeclaration(
14873         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14874     if (!CallOp)
14875       return;
14876 
14877     Invoker = InstantiateFunctionDeclaration(
14878         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14879     if (!Invoker)
14880       return;
14881   }
14882 
14883   if (CallOp->isInvalidDecl())
14884     return;
14885 
14886   // Mark the call operator referenced (and add to pending instantiations
14887   // if necessary).
14888   // For both the conversion and static-invoker template specializations
14889   // we construct their body's in this function, so no need to add them
14890   // to the PendingInstantiations.
14891   MarkFunctionReferenced(CurrentLocation, CallOp);
14892 
14893   // Fill in the __invoke function with a dummy implementation. IR generation
14894   // will fill in the actual details. Update its type in case it contained
14895   // an 'auto'.
14896   Invoker->markUsed(Context);
14897   Invoker->setReferenced();
14898   Invoker->setType(Conv->getReturnType()->getPointeeType());
14899   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14900 
14901   // Construct the body of the conversion function { return __invoke; }.
14902   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14903                                        VK_LValue, Conv->getLocation());
14904   assert(FunctionRef && "Can't refer to __invoke function?");
14905   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14906   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14907                                      Conv->getLocation()));
14908   Conv->markUsed(Context);
14909   Conv->setReferenced();
14910 
14911   if (ASTMutationListener *L = getASTMutationListener()) {
14912     L->CompletedImplicitDefinition(Conv);
14913     L->CompletedImplicitDefinition(Invoker);
14914   }
14915 }
14916 
14917 
14918 
14919 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14920        SourceLocation CurrentLocation,
14921        CXXConversionDecl *Conv)
14922 {
14923   assert(!Conv->getParent()->isGenericLambda());
14924 
14925   SynthesizedFunctionScope Scope(*this, Conv);
14926 
14927   // Copy-initialize the lambda object as needed to capture it.
14928   Expr *This = ActOnCXXThis(CurrentLocation).get();
14929   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14930 
14931   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14932                                                         Conv->getLocation(),
14933                                                         Conv, DerefThis);
14934 
14935   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14936   // behavior.  Note that only the general conversion function does this
14937   // (since it's unusable otherwise); in the case where we inline the
14938   // block literal, it has block literal lifetime semantics.
14939   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14940     BuildBlock = ImplicitCastExpr::Create(
14941         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14942         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14943 
14944   if (BuildBlock.isInvalid()) {
14945     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14946     Conv->setInvalidDecl();
14947     return;
14948   }
14949 
14950   // Create the return statement that returns the block from the conversion
14951   // function.
14952   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14953   if (Return.isInvalid()) {
14954     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14955     Conv->setInvalidDecl();
14956     return;
14957   }
14958 
14959   // Set the body of the conversion function.
14960   Stmt *ReturnS = Return.get();
14961   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14962                                      Conv->getLocation()));
14963   Conv->markUsed(Context);
14964 
14965   // We're done; notify the mutation listener, if any.
14966   if (ASTMutationListener *L = getASTMutationListener()) {
14967     L->CompletedImplicitDefinition(Conv);
14968   }
14969 }
14970 
14971 /// Determine whether the given list arguments contains exactly one
14972 /// "real" (non-default) argument.
14973 static bool hasOneRealArgument(MultiExprArg Args) {
14974   switch (Args.size()) {
14975   case 0:
14976     return false;
14977 
14978   default:
14979     if (!Args[1]->isDefaultArgument())
14980       return false;
14981 
14982     LLVM_FALLTHROUGH;
14983   case 1:
14984     return !Args[0]->isDefaultArgument();
14985   }
14986 
14987   return false;
14988 }
14989 
14990 ExprResult
14991 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14992                             NamedDecl *FoundDecl,
14993                             CXXConstructorDecl *Constructor,
14994                             MultiExprArg ExprArgs,
14995                             bool HadMultipleCandidates,
14996                             bool IsListInitialization,
14997                             bool IsStdInitListInitialization,
14998                             bool RequiresZeroInit,
14999                             unsigned ConstructKind,
15000                             SourceRange ParenRange) {
15001   bool Elidable = false;
15002 
15003   // C++0x [class.copy]p34:
15004   //   When certain criteria are met, an implementation is allowed to
15005   //   omit the copy/move construction of a class object, even if the
15006   //   copy/move constructor and/or destructor for the object have
15007   //   side effects. [...]
15008   //     - when a temporary class object that has not been bound to a
15009   //       reference (12.2) would be copied/moved to a class object
15010   //       with the same cv-unqualified type, the copy/move operation
15011   //       can be omitted by constructing the temporary object
15012   //       directly into the target of the omitted copy/move
15013   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15014       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15015     Expr *SubExpr = ExprArgs[0];
15016     Elidable = SubExpr->isTemporaryObject(
15017         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15018   }
15019 
15020   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15021                                FoundDecl, Constructor,
15022                                Elidable, ExprArgs, HadMultipleCandidates,
15023                                IsListInitialization,
15024                                IsStdInitListInitialization, RequiresZeroInit,
15025                                ConstructKind, ParenRange);
15026 }
15027 
15028 ExprResult
15029 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15030                             NamedDecl *FoundDecl,
15031                             CXXConstructorDecl *Constructor,
15032                             bool Elidable,
15033                             MultiExprArg ExprArgs,
15034                             bool HadMultipleCandidates,
15035                             bool IsListInitialization,
15036                             bool IsStdInitListInitialization,
15037                             bool RequiresZeroInit,
15038                             unsigned ConstructKind,
15039                             SourceRange ParenRange) {
15040   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15041     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15042     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15043       return ExprError();
15044   }
15045 
15046   return BuildCXXConstructExpr(
15047       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15048       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15049       RequiresZeroInit, ConstructKind, ParenRange);
15050 }
15051 
15052 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15053 /// including handling of its default argument expressions.
15054 ExprResult
15055 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15056                             CXXConstructorDecl *Constructor,
15057                             bool Elidable,
15058                             MultiExprArg ExprArgs,
15059                             bool HadMultipleCandidates,
15060                             bool IsListInitialization,
15061                             bool IsStdInitListInitialization,
15062                             bool RequiresZeroInit,
15063                             unsigned ConstructKind,
15064                             SourceRange ParenRange) {
15065   assert(declaresSameEntity(
15066              Constructor->getParent(),
15067              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15068          "given constructor for wrong type");
15069   MarkFunctionReferenced(ConstructLoc, Constructor);
15070   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15071     return ExprError();
15072   if (getLangOpts().SYCLIsDevice &&
15073       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15074     return ExprError();
15075 
15076   return CheckForImmediateInvocation(
15077       CXXConstructExpr::Create(
15078           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15079           HadMultipleCandidates, IsListInitialization,
15080           IsStdInitListInitialization, RequiresZeroInit,
15081           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15082           ParenRange),
15083       Constructor);
15084 }
15085 
15086 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15087   assert(Field->hasInClassInitializer());
15088 
15089   // If we already have the in-class initializer nothing needs to be done.
15090   if (Field->getInClassInitializer())
15091     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15092 
15093   // If we might have already tried and failed to instantiate, don't try again.
15094   if (Field->isInvalidDecl())
15095     return ExprError();
15096 
15097   // Maybe we haven't instantiated the in-class initializer. Go check the
15098   // pattern FieldDecl to see if it has one.
15099   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15100 
15101   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15102     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15103     DeclContext::lookup_result Lookup =
15104         ClassPattern->lookup(Field->getDeclName());
15105 
15106     FieldDecl *Pattern = nullptr;
15107     for (auto L : Lookup) {
15108       if (isa<FieldDecl>(L)) {
15109         Pattern = cast<FieldDecl>(L);
15110         break;
15111       }
15112     }
15113     assert(Pattern && "We must have set the Pattern!");
15114 
15115     if (!Pattern->hasInClassInitializer() ||
15116         InstantiateInClassInitializer(Loc, Field, Pattern,
15117                                       getTemplateInstantiationArgs(Field))) {
15118       // Don't diagnose this again.
15119       Field->setInvalidDecl();
15120       return ExprError();
15121     }
15122     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15123   }
15124 
15125   // DR1351:
15126   //   If the brace-or-equal-initializer of a non-static data member
15127   //   invokes a defaulted default constructor of its class or of an
15128   //   enclosing class in a potentially evaluated subexpression, the
15129   //   program is ill-formed.
15130   //
15131   // This resolution is unworkable: the exception specification of the
15132   // default constructor can be needed in an unevaluated context, in
15133   // particular, in the operand of a noexcept-expression, and we can be
15134   // unable to compute an exception specification for an enclosed class.
15135   //
15136   // Any attempt to resolve the exception specification of a defaulted default
15137   // constructor before the initializer is lexically complete will ultimately
15138   // come here at which point we can diagnose it.
15139   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15140   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15141       << OutermostClass << Field;
15142   Diag(Field->getEndLoc(),
15143        diag::note_default_member_initializer_not_yet_parsed);
15144   // Recover by marking the field invalid, unless we're in a SFINAE context.
15145   if (!isSFINAEContext())
15146     Field->setInvalidDecl();
15147   return ExprError();
15148 }
15149 
15150 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15151   if (VD->isInvalidDecl()) return;
15152   // If initializing the variable failed, don't also diagnose problems with
15153   // the desctructor, they're likely related.
15154   if (VD->getInit() && VD->getInit()->containsErrors())
15155     return;
15156 
15157   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15158   if (ClassDecl->isInvalidDecl()) return;
15159   if (ClassDecl->hasIrrelevantDestructor()) return;
15160   if (ClassDecl->isDependentContext()) return;
15161 
15162   if (VD->isNoDestroy(getASTContext()))
15163     return;
15164 
15165   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15166 
15167   // If this is an array, we'll require the destructor during initialization, so
15168   // we can skip over this. We still want to emit exit-time destructor warnings
15169   // though.
15170   if (!VD->getType()->isArrayType()) {
15171     MarkFunctionReferenced(VD->getLocation(), Destructor);
15172     CheckDestructorAccess(VD->getLocation(), Destructor,
15173                           PDiag(diag::err_access_dtor_var)
15174                               << VD->getDeclName() << VD->getType());
15175     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15176   }
15177 
15178   if (Destructor->isTrivial()) return;
15179 
15180   // If the destructor is constexpr, check whether the variable has constant
15181   // destruction now.
15182   if (Destructor->isConstexpr()) {
15183     bool HasConstantInit = false;
15184     if (VD->getInit() && !VD->getInit()->isValueDependent())
15185       HasConstantInit = VD->evaluateValue();
15186     SmallVector<PartialDiagnosticAt, 8> Notes;
15187     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15188         HasConstantInit) {
15189       Diag(VD->getLocation(),
15190            diag::err_constexpr_var_requires_const_destruction) << VD;
15191       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15192         Diag(Notes[I].first, Notes[I].second);
15193     }
15194   }
15195 
15196   if (!VD->hasGlobalStorage()) return;
15197 
15198   // Emit warning for non-trivial dtor in global scope (a real global,
15199   // class-static, function-static).
15200   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15201 
15202   // TODO: this should be re-enabled for static locals by !CXAAtExit
15203   if (!VD->isStaticLocal())
15204     Diag(VD->getLocation(), diag::warn_global_destructor);
15205 }
15206 
15207 /// Given a constructor and the set of arguments provided for the
15208 /// constructor, convert the arguments and add any required default arguments
15209 /// to form a proper call to this constructor.
15210 ///
15211 /// \returns true if an error occurred, false otherwise.
15212 bool
15213 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15214                               MultiExprArg ArgsPtr,
15215                               SourceLocation Loc,
15216                               SmallVectorImpl<Expr*> &ConvertedArgs,
15217                               bool AllowExplicit,
15218                               bool IsListInitialization) {
15219   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15220   unsigned NumArgs = ArgsPtr.size();
15221   Expr **Args = ArgsPtr.data();
15222 
15223   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15224   unsigned NumParams = Proto->getNumParams();
15225 
15226   // If too few arguments are available, we'll fill in the rest with defaults.
15227   if (NumArgs < NumParams)
15228     ConvertedArgs.reserve(NumParams);
15229   else
15230     ConvertedArgs.reserve(NumArgs);
15231 
15232   VariadicCallType CallType =
15233     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15234   SmallVector<Expr *, 8> AllArgs;
15235   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15236                                         Proto, 0,
15237                                         llvm::makeArrayRef(Args, NumArgs),
15238                                         AllArgs,
15239                                         CallType, AllowExplicit,
15240                                         IsListInitialization);
15241   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15242 
15243   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15244 
15245   CheckConstructorCall(Constructor,
15246                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15247                        Proto, Loc);
15248 
15249   return Invalid;
15250 }
15251 
15252 static inline bool
15253 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15254                                        const FunctionDecl *FnDecl) {
15255   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15256   if (isa<NamespaceDecl>(DC)) {
15257     return SemaRef.Diag(FnDecl->getLocation(),
15258                         diag::err_operator_new_delete_declared_in_namespace)
15259       << FnDecl->getDeclName();
15260   }
15261 
15262   if (isa<TranslationUnitDecl>(DC) &&
15263       FnDecl->getStorageClass() == SC_Static) {
15264     return SemaRef.Diag(FnDecl->getLocation(),
15265                         diag::err_operator_new_delete_declared_static)
15266       << FnDecl->getDeclName();
15267   }
15268 
15269   return false;
15270 }
15271 
15272 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15273                                              const PointerType *PtrTy) {
15274   auto &Ctx = SemaRef.Context;
15275   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15276   PtrQuals.removeAddressSpace();
15277   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15278       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15279 }
15280 
15281 static inline bool
15282 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15283                             CanQualType ExpectedResultType,
15284                             CanQualType ExpectedFirstParamType,
15285                             unsigned DependentParamTypeDiag,
15286                             unsigned InvalidParamTypeDiag) {
15287   QualType ResultType =
15288       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15289 
15290   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15291     // The operator is valid on any address space for OpenCL.
15292     // Drop address space from actual and expected result types.
15293     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15294       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15295 
15296     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15297       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15298   }
15299 
15300   // Check that the result type is what we expect.
15301   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15302     // Reject even if the type is dependent; an operator delete function is
15303     // required to have a non-dependent result type.
15304     return SemaRef.Diag(
15305                FnDecl->getLocation(),
15306                ResultType->isDependentType()
15307                    ? diag::err_operator_new_delete_dependent_result_type
15308                    : diag::err_operator_new_delete_invalid_result_type)
15309            << FnDecl->getDeclName() << ExpectedResultType;
15310   }
15311 
15312   // A function template must have at least 2 parameters.
15313   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15314     return SemaRef.Diag(FnDecl->getLocation(),
15315                       diag::err_operator_new_delete_template_too_few_parameters)
15316         << FnDecl->getDeclName();
15317 
15318   // The function decl must have at least 1 parameter.
15319   if (FnDecl->getNumParams() == 0)
15320     return SemaRef.Diag(FnDecl->getLocation(),
15321                         diag::err_operator_new_delete_too_few_parameters)
15322       << FnDecl->getDeclName();
15323 
15324   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15325   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15326     // The operator is valid on any address space for OpenCL.
15327     // Drop address space from actual and expected first parameter types.
15328     if (const auto *PtrTy =
15329             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15330       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15331 
15332     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15333       ExpectedFirstParamType =
15334           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15335   }
15336 
15337   // Check that the first parameter type is what we expect.
15338   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15339       ExpectedFirstParamType) {
15340     // The first parameter type is not allowed to be dependent. As a tentative
15341     // DR resolution, we allow a dependent parameter type if it is the right
15342     // type anyway, to allow destroying operator delete in class templates.
15343     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15344                                                    ? DependentParamTypeDiag
15345                                                    : InvalidParamTypeDiag)
15346            << FnDecl->getDeclName() << ExpectedFirstParamType;
15347   }
15348 
15349   return false;
15350 }
15351 
15352 static bool
15353 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15354   // C++ [basic.stc.dynamic.allocation]p1:
15355   //   A program is ill-formed if an allocation function is declared in a
15356   //   namespace scope other than global scope or declared static in global
15357   //   scope.
15358   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15359     return true;
15360 
15361   CanQualType SizeTy =
15362     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15363 
15364   // C++ [basic.stc.dynamic.allocation]p1:
15365   //  The return type shall be void*. The first parameter shall have type
15366   //  std::size_t.
15367   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15368                                   SizeTy,
15369                                   diag::err_operator_new_dependent_param_type,
15370                                   diag::err_operator_new_param_type))
15371     return true;
15372 
15373   // C++ [basic.stc.dynamic.allocation]p1:
15374   //  The first parameter shall not have an associated default argument.
15375   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15376     return SemaRef.Diag(FnDecl->getLocation(),
15377                         diag::err_operator_new_default_arg)
15378       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15379 
15380   return false;
15381 }
15382 
15383 static bool
15384 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15385   // C++ [basic.stc.dynamic.deallocation]p1:
15386   //   A program is ill-formed if deallocation functions are declared in a
15387   //   namespace scope other than global scope or declared static in global
15388   //   scope.
15389   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15390     return true;
15391 
15392   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15393 
15394   // C++ P0722:
15395   //   Within a class C, the first parameter of a destroying operator delete
15396   //   shall be of type C *. The first parameter of any other deallocation
15397   //   function shall be of type void *.
15398   CanQualType ExpectedFirstParamType =
15399       MD && MD->isDestroyingOperatorDelete()
15400           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15401                 SemaRef.Context.getRecordType(MD->getParent())))
15402           : SemaRef.Context.VoidPtrTy;
15403 
15404   // C++ [basic.stc.dynamic.deallocation]p2:
15405   //   Each deallocation function shall return void
15406   if (CheckOperatorNewDeleteTypes(
15407           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15408           diag::err_operator_delete_dependent_param_type,
15409           diag::err_operator_delete_param_type))
15410     return true;
15411 
15412   // C++ P0722:
15413   //   A destroying operator delete shall be a usual deallocation function.
15414   if (MD && !MD->getParent()->isDependentContext() &&
15415       MD->isDestroyingOperatorDelete() &&
15416       !SemaRef.isUsualDeallocationFunction(MD)) {
15417     SemaRef.Diag(MD->getLocation(),
15418                  diag::err_destroying_operator_delete_not_usual);
15419     return true;
15420   }
15421 
15422   return false;
15423 }
15424 
15425 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15426 /// of this overloaded operator is well-formed. If so, returns false;
15427 /// otherwise, emits appropriate diagnostics and returns true.
15428 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15429   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15430          "Expected an overloaded operator declaration");
15431 
15432   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15433 
15434   // C++ [over.oper]p5:
15435   //   The allocation and deallocation functions, operator new,
15436   //   operator new[], operator delete and operator delete[], are
15437   //   described completely in 3.7.3. The attributes and restrictions
15438   //   found in the rest of this subclause do not apply to them unless
15439   //   explicitly stated in 3.7.3.
15440   if (Op == OO_Delete || Op == OO_Array_Delete)
15441     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15442 
15443   if (Op == OO_New || Op == OO_Array_New)
15444     return CheckOperatorNewDeclaration(*this, FnDecl);
15445 
15446   // C++ [over.oper]p6:
15447   //   An operator function shall either be a non-static member
15448   //   function or be a non-member function and have at least one
15449   //   parameter whose type is a class, a reference to a class, an
15450   //   enumeration, or a reference to an enumeration.
15451   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15452     if (MethodDecl->isStatic())
15453       return Diag(FnDecl->getLocation(),
15454                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15455   } else {
15456     bool ClassOrEnumParam = false;
15457     for (auto Param : FnDecl->parameters()) {
15458       QualType ParamType = Param->getType().getNonReferenceType();
15459       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15460           ParamType->isEnumeralType()) {
15461         ClassOrEnumParam = true;
15462         break;
15463       }
15464     }
15465 
15466     if (!ClassOrEnumParam)
15467       return Diag(FnDecl->getLocation(),
15468                   diag::err_operator_overload_needs_class_or_enum)
15469         << FnDecl->getDeclName();
15470   }
15471 
15472   // C++ [over.oper]p8:
15473   //   An operator function cannot have default arguments (8.3.6),
15474   //   except where explicitly stated below.
15475   //
15476   // Only the function-call operator allows default arguments
15477   // (C++ [over.call]p1).
15478   if (Op != OO_Call) {
15479     for (auto Param : FnDecl->parameters()) {
15480       if (Param->hasDefaultArg())
15481         return Diag(Param->getLocation(),
15482                     diag::err_operator_overload_default_arg)
15483           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15484     }
15485   }
15486 
15487   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15488     { false, false, false }
15489 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15490     , { Unary, Binary, MemberOnly }
15491 #include "clang/Basic/OperatorKinds.def"
15492   };
15493 
15494   bool CanBeUnaryOperator = OperatorUses[Op][0];
15495   bool CanBeBinaryOperator = OperatorUses[Op][1];
15496   bool MustBeMemberOperator = OperatorUses[Op][2];
15497 
15498   // C++ [over.oper]p8:
15499   //   [...] Operator functions cannot have more or fewer parameters
15500   //   than the number required for the corresponding operator, as
15501   //   described in the rest of this subclause.
15502   unsigned NumParams = FnDecl->getNumParams()
15503                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15504   if (Op != OO_Call &&
15505       ((NumParams == 1 && !CanBeUnaryOperator) ||
15506        (NumParams == 2 && !CanBeBinaryOperator) ||
15507        (NumParams < 1) || (NumParams > 2))) {
15508     // We have the wrong number of parameters.
15509     unsigned ErrorKind;
15510     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15511       ErrorKind = 2;  // 2 -> unary or binary.
15512     } else if (CanBeUnaryOperator) {
15513       ErrorKind = 0;  // 0 -> unary
15514     } else {
15515       assert(CanBeBinaryOperator &&
15516              "All non-call overloaded operators are unary or binary!");
15517       ErrorKind = 1;  // 1 -> binary
15518     }
15519 
15520     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15521       << FnDecl->getDeclName() << NumParams << ErrorKind;
15522   }
15523 
15524   // Overloaded operators other than operator() cannot be variadic.
15525   if (Op != OO_Call &&
15526       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15527     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15528       << FnDecl->getDeclName();
15529   }
15530 
15531   // Some operators must be non-static member functions.
15532   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15533     return Diag(FnDecl->getLocation(),
15534                 diag::err_operator_overload_must_be_member)
15535       << FnDecl->getDeclName();
15536   }
15537 
15538   // C++ [over.inc]p1:
15539   //   The user-defined function called operator++ implements the
15540   //   prefix and postfix ++ operator. If this function is a member
15541   //   function with no parameters, or a non-member function with one
15542   //   parameter of class or enumeration type, it defines the prefix
15543   //   increment operator ++ for objects of that type. If the function
15544   //   is a member function with one parameter (which shall be of type
15545   //   int) or a non-member function with two parameters (the second
15546   //   of which shall be of type int), it defines the postfix
15547   //   increment operator ++ for objects of that type.
15548   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15549     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15550     QualType ParamType = LastParam->getType();
15551 
15552     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15553         !ParamType->isDependentType())
15554       return Diag(LastParam->getLocation(),
15555                   diag::err_operator_overload_post_incdec_must_be_int)
15556         << LastParam->getType() << (Op == OO_MinusMinus);
15557   }
15558 
15559   return false;
15560 }
15561 
15562 static bool
15563 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15564                                           FunctionTemplateDecl *TpDecl) {
15565   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15566 
15567   // Must have one or two template parameters.
15568   if (TemplateParams->size() == 1) {
15569     NonTypeTemplateParmDecl *PmDecl =
15570         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15571 
15572     // The template parameter must be a char parameter pack.
15573     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15574         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15575       return false;
15576 
15577     // C++20 [over.literal]p5:
15578     //   A string literal operator template is a literal operator template
15579     //   whose template-parameter-list comprises a single non-type
15580     //   template-parameter of class type.
15581     //
15582     // As a DR resolution, we also allow placeholders for deduced class
15583     // template specializations.
15584     if (SemaRef.getLangOpts().CPlusPlus20 &&
15585         !PmDecl->isTemplateParameterPack() &&
15586         (PmDecl->getType()->isRecordType() ||
15587          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15588       return false;
15589   } else if (TemplateParams->size() == 2) {
15590     TemplateTypeParmDecl *PmType =
15591         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15592     NonTypeTemplateParmDecl *PmArgs =
15593         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15594 
15595     // The second template parameter must be a parameter pack with the
15596     // first template parameter as its type.
15597     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15598         PmArgs->isTemplateParameterPack()) {
15599       const TemplateTypeParmType *TArgs =
15600           PmArgs->getType()->getAs<TemplateTypeParmType>();
15601       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15602           TArgs->getIndex() == PmType->getIndex()) {
15603         if (!SemaRef.inTemplateInstantiation())
15604           SemaRef.Diag(TpDecl->getLocation(),
15605                        diag::ext_string_literal_operator_template);
15606         return false;
15607       }
15608     }
15609   }
15610 
15611   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15612                diag::err_literal_operator_template)
15613       << TpDecl->getTemplateParameters()->getSourceRange();
15614   return true;
15615 }
15616 
15617 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15618 /// of this literal operator function is well-formed. If so, returns
15619 /// false; otherwise, emits appropriate diagnostics and returns true.
15620 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15621   if (isa<CXXMethodDecl>(FnDecl)) {
15622     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15623       << FnDecl->getDeclName();
15624     return true;
15625   }
15626 
15627   if (FnDecl->isExternC()) {
15628     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15629     if (const LinkageSpecDecl *LSD =
15630             FnDecl->getDeclContext()->getExternCContext())
15631       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15632     return true;
15633   }
15634 
15635   // This might be the definition of a literal operator template.
15636   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15637 
15638   // This might be a specialization of a literal operator template.
15639   if (!TpDecl)
15640     TpDecl = FnDecl->getPrimaryTemplate();
15641 
15642   // template <char...> type operator "" name() and
15643   // template <class T, T...> type operator "" name() are the only valid
15644   // template signatures, and the only valid signatures with no parameters.
15645   //
15646   // C++20 also allows template <SomeClass T> type operator "" name().
15647   if (TpDecl) {
15648     if (FnDecl->param_size() != 0) {
15649       Diag(FnDecl->getLocation(),
15650            diag::err_literal_operator_template_with_params);
15651       return true;
15652     }
15653 
15654     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15655       return true;
15656 
15657   } else if (FnDecl->param_size() == 1) {
15658     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15659 
15660     QualType ParamType = Param->getType().getUnqualifiedType();
15661 
15662     // Only unsigned long long int, long double, any character type, and const
15663     // char * are allowed as the only parameters.
15664     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15665         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15666         Context.hasSameType(ParamType, Context.CharTy) ||
15667         Context.hasSameType(ParamType, Context.WideCharTy) ||
15668         Context.hasSameType(ParamType, Context.Char8Ty) ||
15669         Context.hasSameType(ParamType, Context.Char16Ty) ||
15670         Context.hasSameType(ParamType, Context.Char32Ty)) {
15671     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15672       QualType InnerType = Ptr->getPointeeType();
15673 
15674       // Pointer parameter must be a const char *.
15675       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15676                                 Context.CharTy) &&
15677             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15678         Diag(Param->getSourceRange().getBegin(),
15679              diag::err_literal_operator_param)
15680             << ParamType << "'const char *'" << Param->getSourceRange();
15681         return true;
15682       }
15683 
15684     } else if (ParamType->isRealFloatingType()) {
15685       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15686           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15687       return true;
15688 
15689     } else if (ParamType->isIntegerType()) {
15690       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15691           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15692       return true;
15693 
15694     } else {
15695       Diag(Param->getSourceRange().getBegin(),
15696            diag::err_literal_operator_invalid_param)
15697           << ParamType << Param->getSourceRange();
15698       return true;
15699     }
15700 
15701   } else if (FnDecl->param_size() == 2) {
15702     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15703 
15704     // First, verify that the first parameter is correct.
15705 
15706     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15707 
15708     // Two parameter function must have a pointer to const as a
15709     // first parameter; let's strip those qualifiers.
15710     const PointerType *PT = FirstParamType->getAs<PointerType>();
15711 
15712     if (!PT) {
15713       Diag((*Param)->getSourceRange().getBegin(),
15714            diag::err_literal_operator_param)
15715           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15716       return true;
15717     }
15718 
15719     QualType PointeeType = PT->getPointeeType();
15720     // First parameter must be const
15721     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15722       Diag((*Param)->getSourceRange().getBegin(),
15723            diag::err_literal_operator_param)
15724           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15725       return true;
15726     }
15727 
15728     QualType InnerType = PointeeType.getUnqualifiedType();
15729     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15730     // const char32_t* are allowed as the first parameter to a two-parameter
15731     // function
15732     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15733           Context.hasSameType(InnerType, Context.WideCharTy) ||
15734           Context.hasSameType(InnerType, Context.Char8Ty) ||
15735           Context.hasSameType(InnerType, Context.Char16Ty) ||
15736           Context.hasSameType(InnerType, Context.Char32Ty))) {
15737       Diag((*Param)->getSourceRange().getBegin(),
15738            diag::err_literal_operator_param)
15739           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15740       return true;
15741     }
15742 
15743     // Move on to the second and final parameter.
15744     ++Param;
15745 
15746     // The second parameter must be a std::size_t.
15747     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15748     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15749       Diag((*Param)->getSourceRange().getBegin(),
15750            diag::err_literal_operator_param)
15751           << SecondParamType << Context.getSizeType()
15752           << (*Param)->getSourceRange();
15753       return true;
15754     }
15755   } else {
15756     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15757     return true;
15758   }
15759 
15760   // Parameters are good.
15761 
15762   // A parameter-declaration-clause containing a default argument is not
15763   // equivalent to any of the permitted forms.
15764   for (auto Param : FnDecl->parameters()) {
15765     if (Param->hasDefaultArg()) {
15766       Diag(Param->getDefaultArgRange().getBegin(),
15767            diag::err_literal_operator_default_argument)
15768         << Param->getDefaultArgRange();
15769       break;
15770     }
15771   }
15772 
15773   StringRef LiteralName
15774     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15775   if (LiteralName[0] != '_' &&
15776       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15777     // C++11 [usrlit.suffix]p1:
15778     //   Literal suffix identifiers that do not start with an underscore
15779     //   are reserved for future standardization.
15780     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15781       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15782   }
15783 
15784   return false;
15785 }
15786 
15787 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15788 /// linkage specification, including the language and (if present)
15789 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15790 /// language string literal. LBraceLoc, if valid, provides the location of
15791 /// the '{' brace. Otherwise, this linkage specification does not
15792 /// have any braces.
15793 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15794                                            Expr *LangStr,
15795                                            SourceLocation LBraceLoc) {
15796   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15797   if (!Lit->isAscii()) {
15798     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15799       << LangStr->getSourceRange();
15800     return nullptr;
15801   }
15802 
15803   StringRef Lang = Lit->getString();
15804   LinkageSpecDecl::LanguageIDs Language;
15805   if (Lang == "C")
15806     Language = LinkageSpecDecl::lang_c;
15807   else if (Lang == "C++")
15808     Language = LinkageSpecDecl::lang_cxx;
15809   else {
15810     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15811       << LangStr->getSourceRange();
15812     return nullptr;
15813   }
15814 
15815   // FIXME: Add all the various semantics of linkage specifications
15816 
15817   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15818                                                LangStr->getExprLoc(), Language,
15819                                                LBraceLoc.isValid());
15820   CurContext->addDecl(D);
15821   PushDeclContext(S, D);
15822   return D;
15823 }
15824 
15825 /// ActOnFinishLinkageSpecification - Complete the definition of
15826 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15827 /// valid, it's the position of the closing '}' brace in a linkage
15828 /// specification that uses braces.
15829 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15830                                             Decl *LinkageSpec,
15831                                             SourceLocation RBraceLoc) {
15832   if (RBraceLoc.isValid()) {
15833     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15834     LSDecl->setRBraceLoc(RBraceLoc);
15835   }
15836   PopDeclContext();
15837   return LinkageSpec;
15838 }
15839 
15840 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15841                                   const ParsedAttributesView &AttrList,
15842                                   SourceLocation SemiLoc) {
15843   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15844   // Attribute declarations appertain to empty declaration so we handle
15845   // them here.
15846   ProcessDeclAttributeList(S, ED, AttrList);
15847 
15848   CurContext->addDecl(ED);
15849   return ED;
15850 }
15851 
15852 /// Perform semantic analysis for the variable declaration that
15853 /// occurs within a C++ catch clause, returning the newly-created
15854 /// variable.
15855 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15856                                          TypeSourceInfo *TInfo,
15857                                          SourceLocation StartLoc,
15858                                          SourceLocation Loc,
15859                                          IdentifierInfo *Name) {
15860   bool Invalid = false;
15861   QualType ExDeclType = TInfo->getType();
15862 
15863   // Arrays and functions decay.
15864   if (ExDeclType->isArrayType())
15865     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15866   else if (ExDeclType->isFunctionType())
15867     ExDeclType = Context.getPointerType(ExDeclType);
15868 
15869   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15870   // The exception-declaration shall not denote a pointer or reference to an
15871   // incomplete type, other than [cv] void*.
15872   // N2844 forbids rvalue references.
15873   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15874     Diag(Loc, diag::err_catch_rvalue_ref);
15875     Invalid = true;
15876   }
15877 
15878   if (ExDeclType->isVariablyModifiedType()) {
15879     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15880     Invalid = true;
15881   }
15882 
15883   QualType BaseType = ExDeclType;
15884   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15885   unsigned DK = diag::err_catch_incomplete;
15886   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15887     BaseType = Ptr->getPointeeType();
15888     Mode = 1;
15889     DK = diag::err_catch_incomplete_ptr;
15890   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15891     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15892     BaseType = Ref->getPointeeType();
15893     Mode = 2;
15894     DK = diag::err_catch_incomplete_ref;
15895   }
15896   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15897       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15898     Invalid = true;
15899 
15900   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15901     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15902     Invalid = true;
15903   }
15904 
15905   if (!Invalid && !ExDeclType->isDependentType() &&
15906       RequireNonAbstractType(Loc, ExDeclType,
15907                              diag::err_abstract_type_in_decl,
15908                              AbstractVariableType))
15909     Invalid = true;
15910 
15911   // Only the non-fragile NeXT runtime currently supports C++ catches
15912   // of ObjC types, and no runtime supports catching ObjC types by value.
15913   if (!Invalid && getLangOpts().ObjC) {
15914     QualType T = ExDeclType;
15915     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15916       T = RT->getPointeeType();
15917 
15918     if (T->isObjCObjectType()) {
15919       Diag(Loc, diag::err_objc_object_catch);
15920       Invalid = true;
15921     } else if (T->isObjCObjectPointerType()) {
15922       // FIXME: should this be a test for macosx-fragile specifically?
15923       if (getLangOpts().ObjCRuntime.isFragile())
15924         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15925     }
15926   }
15927 
15928   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15929                                     ExDeclType, TInfo, SC_None);
15930   ExDecl->setExceptionVariable(true);
15931 
15932   // In ARC, infer 'retaining' for variables of retainable type.
15933   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15934     Invalid = true;
15935 
15936   if (!Invalid && !ExDeclType->isDependentType()) {
15937     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15938       // Insulate this from anything else we might currently be parsing.
15939       EnterExpressionEvaluationContext scope(
15940           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15941 
15942       // C++ [except.handle]p16:
15943       //   The object declared in an exception-declaration or, if the
15944       //   exception-declaration does not specify a name, a temporary (12.2) is
15945       //   copy-initialized (8.5) from the exception object. [...]
15946       //   The object is destroyed when the handler exits, after the destruction
15947       //   of any automatic objects initialized within the handler.
15948       //
15949       // We just pretend to initialize the object with itself, then make sure
15950       // it can be destroyed later.
15951       QualType initType = Context.getExceptionObjectType(ExDeclType);
15952 
15953       InitializedEntity entity =
15954         InitializedEntity::InitializeVariable(ExDecl);
15955       InitializationKind initKind =
15956         InitializationKind::CreateCopy(Loc, SourceLocation());
15957 
15958       Expr *opaqueValue =
15959         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15960       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15961       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15962       if (result.isInvalid())
15963         Invalid = true;
15964       else {
15965         // If the constructor used was non-trivial, set this as the
15966         // "initializer".
15967         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15968         if (!construct->getConstructor()->isTrivial()) {
15969           Expr *init = MaybeCreateExprWithCleanups(construct);
15970           ExDecl->setInit(init);
15971         }
15972 
15973         // And make sure it's destructable.
15974         FinalizeVarWithDestructor(ExDecl, recordType);
15975       }
15976     }
15977   }
15978 
15979   if (Invalid)
15980     ExDecl->setInvalidDecl();
15981 
15982   return ExDecl;
15983 }
15984 
15985 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15986 /// handler.
15987 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15988   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15989   bool Invalid = D.isInvalidType();
15990 
15991   // Check for unexpanded parameter packs.
15992   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15993                                       UPPC_ExceptionType)) {
15994     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15995                                              D.getIdentifierLoc());
15996     Invalid = true;
15997   }
15998 
15999   IdentifierInfo *II = D.getIdentifier();
16000   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16001                                              LookupOrdinaryName,
16002                                              ForVisibleRedeclaration)) {
16003     // The scope should be freshly made just for us. There is just no way
16004     // it contains any previous declaration, except for function parameters in
16005     // a function-try-block's catch statement.
16006     assert(!S->isDeclScope(PrevDecl));
16007     if (isDeclInScope(PrevDecl, CurContext, S)) {
16008       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16009         << D.getIdentifier();
16010       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16011       Invalid = true;
16012     } else if (PrevDecl->isTemplateParameter())
16013       // Maybe we will complain about the shadowed template parameter.
16014       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16015   }
16016 
16017   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16018     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16019       << D.getCXXScopeSpec().getRange();
16020     Invalid = true;
16021   }
16022 
16023   VarDecl *ExDecl = BuildExceptionDeclaration(
16024       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16025   if (Invalid)
16026     ExDecl->setInvalidDecl();
16027 
16028   // Add the exception declaration into this scope.
16029   if (II)
16030     PushOnScopeChains(ExDecl, S);
16031   else
16032     CurContext->addDecl(ExDecl);
16033 
16034   ProcessDeclAttributes(S, ExDecl, D);
16035   return ExDecl;
16036 }
16037 
16038 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16039                                          Expr *AssertExpr,
16040                                          Expr *AssertMessageExpr,
16041                                          SourceLocation RParenLoc) {
16042   StringLiteral *AssertMessage =
16043       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16044 
16045   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16046     return nullptr;
16047 
16048   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16049                                       AssertMessage, RParenLoc, false);
16050 }
16051 
16052 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16053                                          Expr *AssertExpr,
16054                                          StringLiteral *AssertMessage,
16055                                          SourceLocation RParenLoc,
16056                                          bool Failed) {
16057   assert(AssertExpr != nullptr && "Expected non-null condition");
16058   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16059       !Failed) {
16060     // In a static_assert-declaration, the constant-expression shall be a
16061     // constant expression that can be contextually converted to bool.
16062     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16063     if (Converted.isInvalid())
16064       Failed = true;
16065 
16066     ExprResult FullAssertExpr =
16067         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16068                             /*DiscardedValue*/ false,
16069                             /*IsConstexpr*/ true);
16070     if (FullAssertExpr.isInvalid())
16071       Failed = true;
16072     else
16073       AssertExpr = FullAssertExpr.get();
16074 
16075     llvm::APSInt Cond;
16076     if (!Failed && VerifyIntegerConstantExpression(
16077                        AssertExpr, &Cond,
16078                        diag::err_static_assert_expression_is_not_constant)
16079                        .isInvalid())
16080       Failed = true;
16081 
16082     if (!Failed && !Cond) {
16083       SmallString<256> MsgBuffer;
16084       llvm::raw_svector_ostream Msg(MsgBuffer);
16085       if (AssertMessage)
16086         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16087 
16088       Expr *InnerCond = nullptr;
16089       std::string InnerCondDescription;
16090       std::tie(InnerCond, InnerCondDescription) =
16091         findFailedBooleanCondition(Converted.get());
16092       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16093         // Drill down into concept specialization expressions to see why they
16094         // weren't satisfied.
16095         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16096           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16097         ConstraintSatisfaction Satisfaction;
16098         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16099           DiagnoseUnsatisfiedConstraint(Satisfaction);
16100       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16101                            && !isa<IntegerLiteral>(InnerCond)) {
16102         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16103           << InnerCondDescription << !AssertMessage
16104           << Msg.str() << InnerCond->getSourceRange();
16105       } else {
16106         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16107           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16108       }
16109       Failed = true;
16110     }
16111   } else {
16112     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16113                                                     /*DiscardedValue*/false,
16114                                                     /*IsConstexpr*/true);
16115     if (FullAssertExpr.isInvalid())
16116       Failed = true;
16117     else
16118       AssertExpr = FullAssertExpr.get();
16119   }
16120 
16121   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16122                                         AssertExpr, AssertMessage, RParenLoc,
16123                                         Failed);
16124 
16125   CurContext->addDecl(Decl);
16126   return Decl;
16127 }
16128 
16129 /// Perform semantic analysis of the given friend type declaration.
16130 ///
16131 /// \returns A friend declaration that.
16132 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16133                                       SourceLocation FriendLoc,
16134                                       TypeSourceInfo *TSInfo) {
16135   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16136 
16137   QualType T = TSInfo->getType();
16138   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16139 
16140   // C++03 [class.friend]p2:
16141   //   An elaborated-type-specifier shall be used in a friend declaration
16142   //   for a class.*
16143   //
16144   //   * The class-key of the elaborated-type-specifier is required.
16145   if (!CodeSynthesisContexts.empty()) {
16146     // Do not complain about the form of friend template types during any kind
16147     // of code synthesis. For template instantiation, we will have complained
16148     // when the template was defined.
16149   } else {
16150     if (!T->isElaboratedTypeSpecifier()) {
16151       // If we evaluated the type to a record type, suggest putting
16152       // a tag in front.
16153       if (const RecordType *RT = T->getAs<RecordType>()) {
16154         RecordDecl *RD = RT->getDecl();
16155 
16156         SmallString<16> InsertionText(" ");
16157         InsertionText += RD->getKindName();
16158 
16159         Diag(TypeRange.getBegin(),
16160              getLangOpts().CPlusPlus11 ?
16161                diag::warn_cxx98_compat_unelaborated_friend_type :
16162                diag::ext_unelaborated_friend_type)
16163           << (unsigned) RD->getTagKind()
16164           << T
16165           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16166                                         InsertionText);
16167       } else {
16168         Diag(FriendLoc,
16169              getLangOpts().CPlusPlus11 ?
16170                diag::warn_cxx98_compat_nonclass_type_friend :
16171                diag::ext_nonclass_type_friend)
16172           << T
16173           << TypeRange;
16174       }
16175     } else if (T->getAs<EnumType>()) {
16176       Diag(FriendLoc,
16177            getLangOpts().CPlusPlus11 ?
16178              diag::warn_cxx98_compat_enum_friend :
16179              diag::ext_enum_friend)
16180         << T
16181         << TypeRange;
16182     }
16183 
16184     // C++11 [class.friend]p3:
16185     //   A friend declaration that does not declare a function shall have one
16186     //   of the following forms:
16187     //     friend elaborated-type-specifier ;
16188     //     friend simple-type-specifier ;
16189     //     friend typename-specifier ;
16190     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16191       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16192   }
16193 
16194   //   If the type specifier in a friend declaration designates a (possibly
16195   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16196   //   the friend declaration is ignored.
16197   return FriendDecl::Create(Context, CurContext,
16198                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16199                             FriendLoc);
16200 }
16201 
16202 /// Handle a friend tag declaration where the scope specifier was
16203 /// templated.
16204 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16205                                     unsigned TagSpec, SourceLocation TagLoc,
16206                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16207                                     SourceLocation NameLoc,
16208                                     const ParsedAttributesView &Attr,
16209                                     MultiTemplateParamsArg TempParamLists) {
16210   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16211 
16212   bool IsMemberSpecialization = false;
16213   bool Invalid = false;
16214 
16215   if (TemplateParameterList *TemplateParams =
16216           MatchTemplateParametersToScopeSpecifier(
16217               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16218               IsMemberSpecialization, Invalid)) {
16219     if (TemplateParams->size() > 0) {
16220       // This is a declaration of a class template.
16221       if (Invalid)
16222         return nullptr;
16223 
16224       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16225                                 NameLoc, Attr, TemplateParams, AS_public,
16226                                 /*ModulePrivateLoc=*/SourceLocation(),
16227                                 FriendLoc, TempParamLists.size() - 1,
16228                                 TempParamLists.data()).get();
16229     } else {
16230       // The "template<>" header is extraneous.
16231       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16232         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16233       IsMemberSpecialization = true;
16234     }
16235   }
16236 
16237   if (Invalid) return nullptr;
16238 
16239   bool isAllExplicitSpecializations = true;
16240   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16241     if (TempParamLists[I]->size()) {
16242       isAllExplicitSpecializations = false;
16243       break;
16244     }
16245   }
16246 
16247   // FIXME: don't ignore attributes.
16248 
16249   // If it's explicit specializations all the way down, just forget
16250   // about the template header and build an appropriate non-templated
16251   // friend.  TODO: for source fidelity, remember the headers.
16252   if (isAllExplicitSpecializations) {
16253     if (SS.isEmpty()) {
16254       bool Owned = false;
16255       bool IsDependent = false;
16256       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16257                       Attr, AS_public,
16258                       /*ModulePrivateLoc=*/SourceLocation(),
16259                       MultiTemplateParamsArg(), Owned, IsDependent,
16260                       /*ScopedEnumKWLoc=*/SourceLocation(),
16261                       /*ScopedEnumUsesClassTag=*/false,
16262                       /*UnderlyingType=*/TypeResult(),
16263                       /*IsTypeSpecifier=*/false,
16264                       /*IsTemplateParamOrArg=*/false);
16265     }
16266 
16267     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16268     ElaboratedTypeKeyword Keyword
16269       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16270     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16271                                    *Name, NameLoc);
16272     if (T.isNull())
16273       return nullptr;
16274 
16275     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16276     if (isa<DependentNameType>(T)) {
16277       DependentNameTypeLoc TL =
16278           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16279       TL.setElaboratedKeywordLoc(TagLoc);
16280       TL.setQualifierLoc(QualifierLoc);
16281       TL.setNameLoc(NameLoc);
16282     } else {
16283       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16284       TL.setElaboratedKeywordLoc(TagLoc);
16285       TL.setQualifierLoc(QualifierLoc);
16286       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16287     }
16288 
16289     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16290                                             TSI, FriendLoc, TempParamLists);
16291     Friend->setAccess(AS_public);
16292     CurContext->addDecl(Friend);
16293     return Friend;
16294   }
16295 
16296   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16297 
16298 
16299 
16300   // Handle the case of a templated-scope friend class.  e.g.
16301   //   template <class T> class A<T>::B;
16302   // FIXME: we don't support these right now.
16303   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16304     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16305   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16306   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16307   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16308   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16309   TL.setElaboratedKeywordLoc(TagLoc);
16310   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16311   TL.setNameLoc(NameLoc);
16312 
16313   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16314                                           TSI, FriendLoc, TempParamLists);
16315   Friend->setAccess(AS_public);
16316   Friend->setUnsupportedFriend(true);
16317   CurContext->addDecl(Friend);
16318   return Friend;
16319 }
16320 
16321 /// Handle a friend type declaration.  This works in tandem with
16322 /// ActOnTag.
16323 ///
16324 /// Notes on friend class templates:
16325 ///
16326 /// We generally treat friend class declarations as if they were
16327 /// declaring a class.  So, for example, the elaborated type specifier
16328 /// in a friend declaration is required to obey the restrictions of a
16329 /// class-head (i.e. no typedefs in the scope chain), template
16330 /// parameters are required to match up with simple template-ids, &c.
16331 /// However, unlike when declaring a template specialization, it's
16332 /// okay to refer to a template specialization without an empty
16333 /// template parameter declaration, e.g.
16334 ///   friend class A<T>::B<unsigned>;
16335 /// We permit this as a special case; if there are any template
16336 /// parameters present at all, require proper matching, i.e.
16337 ///   template <> template \<class T> friend class A<int>::B;
16338 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16339                                 MultiTemplateParamsArg TempParams) {
16340   SourceLocation Loc = DS.getBeginLoc();
16341 
16342   assert(DS.isFriendSpecified());
16343   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16344 
16345   // C++ [class.friend]p3:
16346   // A friend declaration that does not declare a function shall have one of
16347   // the following forms:
16348   //     friend elaborated-type-specifier ;
16349   //     friend simple-type-specifier ;
16350   //     friend typename-specifier ;
16351   //
16352   // Any declaration with a type qualifier does not have that form. (It's
16353   // legal to specify a qualified type as a friend, you just can't write the
16354   // keywords.)
16355   if (DS.getTypeQualifiers()) {
16356     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16357       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16358     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16359       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16360     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16361       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16362     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16363       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16364     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16365       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16366   }
16367 
16368   // Try to convert the decl specifier to a type.  This works for
16369   // friend templates because ActOnTag never produces a ClassTemplateDecl
16370   // for a TUK_Friend.
16371   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16372   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16373   QualType T = TSI->getType();
16374   if (TheDeclarator.isInvalidType())
16375     return nullptr;
16376 
16377   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16378     return nullptr;
16379 
16380   // This is definitely an error in C++98.  It's probably meant to
16381   // be forbidden in C++0x, too, but the specification is just
16382   // poorly written.
16383   //
16384   // The problem is with declarations like the following:
16385   //   template <T> friend A<T>::foo;
16386   // where deciding whether a class C is a friend or not now hinges
16387   // on whether there exists an instantiation of A that causes
16388   // 'foo' to equal C.  There are restrictions on class-heads
16389   // (which we declare (by fiat) elaborated friend declarations to
16390   // be) that makes this tractable.
16391   //
16392   // FIXME: handle "template <> friend class A<T>;", which
16393   // is possibly well-formed?  Who even knows?
16394   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16395     Diag(Loc, diag::err_tagless_friend_type_template)
16396       << DS.getSourceRange();
16397     return nullptr;
16398   }
16399 
16400   // C++98 [class.friend]p1: A friend of a class is a function
16401   //   or class that is not a member of the class . . .
16402   // This is fixed in DR77, which just barely didn't make the C++03
16403   // deadline.  It's also a very silly restriction that seriously
16404   // affects inner classes and which nobody else seems to implement;
16405   // thus we never diagnose it, not even in -pedantic.
16406   //
16407   // But note that we could warn about it: it's always useless to
16408   // friend one of your own members (it's not, however, worthless to
16409   // friend a member of an arbitrary specialization of your template).
16410 
16411   Decl *D;
16412   if (!TempParams.empty())
16413     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16414                                    TempParams,
16415                                    TSI,
16416                                    DS.getFriendSpecLoc());
16417   else
16418     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16419 
16420   if (!D)
16421     return nullptr;
16422 
16423   D->setAccess(AS_public);
16424   CurContext->addDecl(D);
16425 
16426   return D;
16427 }
16428 
16429 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16430                                         MultiTemplateParamsArg TemplateParams) {
16431   const DeclSpec &DS = D.getDeclSpec();
16432 
16433   assert(DS.isFriendSpecified());
16434   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16435 
16436   SourceLocation Loc = D.getIdentifierLoc();
16437   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16438 
16439   // C++ [class.friend]p1
16440   //   A friend of a class is a function or class....
16441   // Note that this sees through typedefs, which is intended.
16442   // It *doesn't* see through dependent types, which is correct
16443   // according to [temp.arg.type]p3:
16444   //   If a declaration acquires a function type through a
16445   //   type dependent on a template-parameter and this causes
16446   //   a declaration that does not use the syntactic form of a
16447   //   function declarator to have a function type, the program
16448   //   is ill-formed.
16449   if (!TInfo->getType()->isFunctionType()) {
16450     Diag(Loc, diag::err_unexpected_friend);
16451 
16452     // It might be worthwhile to try to recover by creating an
16453     // appropriate declaration.
16454     return nullptr;
16455   }
16456 
16457   // C++ [namespace.memdef]p3
16458   //  - If a friend declaration in a non-local class first declares a
16459   //    class or function, the friend class or function is a member
16460   //    of the innermost enclosing namespace.
16461   //  - The name of the friend is not found by simple name lookup
16462   //    until a matching declaration is provided in that namespace
16463   //    scope (either before or after the class declaration granting
16464   //    friendship).
16465   //  - If a friend function is called, its name may be found by the
16466   //    name lookup that considers functions from namespaces and
16467   //    classes associated with the types of the function arguments.
16468   //  - When looking for a prior declaration of a class or a function
16469   //    declared as a friend, scopes outside the innermost enclosing
16470   //    namespace scope are not considered.
16471 
16472   CXXScopeSpec &SS = D.getCXXScopeSpec();
16473   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16474   assert(NameInfo.getName());
16475 
16476   // Check for unexpanded parameter packs.
16477   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16478       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16479       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16480     return nullptr;
16481 
16482   // The context we found the declaration in, or in which we should
16483   // create the declaration.
16484   DeclContext *DC;
16485   Scope *DCScope = S;
16486   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16487                         ForExternalRedeclaration);
16488 
16489   // There are five cases here.
16490   //   - There's no scope specifier and we're in a local class. Only look
16491   //     for functions declared in the immediately-enclosing block scope.
16492   // We recover from invalid scope qualifiers as if they just weren't there.
16493   FunctionDecl *FunctionContainingLocalClass = nullptr;
16494   if ((SS.isInvalid() || !SS.isSet()) &&
16495       (FunctionContainingLocalClass =
16496            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16497     // C++11 [class.friend]p11:
16498     //   If a friend declaration appears in a local class and the name
16499     //   specified is an unqualified name, a prior declaration is
16500     //   looked up without considering scopes that are outside the
16501     //   innermost enclosing non-class scope. For a friend function
16502     //   declaration, if there is no prior declaration, the program is
16503     //   ill-formed.
16504 
16505     // Find the innermost enclosing non-class scope. This is the block
16506     // scope containing the local class definition (or for a nested class,
16507     // the outer local class).
16508     DCScope = S->getFnParent();
16509 
16510     // Look up the function name in the scope.
16511     Previous.clear(LookupLocalFriendName);
16512     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16513 
16514     if (!Previous.empty()) {
16515       // All possible previous declarations must have the same context:
16516       // either they were declared at block scope or they are members of
16517       // one of the enclosing local classes.
16518       DC = Previous.getRepresentativeDecl()->getDeclContext();
16519     } else {
16520       // This is ill-formed, but provide the context that we would have
16521       // declared the function in, if we were permitted to, for error recovery.
16522       DC = FunctionContainingLocalClass;
16523     }
16524     adjustContextForLocalExternDecl(DC);
16525 
16526     // C++ [class.friend]p6:
16527     //   A function can be defined in a friend declaration of a class if and
16528     //   only if the class is a non-local class (9.8), the function name is
16529     //   unqualified, and the function has namespace scope.
16530     if (D.isFunctionDefinition()) {
16531       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16532     }
16533 
16534   //   - There's no scope specifier, in which case we just go to the
16535   //     appropriate scope and look for a function or function template
16536   //     there as appropriate.
16537   } else if (SS.isInvalid() || !SS.isSet()) {
16538     // C++11 [namespace.memdef]p3:
16539     //   If the name in a friend declaration is neither qualified nor
16540     //   a template-id and the declaration is a function or an
16541     //   elaborated-type-specifier, the lookup to determine whether
16542     //   the entity has been previously declared shall not consider
16543     //   any scopes outside the innermost enclosing namespace.
16544     bool isTemplateId =
16545         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16546 
16547     // Find the appropriate context according to the above.
16548     DC = CurContext;
16549 
16550     // Skip class contexts.  If someone can cite chapter and verse
16551     // for this behavior, that would be nice --- it's what GCC and
16552     // EDG do, and it seems like a reasonable intent, but the spec
16553     // really only says that checks for unqualified existing
16554     // declarations should stop at the nearest enclosing namespace,
16555     // not that they should only consider the nearest enclosing
16556     // namespace.
16557     while (DC->isRecord())
16558       DC = DC->getParent();
16559 
16560     DeclContext *LookupDC = DC;
16561     while (LookupDC->isTransparentContext())
16562       LookupDC = LookupDC->getParent();
16563 
16564     while (true) {
16565       LookupQualifiedName(Previous, LookupDC);
16566 
16567       if (!Previous.empty()) {
16568         DC = LookupDC;
16569         break;
16570       }
16571 
16572       if (isTemplateId) {
16573         if (isa<TranslationUnitDecl>(LookupDC)) break;
16574       } else {
16575         if (LookupDC->isFileContext()) break;
16576       }
16577       LookupDC = LookupDC->getParent();
16578     }
16579 
16580     DCScope = getScopeForDeclContext(S, DC);
16581 
16582   //   - There's a non-dependent scope specifier, in which case we
16583   //     compute it and do a previous lookup there for a function
16584   //     or function template.
16585   } else if (!SS.getScopeRep()->isDependent()) {
16586     DC = computeDeclContext(SS);
16587     if (!DC) return nullptr;
16588 
16589     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16590 
16591     LookupQualifiedName(Previous, DC);
16592 
16593     // C++ [class.friend]p1: A friend of a class is a function or
16594     //   class that is not a member of the class . . .
16595     if (DC->Equals(CurContext))
16596       Diag(DS.getFriendSpecLoc(),
16597            getLangOpts().CPlusPlus11 ?
16598              diag::warn_cxx98_compat_friend_is_member :
16599              diag::err_friend_is_member);
16600 
16601     if (D.isFunctionDefinition()) {
16602       // C++ [class.friend]p6:
16603       //   A function can be defined in a friend declaration of a class if and
16604       //   only if the class is a non-local class (9.8), the function name is
16605       //   unqualified, and the function has namespace scope.
16606       //
16607       // FIXME: We should only do this if the scope specifier names the
16608       // innermost enclosing namespace; otherwise the fixit changes the
16609       // meaning of the code.
16610       SemaDiagnosticBuilder DB
16611         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16612 
16613       DB << SS.getScopeRep();
16614       if (DC->isFileContext())
16615         DB << FixItHint::CreateRemoval(SS.getRange());
16616       SS.clear();
16617     }
16618 
16619   //   - There's a scope specifier that does not match any template
16620   //     parameter lists, in which case we use some arbitrary context,
16621   //     create a method or method template, and wait for instantiation.
16622   //   - There's a scope specifier that does match some template
16623   //     parameter lists, which we don't handle right now.
16624   } else {
16625     if (D.isFunctionDefinition()) {
16626       // C++ [class.friend]p6:
16627       //   A function can be defined in a friend declaration of a class if and
16628       //   only if the class is a non-local class (9.8), the function name is
16629       //   unqualified, and the function has namespace scope.
16630       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16631         << SS.getScopeRep();
16632     }
16633 
16634     DC = CurContext;
16635     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16636   }
16637 
16638   if (!DC->isRecord()) {
16639     int DiagArg = -1;
16640     switch (D.getName().getKind()) {
16641     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16642     case UnqualifiedIdKind::IK_ConstructorName:
16643       DiagArg = 0;
16644       break;
16645     case UnqualifiedIdKind::IK_DestructorName:
16646       DiagArg = 1;
16647       break;
16648     case UnqualifiedIdKind::IK_ConversionFunctionId:
16649       DiagArg = 2;
16650       break;
16651     case UnqualifiedIdKind::IK_DeductionGuideName:
16652       DiagArg = 3;
16653       break;
16654     case UnqualifiedIdKind::IK_Identifier:
16655     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16656     case UnqualifiedIdKind::IK_LiteralOperatorId:
16657     case UnqualifiedIdKind::IK_OperatorFunctionId:
16658     case UnqualifiedIdKind::IK_TemplateId:
16659       break;
16660     }
16661     // This implies that it has to be an operator or function.
16662     if (DiagArg >= 0) {
16663       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16664       return nullptr;
16665     }
16666   }
16667 
16668   // FIXME: This is an egregious hack to cope with cases where the scope stack
16669   // does not contain the declaration context, i.e., in an out-of-line
16670   // definition of a class.
16671   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16672   if (!DCScope) {
16673     FakeDCScope.setEntity(DC);
16674     DCScope = &FakeDCScope;
16675   }
16676 
16677   bool AddToScope = true;
16678   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16679                                           TemplateParams, AddToScope);
16680   if (!ND) return nullptr;
16681 
16682   assert(ND->getLexicalDeclContext() == CurContext);
16683 
16684   // If we performed typo correction, we might have added a scope specifier
16685   // and changed the decl context.
16686   DC = ND->getDeclContext();
16687 
16688   // Add the function declaration to the appropriate lookup tables,
16689   // adjusting the redeclarations list as necessary.  We don't
16690   // want to do this yet if the friending class is dependent.
16691   //
16692   // Also update the scope-based lookup if the target context's
16693   // lookup context is in lexical scope.
16694   if (!CurContext->isDependentContext()) {
16695     DC = DC->getRedeclContext();
16696     DC->makeDeclVisibleInContext(ND);
16697     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16698       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16699   }
16700 
16701   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16702                                        D.getIdentifierLoc(), ND,
16703                                        DS.getFriendSpecLoc());
16704   FrD->setAccess(AS_public);
16705   CurContext->addDecl(FrD);
16706 
16707   if (ND->isInvalidDecl()) {
16708     FrD->setInvalidDecl();
16709   } else {
16710     if (DC->isRecord()) CheckFriendAccess(ND);
16711 
16712     FunctionDecl *FD;
16713     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16714       FD = FTD->getTemplatedDecl();
16715     else
16716       FD = cast<FunctionDecl>(ND);
16717 
16718     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16719     // default argument expression, that declaration shall be a definition
16720     // and shall be the only declaration of the function or function
16721     // template in the translation unit.
16722     if (functionDeclHasDefaultArgument(FD)) {
16723       // We can't look at FD->getPreviousDecl() because it may not have been set
16724       // if we're in a dependent context. If the function is known to be a
16725       // redeclaration, we will have narrowed Previous down to the right decl.
16726       if (D.isRedeclaration()) {
16727         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16728         Diag(Previous.getRepresentativeDecl()->getLocation(),
16729              diag::note_previous_declaration);
16730       } else if (!D.isFunctionDefinition())
16731         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16732     }
16733 
16734     // Mark templated-scope function declarations as unsupported.
16735     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16736       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16737         << SS.getScopeRep() << SS.getRange()
16738         << cast<CXXRecordDecl>(CurContext);
16739       FrD->setUnsupportedFriend(true);
16740     }
16741   }
16742 
16743   return ND;
16744 }
16745 
16746 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16747   AdjustDeclIfTemplate(Dcl);
16748 
16749   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16750   if (!Fn) {
16751     Diag(DelLoc, diag::err_deleted_non_function);
16752     return;
16753   }
16754 
16755   // Deleted function does not have a body.
16756   Fn->setWillHaveBody(false);
16757 
16758   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16759     // Don't consider the implicit declaration we generate for explicit
16760     // specializations. FIXME: Do not generate these implicit declarations.
16761     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16762          Prev->getPreviousDecl()) &&
16763         !Prev->isDefined()) {
16764       Diag(DelLoc, diag::err_deleted_decl_not_first);
16765       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16766            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16767                               : diag::note_previous_declaration);
16768       // We can't recover from this; the declaration might have already
16769       // been used.
16770       Fn->setInvalidDecl();
16771       return;
16772     }
16773 
16774     // To maintain the invariant that functions are only deleted on their first
16775     // declaration, mark the implicitly-instantiated declaration of the
16776     // explicitly-specialized function as deleted instead of marking the
16777     // instantiated redeclaration.
16778     Fn = Fn->getCanonicalDecl();
16779   }
16780 
16781   // dllimport/dllexport cannot be deleted.
16782   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16783     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16784     Fn->setInvalidDecl();
16785   }
16786 
16787   // C++11 [basic.start.main]p3:
16788   //   A program that defines main as deleted [...] is ill-formed.
16789   if (Fn->isMain())
16790     Diag(DelLoc, diag::err_deleted_main);
16791 
16792   // C++11 [dcl.fct.def.delete]p4:
16793   //  A deleted function is implicitly inline.
16794   Fn->setImplicitlyInline();
16795   Fn->setDeletedAsWritten();
16796 }
16797 
16798 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16799   if (!Dcl || Dcl->isInvalidDecl())
16800     return;
16801 
16802   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16803   if (!FD) {
16804     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16805       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16806         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16807         return;
16808       }
16809     }
16810 
16811     Diag(DefaultLoc, diag::err_default_special_members)
16812         << getLangOpts().CPlusPlus20;
16813     return;
16814   }
16815 
16816   // Reject if this can't possibly be a defaultable function.
16817   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16818   if (!DefKind &&
16819       // A dependent function that doesn't locally look defaultable can
16820       // still instantiate to a defaultable function if it's a constructor
16821       // or assignment operator.
16822       (!FD->isDependentContext() ||
16823        (!isa<CXXConstructorDecl>(FD) &&
16824         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16825     Diag(DefaultLoc, diag::err_default_special_members)
16826         << getLangOpts().CPlusPlus20;
16827     return;
16828   }
16829 
16830   if (DefKind.isComparison() &&
16831       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16832     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16833         << (int)DefKind.asComparison();
16834     return;
16835   }
16836 
16837   // Issue compatibility warning. We already warned if the operator is
16838   // 'operator<=>' when parsing the '<=>' token.
16839   if (DefKind.isComparison() &&
16840       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16841     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16842                          ? diag::warn_cxx17_compat_defaulted_comparison
16843                          : diag::ext_defaulted_comparison);
16844   }
16845 
16846   FD->setDefaulted();
16847   FD->setExplicitlyDefaulted();
16848 
16849   // Defer checking functions that are defaulted in a dependent context.
16850   if (FD->isDependentContext())
16851     return;
16852 
16853   // Unset that we will have a body for this function. We might not,
16854   // if it turns out to be trivial, and we don't need this marking now
16855   // that we've marked it as defaulted.
16856   FD->setWillHaveBody(false);
16857 
16858   // If this definition appears within the record, do the checking when
16859   // the record is complete. This is always the case for a defaulted
16860   // comparison.
16861   if (DefKind.isComparison())
16862     return;
16863   auto *MD = cast<CXXMethodDecl>(FD);
16864 
16865   const FunctionDecl *Primary = FD;
16866   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16867     // Ask the template instantiation pattern that actually had the
16868     // '= default' on it.
16869     Primary = Pattern;
16870 
16871   // If the method was defaulted on its first declaration, we will have
16872   // already performed the checking in CheckCompletedCXXClass. Such a
16873   // declaration doesn't trigger an implicit definition.
16874   if (Primary->getCanonicalDecl()->isDefaulted())
16875     return;
16876 
16877   // FIXME: Once we support defining comparisons out of class, check for a
16878   // defaulted comparison here.
16879   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16880     MD->setInvalidDecl();
16881   else
16882     DefineDefaultedFunction(*this, MD, DefaultLoc);
16883 }
16884 
16885 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16886   for (Stmt *SubStmt : S->children()) {
16887     if (!SubStmt)
16888       continue;
16889     if (isa<ReturnStmt>(SubStmt))
16890       Self.Diag(SubStmt->getBeginLoc(),
16891                 diag::err_return_in_constructor_handler);
16892     if (!isa<Expr>(SubStmt))
16893       SearchForReturnInStmt(Self, SubStmt);
16894   }
16895 }
16896 
16897 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16898   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16899     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16900     SearchForReturnInStmt(*this, Handler);
16901   }
16902 }
16903 
16904 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16905                                              const CXXMethodDecl *Old) {
16906   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16907   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16908 
16909   if (OldFT->hasExtParameterInfos()) {
16910     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16911       // A parameter of the overriding method should be annotated with noescape
16912       // if the corresponding parameter of the overridden method is annotated.
16913       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16914           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16915         Diag(New->getParamDecl(I)->getLocation(),
16916              diag::warn_overriding_method_missing_noescape);
16917         Diag(Old->getParamDecl(I)->getLocation(),
16918              diag::note_overridden_marked_noescape);
16919       }
16920   }
16921 
16922   // Virtual overrides must have the same code_seg.
16923   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16924   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16925   if ((NewCSA || OldCSA) &&
16926       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16927     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16928     Diag(Old->getLocation(), diag::note_previous_declaration);
16929     return true;
16930   }
16931 
16932   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16933 
16934   // If the calling conventions match, everything is fine
16935   if (NewCC == OldCC)
16936     return false;
16937 
16938   // If the calling conventions mismatch because the new function is static,
16939   // suppress the calling convention mismatch error; the error about static
16940   // function override (err_static_overrides_virtual from
16941   // Sema::CheckFunctionDeclaration) is more clear.
16942   if (New->getStorageClass() == SC_Static)
16943     return false;
16944 
16945   Diag(New->getLocation(),
16946        diag::err_conflicting_overriding_cc_attributes)
16947     << New->getDeclName() << New->getType() << Old->getType();
16948   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16949   return true;
16950 }
16951 
16952 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16953                                              const CXXMethodDecl *Old) {
16954   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16955   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16956 
16957   if (Context.hasSameType(NewTy, OldTy) ||
16958       NewTy->isDependentType() || OldTy->isDependentType())
16959     return false;
16960 
16961   // Check if the return types are covariant
16962   QualType NewClassTy, OldClassTy;
16963 
16964   /// Both types must be pointers or references to classes.
16965   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16966     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16967       NewClassTy = NewPT->getPointeeType();
16968       OldClassTy = OldPT->getPointeeType();
16969     }
16970   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16971     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16972       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16973         NewClassTy = NewRT->getPointeeType();
16974         OldClassTy = OldRT->getPointeeType();
16975       }
16976     }
16977   }
16978 
16979   // The return types aren't either both pointers or references to a class type.
16980   if (NewClassTy.isNull()) {
16981     Diag(New->getLocation(),
16982          diag::err_different_return_type_for_overriding_virtual_function)
16983         << New->getDeclName() << NewTy << OldTy
16984         << New->getReturnTypeSourceRange();
16985     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16986         << Old->getReturnTypeSourceRange();
16987 
16988     return true;
16989   }
16990 
16991   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16992     // C++14 [class.virtual]p8:
16993     //   If the class type in the covariant return type of D::f differs from
16994     //   that of B::f, the class type in the return type of D::f shall be
16995     //   complete at the point of declaration of D::f or shall be the class
16996     //   type D.
16997     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16998       if (!RT->isBeingDefined() &&
16999           RequireCompleteType(New->getLocation(), NewClassTy,
17000                               diag::err_covariant_return_incomplete,
17001                               New->getDeclName()))
17002         return true;
17003     }
17004 
17005     // Check if the new class derives from the old class.
17006     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17007       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17008           << New->getDeclName() << NewTy << OldTy
17009           << New->getReturnTypeSourceRange();
17010       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17011           << Old->getReturnTypeSourceRange();
17012       return true;
17013     }
17014 
17015     // Check if we the conversion from derived to base is valid.
17016     if (CheckDerivedToBaseConversion(
17017             NewClassTy, OldClassTy,
17018             diag::err_covariant_return_inaccessible_base,
17019             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17020             New->getLocation(), New->getReturnTypeSourceRange(),
17021             New->getDeclName(), nullptr)) {
17022       // FIXME: this note won't trigger for delayed access control
17023       // diagnostics, and it's impossible to get an undelayed error
17024       // here from access control during the original parse because
17025       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17026       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17027           << Old->getReturnTypeSourceRange();
17028       return true;
17029     }
17030   }
17031 
17032   // The qualifiers of the return types must be the same.
17033   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17034     Diag(New->getLocation(),
17035          diag::err_covariant_return_type_different_qualifications)
17036         << New->getDeclName() << NewTy << OldTy
17037         << New->getReturnTypeSourceRange();
17038     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17039         << Old->getReturnTypeSourceRange();
17040     return true;
17041   }
17042 
17043 
17044   // The new class type must have the same or less qualifiers as the old type.
17045   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17046     Diag(New->getLocation(),
17047          diag::err_covariant_return_type_class_type_more_qualified)
17048         << New->getDeclName() << NewTy << OldTy
17049         << New->getReturnTypeSourceRange();
17050     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17051         << Old->getReturnTypeSourceRange();
17052     return true;
17053   }
17054 
17055   return false;
17056 }
17057 
17058 /// Mark the given method pure.
17059 ///
17060 /// \param Method the method to be marked pure.
17061 ///
17062 /// \param InitRange the source range that covers the "0" initializer.
17063 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17064   SourceLocation EndLoc = InitRange.getEnd();
17065   if (EndLoc.isValid())
17066     Method->setRangeEnd(EndLoc);
17067 
17068   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17069     Method->setPure();
17070     return false;
17071   }
17072 
17073   if (!Method->isInvalidDecl())
17074     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17075       << Method->getDeclName() << InitRange;
17076   return true;
17077 }
17078 
17079 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17080   if (D->getFriendObjectKind())
17081     Diag(D->getLocation(), diag::err_pure_friend);
17082   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17083     CheckPureMethod(M, ZeroLoc);
17084   else
17085     Diag(D->getLocation(), diag::err_illegal_initializer);
17086 }
17087 
17088 /// Determine whether the given declaration is a global variable or
17089 /// static data member.
17090 static bool isNonlocalVariable(const Decl *D) {
17091   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17092     return Var->hasGlobalStorage();
17093 
17094   return false;
17095 }
17096 
17097 /// Invoked when we are about to parse an initializer for the declaration
17098 /// 'Dcl'.
17099 ///
17100 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17101 /// static data member of class X, names should be looked up in the scope of
17102 /// class X. If the declaration had a scope specifier, a scope will have
17103 /// been created and passed in for this purpose. Otherwise, S will be null.
17104 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17105   // If there is no declaration, there was an error parsing it.
17106   if (!D || D->isInvalidDecl())
17107     return;
17108 
17109   // We will always have a nested name specifier here, but this declaration
17110   // might not be out of line if the specifier names the current namespace:
17111   //   extern int n;
17112   //   int ::n = 0;
17113   if (S && D->isOutOfLine())
17114     EnterDeclaratorContext(S, D->getDeclContext());
17115 
17116   // If we are parsing the initializer for a static data member, push a
17117   // new expression evaluation context that is associated with this static
17118   // data member.
17119   if (isNonlocalVariable(D))
17120     PushExpressionEvaluationContext(
17121         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17122 }
17123 
17124 /// Invoked after we are finished parsing an initializer for the declaration D.
17125 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17126   // If there is no declaration, there was an error parsing it.
17127   if (!D || D->isInvalidDecl())
17128     return;
17129 
17130   if (isNonlocalVariable(D))
17131     PopExpressionEvaluationContext();
17132 
17133   if (S && D->isOutOfLine())
17134     ExitDeclaratorContext(S);
17135 }
17136 
17137 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17138 /// C++ if/switch/while/for statement.
17139 /// e.g: "if (int x = f()) {...}"
17140 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17141   // C++ 6.4p2:
17142   // The declarator shall not specify a function or an array.
17143   // The type-specifier-seq shall not contain typedef and shall not declare a
17144   // new class or enumeration.
17145   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17146          "Parser allowed 'typedef' as storage class of condition decl.");
17147 
17148   Decl *Dcl = ActOnDeclarator(S, D);
17149   if (!Dcl)
17150     return true;
17151 
17152   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17153     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17154       << D.getSourceRange();
17155     return true;
17156   }
17157 
17158   return Dcl;
17159 }
17160 
17161 void Sema::LoadExternalVTableUses() {
17162   if (!ExternalSource)
17163     return;
17164 
17165   SmallVector<ExternalVTableUse, 4> VTables;
17166   ExternalSource->ReadUsedVTables(VTables);
17167   SmallVector<VTableUse, 4> NewUses;
17168   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17169     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17170       = VTablesUsed.find(VTables[I].Record);
17171     // Even if a definition wasn't required before, it may be required now.
17172     if (Pos != VTablesUsed.end()) {
17173       if (!Pos->second && VTables[I].DefinitionRequired)
17174         Pos->second = true;
17175       continue;
17176     }
17177 
17178     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17179     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17180   }
17181 
17182   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17183 }
17184 
17185 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17186                           bool DefinitionRequired) {
17187   // Ignore any vtable uses in unevaluated operands or for classes that do
17188   // not have a vtable.
17189   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17190       CurContext->isDependentContext() || isUnevaluatedContext())
17191     return;
17192   // Do not mark as used if compiling for the device outside of the target
17193   // region.
17194   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17195       !isInOpenMPDeclareTargetContext() &&
17196       !isInOpenMPTargetExecutionDirective()) {
17197     if (!DefinitionRequired)
17198       MarkVirtualMembersReferenced(Loc, Class);
17199     return;
17200   }
17201 
17202   // Try to insert this class into the map.
17203   LoadExternalVTableUses();
17204   Class = Class->getCanonicalDecl();
17205   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17206     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17207   if (!Pos.second) {
17208     // If we already had an entry, check to see if we are promoting this vtable
17209     // to require a definition. If so, we need to reappend to the VTableUses
17210     // list, since we may have already processed the first entry.
17211     if (DefinitionRequired && !Pos.first->second) {
17212       Pos.first->second = true;
17213     } else {
17214       // Otherwise, we can early exit.
17215       return;
17216     }
17217   } else {
17218     // The Microsoft ABI requires that we perform the destructor body
17219     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17220     // the deleting destructor is emitted with the vtable, not with the
17221     // destructor definition as in the Itanium ABI.
17222     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17223       CXXDestructorDecl *DD = Class->getDestructor();
17224       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17225         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17226           // If this is an out-of-line declaration, marking it referenced will
17227           // not do anything. Manually call CheckDestructor to look up operator
17228           // delete().
17229           ContextRAII SavedContext(*this, DD);
17230           CheckDestructor(DD);
17231         } else {
17232           MarkFunctionReferenced(Loc, Class->getDestructor());
17233         }
17234       }
17235     }
17236   }
17237 
17238   // Local classes need to have their virtual members marked
17239   // immediately. For all other classes, we mark their virtual members
17240   // at the end of the translation unit.
17241   if (Class->isLocalClass())
17242     MarkVirtualMembersReferenced(Loc, Class);
17243   else
17244     VTableUses.push_back(std::make_pair(Class, Loc));
17245 }
17246 
17247 bool Sema::DefineUsedVTables() {
17248   LoadExternalVTableUses();
17249   if (VTableUses.empty())
17250     return false;
17251 
17252   // Note: The VTableUses vector could grow as a result of marking
17253   // the members of a class as "used", so we check the size each
17254   // time through the loop and prefer indices (which are stable) to
17255   // iterators (which are not).
17256   bool DefinedAnything = false;
17257   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17258     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17259     if (!Class)
17260       continue;
17261     TemplateSpecializationKind ClassTSK =
17262         Class->getTemplateSpecializationKind();
17263 
17264     SourceLocation Loc = VTableUses[I].second;
17265 
17266     bool DefineVTable = true;
17267 
17268     // If this class has a key function, but that key function is
17269     // defined in another translation unit, we don't need to emit the
17270     // vtable even though we're using it.
17271     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17272     if (KeyFunction && !KeyFunction->hasBody()) {
17273       // The key function is in another translation unit.
17274       DefineVTable = false;
17275       TemplateSpecializationKind TSK =
17276           KeyFunction->getTemplateSpecializationKind();
17277       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17278              TSK != TSK_ImplicitInstantiation &&
17279              "Instantiations don't have key functions");
17280       (void)TSK;
17281     } else if (!KeyFunction) {
17282       // If we have a class with no key function that is the subject
17283       // of an explicit instantiation declaration, suppress the
17284       // vtable; it will live with the explicit instantiation
17285       // definition.
17286       bool IsExplicitInstantiationDeclaration =
17287           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17288       for (auto R : Class->redecls()) {
17289         TemplateSpecializationKind TSK
17290           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17291         if (TSK == TSK_ExplicitInstantiationDeclaration)
17292           IsExplicitInstantiationDeclaration = true;
17293         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17294           IsExplicitInstantiationDeclaration = false;
17295           break;
17296         }
17297       }
17298 
17299       if (IsExplicitInstantiationDeclaration)
17300         DefineVTable = false;
17301     }
17302 
17303     // The exception specifications for all virtual members may be needed even
17304     // if we are not providing an authoritative form of the vtable in this TU.
17305     // We may choose to emit it available_externally anyway.
17306     if (!DefineVTable) {
17307       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17308       continue;
17309     }
17310 
17311     // Mark all of the virtual members of this class as referenced, so
17312     // that we can build a vtable. Then, tell the AST consumer that a
17313     // vtable for this class is required.
17314     DefinedAnything = true;
17315     MarkVirtualMembersReferenced(Loc, Class);
17316     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17317     if (VTablesUsed[Canonical])
17318       Consumer.HandleVTable(Class);
17319 
17320     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17321     // no key function or the key function is inlined. Don't warn in C++ ABIs
17322     // that lack key functions, since the user won't be able to make one.
17323     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17324         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17325       const FunctionDecl *KeyFunctionDef = nullptr;
17326       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17327                            KeyFunctionDef->isInlined())) {
17328         Diag(Class->getLocation(),
17329              ClassTSK == TSK_ExplicitInstantiationDefinition
17330                  ? diag::warn_weak_template_vtable
17331                  : diag::warn_weak_vtable)
17332             << Class;
17333       }
17334     }
17335   }
17336   VTableUses.clear();
17337 
17338   return DefinedAnything;
17339 }
17340 
17341 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17342                                                  const CXXRecordDecl *RD) {
17343   for (const auto *I : RD->methods())
17344     if (I->isVirtual() && !I->isPure())
17345       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17346 }
17347 
17348 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17349                                         const CXXRecordDecl *RD,
17350                                         bool ConstexprOnly) {
17351   // Mark all functions which will appear in RD's vtable as used.
17352   CXXFinalOverriderMap FinalOverriders;
17353   RD->getFinalOverriders(FinalOverriders);
17354   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17355                                             E = FinalOverriders.end();
17356        I != E; ++I) {
17357     for (OverridingMethods::const_iterator OI = I->second.begin(),
17358                                            OE = I->second.end();
17359          OI != OE; ++OI) {
17360       assert(OI->second.size() > 0 && "no final overrider");
17361       CXXMethodDecl *Overrider = OI->second.front().Method;
17362 
17363       // C++ [basic.def.odr]p2:
17364       //   [...] A virtual member function is used if it is not pure. [...]
17365       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17366         MarkFunctionReferenced(Loc, Overrider);
17367     }
17368   }
17369 
17370   // Only classes that have virtual bases need a VTT.
17371   if (RD->getNumVBases() == 0)
17372     return;
17373 
17374   for (const auto &I : RD->bases()) {
17375     const auto *Base =
17376         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17377     if (Base->getNumVBases() == 0)
17378       continue;
17379     MarkVirtualMembersReferenced(Loc, Base);
17380   }
17381 }
17382 
17383 /// SetIvarInitializers - This routine builds initialization ASTs for the
17384 /// Objective-C implementation whose ivars need be initialized.
17385 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17386   if (!getLangOpts().CPlusPlus)
17387     return;
17388   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17389     SmallVector<ObjCIvarDecl*, 8> ivars;
17390     CollectIvarsToConstructOrDestruct(OID, ivars);
17391     if (ivars.empty())
17392       return;
17393     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17394     for (unsigned i = 0; i < ivars.size(); i++) {
17395       FieldDecl *Field = ivars[i];
17396       if (Field->isInvalidDecl())
17397         continue;
17398 
17399       CXXCtorInitializer *Member;
17400       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17401       InitializationKind InitKind =
17402         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17403 
17404       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17405       ExprResult MemberInit =
17406         InitSeq.Perform(*this, InitEntity, InitKind, None);
17407       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17408       // Note, MemberInit could actually come back empty if no initialization
17409       // is required (e.g., because it would call a trivial default constructor)
17410       if (!MemberInit.get() || MemberInit.isInvalid())
17411         continue;
17412 
17413       Member =
17414         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17415                                          SourceLocation(),
17416                                          MemberInit.getAs<Expr>(),
17417                                          SourceLocation());
17418       AllToInit.push_back(Member);
17419 
17420       // Be sure that the destructor is accessible and is marked as referenced.
17421       if (const RecordType *RecordTy =
17422               Context.getBaseElementType(Field->getType())
17423                   ->getAs<RecordType>()) {
17424         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17425         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17426           MarkFunctionReferenced(Field->getLocation(), Destructor);
17427           CheckDestructorAccess(Field->getLocation(), Destructor,
17428                             PDiag(diag::err_access_dtor_ivar)
17429                               << Context.getBaseElementType(Field->getType()));
17430         }
17431       }
17432     }
17433     ObjCImplementation->setIvarInitializers(Context,
17434                                             AllToInit.data(), AllToInit.size());
17435   }
17436 }
17437 
17438 static
17439 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17440                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17441                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17442                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17443                            Sema &S) {
17444   if (Ctor->isInvalidDecl())
17445     return;
17446 
17447   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17448 
17449   // Target may not be determinable yet, for instance if this is a dependent
17450   // call in an uninstantiated template.
17451   if (Target) {
17452     const FunctionDecl *FNTarget = nullptr;
17453     (void)Target->hasBody(FNTarget);
17454     Target = const_cast<CXXConstructorDecl*>(
17455       cast_or_null<CXXConstructorDecl>(FNTarget));
17456   }
17457 
17458   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17459                      // Avoid dereferencing a null pointer here.
17460                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17461 
17462   if (!Current.insert(Canonical).second)
17463     return;
17464 
17465   // We know that beyond here, we aren't chaining into a cycle.
17466   if (!Target || !Target->isDelegatingConstructor() ||
17467       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17468     Valid.insert(Current.begin(), Current.end());
17469     Current.clear();
17470   // We've hit a cycle.
17471   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17472              Current.count(TCanonical)) {
17473     // If we haven't diagnosed this cycle yet, do so now.
17474     if (!Invalid.count(TCanonical)) {
17475       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17476              diag::warn_delegating_ctor_cycle)
17477         << Ctor;
17478 
17479       // Don't add a note for a function delegating directly to itself.
17480       if (TCanonical != Canonical)
17481         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17482 
17483       CXXConstructorDecl *C = Target;
17484       while (C->getCanonicalDecl() != Canonical) {
17485         const FunctionDecl *FNTarget = nullptr;
17486         (void)C->getTargetConstructor()->hasBody(FNTarget);
17487         assert(FNTarget && "Ctor cycle through bodiless function");
17488 
17489         C = const_cast<CXXConstructorDecl*>(
17490           cast<CXXConstructorDecl>(FNTarget));
17491         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17492       }
17493     }
17494 
17495     Invalid.insert(Current.begin(), Current.end());
17496     Current.clear();
17497   } else {
17498     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17499   }
17500 }
17501 
17502 
17503 void Sema::CheckDelegatingCtorCycles() {
17504   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17505 
17506   for (DelegatingCtorDeclsType::iterator
17507          I = DelegatingCtorDecls.begin(ExternalSource),
17508          E = DelegatingCtorDecls.end();
17509        I != E; ++I)
17510     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17511 
17512   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17513     (*CI)->setInvalidDecl();
17514 }
17515 
17516 namespace {
17517   /// AST visitor that finds references to the 'this' expression.
17518   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17519     Sema &S;
17520 
17521   public:
17522     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17523 
17524     bool VisitCXXThisExpr(CXXThisExpr *E) {
17525       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17526         << E->isImplicit();
17527       return false;
17528     }
17529   };
17530 }
17531 
17532 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17533   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17534   if (!TSInfo)
17535     return false;
17536 
17537   TypeLoc TL = TSInfo->getTypeLoc();
17538   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17539   if (!ProtoTL)
17540     return false;
17541 
17542   // C++11 [expr.prim.general]p3:
17543   //   [The expression this] shall not appear before the optional
17544   //   cv-qualifier-seq and it shall not appear within the declaration of a
17545   //   static member function (although its type and value category are defined
17546   //   within a static member function as they are within a non-static member
17547   //   function). [ Note: this is because declaration matching does not occur
17548   //  until the complete declarator is known. - end note ]
17549   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17550   FindCXXThisExpr Finder(*this);
17551 
17552   // If the return type came after the cv-qualifier-seq, check it now.
17553   if (Proto->hasTrailingReturn() &&
17554       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17555     return true;
17556 
17557   // Check the exception specification.
17558   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17559     return true;
17560 
17561   // Check the trailing requires clause
17562   if (Expr *E = Method->getTrailingRequiresClause())
17563     if (!Finder.TraverseStmt(E))
17564       return true;
17565 
17566   return checkThisInStaticMemberFunctionAttributes(Method);
17567 }
17568 
17569 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17570   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17571   if (!TSInfo)
17572     return false;
17573 
17574   TypeLoc TL = TSInfo->getTypeLoc();
17575   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17576   if (!ProtoTL)
17577     return false;
17578 
17579   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17580   FindCXXThisExpr Finder(*this);
17581 
17582   switch (Proto->getExceptionSpecType()) {
17583   case EST_Unparsed:
17584   case EST_Uninstantiated:
17585   case EST_Unevaluated:
17586   case EST_BasicNoexcept:
17587   case EST_NoThrow:
17588   case EST_DynamicNone:
17589   case EST_MSAny:
17590   case EST_None:
17591     break;
17592 
17593   case EST_DependentNoexcept:
17594   case EST_NoexceptFalse:
17595   case EST_NoexceptTrue:
17596     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17597       return true;
17598     LLVM_FALLTHROUGH;
17599 
17600   case EST_Dynamic:
17601     for (const auto &E : Proto->exceptions()) {
17602       if (!Finder.TraverseType(E))
17603         return true;
17604     }
17605     break;
17606   }
17607 
17608   return false;
17609 }
17610 
17611 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17612   FindCXXThisExpr Finder(*this);
17613 
17614   // Check attributes.
17615   for (const auto *A : Method->attrs()) {
17616     // FIXME: This should be emitted by tblgen.
17617     Expr *Arg = nullptr;
17618     ArrayRef<Expr *> Args;
17619     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17620       Arg = G->getArg();
17621     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17622       Arg = G->getArg();
17623     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17624       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17625     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17626       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17627     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17628       Arg = ETLF->getSuccessValue();
17629       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17630     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17631       Arg = STLF->getSuccessValue();
17632       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17633     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17634       Arg = LR->getArg();
17635     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17636       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17637     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17638       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17639     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17640       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17641     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17642       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17643     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17644       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17645 
17646     if (Arg && !Finder.TraverseStmt(Arg))
17647       return true;
17648 
17649     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17650       if (!Finder.TraverseStmt(Args[I]))
17651         return true;
17652     }
17653   }
17654 
17655   return false;
17656 }
17657 
17658 void Sema::checkExceptionSpecification(
17659     bool IsTopLevel, ExceptionSpecificationType EST,
17660     ArrayRef<ParsedType> DynamicExceptions,
17661     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17662     SmallVectorImpl<QualType> &Exceptions,
17663     FunctionProtoType::ExceptionSpecInfo &ESI) {
17664   Exceptions.clear();
17665   ESI.Type = EST;
17666   if (EST == EST_Dynamic) {
17667     Exceptions.reserve(DynamicExceptions.size());
17668     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17669       // FIXME: Preserve type source info.
17670       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17671 
17672       if (IsTopLevel) {
17673         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17674         collectUnexpandedParameterPacks(ET, Unexpanded);
17675         if (!Unexpanded.empty()) {
17676           DiagnoseUnexpandedParameterPacks(
17677               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17678               Unexpanded);
17679           continue;
17680         }
17681       }
17682 
17683       // Check that the type is valid for an exception spec, and
17684       // drop it if not.
17685       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17686         Exceptions.push_back(ET);
17687     }
17688     ESI.Exceptions = Exceptions;
17689     return;
17690   }
17691 
17692   if (isComputedNoexcept(EST)) {
17693     assert((NoexceptExpr->isTypeDependent() ||
17694             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17695             Context.BoolTy) &&
17696            "Parser should have made sure that the expression is boolean");
17697     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17698       ESI.Type = EST_BasicNoexcept;
17699       return;
17700     }
17701 
17702     ESI.NoexceptExpr = NoexceptExpr;
17703     return;
17704   }
17705 }
17706 
17707 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17708              ExceptionSpecificationType EST,
17709              SourceRange SpecificationRange,
17710              ArrayRef<ParsedType> DynamicExceptions,
17711              ArrayRef<SourceRange> DynamicExceptionRanges,
17712              Expr *NoexceptExpr) {
17713   if (!MethodD)
17714     return;
17715 
17716   // Dig out the method we're referring to.
17717   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17718     MethodD = FunTmpl->getTemplatedDecl();
17719 
17720   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17721   if (!Method)
17722     return;
17723 
17724   // Check the exception specification.
17725   llvm::SmallVector<QualType, 4> Exceptions;
17726   FunctionProtoType::ExceptionSpecInfo ESI;
17727   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17728                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17729                               ESI);
17730 
17731   // Update the exception specification on the function type.
17732   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17733 
17734   if (Method->isStatic())
17735     checkThisInStaticMemberFunctionExceptionSpec(Method);
17736 
17737   if (Method->isVirtual()) {
17738     // Check overrides, which we previously had to delay.
17739     for (const CXXMethodDecl *O : Method->overridden_methods())
17740       CheckOverridingFunctionExceptionSpec(Method, O);
17741   }
17742 }
17743 
17744 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17745 ///
17746 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17747                                        SourceLocation DeclStart, Declarator &D,
17748                                        Expr *BitWidth,
17749                                        InClassInitStyle InitStyle,
17750                                        AccessSpecifier AS,
17751                                        const ParsedAttr &MSPropertyAttr) {
17752   IdentifierInfo *II = D.getIdentifier();
17753   if (!II) {
17754     Diag(DeclStart, diag::err_anonymous_property);
17755     return nullptr;
17756   }
17757   SourceLocation Loc = D.getIdentifierLoc();
17758 
17759   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17760   QualType T = TInfo->getType();
17761   if (getLangOpts().CPlusPlus) {
17762     CheckExtraCXXDefaultArguments(D);
17763 
17764     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17765                                         UPPC_DataMemberType)) {
17766       D.setInvalidType();
17767       T = Context.IntTy;
17768       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17769     }
17770   }
17771 
17772   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17773 
17774   if (D.getDeclSpec().isInlineSpecified())
17775     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17776         << getLangOpts().CPlusPlus17;
17777   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17778     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17779          diag::err_invalid_thread)
17780       << DeclSpec::getSpecifierName(TSCS);
17781 
17782   // Check to see if this name was declared as a member previously
17783   NamedDecl *PrevDecl = nullptr;
17784   LookupResult Previous(*this, II, Loc, LookupMemberName,
17785                         ForVisibleRedeclaration);
17786   LookupName(Previous, S);
17787   switch (Previous.getResultKind()) {
17788   case LookupResult::Found:
17789   case LookupResult::FoundUnresolvedValue:
17790     PrevDecl = Previous.getAsSingle<NamedDecl>();
17791     break;
17792 
17793   case LookupResult::FoundOverloaded:
17794     PrevDecl = Previous.getRepresentativeDecl();
17795     break;
17796 
17797   case LookupResult::NotFound:
17798   case LookupResult::NotFoundInCurrentInstantiation:
17799   case LookupResult::Ambiguous:
17800     break;
17801   }
17802 
17803   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17804     // Maybe we will complain about the shadowed template parameter.
17805     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17806     // Just pretend that we didn't see the previous declaration.
17807     PrevDecl = nullptr;
17808   }
17809 
17810   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17811     PrevDecl = nullptr;
17812 
17813   SourceLocation TSSL = D.getBeginLoc();
17814   MSPropertyDecl *NewPD =
17815       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17816                              MSPropertyAttr.getPropertyDataGetter(),
17817                              MSPropertyAttr.getPropertyDataSetter());
17818   ProcessDeclAttributes(TUScope, NewPD, D);
17819   NewPD->setAccess(AS);
17820 
17821   if (NewPD->isInvalidDecl())
17822     Record->setInvalidDecl();
17823 
17824   if (D.getDeclSpec().isModulePrivateSpecified())
17825     NewPD->setModulePrivate();
17826 
17827   if (NewPD->isInvalidDecl() && PrevDecl) {
17828     // Don't introduce NewFD into scope; there's already something
17829     // with the same name in the same scope.
17830   } else if (II) {
17831     PushOnScopeChains(NewPD, S);
17832   } else
17833     Record->addDecl(NewPD);
17834 
17835   return NewPD;
17836 }
17837 
17838 void Sema::ActOnStartFunctionDeclarationDeclarator(
17839     Declarator &Declarator, unsigned TemplateParameterDepth) {
17840   auto &Info = InventedParameterInfos.emplace_back();
17841   TemplateParameterList *ExplicitParams = nullptr;
17842   ArrayRef<TemplateParameterList *> ExplicitLists =
17843       Declarator.getTemplateParameterLists();
17844   if (!ExplicitLists.empty()) {
17845     bool IsMemberSpecialization, IsInvalid;
17846     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17847         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17848         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17849         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17850         /*SuppressDiagnostic=*/true);
17851   }
17852   if (ExplicitParams) {
17853     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17854     for (NamedDecl *Param : *ExplicitParams)
17855       Info.TemplateParams.push_back(Param);
17856     Info.NumExplicitTemplateParams = ExplicitParams->size();
17857   } else {
17858     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17859     Info.NumExplicitTemplateParams = 0;
17860   }
17861 }
17862 
17863 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17864   auto &FSI = InventedParameterInfos.back();
17865   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17866     if (FSI.NumExplicitTemplateParams != 0) {
17867       TemplateParameterList *ExplicitParams =
17868           Declarator.getTemplateParameterLists().back();
17869       Declarator.setInventedTemplateParameterList(
17870           TemplateParameterList::Create(
17871               Context, ExplicitParams->getTemplateLoc(),
17872               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17873               ExplicitParams->getRAngleLoc(),
17874               ExplicitParams->getRequiresClause()));
17875     } else {
17876       Declarator.setInventedTemplateParameterList(
17877           TemplateParameterList::Create(
17878               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17879               SourceLocation(), /*RequiresClause=*/nullptr));
17880     }
17881   }
17882   InventedParameterInfos.pop_back();
17883 }
17884