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   for (auto *D : ClassDecl->lookup(MemberOrBase))
4134     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4135       return cast<ValueDecl>(D);
4136   return nullptr;
4137 }
4138 
4139 /// Handle a C++ member initializer.
4140 MemInitResult
4141 Sema::BuildMemInitializer(Decl *ConstructorD,
4142                           Scope *S,
4143                           CXXScopeSpec &SS,
4144                           IdentifierInfo *MemberOrBase,
4145                           ParsedType TemplateTypeTy,
4146                           const DeclSpec &DS,
4147                           SourceLocation IdLoc,
4148                           Expr *Init,
4149                           SourceLocation EllipsisLoc) {
4150   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4151   if (!Res.isUsable())
4152     return true;
4153   Init = Res.get();
4154 
4155   if (!ConstructorD)
4156     return true;
4157 
4158   AdjustDeclIfTemplate(ConstructorD);
4159 
4160   CXXConstructorDecl *Constructor
4161     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4162   if (!Constructor) {
4163     // The user wrote a constructor initializer on a function that is
4164     // not a C++ constructor. Ignore the error for now, because we may
4165     // have more member initializers coming; we'll diagnose it just
4166     // once in ActOnMemInitializers.
4167     return true;
4168   }
4169 
4170   CXXRecordDecl *ClassDecl = Constructor->getParent();
4171 
4172   // C++ [class.base.init]p2:
4173   //   Names in a mem-initializer-id are looked up in the scope of the
4174   //   constructor's class and, if not found in that scope, are looked
4175   //   up in the scope containing the constructor's definition.
4176   //   [Note: if the constructor's class contains a member with the
4177   //   same name as a direct or virtual base class of the class, a
4178   //   mem-initializer-id naming the member or base class and composed
4179   //   of a single identifier refers to the class member. A
4180   //   mem-initializer-id for the hidden base class may be specified
4181   //   using a qualified name. ]
4182 
4183   // Look for a member, first.
4184   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4185           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4186     if (EllipsisLoc.isValid())
4187       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4188           << MemberOrBase
4189           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4190 
4191     return BuildMemberInitializer(Member, Init, IdLoc);
4192   }
4193   // It didn't name a member, so see if it names a class.
4194   QualType BaseType;
4195   TypeSourceInfo *TInfo = nullptr;
4196 
4197   if (TemplateTypeTy) {
4198     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4199     if (BaseType.isNull())
4200       return true;
4201   } else if (DS.getTypeSpecType() == TST_decltype) {
4202     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4203   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4204     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4205     return true;
4206   } else {
4207     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4208     LookupParsedName(R, S, &SS);
4209 
4210     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4211     if (!TyD) {
4212       if (R.isAmbiguous()) return true;
4213 
4214       // We don't want access-control diagnostics here.
4215       R.suppressDiagnostics();
4216 
4217       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4218         bool NotUnknownSpecialization = false;
4219         DeclContext *DC = computeDeclContext(SS, false);
4220         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4221           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4222 
4223         if (!NotUnknownSpecialization) {
4224           // When the scope specifier can refer to a member of an unknown
4225           // specialization, we take it as a type name.
4226           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4227                                        SS.getWithLocInContext(Context),
4228                                        *MemberOrBase, IdLoc);
4229           if (BaseType.isNull())
4230             return true;
4231 
4232           TInfo = Context.CreateTypeSourceInfo(BaseType);
4233           DependentNameTypeLoc TL =
4234               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4235           if (!TL.isNull()) {
4236             TL.setNameLoc(IdLoc);
4237             TL.setElaboratedKeywordLoc(SourceLocation());
4238             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4239           }
4240 
4241           R.clear();
4242           R.setLookupName(MemberOrBase);
4243         }
4244       }
4245 
4246       // If no results were found, try to correct typos.
4247       TypoCorrection Corr;
4248       MemInitializerValidatorCCC CCC(ClassDecl);
4249       if (R.empty() && BaseType.isNull() &&
4250           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4251                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4252         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4253           // We have found a non-static data member with a similar
4254           // name to what was typed; complain and initialize that
4255           // member.
4256           diagnoseTypo(Corr,
4257                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4258                          << MemberOrBase << true);
4259           return BuildMemberInitializer(Member, Init, IdLoc);
4260         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4261           const CXXBaseSpecifier *DirectBaseSpec;
4262           const CXXBaseSpecifier *VirtualBaseSpec;
4263           if (FindBaseInitializer(*this, ClassDecl,
4264                                   Context.getTypeDeclType(Type),
4265                                   DirectBaseSpec, VirtualBaseSpec)) {
4266             // We have found a direct or virtual base class with a
4267             // similar name to what was typed; complain and initialize
4268             // that base class.
4269             diagnoseTypo(Corr,
4270                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4271                            << MemberOrBase << false,
4272                          PDiag() /*Suppress note, we provide our own.*/);
4273 
4274             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4275                                                               : VirtualBaseSpec;
4276             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4277                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4278 
4279             TyD = Type;
4280           }
4281         }
4282       }
4283 
4284       if (!TyD && BaseType.isNull()) {
4285         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4286           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4287         return true;
4288       }
4289     }
4290 
4291     if (BaseType.isNull()) {
4292       BaseType = Context.getTypeDeclType(TyD);
4293       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4294       if (SS.isSet()) {
4295         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4296                                              BaseType);
4297         TInfo = Context.CreateTypeSourceInfo(BaseType);
4298         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4299         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4300         TL.setElaboratedKeywordLoc(SourceLocation());
4301         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4302       }
4303     }
4304   }
4305 
4306   if (!TInfo)
4307     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4308 
4309   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4310 }
4311 
4312 MemInitResult
4313 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4314                              SourceLocation IdLoc) {
4315   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4316   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4317   assert((DirectMember || IndirectMember) &&
4318          "Member must be a FieldDecl or IndirectFieldDecl");
4319 
4320   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4321     return true;
4322 
4323   if (Member->isInvalidDecl())
4324     return true;
4325 
4326   MultiExprArg Args;
4327   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4328     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4329   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4330     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4331   } else {
4332     // Template instantiation doesn't reconstruct ParenListExprs for us.
4333     Args = Init;
4334   }
4335 
4336   SourceRange InitRange = Init->getSourceRange();
4337 
4338   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4339     // Can't check initialization for a member of dependent type or when
4340     // any of the arguments are type-dependent expressions.
4341     DiscardCleanupsInEvaluationContext();
4342   } else {
4343     bool InitList = false;
4344     if (isa<InitListExpr>(Init)) {
4345       InitList = true;
4346       Args = Init;
4347     }
4348 
4349     // Initialize the member.
4350     InitializedEntity MemberEntity =
4351       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4352                    : InitializedEntity::InitializeMember(IndirectMember,
4353                                                          nullptr);
4354     InitializationKind Kind =
4355         InitList ? InitializationKind::CreateDirectList(
4356                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4357                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4358                                                     InitRange.getEnd());
4359 
4360     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4361     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4362                                             nullptr);
4363     if (MemberInit.isInvalid())
4364       return true;
4365 
4366     // C++11 [class.base.init]p7:
4367     //   The initialization of each base and member constitutes a
4368     //   full-expression.
4369     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4370                                      /*DiscardedValue*/ false);
4371     if (MemberInit.isInvalid())
4372       return true;
4373 
4374     Init = MemberInit.get();
4375   }
4376 
4377   if (DirectMember) {
4378     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4379                                             InitRange.getBegin(), Init,
4380                                             InitRange.getEnd());
4381   } else {
4382     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4383                                             InitRange.getBegin(), Init,
4384                                             InitRange.getEnd());
4385   }
4386 }
4387 
4388 MemInitResult
4389 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4390                                  CXXRecordDecl *ClassDecl) {
4391   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4392   if (!LangOpts.CPlusPlus11)
4393     return Diag(NameLoc, diag::err_delegating_ctor)
4394       << TInfo->getTypeLoc().getLocalSourceRange();
4395   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4396 
4397   bool InitList = true;
4398   MultiExprArg Args = Init;
4399   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4400     InitList = false;
4401     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4402   }
4403 
4404   SourceRange InitRange = Init->getSourceRange();
4405   // Initialize the object.
4406   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4407                                      QualType(ClassDecl->getTypeForDecl(), 0));
4408   InitializationKind Kind =
4409       InitList ? InitializationKind::CreateDirectList(
4410                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4411                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4412                                                   InitRange.getEnd());
4413   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4414   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4415                                               Args, nullptr);
4416   if (DelegationInit.isInvalid())
4417     return true;
4418 
4419   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4420          "Delegating constructor with no target?");
4421 
4422   // C++11 [class.base.init]p7:
4423   //   The initialization of each base and member constitutes a
4424   //   full-expression.
4425   DelegationInit = ActOnFinishFullExpr(
4426       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4427   if (DelegationInit.isInvalid())
4428     return true;
4429 
4430   // If we are in a dependent context, template instantiation will
4431   // perform this type-checking again. Just save the arguments that we
4432   // received in a ParenListExpr.
4433   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4434   // of the information that we have about the base
4435   // initializer. However, deconstructing the ASTs is a dicey process,
4436   // and this approach is far more likely to get the corner cases right.
4437   if (CurContext->isDependentContext())
4438     DelegationInit = Init;
4439 
4440   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4441                                           DelegationInit.getAs<Expr>(),
4442                                           InitRange.getEnd());
4443 }
4444 
4445 MemInitResult
4446 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4447                            Expr *Init, CXXRecordDecl *ClassDecl,
4448                            SourceLocation EllipsisLoc) {
4449   SourceLocation BaseLoc
4450     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4451 
4452   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4453     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4454              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4455 
4456   // C++ [class.base.init]p2:
4457   //   [...] Unless the mem-initializer-id names a nonstatic data
4458   //   member of the constructor's class or a direct or virtual base
4459   //   of that class, the mem-initializer is ill-formed. A
4460   //   mem-initializer-list can initialize a base class using any
4461   //   name that denotes that base class type.
4462   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4463 
4464   SourceRange InitRange = Init->getSourceRange();
4465   if (EllipsisLoc.isValid()) {
4466     // This is a pack expansion.
4467     if (!BaseType->containsUnexpandedParameterPack())  {
4468       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4469         << SourceRange(BaseLoc, InitRange.getEnd());
4470 
4471       EllipsisLoc = SourceLocation();
4472     }
4473   } else {
4474     // Check for any unexpanded parameter packs.
4475     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4476       return true;
4477 
4478     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4479       return true;
4480   }
4481 
4482   // Check for direct and virtual base classes.
4483   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4484   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4485   if (!Dependent) {
4486     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4487                                        BaseType))
4488       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4489 
4490     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4491                         VirtualBaseSpec);
4492 
4493     // C++ [base.class.init]p2:
4494     // Unless the mem-initializer-id names a nonstatic data member of the
4495     // constructor's class or a direct or virtual base of that class, the
4496     // mem-initializer is ill-formed.
4497     if (!DirectBaseSpec && !VirtualBaseSpec) {
4498       // If the class has any dependent bases, then it's possible that
4499       // one of those types will resolve to the same type as
4500       // BaseType. Therefore, just treat this as a dependent base
4501       // class initialization.  FIXME: Should we try to check the
4502       // initialization anyway? It seems odd.
4503       if (ClassDecl->hasAnyDependentBases())
4504         Dependent = true;
4505       else
4506         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4507           << BaseType << Context.getTypeDeclType(ClassDecl)
4508           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4509     }
4510   }
4511 
4512   if (Dependent) {
4513     DiscardCleanupsInEvaluationContext();
4514 
4515     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4516                                             /*IsVirtual=*/false,
4517                                             InitRange.getBegin(), Init,
4518                                             InitRange.getEnd(), EllipsisLoc);
4519   }
4520 
4521   // C++ [base.class.init]p2:
4522   //   If a mem-initializer-id is ambiguous because it designates both
4523   //   a direct non-virtual base class and an inherited virtual base
4524   //   class, the mem-initializer is ill-formed.
4525   if (DirectBaseSpec && VirtualBaseSpec)
4526     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4527       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4528 
4529   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4530   if (!BaseSpec)
4531     BaseSpec = VirtualBaseSpec;
4532 
4533   // Initialize the base.
4534   bool InitList = true;
4535   MultiExprArg Args = Init;
4536   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4537     InitList = false;
4538     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4539   }
4540 
4541   InitializedEntity BaseEntity =
4542     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4543   InitializationKind Kind =
4544       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4545                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4546                                                   InitRange.getEnd());
4547   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4548   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4549   if (BaseInit.isInvalid())
4550     return true;
4551 
4552   // C++11 [class.base.init]p7:
4553   //   The initialization of each base and member constitutes a
4554   //   full-expression.
4555   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4556                                  /*DiscardedValue*/ false);
4557   if (BaseInit.isInvalid())
4558     return true;
4559 
4560   // If we are in a dependent context, template instantiation will
4561   // perform this type-checking again. Just save the arguments that we
4562   // received in a ParenListExpr.
4563   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4564   // of the information that we have about the base
4565   // initializer. However, deconstructing the ASTs is a dicey process,
4566   // and this approach is far more likely to get the corner cases right.
4567   if (CurContext->isDependentContext())
4568     BaseInit = Init;
4569 
4570   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4571                                           BaseSpec->isVirtual(),
4572                                           InitRange.getBegin(),
4573                                           BaseInit.getAs<Expr>(),
4574                                           InitRange.getEnd(), EllipsisLoc);
4575 }
4576 
4577 // Create a static_cast\<T&&>(expr).
4578 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4579   if (T.isNull()) T = E->getType();
4580   QualType TargetType = SemaRef.BuildReferenceType(
4581       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4582   SourceLocation ExprLoc = E->getBeginLoc();
4583   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4584       TargetType, ExprLoc);
4585 
4586   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4587                                    SourceRange(ExprLoc, ExprLoc),
4588                                    E->getSourceRange()).get();
4589 }
4590 
4591 /// ImplicitInitializerKind - How an implicit base or member initializer should
4592 /// initialize its base or member.
4593 enum ImplicitInitializerKind {
4594   IIK_Default,
4595   IIK_Copy,
4596   IIK_Move,
4597   IIK_Inherit
4598 };
4599 
4600 static bool
4601 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4602                              ImplicitInitializerKind ImplicitInitKind,
4603                              CXXBaseSpecifier *BaseSpec,
4604                              bool IsInheritedVirtualBase,
4605                              CXXCtorInitializer *&CXXBaseInit) {
4606   InitializedEntity InitEntity
4607     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4608                                         IsInheritedVirtualBase);
4609 
4610   ExprResult BaseInit;
4611 
4612   switch (ImplicitInitKind) {
4613   case IIK_Inherit:
4614   case IIK_Default: {
4615     InitializationKind InitKind
4616       = InitializationKind::CreateDefault(Constructor->getLocation());
4617     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4618     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4619     break;
4620   }
4621 
4622   case IIK_Move:
4623   case IIK_Copy: {
4624     bool Moving = ImplicitInitKind == IIK_Move;
4625     ParmVarDecl *Param = Constructor->getParamDecl(0);
4626     QualType ParamType = Param->getType().getNonReferenceType();
4627 
4628     Expr *CopyCtorArg =
4629       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4630                           SourceLocation(), Param, false,
4631                           Constructor->getLocation(), ParamType,
4632                           VK_LValue, nullptr);
4633 
4634     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4635 
4636     // Cast to the base class to avoid ambiguities.
4637     QualType ArgTy =
4638       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4639                                        ParamType.getQualifiers());
4640 
4641     if (Moving) {
4642       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4643     }
4644 
4645     CXXCastPath BasePath;
4646     BasePath.push_back(BaseSpec);
4647     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4648                                             CK_UncheckedDerivedToBase,
4649                                             Moving ? VK_XValue : VK_LValue,
4650                                             &BasePath).get();
4651 
4652     InitializationKind InitKind
4653       = InitializationKind::CreateDirect(Constructor->getLocation(),
4654                                          SourceLocation(), SourceLocation());
4655     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4656     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4657     break;
4658   }
4659   }
4660 
4661   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4662   if (BaseInit.isInvalid())
4663     return true;
4664 
4665   CXXBaseInit =
4666     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4667                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4668                                                         SourceLocation()),
4669                                              BaseSpec->isVirtual(),
4670                                              SourceLocation(),
4671                                              BaseInit.getAs<Expr>(),
4672                                              SourceLocation(),
4673                                              SourceLocation());
4674 
4675   return false;
4676 }
4677 
4678 static bool RefersToRValueRef(Expr *MemRef) {
4679   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4680   return Referenced->getType()->isRValueReferenceType();
4681 }
4682 
4683 static bool
4684 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4685                                ImplicitInitializerKind ImplicitInitKind,
4686                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4687                                CXXCtorInitializer *&CXXMemberInit) {
4688   if (Field->isInvalidDecl())
4689     return true;
4690 
4691   SourceLocation Loc = Constructor->getLocation();
4692 
4693   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4694     bool Moving = ImplicitInitKind == IIK_Move;
4695     ParmVarDecl *Param = Constructor->getParamDecl(0);
4696     QualType ParamType = Param->getType().getNonReferenceType();
4697 
4698     // Suppress copying zero-width bitfields.
4699     if (Field->isZeroLengthBitField(SemaRef.Context))
4700       return false;
4701 
4702     Expr *MemberExprBase =
4703       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4704                           SourceLocation(), Param, false,
4705                           Loc, ParamType, VK_LValue, nullptr);
4706 
4707     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4708 
4709     if (Moving) {
4710       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4711     }
4712 
4713     // Build a reference to this field within the parameter.
4714     CXXScopeSpec SS;
4715     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4716                               Sema::LookupMemberName);
4717     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4718                                   : cast<ValueDecl>(Field), AS_public);
4719     MemberLookup.resolveKind();
4720     ExprResult CtorArg
4721       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4722                                          ParamType, Loc,
4723                                          /*IsArrow=*/false,
4724                                          SS,
4725                                          /*TemplateKWLoc=*/SourceLocation(),
4726                                          /*FirstQualifierInScope=*/nullptr,
4727                                          MemberLookup,
4728                                          /*TemplateArgs=*/nullptr,
4729                                          /*S*/nullptr);
4730     if (CtorArg.isInvalid())
4731       return true;
4732 
4733     // C++11 [class.copy]p15:
4734     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4735     //     with static_cast<T&&>(x.m);
4736     if (RefersToRValueRef(CtorArg.get())) {
4737       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4738     }
4739 
4740     InitializedEntity Entity =
4741         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4742                                                        /*Implicit*/ true)
4743                  : InitializedEntity::InitializeMember(Field, nullptr,
4744                                                        /*Implicit*/ true);
4745 
4746     // Direct-initialize to use the copy constructor.
4747     InitializationKind InitKind =
4748       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4749 
4750     Expr *CtorArgE = CtorArg.getAs<Expr>();
4751     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4752     ExprResult MemberInit =
4753         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4754     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4755     if (MemberInit.isInvalid())
4756       return true;
4757 
4758     if (Indirect)
4759       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4760           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4761     else
4762       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4763           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4764     return false;
4765   }
4766 
4767   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4768          "Unhandled implicit init kind!");
4769 
4770   QualType FieldBaseElementType =
4771     SemaRef.Context.getBaseElementType(Field->getType());
4772 
4773   if (FieldBaseElementType->isRecordType()) {
4774     InitializedEntity InitEntity =
4775         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4776                                                        /*Implicit*/ true)
4777                  : InitializedEntity::InitializeMember(Field, nullptr,
4778                                                        /*Implicit*/ true);
4779     InitializationKind InitKind =
4780       InitializationKind::CreateDefault(Loc);
4781 
4782     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4783     ExprResult MemberInit =
4784       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4785 
4786     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4787     if (MemberInit.isInvalid())
4788       return true;
4789 
4790     if (Indirect)
4791       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4792                                                                Indirect, Loc,
4793                                                                Loc,
4794                                                                MemberInit.get(),
4795                                                                Loc);
4796     else
4797       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4798                                                                Field, Loc, Loc,
4799                                                                MemberInit.get(),
4800                                                                Loc);
4801     return false;
4802   }
4803 
4804   if (!Field->getParent()->isUnion()) {
4805     if (FieldBaseElementType->isReferenceType()) {
4806       SemaRef.Diag(Constructor->getLocation(),
4807                    diag::err_uninitialized_member_in_ctor)
4808       << (int)Constructor->isImplicit()
4809       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4810       << 0 << Field->getDeclName();
4811       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4812       return true;
4813     }
4814 
4815     if (FieldBaseElementType.isConstQualified()) {
4816       SemaRef.Diag(Constructor->getLocation(),
4817                    diag::err_uninitialized_member_in_ctor)
4818       << (int)Constructor->isImplicit()
4819       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4820       << 1 << Field->getDeclName();
4821       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4822       return true;
4823     }
4824   }
4825 
4826   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4827     // ARC and Weak:
4828     //   Default-initialize Objective-C pointers to NULL.
4829     CXXMemberInit
4830       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4831                                                  Loc, Loc,
4832                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4833                                                  Loc);
4834     return false;
4835   }
4836 
4837   // Nothing to initialize.
4838   CXXMemberInit = nullptr;
4839   return false;
4840 }
4841 
4842 namespace {
4843 struct BaseAndFieldInfo {
4844   Sema &S;
4845   CXXConstructorDecl *Ctor;
4846   bool AnyErrorsInInits;
4847   ImplicitInitializerKind IIK;
4848   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4849   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4850   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4851 
4852   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4853     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4854     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4855     if (Ctor->getInheritedConstructor())
4856       IIK = IIK_Inherit;
4857     else if (Generated && Ctor->isCopyConstructor())
4858       IIK = IIK_Copy;
4859     else if (Generated && Ctor->isMoveConstructor())
4860       IIK = IIK_Move;
4861     else
4862       IIK = IIK_Default;
4863   }
4864 
4865   bool isImplicitCopyOrMove() const {
4866     switch (IIK) {
4867     case IIK_Copy:
4868     case IIK_Move:
4869       return true;
4870 
4871     case IIK_Default:
4872     case IIK_Inherit:
4873       return false;
4874     }
4875 
4876     llvm_unreachable("Invalid ImplicitInitializerKind!");
4877   }
4878 
4879   bool addFieldInitializer(CXXCtorInitializer *Init) {
4880     AllToInit.push_back(Init);
4881 
4882     // Check whether this initializer makes the field "used".
4883     if (Init->getInit()->HasSideEffects(S.Context))
4884       S.UnusedPrivateFields.remove(Init->getAnyMember());
4885 
4886     return false;
4887   }
4888 
4889   bool isInactiveUnionMember(FieldDecl *Field) {
4890     RecordDecl *Record = Field->getParent();
4891     if (!Record->isUnion())
4892       return false;
4893 
4894     if (FieldDecl *Active =
4895             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4896       return Active != Field->getCanonicalDecl();
4897 
4898     // In an implicit copy or move constructor, ignore any in-class initializer.
4899     if (isImplicitCopyOrMove())
4900       return true;
4901 
4902     // If there's no explicit initialization, the field is active only if it
4903     // has an in-class initializer...
4904     if (Field->hasInClassInitializer())
4905       return false;
4906     // ... or it's an anonymous struct or union whose class has an in-class
4907     // initializer.
4908     if (!Field->isAnonymousStructOrUnion())
4909       return true;
4910     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4911     return !FieldRD->hasInClassInitializer();
4912   }
4913 
4914   /// Determine whether the given field is, or is within, a union member
4915   /// that is inactive (because there was an initializer given for a different
4916   /// member of the union, or because the union was not initialized at all).
4917   bool isWithinInactiveUnionMember(FieldDecl *Field,
4918                                    IndirectFieldDecl *Indirect) {
4919     if (!Indirect)
4920       return isInactiveUnionMember(Field);
4921 
4922     for (auto *C : Indirect->chain()) {
4923       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4924       if (Field && isInactiveUnionMember(Field))
4925         return true;
4926     }
4927     return false;
4928   }
4929 };
4930 }
4931 
4932 /// Determine whether the given type is an incomplete or zero-lenfgth
4933 /// array type.
4934 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4935   if (T->isIncompleteArrayType())
4936     return true;
4937 
4938   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4939     if (!ArrayT->getSize())
4940       return true;
4941 
4942     T = ArrayT->getElementType();
4943   }
4944 
4945   return false;
4946 }
4947 
4948 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4949                                     FieldDecl *Field,
4950                                     IndirectFieldDecl *Indirect = nullptr) {
4951   if (Field->isInvalidDecl())
4952     return false;
4953 
4954   // Overwhelmingly common case: we have a direct initializer for this field.
4955   if (CXXCtorInitializer *Init =
4956           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4957     return Info.addFieldInitializer(Init);
4958 
4959   // C++11 [class.base.init]p8:
4960   //   if the entity is a non-static data member that has a
4961   //   brace-or-equal-initializer and either
4962   //   -- the constructor's class is a union and no other variant member of that
4963   //      union is designated by a mem-initializer-id or
4964   //   -- the constructor's class is not a union, and, if the entity is a member
4965   //      of an anonymous union, no other member of that union is designated by
4966   //      a mem-initializer-id,
4967   //   the entity is initialized as specified in [dcl.init].
4968   //
4969   // We also apply the same rules to handle anonymous structs within anonymous
4970   // unions.
4971   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4972     return false;
4973 
4974   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4975     ExprResult DIE =
4976         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4977     if (DIE.isInvalid())
4978       return true;
4979 
4980     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4981     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4982 
4983     CXXCtorInitializer *Init;
4984     if (Indirect)
4985       Init = new (SemaRef.Context)
4986           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4987                              SourceLocation(), DIE.get(), SourceLocation());
4988     else
4989       Init = new (SemaRef.Context)
4990           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4991                              SourceLocation(), DIE.get(), SourceLocation());
4992     return Info.addFieldInitializer(Init);
4993   }
4994 
4995   // Don't initialize incomplete or zero-length arrays.
4996   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4997     return false;
4998 
4999   // Don't try to build an implicit initializer if there were semantic
5000   // errors in any of the initializers (and therefore we might be
5001   // missing some that the user actually wrote).
5002   if (Info.AnyErrorsInInits)
5003     return false;
5004 
5005   CXXCtorInitializer *Init = nullptr;
5006   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5007                                      Indirect, Init))
5008     return true;
5009 
5010   if (!Init)
5011     return false;
5012 
5013   return Info.addFieldInitializer(Init);
5014 }
5015 
5016 bool
5017 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5018                                CXXCtorInitializer *Initializer) {
5019   assert(Initializer->isDelegatingInitializer());
5020   Constructor->setNumCtorInitializers(1);
5021   CXXCtorInitializer **initializer =
5022     new (Context) CXXCtorInitializer*[1];
5023   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5024   Constructor->setCtorInitializers(initializer);
5025 
5026   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5027     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5028     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5029   }
5030 
5031   DelegatingCtorDecls.push_back(Constructor);
5032 
5033   DiagnoseUninitializedFields(*this, Constructor);
5034 
5035   return false;
5036 }
5037 
5038 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5039                                ArrayRef<CXXCtorInitializer *> Initializers) {
5040   if (Constructor->isDependentContext()) {
5041     // Just store the initializers as written, they will be checked during
5042     // instantiation.
5043     if (!Initializers.empty()) {
5044       Constructor->setNumCtorInitializers(Initializers.size());
5045       CXXCtorInitializer **baseOrMemberInitializers =
5046         new (Context) CXXCtorInitializer*[Initializers.size()];
5047       memcpy(baseOrMemberInitializers, Initializers.data(),
5048              Initializers.size() * sizeof(CXXCtorInitializer*));
5049       Constructor->setCtorInitializers(baseOrMemberInitializers);
5050     }
5051 
5052     // Let template instantiation know whether we had errors.
5053     if (AnyErrors)
5054       Constructor->setInvalidDecl();
5055 
5056     return false;
5057   }
5058 
5059   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5060 
5061   // We need to build the initializer AST according to order of construction
5062   // and not what user specified in the Initializers list.
5063   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5064   if (!ClassDecl)
5065     return true;
5066 
5067   bool HadError = false;
5068 
5069   for (unsigned i = 0; i < Initializers.size(); i++) {
5070     CXXCtorInitializer *Member = Initializers[i];
5071 
5072     if (Member->isBaseInitializer())
5073       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5074     else {
5075       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5076 
5077       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5078         for (auto *C : F->chain()) {
5079           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5080           if (FD && FD->getParent()->isUnion())
5081             Info.ActiveUnionMember.insert(std::make_pair(
5082                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5083         }
5084       } else if (FieldDecl *FD = Member->getMember()) {
5085         if (FD->getParent()->isUnion())
5086           Info.ActiveUnionMember.insert(std::make_pair(
5087               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5088       }
5089     }
5090   }
5091 
5092   // Keep track of the direct virtual bases.
5093   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5094   for (auto &I : ClassDecl->bases()) {
5095     if (I.isVirtual())
5096       DirectVBases.insert(&I);
5097   }
5098 
5099   // Push virtual bases before others.
5100   for (auto &VBase : ClassDecl->vbases()) {
5101     if (CXXCtorInitializer *Value
5102         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5103       // [class.base.init]p7, per DR257:
5104       //   A mem-initializer where the mem-initializer-id names a virtual base
5105       //   class is ignored during execution of a constructor of any class that
5106       //   is not the most derived class.
5107       if (ClassDecl->isAbstract()) {
5108         // FIXME: Provide a fixit to remove the base specifier. This requires
5109         // tracking the location of the associated comma for a base specifier.
5110         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5111           << VBase.getType() << ClassDecl;
5112         DiagnoseAbstractType(ClassDecl);
5113       }
5114 
5115       Info.AllToInit.push_back(Value);
5116     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5117       // [class.base.init]p8, per DR257:
5118       //   If a given [...] base class is not named by a mem-initializer-id
5119       //   [...] and the entity is not a virtual base class of an abstract
5120       //   class, then [...] the entity is default-initialized.
5121       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5122       CXXCtorInitializer *CXXBaseInit;
5123       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5124                                        &VBase, IsInheritedVirtualBase,
5125                                        CXXBaseInit)) {
5126         HadError = true;
5127         continue;
5128       }
5129 
5130       Info.AllToInit.push_back(CXXBaseInit);
5131     }
5132   }
5133 
5134   // Non-virtual bases.
5135   for (auto &Base : ClassDecl->bases()) {
5136     // Virtuals are in the virtual base list and already constructed.
5137     if (Base.isVirtual())
5138       continue;
5139 
5140     if (CXXCtorInitializer *Value
5141           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5142       Info.AllToInit.push_back(Value);
5143     } else if (!AnyErrors) {
5144       CXXCtorInitializer *CXXBaseInit;
5145       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5146                                        &Base, /*IsInheritedVirtualBase=*/false,
5147                                        CXXBaseInit)) {
5148         HadError = true;
5149         continue;
5150       }
5151 
5152       Info.AllToInit.push_back(CXXBaseInit);
5153     }
5154   }
5155 
5156   // Fields.
5157   for (auto *Mem : ClassDecl->decls()) {
5158     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5159       // C++ [class.bit]p2:
5160       //   A declaration for a bit-field that omits the identifier declares an
5161       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5162       //   initialized.
5163       if (F->isUnnamedBitfield())
5164         continue;
5165 
5166       // If we're not generating the implicit copy/move constructor, then we'll
5167       // handle anonymous struct/union fields based on their individual
5168       // indirect fields.
5169       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5170         continue;
5171 
5172       if (CollectFieldInitializer(*this, Info, F))
5173         HadError = true;
5174       continue;
5175     }
5176 
5177     // Beyond this point, we only consider default initialization.
5178     if (Info.isImplicitCopyOrMove())
5179       continue;
5180 
5181     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5182       if (F->getType()->isIncompleteArrayType()) {
5183         assert(ClassDecl->hasFlexibleArrayMember() &&
5184                "Incomplete array type is not valid");
5185         continue;
5186       }
5187 
5188       // Initialize each field of an anonymous struct individually.
5189       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5190         HadError = true;
5191 
5192       continue;
5193     }
5194   }
5195 
5196   unsigned NumInitializers = Info.AllToInit.size();
5197   if (NumInitializers > 0) {
5198     Constructor->setNumCtorInitializers(NumInitializers);
5199     CXXCtorInitializer **baseOrMemberInitializers =
5200       new (Context) CXXCtorInitializer*[NumInitializers];
5201     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5202            NumInitializers * sizeof(CXXCtorInitializer*));
5203     Constructor->setCtorInitializers(baseOrMemberInitializers);
5204 
5205     // Constructors implicitly reference the base and member
5206     // destructors.
5207     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5208                                            Constructor->getParent());
5209   }
5210 
5211   return HadError;
5212 }
5213 
5214 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5215   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5216     const RecordDecl *RD = RT->getDecl();
5217     if (RD->isAnonymousStructOrUnion()) {
5218       for (auto *Field : RD->fields())
5219         PopulateKeysForFields(Field, IdealInits);
5220       return;
5221     }
5222   }
5223   IdealInits.push_back(Field->getCanonicalDecl());
5224 }
5225 
5226 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5227   return Context.getCanonicalType(BaseType).getTypePtr();
5228 }
5229 
5230 static const void *GetKeyForMember(ASTContext &Context,
5231                                    CXXCtorInitializer *Member) {
5232   if (!Member->isAnyMemberInitializer())
5233     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5234 
5235   return Member->getAnyMember()->getCanonicalDecl();
5236 }
5237 
5238 static void DiagnoseBaseOrMemInitializerOrder(
5239     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5240     ArrayRef<CXXCtorInitializer *> Inits) {
5241   if (Constructor->getDeclContext()->isDependentContext())
5242     return;
5243 
5244   // Don't check initializers order unless the warning is enabled at the
5245   // location of at least one initializer.
5246   bool ShouldCheckOrder = false;
5247   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5248     CXXCtorInitializer *Init = Inits[InitIndex];
5249     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5250                                  Init->getSourceLocation())) {
5251       ShouldCheckOrder = true;
5252       break;
5253     }
5254   }
5255   if (!ShouldCheckOrder)
5256     return;
5257 
5258   // Build the list of bases and members in the order that they'll
5259   // actually be initialized.  The explicit initializers should be in
5260   // this same order but may be missing things.
5261   SmallVector<const void*, 32> IdealInitKeys;
5262 
5263   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5264 
5265   // 1. Virtual bases.
5266   for (const auto &VBase : ClassDecl->vbases())
5267     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5268 
5269   // 2. Non-virtual bases.
5270   for (const auto &Base : ClassDecl->bases()) {
5271     if (Base.isVirtual())
5272       continue;
5273     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5274   }
5275 
5276   // 3. Direct fields.
5277   for (auto *Field : ClassDecl->fields()) {
5278     if (Field->isUnnamedBitfield())
5279       continue;
5280 
5281     PopulateKeysForFields(Field, IdealInitKeys);
5282   }
5283 
5284   unsigned NumIdealInits = IdealInitKeys.size();
5285   unsigned IdealIndex = 0;
5286 
5287   CXXCtorInitializer *PrevInit = nullptr;
5288   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5289     CXXCtorInitializer *Init = Inits[InitIndex];
5290     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5291 
5292     // Scan forward to try to find this initializer in the idealized
5293     // initializers list.
5294     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5295       if (InitKey == IdealInitKeys[IdealIndex])
5296         break;
5297 
5298     // If we didn't find this initializer, it must be because we
5299     // scanned past it on a previous iteration.  That can only
5300     // happen if we're out of order;  emit a warning.
5301     if (IdealIndex == NumIdealInits && PrevInit) {
5302       Sema::SemaDiagnosticBuilder D =
5303         SemaRef.Diag(PrevInit->getSourceLocation(),
5304                      diag::warn_initializer_out_of_order);
5305 
5306       if (PrevInit->isAnyMemberInitializer())
5307         D << 0 << PrevInit->getAnyMember()->getDeclName();
5308       else
5309         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5310 
5311       if (Init->isAnyMemberInitializer())
5312         D << 0 << Init->getAnyMember()->getDeclName();
5313       else
5314         D << 1 << Init->getTypeSourceInfo()->getType();
5315 
5316       // Move back to the initializer's location in the ideal list.
5317       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5318         if (InitKey == IdealInitKeys[IdealIndex])
5319           break;
5320 
5321       assert(IdealIndex < NumIdealInits &&
5322              "initializer not found in initializer list");
5323     }
5324 
5325     PrevInit = Init;
5326   }
5327 }
5328 
5329 namespace {
5330 bool CheckRedundantInit(Sema &S,
5331                         CXXCtorInitializer *Init,
5332                         CXXCtorInitializer *&PrevInit) {
5333   if (!PrevInit) {
5334     PrevInit = Init;
5335     return false;
5336   }
5337 
5338   if (FieldDecl *Field = Init->getAnyMember())
5339     S.Diag(Init->getSourceLocation(),
5340            diag::err_multiple_mem_initialization)
5341       << Field->getDeclName()
5342       << Init->getSourceRange();
5343   else {
5344     const Type *BaseClass = Init->getBaseClass();
5345     assert(BaseClass && "neither field nor base");
5346     S.Diag(Init->getSourceLocation(),
5347            diag::err_multiple_base_initialization)
5348       << QualType(BaseClass, 0)
5349       << Init->getSourceRange();
5350   }
5351   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5352     << 0 << PrevInit->getSourceRange();
5353 
5354   return true;
5355 }
5356 
5357 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5358 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5359 
5360 bool CheckRedundantUnionInit(Sema &S,
5361                              CXXCtorInitializer *Init,
5362                              RedundantUnionMap &Unions) {
5363   FieldDecl *Field = Init->getAnyMember();
5364   RecordDecl *Parent = Field->getParent();
5365   NamedDecl *Child = Field;
5366 
5367   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5368     if (Parent->isUnion()) {
5369       UnionEntry &En = Unions[Parent];
5370       if (En.first && En.first != Child) {
5371         S.Diag(Init->getSourceLocation(),
5372                diag::err_multiple_mem_union_initialization)
5373           << Field->getDeclName()
5374           << Init->getSourceRange();
5375         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5376           << 0 << En.second->getSourceRange();
5377         return true;
5378       }
5379       if (!En.first) {
5380         En.first = Child;
5381         En.second = Init;
5382       }
5383       if (!Parent->isAnonymousStructOrUnion())
5384         return false;
5385     }
5386 
5387     Child = Parent;
5388     Parent = cast<RecordDecl>(Parent->getDeclContext());
5389   }
5390 
5391   return false;
5392 }
5393 }
5394 
5395 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5396 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5397                                 SourceLocation ColonLoc,
5398                                 ArrayRef<CXXCtorInitializer*> MemInits,
5399                                 bool AnyErrors) {
5400   if (!ConstructorDecl)
5401     return;
5402 
5403   AdjustDeclIfTemplate(ConstructorDecl);
5404 
5405   CXXConstructorDecl *Constructor
5406     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5407 
5408   if (!Constructor) {
5409     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5410     return;
5411   }
5412 
5413   // Mapping for the duplicate initializers check.
5414   // For member initializers, this is keyed with a FieldDecl*.
5415   // For base initializers, this is keyed with a Type*.
5416   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5417 
5418   // Mapping for the inconsistent anonymous-union initializers check.
5419   RedundantUnionMap MemberUnions;
5420 
5421   bool HadError = false;
5422   for (unsigned i = 0; i < MemInits.size(); i++) {
5423     CXXCtorInitializer *Init = MemInits[i];
5424 
5425     // Set the source order index.
5426     Init->setSourceOrder(i);
5427 
5428     if (Init->isAnyMemberInitializer()) {
5429       const void *Key = GetKeyForMember(Context, Init);
5430       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5431           CheckRedundantUnionInit(*this, Init, MemberUnions))
5432         HadError = true;
5433     } else if (Init->isBaseInitializer()) {
5434       const void *Key = GetKeyForMember(Context, Init);
5435       if (CheckRedundantInit(*this, Init, Members[Key]))
5436         HadError = true;
5437     } else {
5438       assert(Init->isDelegatingInitializer());
5439       // This must be the only initializer
5440       if (MemInits.size() != 1) {
5441         Diag(Init->getSourceLocation(),
5442              diag::err_delegating_initializer_alone)
5443           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5444         // We will treat this as being the only initializer.
5445       }
5446       SetDelegatingInitializer(Constructor, MemInits[i]);
5447       // Return immediately as the initializer is set.
5448       return;
5449     }
5450   }
5451 
5452   if (HadError)
5453     return;
5454 
5455   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5456 
5457   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5458 
5459   DiagnoseUninitializedFields(*this, Constructor);
5460 }
5461 
5462 void
5463 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5464                                              CXXRecordDecl *ClassDecl) {
5465   // Ignore dependent contexts. Also ignore unions, since their members never
5466   // have destructors implicitly called.
5467   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5468     return;
5469 
5470   // FIXME: all the access-control diagnostics are positioned on the
5471   // field/base declaration.  That's probably good; that said, the
5472   // user might reasonably want to know why the destructor is being
5473   // emitted, and we currently don't say.
5474 
5475   // Non-static data members.
5476   for (auto *Field : ClassDecl->fields()) {
5477     if (Field->isInvalidDecl())
5478       continue;
5479 
5480     // Don't destroy incomplete or zero-length arrays.
5481     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5482       continue;
5483 
5484     QualType FieldType = Context.getBaseElementType(Field->getType());
5485 
5486     const RecordType* RT = FieldType->getAs<RecordType>();
5487     if (!RT)
5488       continue;
5489 
5490     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5491     if (FieldClassDecl->isInvalidDecl())
5492       continue;
5493     if (FieldClassDecl->hasIrrelevantDestructor())
5494       continue;
5495     // The destructor for an implicit anonymous union member is never invoked.
5496     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5497       continue;
5498 
5499     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5500     assert(Dtor && "No dtor found for FieldClassDecl!");
5501     CheckDestructorAccess(Field->getLocation(), Dtor,
5502                           PDiag(diag::err_access_dtor_field)
5503                             << Field->getDeclName()
5504                             << FieldType);
5505 
5506     MarkFunctionReferenced(Location, Dtor);
5507     DiagnoseUseOfDecl(Dtor, Location);
5508   }
5509 
5510   // We only potentially invoke the destructors of potentially constructed
5511   // subobjects.
5512   bool VisitVirtualBases = !ClassDecl->isAbstract();
5513 
5514   // If the destructor exists and has already been marked used in the MS ABI,
5515   // then virtual base destructors have already been checked and marked used.
5516   // Skip checking them again to avoid duplicate diagnostics.
5517   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5518     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5519     if (Dtor && Dtor->isUsed())
5520       VisitVirtualBases = false;
5521   }
5522 
5523   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5524 
5525   // Bases.
5526   for (const auto &Base : ClassDecl->bases()) {
5527     const RecordType *RT = Base.getType()->getAs<RecordType>();
5528     if (!RT)
5529       continue;
5530 
5531     // Remember direct virtual bases.
5532     if (Base.isVirtual()) {
5533       if (!VisitVirtualBases)
5534         continue;
5535       DirectVirtualBases.insert(RT);
5536     }
5537 
5538     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5539     // If our base class is invalid, we probably can't get its dtor anyway.
5540     if (BaseClassDecl->isInvalidDecl())
5541       continue;
5542     if (BaseClassDecl->hasIrrelevantDestructor())
5543       continue;
5544 
5545     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5546     assert(Dtor && "No dtor found for BaseClassDecl!");
5547 
5548     // FIXME: caret should be on the start of the class name
5549     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5550                           PDiag(diag::err_access_dtor_base)
5551                               << Base.getType() << Base.getSourceRange(),
5552                           Context.getTypeDeclType(ClassDecl));
5553 
5554     MarkFunctionReferenced(Location, Dtor);
5555     DiagnoseUseOfDecl(Dtor, Location);
5556   }
5557 
5558   if (VisitVirtualBases)
5559     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5560                                          &DirectVirtualBases);
5561 }
5562 
5563 void Sema::MarkVirtualBaseDestructorsReferenced(
5564     SourceLocation Location, CXXRecordDecl *ClassDecl,
5565     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5566   // Virtual bases.
5567   for (const auto &VBase : ClassDecl->vbases()) {
5568     // Bases are always records in a well-formed non-dependent class.
5569     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5570 
5571     // Ignore already visited direct virtual bases.
5572     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5573       continue;
5574 
5575     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5576     // If our base class is invalid, we probably can't get its dtor anyway.
5577     if (BaseClassDecl->isInvalidDecl())
5578       continue;
5579     if (BaseClassDecl->hasIrrelevantDestructor())
5580       continue;
5581 
5582     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5583     assert(Dtor && "No dtor found for BaseClassDecl!");
5584     if (CheckDestructorAccess(
5585             ClassDecl->getLocation(), Dtor,
5586             PDiag(diag::err_access_dtor_vbase)
5587                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5588             Context.getTypeDeclType(ClassDecl)) ==
5589         AR_accessible) {
5590       CheckDerivedToBaseConversion(
5591           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5592           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5593           SourceRange(), DeclarationName(), nullptr);
5594     }
5595 
5596     MarkFunctionReferenced(Location, Dtor);
5597     DiagnoseUseOfDecl(Dtor, Location);
5598   }
5599 }
5600 
5601 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5602   if (!CDtorDecl)
5603     return;
5604 
5605   if (CXXConstructorDecl *Constructor
5606       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5607     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5608     DiagnoseUninitializedFields(*this, Constructor);
5609   }
5610 }
5611 
5612 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5613   if (!getLangOpts().CPlusPlus)
5614     return false;
5615 
5616   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5617   if (!RD)
5618     return false;
5619 
5620   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5621   // class template specialization here, but doing so breaks a lot of code.
5622 
5623   // We can't answer whether something is abstract until it has a
5624   // definition. If it's currently being defined, we'll walk back
5625   // over all the declarations when we have a full definition.
5626   const CXXRecordDecl *Def = RD->getDefinition();
5627   if (!Def || Def->isBeingDefined())
5628     return false;
5629 
5630   return RD->isAbstract();
5631 }
5632 
5633 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5634                                   TypeDiagnoser &Diagnoser) {
5635   if (!isAbstractType(Loc, T))
5636     return false;
5637 
5638   T = Context.getBaseElementType(T);
5639   Diagnoser.diagnose(*this, Loc, T);
5640   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5641   return true;
5642 }
5643 
5644 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5645   // Check if we've already emitted the list of pure virtual functions
5646   // for this class.
5647   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5648     return;
5649 
5650   // If the diagnostic is suppressed, don't emit the notes. We're only
5651   // going to emit them once, so try to attach them to a diagnostic we're
5652   // actually going to show.
5653   if (Diags.isLastDiagnosticIgnored())
5654     return;
5655 
5656   CXXFinalOverriderMap FinalOverriders;
5657   RD->getFinalOverriders(FinalOverriders);
5658 
5659   // Keep a set of seen pure methods so we won't diagnose the same method
5660   // more than once.
5661   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5662 
5663   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5664                                    MEnd = FinalOverriders.end();
5665        M != MEnd;
5666        ++M) {
5667     for (OverridingMethods::iterator SO = M->second.begin(),
5668                                   SOEnd = M->second.end();
5669          SO != SOEnd; ++SO) {
5670       // C++ [class.abstract]p4:
5671       //   A class is abstract if it contains or inherits at least one
5672       //   pure virtual function for which the final overrider is pure
5673       //   virtual.
5674 
5675       //
5676       if (SO->second.size() != 1)
5677         continue;
5678 
5679       if (!SO->second.front().Method->isPure())
5680         continue;
5681 
5682       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5683         continue;
5684 
5685       Diag(SO->second.front().Method->getLocation(),
5686            diag::note_pure_virtual_function)
5687         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5688     }
5689   }
5690 
5691   if (!PureVirtualClassDiagSet)
5692     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5693   PureVirtualClassDiagSet->insert(RD);
5694 }
5695 
5696 namespace {
5697 struct AbstractUsageInfo {
5698   Sema &S;
5699   CXXRecordDecl *Record;
5700   CanQualType AbstractType;
5701   bool Invalid;
5702 
5703   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5704     : S(S), Record(Record),
5705       AbstractType(S.Context.getCanonicalType(
5706                    S.Context.getTypeDeclType(Record))),
5707       Invalid(false) {}
5708 
5709   void DiagnoseAbstractType() {
5710     if (Invalid) return;
5711     S.DiagnoseAbstractType(Record);
5712     Invalid = true;
5713   }
5714 
5715   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5716 };
5717 
5718 struct CheckAbstractUsage {
5719   AbstractUsageInfo &Info;
5720   const NamedDecl *Ctx;
5721 
5722   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5723     : Info(Info), Ctx(Ctx) {}
5724 
5725   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5726     switch (TL.getTypeLocClass()) {
5727 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5728 #define TYPELOC(CLASS, PARENT) \
5729     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5730 #include "clang/AST/TypeLocNodes.def"
5731     }
5732   }
5733 
5734   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5735     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5736     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5737       if (!TL.getParam(I))
5738         continue;
5739 
5740       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5741       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5742     }
5743   }
5744 
5745   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5746     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5747   }
5748 
5749   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5750     // Visit the type parameters from a permissive context.
5751     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5752       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5753       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5754         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5755           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5756       // TODO: other template argument types?
5757     }
5758   }
5759 
5760   // Visit pointee types from a permissive context.
5761 #define CheckPolymorphic(Type) \
5762   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5763     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5764   }
5765   CheckPolymorphic(PointerTypeLoc)
5766   CheckPolymorphic(ReferenceTypeLoc)
5767   CheckPolymorphic(MemberPointerTypeLoc)
5768   CheckPolymorphic(BlockPointerTypeLoc)
5769   CheckPolymorphic(AtomicTypeLoc)
5770 
5771   /// Handle all the types we haven't given a more specific
5772   /// implementation for above.
5773   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5774     // Every other kind of type that we haven't called out already
5775     // that has an inner type is either (1) sugar or (2) contains that
5776     // inner type in some way as a subobject.
5777     if (TypeLoc Next = TL.getNextTypeLoc())
5778       return Visit(Next, Sel);
5779 
5780     // If there's no inner type and we're in a permissive context,
5781     // don't diagnose.
5782     if (Sel == Sema::AbstractNone) return;
5783 
5784     // Check whether the type matches the abstract type.
5785     QualType T = TL.getType();
5786     if (T->isArrayType()) {
5787       Sel = Sema::AbstractArrayType;
5788       T = Info.S.Context.getBaseElementType(T);
5789     }
5790     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5791     if (CT != Info.AbstractType) return;
5792 
5793     // It matched; do some magic.
5794     if (Sel == Sema::AbstractArrayType) {
5795       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5796         << T << TL.getSourceRange();
5797     } else {
5798       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5799         << Sel << T << TL.getSourceRange();
5800     }
5801     Info.DiagnoseAbstractType();
5802   }
5803 };
5804 
5805 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5806                                   Sema::AbstractDiagSelID Sel) {
5807   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5808 }
5809 
5810 }
5811 
5812 /// Check for invalid uses of an abstract type in a method declaration.
5813 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5814                                     CXXMethodDecl *MD) {
5815   // No need to do the check on definitions, which require that
5816   // the return/param types be complete.
5817   if (MD->doesThisDeclarationHaveABody())
5818     return;
5819 
5820   // For safety's sake, just ignore it if we don't have type source
5821   // information.  This should never happen for non-implicit methods,
5822   // but...
5823   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5824     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5825 }
5826 
5827 /// Check for invalid uses of an abstract type within a class definition.
5828 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5829                                     CXXRecordDecl *RD) {
5830   for (auto *D : RD->decls()) {
5831     if (D->isImplicit()) continue;
5832 
5833     // Methods and method templates.
5834     if (isa<CXXMethodDecl>(D)) {
5835       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5836     } else if (isa<FunctionTemplateDecl>(D)) {
5837       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5838       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5839 
5840     // Fields and static variables.
5841     } else if (isa<FieldDecl>(D)) {
5842       FieldDecl *FD = cast<FieldDecl>(D);
5843       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5844         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5845     } else if (isa<VarDecl>(D)) {
5846       VarDecl *VD = cast<VarDecl>(D);
5847       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5848         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5849 
5850     // Nested classes and class templates.
5851     } else if (isa<CXXRecordDecl>(D)) {
5852       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5853     } else if (isa<ClassTemplateDecl>(D)) {
5854       CheckAbstractClassUsage(Info,
5855                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5856     }
5857   }
5858 }
5859 
5860 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5861   Attr *ClassAttr = getDLLAttr(Class);
5862   if (!ClassAttr)
5863     return;
5864 
5865   assert(ClassAttr->getKind() == attr::DLLExport);
5866 
5867   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5868 
5869   if (TSK == TSK_ExplicitInstantiationDeclaration)
5870     // Don't go any further if this is just an explicit instantiation
5871     // declaration.
5872     return;
5873 
5874   // Add a context note to explain how we got to any diagnostics produced below.
5875   struct MarkingClassDllexported {
5876     Sema &S;
5877     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5878                             SourceLocation AttrLoc)
5879         : S(S) {
5880       Sema::CodeSynthesisContext Ctx;
5881       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5882       Ctx.PointOfInstantiation = AttrLoc;
5883       Ctx.Entity = Class;
5884       S.pushCodeSynthesisContext(Ctx);
5885     }
5886     ~MarkingClassDllexported() {
5887       S.popCodeSynthesisContext();
5888     }
5889   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5890 
5891   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5892     S.MarkVTableUsed(Class->getLocation(), Class, true);
5893 
5894   for (Decl *Member : Class->decls()) {
5895     // Defined static variables that are members of an exported base
5896     // class must be marked export too.
5897     auto *VD = dyn_cast<VarDecl>(Member);
5898     if (VD && Member->getAttr<DLLExportAttr>() &&
5899         VD->getStorageClass() == SC_Static &&
5900         TSK == TSK_ImplicitInstantiation)
5901       S.MarkVariableReferenced(VD->getLocation(), VD);
5902 
5903     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5904     if (!MD)
5905       continue;
5906 
5907     if (Member->getAttr<DLLExportAttr>()) {
5908       if (MD->isUserProvided()) {
5909         // Instantiate non-default class member functions ...
5910 
5911         // .. except for certain kinds of template specializations.
5912         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5913           continue;
5914 
5915         S.MarkFunctionReferenced(Class->getLocation(), MD);
5916 
5917         // The function will be passed to the consumer when its definition is
5918         // encountered.
5919       } else if (MD->isExplicitlyDefaulted()) {
5920         // Synthesize and instantiate explicitly defaulted methods.
5921         S.MarkFunctionReferenced(Class->getLocation(), MD);
5922 
5923         if (TSK != TSK_ExplicitInstantiationDefinition) {
5924           // Except for explicit instantiation defs, we will not see the
5925           // definition again later, so pass it to the consumer now.
5926           S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5927         }
5928       } else if (!MD->isTrivial() ||
5929                  MD->isCopyAssignmentOperator() ||
5930                  MD->isMoveAssignmentOperator()) {
5931         // Synthesize and instantiate non-trivial implicit methods, and the copy
5932         // and move assignment operators. The latter are exported even if they
5933         // are trivial, because the address of an operator can be taken and
5934         // should compare equal across libraries.
5935         S.MarkFunctionReferenced(Class->getLocation(), MD);
5936 
5937         // There is no later point when we will see the definition of this
5938         // function, so pass it to the consumer now.
5939         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5940       }
5941     }
5942   }
5943 }
5944 
5945 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5946                                                         CXXRecordDecl *Class) {
5947   // Only the MS ABI has default constructor closures, so we don't need to do
5948   // this semantic checking anywhere else.
5949   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5950     return;
5951 
5952   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5953   for (Decl *Member : Class->decls()) {
5954     // Look for exported default constructors.
5955     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5956     if (!CD || !CD->isDefaultConstructor())
5957       continue;
5958     auto *Attr = CD->getAttr<DLLExportAttr>();
5959     if (!Attr)
5960       continue;
5961 
5962     // If the class is non-dependent, mark the default arguments as ODR-used so
5963     // that we can properly codegen the constructor closure.
5964     if (!Class->isDependentContext()) {
5965       for (ParmVarDecl *PD : CD->parameters()) {
5966         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5967         S.DiscardCleanupsInEvaluationContext();
5968       }
5969     }
5970 
5971     if (LastExportedDefaultCtor) {
5972       S.Diag(LastExportedDefaultCtor->getLocation(),
5973              diag::err_attribute_dll_ambiguous_default_ctor)
5974           << Class;
5975       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5976           << CD->getDeclName();
5977       return;
5978     }
5979     LastExportedDefaultCtor = CD;
5980   }
5981 }
5982 
5983 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5984                                                        CXXRecordDecl *Class) {
5985   bool ErrorReported = false;
5986   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5987                                                      ClassTemplateDecl *TD) {
5988     if (ErrorReported)
5989       return;
5990     S.Diag(TD->getLocation(),
5991            diag::err_cuda_device_builtin_surftex_cls_template)
5992         << /*surface*/ 0 << TD;
5993     ErrorReported = true;
5994   };
5995 
5996   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5997   if (!TD) {
5998     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5999     if (!SD) {
6000       S.Diag(Class->getLocation(),
6001              diag::err_cuda_device_builtin_surftex_ref_decl)
6002           << /*surface*/ 0 << Class;
6003       S.Diag(Class->getLocation(),
6004              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6005           << Class;
6006       return;
6007     }
6008     TD = SD->getSpecializedTemplate();
6009   }
6010 
6011   TemplateParameterList *Params = TD->getTemplateParameters();
6012   unsigned N = Params->size();
6013 
6014   if (N != 2) {
6015     reportIllegalClassTemplate(S, TD);
6016     S.Diag(TD->getLocation(),
6017            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6018         << TD << 2;
6019   }
6020   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6021     reportIllegalClassTemplate(S, TD);
6022     S.Diag(TD->getLocation(),
6023            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6024         << TD << /*1st*/ 0 << /*type*/ 0;
6025   }
6026   if (N > 1) {
6027     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6028     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6029       reportIllegalClassTemplate(S, TD);
6030       S.Diag(TD->getLocation(),
6031              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6032           << TD << /*2nd*/ 1 << /*integer*/ 1;
6033     }
6034   }
6035 }
6036 
6037 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6038                                                        CXXRecordDecl *Class) {
6039   bool ErrorReported = false;
6040   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6041                                                      ClassTemplateDecl *TD) {
6042     if (ErrorReported)
6043       return;
6044     S.Diag(TD->getLocation(),
6045            diag::err_cuda_device_builtin_surftex_cls_template)
6046         << /*texture*/ 1 << TD;
6047     ErrorReported = true;
6048   };
6049 
6050   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6051   if (!TD) {
6052     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6053     if (!SD) {
6054       S.Diag(Class->getLocation(),
6055              diag::err_cuda_device_builtin_surftex_ref_decl)
6056           << /*texture*/ 1 << Class;
6057       S.Diag(Class->getLocation(),
6058              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6059           << Class;
6060       return;
6061     }
6062     TD = SD->getSpecializedTemplate();
6063   }
6064 
6065   TemplateParameterList *Params = TD->getTemplateParameters();
6066   unsigned N = Params->size();
6067 
6068   if (N != 3) {
6069     reportIllegalClassTemplate(S, TD);
6070     S.Diag(TD->getLocation(),
6071            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6072         << TD << 3;
6073   }
6074   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6075     reportIllegalClassTemplate(S, TD);
6076     S.Diag(TD->getLocation(),
6077            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6078         << TD << /*1st*/ 0 << /*type*/ 0;
6079   }
6080   if (N > 1) {
6081     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6082     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6083       reportIllegalClassTemplate(S, TD);
6084       S.Diag(TD->getLocation(),
6085              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6086           << TD << /*2nd*/ 1 << /*integer*/ 1;
6087     }
6088   }
6089   if (N > 2) {
6090     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6091     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6092       reportIllegalClassTemplate(S, TD);
6093       S.Diag(TD->getLocation(),
6094              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6095           << TD << /*3rd*/ 2 << /*integer*/ 1;
6096     }
6097   }
6098 }
6099 
6100 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6101   // Mark any compiler-generated routines with the implicit code_seg attribute.
6102   for (auto *Method : Class->methods()) {
6103     if (Method->isUserProvided())
6104       continue;
6105     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6106       Method->addAttr(A);
6107   }
6108 }
6109 
6110 /// Check class-level dllimport/dllexport attribute.
6111 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6112   Attr *ClassAttr = getDLLAttr(Class);
6113 
6114   // MSVC inherits DLL attributes to partial class template specializations.
6115   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6116     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6117       if (Attr *TemplateAttr =
6118               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6119         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6120         A->setInherited(true);
6121         ClassAttr = A;
6122       }
6123     }
6124   }
6125 
6126   if (!ClassAttr)
6127     return;
6128 
6129   if (!Class->isExternallyVisible()) {
6130     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6131         << Class << ClassAttr;
6132     return;
6133   }
6134 
6135   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6136       !ClassAttr->isInherited()) {
6137     // Diagnose dll attributes on members of class with dll attribute.
6138     for (Decl *Member : Class->decls()) {
6139       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6140         continue;
6141       InheritableAttr *MemberAttr = getDLLAttr(Member);
6142       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6143         continue;
6144 
6145       Diag(MemberAttr->getLocation(),
6146              diag::err_attribute_dll_member_of_dll_class)
6147           << MemberAttr << ClassAttr;
6148       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6149       Member->setInvalidDecl();
6150     }
6151   }
6152 
6153   if (Class->getDescribedClassTemplate())
6154     // Don't inherit dll attribute until the template is instantiated.
6155     return;
6156 
6157   // The class is either imported or exported.
6158   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6159 
6160   // Check if this was a dllimport attribute propagated from a derived class to
6161   // a base class template specialization. We don't apply these attributes to
6162   // static data members.
6163   const bool PropagatedImport =
6164       !ClassExported &&
6165       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6166 
6167   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6168 
6169   // Ignore explicit dllexport on explicit class template instantiation
6170   // declarations, except in MinGW mode.
6171   if (ClassExported && !ClassAttr->isInherited() &&
6172       TSK == TSK_ExplicitInstantiationDeclaration &&
6173       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6174     Class->dropAttr<DLLExportAttr>();
6175     return;
6176   }
6177 
6178   // Force declaration of implicit members so they can inherit the attribute.
6179   ForceDeclarationOfImplicitMembers(Class);
6180 
6181   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6182   // seem to be true in practice?
6183 
6184   for (Decl *Member : Class->decls()) {
6185     VarDecl *VD = dyn_cast<VarDecl>(Member);
6186     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6187 
6188     // Only methods and static fields inherit the attributes.
6189     if (!VD && !MD)
6190       continue;
6191 
6192     if (MD) {
6193       // Don't process deleted methods.
6194       if (MD->isDeleted())
6195         continue;
6196 
6197       if (MD->isInlined()) {
6198         // MinGW does not import or export inline methods. But do it for
6199         // template instantiations.
6200         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6201             TSK != TSK_ExplicitInstantiationDeclaration &&
6202             TSK != TSK_ExplicitInstantiationDefinition)
6203           continue;
6204 
6205         // MSVC versions before 2015 don't export the move assignment operators
6206         // and move constructor, so don't attempt to import/export them if
6207         // we have a definition.
6208         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6209         if ((MD->isMoveAssignmentOperator() ||
6210              (Ctor && Ctor->isMoveConstructor())) &&
6211             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6212           continue;
6213 
6214         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6215         // operator is exported anyway.
6216         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6217             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6218           continue;
6219       }
6220     }
6221 
6222     // Don't apply dllimport attributes to static data members of class template
6223     // instantiations when the attribute is propagated from a derived class.
6224     if (VD && PropagatedImport)
6225       continue;
6226 
6227     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6228       continue;
6229 
6230     if (!getDLLAttr(Member)) {
6231       InheritableAttr *NewAttr = nullptr;
6232 
6233       // Do not export/import inline function when -fno-dllexport-inlines is
6234       // passed. But add attribute for later local static var check.
6235       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6236           TSK != TSK_ExplicitInstantiationDeclaration &&
6237           TSK != TSK_ExplicitInstantiationDefinition) {
6238         if (ClassExported) {
6239           NewAttr = ::new (getASTContext())
6240               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6241         } else {
6242           NewAttr = ::new (getASTContext())
6243               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6244         }
6245       } else {
6246         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6247       }
6248 
6249       NewAttr->setInherited(true);
6250       Member->addAttr(NewAttr);
6251 
6252       if (MD) {
6253         // Propagate DLLAttr to friend re-declarations of MD that have already
6254         // been constructed.
6255         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6256              FD = FD->getPreviousDecl()) {
6257           if (FD->getFriendObjectKind() == Decl::FOK_None)
6258             continue;
6259           assert(!getDLLAttr(FD) &&
6260                  "friend re-decl should not already have a DLLAttr");
6261           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6262           NewAttr->setInherited(true);
6263           FD->addAttr(NewAttr);
6264         }
6265       }
6266     }
6267   }
6268 
6269   if (ClassExported)
6270     DelayedDllExportClasses.push_back(Class);
6271 }
6272 
6273 /// Perform propagation of DLL attributes from a derived class to a
6274 /// templated base class for MS compatibility.
6275 void Sema::propagateDLLAttrToBaseClassTemplate(
6276     CXXRecordDecl *Class, Attr *ClassAttr,
6277     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6278   if (getDLLAttr(
6279           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6280     // If the base class template has a DLL attribute, don't try to change it.
6281     return;
6282   }
6283 
6284   auto TSK = BaseTemplateSpec->getSpecializationKind();
6285   if (!getDLLAttr(BaseTemplateSpec) &&
6286       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6287        TSK == TSK_ImplicitInstantiation)) {
6288     // The template hasn't been instantiated yet (or it has, but only as an
6289     // explicit instantiation declaration or implicit instantiation, which means
6290     // we haven't codegenned any members yet), so propagate the attribute.
6291     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6292     NewAttr->setInherited(true);
6293     BaseTemplateSpec->addAttr(NewAttr);
6294 
6295     // If this was an import, mark that we propagated it from a derived class to
6296     // a base class template specialization.
6297     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6298       ImportAttr->setPropagatedToBaseTemplate();
6299 
6300     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6301     // needs to be run again to work see the new attribute. Otherwise this will
6302     // get run whenever the template is instantiated.
6303     if (TSK != TSK_Undeclared)
6304       checkClassLevelDLLAttribute(BaseTemplateSpec);
6305 
6306     return;
6307   }
6308 
6309   if (getDLLAttr(BaseTemplateSpec)) {
6310     // The template has already been specialized or instantiated with an
6311     // attribute, explicitly or through propagation. We should not try to change
6312     // it.
6313     return;
6314   }
6315 
6316   // The template was previously instantiated or explicitly specialized without
6317   // a dll attribute, It's too late for us to add an attribute, so warn that
6318   // this is unsupported.
6319   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6320       << BaseTemplateSpec->isExplicitSpecialization();
6321   Diag(ClassAttr->getLocation(), diag::note_attribute);
6322   if (BaseTemplateSpec->isExplicitSpecialization()) {
6323     Diag(BaseTemplateSpec->getLocation(),
6324            diag::note_template_class_explicit_specialization_was_here)
6325         << BaseTemplateSpec;
6326   } else {
6327     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6328            diag::note_template_class_instantiation_was_here)
6329         << BaseTemplateSpec;
6330   }
6331 }
6332 
6333 /// Determine the kind of defaulting that would be done for a given function.
6334 ///
6335 /// If the function is both a default constructor and a copy / move constructor
6336 /// (due to having a default argument for the first parameter), this picks
6337 /// CXXDefaultConstructor.
6338 ///
6339 /// FIXME: Check that case is properly handled by all callers.
6340 Sema::DefaultedFunctionKind
6341 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6342   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6343     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6344       if (Ctor->isDefaultConstructor())
6345         return Sema::CXXDefaultConstructor;
6346 
6347       if (Ctor->isCopyConstructor())
6348         return Sema::CXXCopyConstructor;
6349 
6350       if (Ctor->isMoveConstructor())
6351         return Sema::CXXMoveConstructor;
6352     }
6353 
6354     if (MD->isCopyAssignmentOperator())
6355       return Sema::CXXCopyAssignment;
6356 
6357     if (MD->isMoveAssignmentOperator())
6358       return Sema::CXXMoveAssignment;
6359 
6360     if (isa<CXXDestructorDecl>(FD))
6361       return Sema::CXXDestructor;
6362   }
6363 
6364   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6365   case OO_EqualEqual:
6366     return DefaultedComparisonKind::Equal;
6367 
6368   case OO_ExclaimEqual:
6369     return DefaultedComparisonKind::NotEqual;
6370 
6371   case OO_Spaceship:
6372     // No point allowing this if <=> doesn't exist in the current language mode.
6373     if (!getLangOpts().CPlusPlus20)
6374       break;
6375     return DefaultedComparisonKind::ThreeWay;
6376 
6377   case OO_Less:
6378   case OO_LessEqual:
6379   case OO_Greater:
6380   case OO_GreaterEqual:
6381     // No point allowing this if <=> doesn't exist in the current language mode.
6382     if (!getLangOpts().CPlusPlus20)
6383       break;
6384     return DefaultedComparisonKind::Relational;
6385 
6386   default:
6387     break;
6388   }
6389 
6390   // Not defaultable.
6391   return DefaultedFunctionKind();
6392 }
6393 
6394 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6395                                     SourceLocation DefaultLoc) {
6396   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6397   if (DFK.isComparison())
6398     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6399 
6400   switch (DFK.asSpecialMember()) {
6401   case Sema::CXXDefaultConstructor:
6402     S.DefineImplicitDefaultConstructor(DefaultLoc,
6403                                        cast<CXXConstructorDecl>(FD));
6404     break;
6405   case Sema::CXXCopyConstructor:
6406     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6407     break;
6408   case Sema::CXXCopyAssignment:
6409     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6410     break;
6411   case Sema::CXXDestructor:
6412     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6413     break;
6414   case Sema::CXXMoveConstructor:
6415     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6416     break;
6417   case Sema::CXXMoveAssignment:
6418     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6419     break;
6420   case Sema::CXXInvalid:
6421     llvm_unreachable("Invalid special member.");
6422   }
6423 }
6424 
6425 /// Determine whether a type is permitted to be passed or returned in
6426 /// registers, per C++ [class.temporary]p3.
6427 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6428                                TargetInfo::CallingConvKind CCK) {
6429   if (D->isDependentType() || D->isInvalidDecl())
6430     return false;
6431 
6432   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6433   // The PS4 platform ABI follows the behavior of Clang 3.2.
6434   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6435     return !D->hasNonTrivialDestructorForCall() &&
6436            !D->hasNonTrivialCopyConstructorForCall();
6437 
6438   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6439     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6440     bool DtorIsTrivialForCall = false;
6441 
6442     // If a class has at least one non-deleted, trivial copy constructor, it
6443     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6444     //
6445     // Note: This permits classes with non-trivial copy or move ctors to be
6446     // passed in registers, so long as they *also* have a trivial copy ctor,
6447     // which is non-conforming.
6448     if (D->needsImplicitCopyConstructor()) {
6449       if (!D->defaultedCopyConstructorIsDeleted()) {
6450         if (D->hasTrivialCopyConstructor())
6451           CopyCtorIsTrivial = true;
6452         if (D->hasTrivialCopyConstructorForCall())
6453           CopyCtorIsTrivialForCall = true;
6454       }
6455     } else {
6456       for (const CXXConstructorDecl *CD : D->ctors()) {
6457         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6458           if (CD->isTrivial())
6459             CopyCtorIsTrivial = true;
6460           if (CD->isTrivialForCall())
6461             CopyCtorIsTrivialForCall = true;
6462         }
6463       }
6464     }
6465 
6466     if (D->needsImplicitDestructor()) {
6467       if (!D->defaultedDestructorIsDeleted() &&
6468           D->hasTrivialDestructorForCall())
6469         DtorIsTrivialForCall = true;
6470     } else if (const auto *DD = D->getDestructor()) {
6471       if (!DD->isDeleted() && DD->isTrivialForCall())
6472         DtorIsTrivialForCall = true;
6473     }
6474 
6475     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6476     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6477       return true;
6478 
6479     // If a class has a destructor, we'd really like to pass it indirectly
6480     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6481     // impossible for small types, which it will pass in a single register or
6482     // stack slot. Most objects with dtors are large-ish, so handle that early.
6483     // We can't call out all large objects as being indirect because there are
6484     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6485     // how we pass large POD types.
6486 
6487     // Note: This permits small classes with nontrivial destructors to be
6488     // passed in registers, which is non-conforming.
6489     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6490     uint64_t TypeSize = isAArch64 ? 128 : 64;
6491 
6492     if (CopyCtorIsTrivial &&
6493         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6494       return true;
6495     return false;
6496   }
6497 
6498   // Per C++ [class.temporary]p3, the relevant condition is:
6499   //   each copy constructor, move constructor, and destructor of X is
6500   //   either trivial or deleted, and X has at least one non-deleted copy
6501   //   or move constructor
6502   bool HasNonDeletedCopyOrMove = false;
6503 
6504   if (D->needsImplicitCopyConstructor() &&
6505       !D->defaultedCopyConstructorIsDeleted()) {
6506     if (!D->hasTrivialCopyConstructorForCall())
6507       return false;
6508     HasNonDeletedCopyOrMove = true;
6509   }
6510 
6511   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6512       !D->defaultedMoveConstructorIsDeleted()) {
6513     if (!D->hasTrivialMoveConstructorForCall())
6514       return false;
6515     HasNonDeletedCopyOrMove = true;
6516   }
6517 
6518   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6519       !D->hasTrivialDestructorForCall())
6520     return false;
6521 
6522   for (const CXXMethodDecl *MD : D->methods()) {
6523     if (MD->isDeleted())
6524       continue;
6525 
6526     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6527     if (CD && CD->isCopyOrMoveConstructor())
6528       HasNonDeletedCopyOrMove = true;
6529     else if (!isa<CXXDestructorDecl>(MD))
6530       continue;
6531 
6532     if (!MD->isTrivialForCall())
6533       return false;
6534   }
6535 
6536   return HasNonDeletedCopyOrMove;
6537 }
6538 
6539 /// Report an error regarding overriding, along with any relevant
6540 /// overridden methods.
6541 ///
6542 /// \param DiagID the primary error to report.
6543 /// \param MD the overriding method.
6544 static bool
6545 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6546                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6547   bool IssuedDiagnostic = false;
6548   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6549     if (Report(O)) {
6550       if (!IssuedDiagnostic) {
6551         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6552         IssuedDiagnostic = true;
6553       }
6554       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6555     }
6556   }
6557   return IssuedDiagnostic;
6558 }
6559 
6560 /// Perform semantic checks on a class definition that has been
6561 /// completing, introducing implicitly-declared members, checking for
6562 /// abstract types, etc.
6563 ///
6564 /// \param S The scope in which the class was parsed. Null if we didn't just
6565 ///        parse a class definition.
6566 /// \param Record The completed class.
6567 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6568   if (!Record)
6569     return;
6570 
6571   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6572     AbstractUsageInfo Info(*this, Record);
6573     CheckAbstractClassUsage(Info, Record);
6574   }
6575 
6576   // If this is not an aggregate type and has no user-declared constructor,
6577   // complain about any non-static data members of reference or const scalar
6578   // type, since they will never get initializers.
6579   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6580       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6581       !Record->isLambda()) {
6582     bool Complained = false;
6583     for (const auto *F : Record->fields()) {
6584       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6585         continue;
6586 
6587       if (F->getType()->isReferenceType() ||
6588           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6589         if (!Complained) {
6590           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6591             << Record->getTagKind() << Record;
6592           Complained = true;
6593         }
6594 
6595         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6596           << F->getType()->isReferenceType()
6597           << F->getDeclName();
6598       }
6599     }
6600   }
6601 
6602   if (Record->getIdentifier()) {
6603     // C++ [class.mem]p13:
6604     //   If T is the name of a class, then each of the following shall have a
6605     //   name different from T:
6606     //     - every member of every anonymous union that is a member of class T.
6607     //
6608     // C++ [class.mem]p14:
6609     //   In addition, if class T has a user-declared constructor (12.1), every
6610     //   non-static data member of class T shall have a name different from T.
6611     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6612     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6613          ++I) {
6614       NamedDecl *D = (*I)->getUnderlyingDecl();
6615       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6616            Record->hasUserDeclaredConstructor()) ||
6617           isa<IndirectFieldDecl>(D)) {
6618         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6619           << D->getDeclName();
6620         break;
6621       }
6622     }
6623   }
6624 
6625   // Warn if the class has virtual methods but non-virtual public destructor.
6626   if (Record->isPolymorphic() && !Record->isDependentType()) {
6627     CXXDestructorDecl *dtor = Record->getDestructor();
6628     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6629         !Record->hasAttr<FinalAttr>())
6630       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6631            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6632   }
6633 
6634   if (Record->isAbstract()) {
6635     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6636       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6637         << FA->isSpelledAsSealed();
6638       DiagnoseAbstractType(Record);
6639     }
6640   }
6641 
6642   // Warn if the class has a final destructor but is not itself marked final.
6643   if (!Record->hasAttr<FinalAttr>()) {
6644     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6645       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6646         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6647             << FA->isSpelledAsSealed()
6648             << FixItHint::CreateInsertion(
6649                    getLocForEndOfToken(Record->getLocation()),
6650                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6651         Diag(Record->getLocation(),
6652              diag::note_final_dtor_non_final_class_silence)
6653             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6654       }
6655     }
6656   }
6657 
6658   // See if trivial_abi has to be dropped.
6659   if (Record->hasAttr<TrivialABIAttr>())
6660     checkIllFormedTrivialABIStruct(*Record);
6661 
6662   // Set HasTrivialSpecialMemberForCall if the record has attribute
6663   // "trivial_abi".
6664   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6665 
6666   if (HasTrivialABI)
6667     Record->setHasTrivialSpecialMemberForCall();
6668 
6669   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6670   // We check these last because they can depend on the properties of the
6671   // primary comparison functions (==, <=>).
6672   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6673 
6674   // Perform checks that can't be done until we know all the properties of a
6675   // member function (whether it's defaulted, deleted, virtual, overriding,
6676   // ...).
6677   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6678     // A static function cannot override anything.
6679     if (MD->getStorageClass() == SC_Static) {
6680       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6681                           [](const CXXMethodDecl *) { return true; }))
6682         return;
6683     }
6684 
6685     // A deleted function cannot override a non-deleted function and vice
6686     // versa.
6687     if (ReportOverrides(*this,
6688                         MD->isDeleted() ? diag::err_deleted_override
6689                                         : diag::err_non_deleted_override,
6690                         MD, [&](const CXXMethodDecl *V) {
6691                           return MD->isDeleted() != V->isDeleted();
6692                         })) {
6693       if (MD->isDefaulted() && MD->isDeleted())
6694         // Explain why this defaulted function was deleted.
6695         DiagnoseDeletedDefaultedFunction(MD);
6696       return;
6697     }
6698 
6699     // A consteval function cannot override a non-consteval function and vice
6700     // versa.
6701     if (ReportOverrides(*this,
6702                         MD->isConsteval() ? diag::err_consteval_override
6703                                           : diag::err_non_consteval_override,
6704                         MD, [&](const CXXMethodDecl *V) {
6705                           return MD->isConsteval() != V->isConsteval();
6706                         })) {
6707       if (MD->isDefaulted() && MD->isDeleted())
6708         // Explain why this defaulted function was deleted.
6709         DiagnoseDeletedDefaultedFunction(MD);
6710       return;
6711     }
6712   };
6713 
6714   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6715     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6716       return false;
6717 
6718     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6719     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6720         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6721       DefaultedSecondaryComparisons.push_back(FD);
6722       return true;
6723     }
6724 
6725     CheckExplicitlyDefaultedFunction(S, FD);
6726     return false;
6727   };
6728 
6729   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6730     // Check whether the explicitly-defaulted members are valid.
6731     bool Incomplete = CheckForDefaultedFunction(M);
6732 
6733     // Skip the rest of the checks for a member of a dependent class.
6734     if (Record->isDependentType())
6735       return;
6736 
6737     // For an explicitly defaulted or deleted special member, we defer
6738     // determining triviality until the class is complete. That time is now!
6739     CXXSpecialMember CSM = getSpecialMember(M);
6740     if (!M->isImplicit() && !M->isUserProvided()) {
6741       if (CSM != CXXInvalid) {
6742         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6743         // Inform the class that we've finished declaring this member.
6744         Record->finishedDefaultedOrDeletedMember(M);
6745         M->setTrivialForCall(
6746             HasTrivialABI ||
6747             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6748         Record->setTrivialForCallFlags(M);
6749       }
6750     }
6751 
6752     // Set triviality for the purpose of calls if this is a user-provided
6753     // copy/move constructor or destructor.
6754     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6755          CSM == CXXDestructor) && M->isUserProvided()) {
6756       M->setTrivialForCall(HasTrivialABI);
6757       Record->setTrivialForCallFlags(M);
6758     }
6759 
6760     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6761         M->hasAttr<DLLExportAttr>()) {
6762       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6763           M->isTrivial() &&
6764           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6765            CSM == CXXDestructor))
6766         M->dropAttr<DLLExportAttr>();
6767 
6768       if (M->hasAttr<DLLExportAttr>()) {
6769         // Define after any fields with in-class initializers have been parsed.
6770         DelayedDllExportMemberFunctions.push_back(M);
6771       }
6772     }
6773 
6774     // Define defaulted constexpr virtual functions that override a base class
6775     // function right away.
6776     // FIXME: We can defer doing this until the vtable is marked as used.
6777     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6778       DefineDefaultedFunction(*this, M, M->getLocation());
6779 
6780     if (!Incomplete)
6781       CheckCompletedMemberFunction(M);
6782   };
6783 
6784   // Check the destructor before any other member function. We need to
6785   // determine whether it's trivial in order to determine whether the claas
6786   // type is a literal type, which is a prerequisite for determining whether
6787   // other special member functions are valid and whether they're implicitly
6788   // 'constexpr'.
6789   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6790     CompleteMemberFunction(Dtor);
6791 
6792   bool HasMethodWithOverrideControl = false,
6793        HasOverridingMethodWithoutOverrideControl = false;
6794   for (auto *D : Record->decls()) {
6795     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6796       // FIXME: We could do this check for dependent types with non-dependent
6797       // bases.
6798       if (!Record->isDependentType()) {
6799         // See if a method overloads virtual methods in a base
6800         // class without overriding any.
6801         if (!M->isStatic())
6802           DiagnoseHiddenVirtualMethods(M);
6803         if (M->hasAttr<OverrideAttr>())
6804           HasMethodWithOverrideControl = true;
6805         else if (M->size_overridden_methods() > 0)
6806           HasOverridingMethodWithoutOverrideControl = true;
6807       }
6808 
6809       if (!isa<CXXDestructorDecl>(M))
6810         CompleteMemberFunction(M);
6811     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6812       CheckForDefaultedFunction(
6813           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6814     }
6815   }
6816 
6817   if (HasOverridingMethodWithoutOverrideControl) {
6818     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6819     for (auto *M : Record->methods())
6820       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6821   }
6822 
6823   // Check the defaulted secondary comparisons after any other member functions.
6824   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6825     CheckExplicitlyDefaultedFunction(S, FD);
6826 
6827     // If this is a member function, we deferred checking it until now.
6828     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6829       CheckCompletedMemberFunction(MD);
6830   }
6831 
6832   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6833   // whether this class uses any C++ features that are implemented
6834   // completely differently in MSVC, and if so, emit a diagnostic.
6835   // That diagnostic defaults to an error, but we allow projects to
6836   // map it down to a warning (or ignore it).  It's a fairly common
6837   // practice among users of the ms_struct pragma to mass-annotate
6838   // headers, sweeping up a bunch of types that the project doesn't
6839   // really rely on MSVC-compatible layout for.  We must therefore
6840   // support "ms_struct except for C++ stuff" as a secondary ABI.
6841   // Don't emit this diagnostic if the feature was enabled as a
6842   // language option (as opposed to via a pragma or attribute), as
6843   // the option -mms-bitfields otherwise essentially makes it impossible
6844   // to build C++ code, unless this diagnostic is turned off.
6845   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6846       (Record->isPolymorphic() || Record->getNumBases())) {
6847     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6848   }
6849 
6850   checkClassLevelDLLAttribute(Record);
6851   checkClassLevelCodeSegAttribute(Record);
6852 
6853   bool ClangABICompat4 =
6854       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6855   TargetInfo::CallingConvKind CCK =
6856       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6857   bool CanPass = canPassInRegisters(*this, Record, CCK);
6858 
6859   // Do not change ArgPassingRestrictions if it has already been set to
6860   // APK_CanNeverPassInRegs.
6861   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6862     Record->setArgPassingRestrictions(CanPass
6863                                           ? RecordDecl::APK_CanPassInRegs
6864                                           : RecordDecl::APK_CannotPassInRegs);
6865 
6866   // If canPassInRegisters returns true despite the record having a non-trivial
6867   // destructor, the record is destructed in the callee. This happens only when
6868   // the record or one of its subobjects has a field annotated with trivial_abi
6869   // or a field qualified with ObjC __strong/__weak.
6870   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6871     Record->setParamDestroyedInCallee(true);
6872   else if (Record->hasNonTrivialDestructor())
6873     Record->setParamDestroyedInCallee(CanPass);
6874 
6875   if (getLangOpts().ForceEmitVTables) {
6876     // If we want to emit all the vtables, we need to mark it as used.  This
6877     // is especially required for cases like vtable assumption loads.
6878     MarkVTableUsed(Record->getInnerLocStart(), Record);
6879   }
6880 
6881   if (getLangOpts().CUDA) {
6882     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6883       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6884     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6885       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6886   }
6887 }
6888 
6889 /// Look up the special member function that would be called by a special
6890 /// member function for a subobject of class type.
6891 ///
6892 /// \param Class The class type of the subobject.
6893 /// \param CSM The kind of special member function.
6894 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6895 /// \param ConstRHS True if this is a copy operation with a const object
6896 ///        on its RHS, that is, if the argument to the outer special member
6897 ///        function is 'const' and this is not a field marked 'mutable'.
6898 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6899     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6900     unsigned FieldQuals, bool ConstRHS) {
6901   unsigned LHSQuals = 0;
6902   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6903     LHSQuals = FieldQuals;
6904 
6905   unsigned RHSQuals = FieldQuals;
6906   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6907     RHSQuals = 0;
6908   else if (ConstRHS)
6909     RHSQuals |= Qualifiers::Const;
6910 
6911   return S.LookupSpecialMember(Class, CSM,
6912                                RHSQuals & Qualifiers::Const,
6913                                RHSQuals & Qualifiers::Volatile,
6914                                false,
6915                                LHSQuals & Qualifiers::Const,
6916                                LHSQuals & Qualifiers::Volatile);
6917 }
6918 
6919 class Sema::InheritedConstructorInfo {
6920   Sema &S;
6921   SourceLocation UseLoc;
6922 
6923   /// A mapping from the base classes through which the constructor was
6924   /// inherited to the using shadow declaration in that base class (or a null
6925   /// pointer if the constructor was declared in that base class).
6926   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6927       InheritedFromBases;
6928 
6929 public:
6930   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6931                            ConstructorUsingShadowDecl *Shadow)
6932       : S(S), UseLoc(UseLoc) {
6933     bool DiagnosedMultipleConstructedBases = false;
6934     CXXRecordDecl *ConstructedBase = nullptr;
6935     UsingDecl *ConstructedBaseUsing = nullptr;
6936 
6937     // Find the set of such base class subobjects and check that there's a
6938     // unique constructed subobject.
6939     for (auto *D : Shadow->redecls()) {
6940       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6941       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6942       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6943 
6944       InheritedFromBases.insert(
6945           std::make_pair(DNominatedBase->getCanonicalDecl(),
6946                          DShadow->getNominatedBaseClassShadowDecl()));
6947       if (DShadow->constructsVirtualBase())
6948         InheritedFromBases.insert(
6949             std::make_pair(DConstructedBase->getCanonicalDecl(),
6950                            DShadow->getConstructedBaseClassShadowDecl()));
6951       else
6952         assert(DNominatedBase == DConstructedBase);
6953 
6954       // [class.inhctor.init]p2:
6955       //   If the constructor was inherited from multiple base class subobjects
6956       //   of type B, the program is ill-formed.
6957       if (!ConstructedBase) {
6958         ConstructedBase = DConstructedBase;
6959         ConstructedBaseUsing = D->getUsingDecl();
6960       } else if (ConstructedBase != DConstructedBase &&
6961                  !Shadow->isInvalidDecl()) {
6962         if (!DiagnosedMultipleConstructedBases) {
6963           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6964               << Shadow->getTargetDecl();
6965           S.Diag(ConstructedBaseUsing->getLocation(),
6966                diag::note_ambiguous_inherited_constructor_using)
6967               << ConstructedBase;
6968           DiagnosedMultipleConstructedBases = true;
6969         }
6970         S.Diag(D->getUsingDecl()->getLocation(),
6971                diag::note_ambiguous_inherited_constructor_using)
6972             << DConstructedBase;
6973       }
6974     }
6975 
6976     if (DiagnosedMultipleConstructedBases)
6977       Shadow->setInvalidDecl();
6978   }
6979 
6980   /// Find the constructor to use for inherited construction of a base class,
6981   /// and whether that base class constructor inherits the constructor from a
6982   /// virtual base class (in which case it won't actually invoke it).
6983   std::pair<CXXConstructorDecl *, bool>
6984   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6985     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6986     if (It == InheritedFromBases.end())
6987       return std::make_pair(nullptr, false);
6988 
6989     // This is an intermediary class.
6990     if (It->second)
6991       return std::make_pair(
6992           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6993           It->second->constructsVirtualBase());
6994 
6995     // This is the base class from which the constructor was inherited.
6996     return std::make_pair(Ctor, false);
6997   }
6998 };
6999 
7000 /// Is the special member function which would be selected to perform the
7001 /// specified operation on the specified class type a constexpr constructor?
7002 static bool
7003 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7004                          Sema::CXXSpecialMember CSM, unsigned Quals,
7005                          bool ConstRHS,
7006                          CXXConstructorDecl *InheritedCtor = nullptr,
7007                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7008   // If we're inheriting a constructor, see if we need to call it for this base
7009   // class.
7010   if (InheritedCtor) {
7011     assert(CSM == Sema::CXXDefaultConstructor);
7012     auto BaseCtor =
7013         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7014     if (BaseCtor)
7015       return BaseCtor->isConstexpr();
7016   }
7017 
7018   if (CSM == Sema::CXXDefaultConstructor)
7019     return ClassDecl->hasConstexprDefaultConstructor();
7020   if (CSM == Sema::CXXDestructor)
7021     return ClassDecl->hasConstexprDestructor();
7022 
7023   Sema::SpecialMemberOverloadResult SMOR =
7024       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7025   if (!SMOR.getMethod())
7026     // A constructor we wouldn't select can't be "involved in initializing"
7027     // anything.
7028     return true;
7029   return SMOR.getMethod()->isConstexpr();
7030 }
7031 
7032 /// Determine whether the specified special member function would be constexpr
7033 /// if it were implicitly defined.
7034 static bool defaultedSpecialMemberIsConstexpr(
7035     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7036     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7037     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7038   if (!S.getLangOpts().CPlusPlus11)
7039     return false;
7040 
7041   // C++11 [dcl.constexpr]p4:
7042   // In the definition of a constexpr constructor [...]
7043   bool Ctor = true;
7044   switch (CSM) {
7045   case Sema::CXXDefaultConstructor:
7046     if (Inherited)
7047       break;
7048     // Since default constructor lookup is essentially trivial (and cannot
7049     // involve, for instance, template instantiation), we compute whether a
7050     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7051     //
7052     // This is important for performance; we need to know whether the default
7053     // constructor is constexpr to determine whether the type is a literal type.
7054     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7055 
7056   case Sema::CXXCopyConstructor:
7057   case Sema::CXXMoveConstructor:
7058     // For copy or move constructors, we need to perform overload resolution.
7059     break;
7060 
7061   case Sema::CXXCopyAssignment:
7062   case Sema::CXXMoveAssignment:
7063     if (!S.getLangOpts().CPlusPlus14)
7064       return false;
7065     // In C++1y, we need to perform overload resolution.
7066     Ctor = false;
7067     break;
7068 
7069   case Sema::CXXDestructor:
7070     return ClassDecl->defaultedDestructorIsConstexpr();
7071 
7072   case Sema::CXXInvalid:
7073     return false;
7074   }
7075 
7076   //   -- if the class is a non-empty union, or for each non-empty anonymous
7077   //      union member of a non-union class, exactly one non-static data member
7078   //      shall be initialized; [DR1359]
7079   //
7080   // If we squint, this is guaranteed, since exactly one non-static data member
7081   // will be initialized (if the constructor isn't deleted), we just don't know
7082   // which one.
7083   if (Ctor && ClassDecl->isUnion())
7084     return CSM == Sema::CXXDefaultConstructor
7085                ? ClassDecl->hasInClassInitializer() ||
7086                      !ClassDecl->hasVariantMembers()
7087                : true;
7088 
7089   //   -- the class shall not have any virtual base classes;
7090   if (Ctor && ClassDecl->getNumVBases())
7091     return false;
7092 
7093   // C++1y [class.copy]p26:
7094   //   -- [the class] is a literal type, and
7095   if (!Ctor && !ClassDecl->isLiteral())
7096     return false;
7097 
7098   //   -- every constructor involved in initializing [...] base class
7099   //      sub-objects shall be a constexpr constructor;
7100   //   -- the assignment operator selected to copy/move each direct base
7101   //      class is a constexpr function, and
7102   for (const auto &B : ClassDecl->bases()) {
7103     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7104     if (!BaseType) continue;
7105 
7106     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7107     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7108                                   InheritedCtor, Inherited))
7109       return false;
7110   }
7111 
7112   //   -- every constructor involved in initializing non-static data members
7113   //      [...] shall be a constexpr constructor;
7114   //   -- every non-static data member and base class sub-object shall be
7115   //      initialized
7116   //   -- for each non-static data member of X that is of class type (or array
7117   //      thereof), the assignment operator selected to copy/move that member is
7118   //      a constexpr function
7119   for (const auto *F : ClassDecl->fields()) {
7120     if (F->isInvalidDecl())
7121       continue;
7122     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7123       continue;
7124     QualType BaseType = S.Context.getBaseElementType(F->getType());
7125     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7126       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7127       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7128                                     BaseType.getCVRQualifiers(),
7129                                     ConstArg && !F->isMutable()))
7130         return false;
7131     } else if (CSM == Sema::CXXDefaultConstructor) {
7132       return false;
7133     }
7134   }
7135 
7136   // All OK, it's constexpr!
7137   return true;
7138 }
7139 
7140 namespace {
7141 /// RAII object to register a defaulted function as having its exception
7142 /// specification computed.
7143 struct ComputingExceptionSpec {
7144   Sema &S;
7145 
7146   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7147       : S(S) {
7148     Sema::CodeSynthesisContext Ctx;
7149     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7150     Ctx.PointOfInstantiation = Loc;
7151     Ctx.Entity = FD;
7152     S.pushCodeSynthesisContext(Ctx);
7153   }
7154   ~ComputingExceptionSpec() {
7155     S.popCodeSynthesisContext();
7156   }
7157 };
7158 }
7159 
7160 static Sema::ImplicitExceptionSpecification
7161 ComputeDefaultedSpecialMemberExceptionSpec(
7162     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7163     Sema::InheritedConstructorInfo *ICI);
7164 
7165 static Sema::ImplicitExceptionSpecification
7166 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7167                                         FunctionDecl *FD,
7168                                         Sema::DefaultedComparisonKind DCK);
7169 
7170 static Sema::ImplicitExceptionSpecification
7171 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7172   auto DFK = S.getDefaultedFunctionKind(FD);
7173   if (DFK.isSpecialMember())
7174     return ComputeDefaultedSpecialMemberExceptionSpec(
7175         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7176   if (DFK.isComparison())
7177     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7178                                                    DFK.asComparison());
7179 
7180   auto *CD = cast<CXXConstructorDecl>(FD);
7181   assert(CD->getInheritedConstructor() &&
7182          "only defaulted functions and inherited constructors have implicit "
7183          "exception specs");
7184   Sema::InheritedConstructorInfo ICI(
7185       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7186   return ComputeDefaultedSpecialMemberExceptionSpec(
7187       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7188 }
7189 
7190 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7191                                                             CXXMethodDecl *MD) {
7192   FunctionProtoType::ExtProtoInfo EPI;
7193 
7194   // Build an exception specification pointing back at this member.
7195   EPI.ExceptionSpec.Type = EST_Unevaluated;
7196   EPI.ExceptionSpec.SourceDecl = MD;
7197 
7198   // Set the calling convention to the default for C++ instance methods.
7199   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7200       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7201                                             /*IsCXXMethod=*/true));
7202   return EPI;
7203 }
7204 
7205 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7206   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7207   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7208     return;
7209 
7210   // Evaluate the exception specification.
7211   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7212   auto ESI = IES.getExceptionSpec();
7213 
7214   // Update the type of the special member to use it.
7215   UpdateExceptionSpec(FD, ESI);
7216 }
7217 
7218 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7219   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7220 
7221   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7222   if (!DefKind) {
7223     assert(FD->getDeclContext()->isDependentContext());
7224     return;
7225   }
7226 
7227   if (DefKind.isSpecialMember()
7228           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7229                                                   DefKind.asSpecialMember())
7230           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7231     FD->setInvalidDecl();
7232 }
7233 
7234 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7235                                                  CXXSpecialMember CSM) {
7236   CXXRecordDecl *RD = MD->getParent();
7237 
7238   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7239          "not an explicitly-defaulted special member");
7240 
7241   // Defer all checking for special members of a dependent type.
7242   if (RD->isDependentType())
7243     return false;
7244 
7245   // Whether this was the first-declared instance of the constructor.
7246   // This affects whether we implicitly add an exception spec and constexpr.
7247   bool First = MD == MD->getCanonicalDecl();
7248 
7249   bool HadError = false;
7250 
7251   // C++11 [dcl.fct.def.default]p1:
7252   //   A function that is explicitly defaulted shall
7253   //     -- be a special member function [...] (checked elsewhere),
7254   //     -- have the same type (except for ref-qualifiers, and except that a
7255   //        copy operation can take a non-const reference) as an implicit
7256   //        declaration, and
7257   //     -- not have default arguments.
7258   // C++2a changes the second bullet to instead delete the function if it's
7259   // defaulted on its first declaration, unless it's "an assignment operator,
7260   // and its return type differs or its parameter type is not a reference".
7261   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7262   bool ShouldDeleteForTypeMismatch = false;
7263   unsigned ExpectedParams = 1;
7264   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7265     ExpectedParams = 0;
7266   if (MD->getNumParams() != ExpectedParams) {
7267     // This checks for default arguments: a copy or move constructor with a
7268     // default argument is classified as a default constructor, and assignment
7269     // operations and destructors can't have default arguments.
7270     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7271       << CSM << MD->getSourceRange();
7272     HadError = true;
7273   } else if (MD->isVariadic()) {
7274     if (DeleteOnTypeMismatch)
7275       ShouldDeleteForTypeMismatch = true;
7276     else {
7277       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7278         << CSM << MD->getSourceRange();
7279       HadError = true;
7280     }
7281   }
7282 
7283   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7284 
7285   bool CanHaveConstParam = false;
7286   if (CSM == CXXCopyConstructor)
7287     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7288   else if (CSM == CXXCopyAssignment)
7289     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7290 
7291   QualType ReturnType = Context.VoidTy;
7292   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7293     // Check for return type matching.
7294     ReturnType = Type->getReturnType();
7295 
7296     QualType DeclType = Context.getTypeDeclType(RD);
7297     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7298     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7299 
7300     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7301       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7302         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7303       HadError = true;
7304     }
7305 
7306     // A defaulted special member cannot have cv-qualifiers.
7307     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7308       if (DeleteOnTypeMismatch)
7309         ShouldDeleteForTypeMismatch = true;
7310       else {
7311         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7312           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7313         HadError = true;
7314       }
7315     }
7316   }
7317 
7318   // Check for parameter type matching.
7319   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7320   bool HasConstParam = false;
7321   if (ExpectedParams && ArgType->isReferenceType()) {
7322     // Argument must be reference to possibly-const T.
7323     QualType ReferentType = ArgType->getPointeeType();
7324     HasConstParam = ReferentType.isConstQualified();
7325 
7326     if (ReferentType.isVolatileQualified()) {
7327       if (DeleteOnTypeMismatch)
7328         ShouldDeleteForTypeMismatch = true;
7329       else {
7330         Diag(MD->getLocation(),
7331              diag::err_defaulted_special_member_volatile_param) << CSM;
7332         HadError = true;
7333       }
7334     }
7335 
7336     if (HasConstParam && !CanHaveConstParam) {
7337       if (DeleteOnTypeMismatch)
7338         ShouldDeleteForTypeMismatch = true;
7339       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7340         Diag(MD->getLocation(),
7341              diag::err_defaulted_special_member_copy_const_param)
7342           << (CSM == CXXCopyAssignment);
7343         // FIXME: Explain why this special member can't be const.
7344         HadError = true;
7345       } else {
7346         Diag(MD->getLocation(),
7347              diag::err_defaulted_special_member_move_const_param)
7348           << (CSM == CXXMoveAssignment);
7349         HadError = true;
7350       }
7351     }
7352   } else if (ExpectedParams) {
7353     // A copy assignment operator can take its argument by value, but a
7354     // defaulted one cannot.
7355     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7356     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7357     HadError = true;
7358   }
7359 
7360   // C++11 [dcl.fct.def.default]p2:
7361   //   An explicitly-defaulted function may be declared constexpr only if it
7362   //   would have been implicitly declared as constexpr,
7363   // Do not apply this rule to members of class templates, since core issue 1358
7364   // makes such functions always instantiate to constexpr functions. For
7365   // functions which cannot be constexpr (for non-constructors in C++11 and for
7366   // destructors in C++14 and C++17), this is checked elsewhere.
7367   //
7368   // FIXME: This should not apply if the member is deleted.
7369   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7370                                                      HasConstParam);
7371   if ((getLangOpts().CPlusPlus20 ||
7372        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7373                                   : isa<CXXConstructorDecl>(MD))) &&
7374       MD->isConstexpr() && !Constexpr &&
7375       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7376     Diag(MD->getBeginLoc(), MD->isConsteval()
7377                                 ? diag::err_incorrect_defaulted_consteval
7378                                 : diag::err_incorrect_defaulted_constexpr)
7379         << CSM;
7380     // FIXME: Explain why the special member can't be constexpr.
7381     HadError = true;
7382   }
7383 
7384   if (First) {
7385     // C++2a [dcl.fct.def.default]p3:
7386     //   If a function is explicitly defaulted on its first declaration, it is
7387     //   implicitly considered to be constexpr if the implicit declaration
7388     //   would be.
7389     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7390                                           ? ConstexprSpecKind::Consteval
7391                                           : ConstexprSpecKind::Constexpr)
7392                                    : ConstexprSpecKind::Unspecified);
7393 
7394     if (!Type->hasExceptionSpec()) {
7395       // C++2a [except.spec]p3:
7396       //   If a declaration of a function does not have a noexcept-specifier
7397       //   [and] is defaulted on its first declaration, [...] the exception
7398       //   specification is as specified below
7399       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7400       EPI.ExceptionSpec.Type = EST_Unevaluated;
7401       EPI.ExceptionSpec.SourceDecl = MD;
7402       MD->setType(Context.getFunctionType(ReturnType,
7403                                           llvm::makeArrayRef(&ArgType,
7404                                                              ExpectedParams),
7405                                           EPI));
7406     }
7407   }
7408 
7409   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7410     if (First) {
7411       SetDeclDeleted(MD, MD->getLocation());
7412       if (!inTemplateInstantiation() && !HadError) {
7413         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7414         if (ShouldDeleteForTypeMismatch) {
7415           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7416         } else {
7417           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7418         }
7419       }
7420       if (ShouldDeleteForTypeMismatch && !HadError) {
7421         Diag(MD->getLocation(),
7422              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7423       }
7424     } else {
7425       // C++11 [dcl.fct.def.default]p4:
7426       //   [For a] user-provided explicitly-defaulted function [...] if such a
7427       //   function is implicitly defined as deleted, the program is ill-formed.
7428       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7429       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7430       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7431       HadError = true;
7432     }
7433   }
7434 
7435   return HadError;
7436 }
7437 
7438 namespace {
7439 /// Helper class for building and checking a defaulted comparison.
7440 ///
7441 /// Defaulted functions are built in two phases:
7442 ///
7443 ///  * First, the set of operations that the function will perform are
7444 ///    identified, and some of them are checked. If any of the checked
7445 ///    operations is invalid in certain ways, the comparison function is
7446 ///    defined as deleted and no body is built.
7447 ///  * Then, if the function is not defined as deleted, the body is built.
7448 ///
7449 /// This is accomplished by performing two visitation steps over the eventual
7450 /// body of the function.
7451 template<typename Derived, typename ResultList, typename Result,
7452          typename Subobject>
7453 class DefaultedComparisonVisitor {
7454 public:
7455   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7456 
7457   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7458                              DefaultedComparisonKind DCK)
7459       : S(S), RD(RD), FD(FD), DCK(DCK) {
7460     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7461       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7462       // UnresolvedSet to avoid this copy.
7463       Fns.assign(Info->getUnqualifiedLookups().begin(),
7464                  Info->getUnqualifiedLookups().end());
7465     }
7466   }
7467 
7468   ResultList visit() {
7469     // The type of an lvalue naming a parameter of this function.
7470     QualType ParamLvalType =
7471         FD->getParamDecl(0)->getType().getNonReferenceType();
7472 
7473     ResultList Results;
7474 
7475     switch (DCK) {
7476     case DefaultedComparisonKind::None:
7477       llvm_unreachable("not a defaulted comparison");
7478 
7479     case DefaultedComparisonKind::Equal:
7480     case DefaultedComparisonKind::ThreeWay:
7481       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7482       return Results;
7483 
7484     case DefaultedComparisonKind::NotEqual:
7485     case DefaultedComparisonKind::Relational:
7486       Results.add(getDerived().visitExpandedSubobject(
7487           ParamLvalType, getDerived().getCompleteObject()));
7488       return Results;
7489     }
7490     llvm_unreachable("");
7491   }
7492 
7493 protected:
7494   Derived &getDerived() { return static_cast<Derived&>(*this); }
7495 
7496   /// Visit the expanded list of subobjects of the given type, as specified in
7497   /// C++2a [class.compare.default].
7498   ///
7499   /// \return \c true if the ResultList object said we're done, \c false if not.
7500   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7501                        Qualifiers Quals) {
7502     // C++2a [class.compare.default]p4:
7503     //   The direct base class subobjects of C
7504     for (CXXBaseSpecifier &Base : Record->bases())
7505       if (Results.add(getDerived().visitSubobject(
7506               S.Context.getQualifiedType(Base.getType(), Quals),
7507               getDerived().getBase(&Base))))
7508         return true;
7509 
7510     //   followed by the non-static data members of C
7511     for (FieldDecl *Field : Record->fields()) {
7512       // Recursively expand anonymous structs.
7513       if (Field->isAnonymousStructOrUnion()) {
7514         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7515                             Quals))
7516           return true;
7517         continue;
7518       }
7519 
7520       // Figure out the type of an lvalue denoting this field.
7521       Qualifiers FieldQuals = Quals;
7522       if (Field->isMutable())
7523         FieldQuals.removeConst();
7524       QualType FieldType =
7525           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7526 
7527       if (Results.add(getDerived().visitSubobject(
7528               FieldType, getDerived().getField(Field))))
7529         return true;
7530     }
7531 
7532     //   form a list of subobjects.
7533     return false;
7534   }
7535 
7536   Result visitSubobject(QualType Type, Subobject Subobj) {
7537     //   In that list, any subobject of array type is recursively expanded
7538     const ArrayType *AT = S.Context.getAsArrayType(Type);
7539     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7540       return getDerived().visitSubobjectArray(CAT->getElementType(),
7541                                               CAT->getSize(), Subobj);
7542     return getDerived().visitExpandedSubobject(Type, Subobj);
7543   }
7544 
7545   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7546                              Subobject Subobj) {
7547     return getDerived().visitSubobject(Type, Subobj);
7548   }
7549 
7550 protected:
7551   Sema &S;
7552   CXXRecordDecl *RD;
7553   FunctionDecl *FD;
7554   DefaultedComparisonKind DCK;
7555   UnresolvedSet<16> Fns;
7556 };
7557 
7558 /// Information about a defaulted comparison, as determined by
7559 /// DefaultedComparisonAnalyzer.
7560 struct DefaultedComparisonInfo {
7561   bool Deleted = false;
7562   bool Constexpr = true;
7563   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7564 
7565   static DefaultedComparisonInfo deleted() {
7566     DefaultedComparisonInfo Deleted;
7567     Deleted.Deleted = true;
7568     return Deleted;
7569   }
7570 
7571   bool add(const DefaultedComparisonInfo &R) {
7572     Deleted |= R.Deleted;
7573     Constexpr &= R.Constexpr;
7574     Category = commonComparisonType(Category, R.Category);
7575     return Deleted;
7576   }
7577 };
7578 
7579 /// An element in the expanded list of subobjects of a defaulted comparison, as
7580 /// specified in C++2a [class.compare.default]p4.
7581 struct DefaultedComparisonSubobject {
7582   enum { CompleteObject, Member, Base } Kind;
7583   NamedDecl *Decl;
7584   SourceLocation Loc;
7585 };
7586 
7587 /// A visitor over the notional body of a defaulted comparison that determines
7588 /// whether that body would be deleted or constexpr.
7589 class DefaultedComparisonAnalyzer
7590     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7591                                         DefaultedComparisonInfo,
7592                                         DefaultedComparisonInfo,
7593                                         DefaultedComparisonSubobject> {
7594 public:
7595   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7596 
7597 private:
7598   DiagnosticKind Diagnose;
7599 
7600 public:
7601   using Base = DefaultedComparisonVisitor;
7602   using Result = DefaultedComparisonInfo;
7603   using Subobject = DefaultedComparisonSubobject;
7604 
7605   friend Base;
7606 
7607   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7608                               DefaultedComparisonKind DCK,
7609                               DiagnosticKind Diagnose = NoDiagnostics)
7610       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7611 
7612   Result visit() {
7613     if ((DCK == DefaultedComparisonKind::Equal ||
7614          DCK == DefaultedComparisonKind::ThreeWay) &&
7615         RD->hasVariantMembers()) {
7616       // C++2a [class.compare.default]p2 [P2002R0]:
7617       //   A defaulted comparison operator function for class C is defined as
7618       //   deleted if [...] C has variant members.
7619       if (Diagnose == ExplainDeleted) {
7620         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7621           << FD << RD->isUnion() << RD;
7622       }
7623       return Result::deleted();
7624     }
7625 
7626     return Base::visit();
7627   }
7628 
7629 private:
7630   Subobject getCompleteObject() {
7631     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7632   }
7633 
7634   Subobject getBase(CXXBaseSpecifier *Base) {
7635     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7636                      Base->getBaseTypeLoc()};
7637   }
7638 
7639   Subobject getField(FieldDecl *Field) {
7640     return Subobject{Subobject::Member, Field, Field->getLocation()};
7641   }
7642 
7643   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7644     // C++2a [class.compare.default]p2 [P2002R0]:
7645     //   A defaulted <=> or == operator function for class C is defined as
7646     //   deleted if any non-static data member of C is of reference type
7647     if (Type->isReferenceType()) {
7648       if (Diagnose == ExplainDeleted) {
7649         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7650             << FD << RD;
7651       }
7652       return Result::deleted();
7653     }
7654 
7655     // [...] Let xi be an lvalue denoting the ith element [...]
7656     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7657     Expr *Args[] = {&Xi, &Xi};
7658 
7659     // All operators start by trying to apply that same operator recursively.
7660     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7661     assert(OO != OO_None && "not an overloaded operator!");
7662     return visitBinaryOperator(OO, Args, Subobj);
7663   }
7664 
7665   Result
7666   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7667                       Subobject Subobj,
7668                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7669     // Note that there is no need to consider rewritten candidates here if
7670     // we've already found there is no viable 'operator<=>' candidate (and are
7671     // considering synthesizing a '<=>' from '==' and '<').
7672     OverloadCandidateSet CandidateSet(
7673         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7674         OverloadCandidateSet::OperatorRewriteInfo(
7675             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7676 
7677     /// C++2a [class.compare.default]p1 [P2002R0]:
7678     ///   [...] the defaulted function itself is never a candidate for overload
7679     ///   resolution [...]
7680     CandidateSet.exclude(FD);
7681 
7682     if (Args[0]->getType()->isOverloadableType())
7683       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7684     else if (OO == OO_EqualEqual ||
7685              !Args[0]->getType()->isFunctionPointerType()) {
7686       // FIXME: We determine whether this is a valid expression by checking to
7687       // see if there's a viable builtin operator candidate for it. That isn't
7688       // really what the rules ask us to do, but should give the right results.
7689       //
7690       // Note that the builtin operator for relational comparisons on function
7691       // pointers is the only known case which cannot be used.
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).begin();
9672          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9673       NamedDecl *D = *Path.Decls;
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 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15213                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15214                                    SourceLocation Loc,
15215                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15216                                    bool AllowExplicit,
15217                                    bool IsListInitialization) {
15218   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15219   unsigned NumArgs = ArgsPtr.size();
15220   Expr **Args = ArgsPtr.data();
15221 
15222   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15223   unsigned NumParams = Proto->getNumParams();
15224 
15225   // If too few arguments are available, we'll fill in the rest with defaults.
15226   if (NumArgs < NumParams)
15227     ConvertedArgs.reserve(NumParams);
15228   else
15229     ConvertedArgs.reserve(NumArgs);
15230 
15231   VariadicCallType CallType =
15232     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15233   SmallVector<Expr *, 8> AllArgs;
15234   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15235                                         Proto, 0,
15236                                         llvm::makeArrayRef(Args, NumArgs),
15237                                         AllArgs,
15238                                         CallType, AllowExplicit,
15239                                         IsListInitialization);
15240   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15241 
15242   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15243 
15244   CheckConstructorCall(Constructor, DeclInitType,
15245                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15246                        Proto, Loc);
15247 
15248   return Invalid;
15249 }
15250 
15251 static inline bool
15252 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15253                                        const FunctionDecl *FnDecl) {
15254   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15255   if (isa<NamespaceDecl>(DC)) {
15256     return SemaRef.Diag(FnDecl->getLocation(),
15257                         diag::err_operator_new_delete_declared_in_namespace)
15258       << FnDecl->getDeclName();
15259   }
15260 
15261   if (isa<TranslationUnitDecl>(DC) &&
15262       FnDecl->getStorageClass() == SC_Static) {
15263     return SemaRef.Diag(FnDecl->getLocation(),
15264                         diag::err_operator_new_delete_declared_static)
15265       << FnDecl->getDeclName();
15266   }
15267 
15268   return false;
15269 }
15270 
15271 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15272                                              const PointerType *PtrTy) {
15273   auto &Ctx = SemaRef.Context;
15274   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15275   PtrQuals.removeAddressSpace();
15276   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15277       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15278 }
15279 
15280 static inline bool
15281 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15282                             CanQualType ExpectedResultType,
15283                             CanQualType ExpectedFirstParamType,
15284                             unsigned DependentParamTypeDiag,
15285                             unsigned InvalidParamTypeDiag) {
15286   QualType ResultType =
15287       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15288 
15289   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15290     // The operator is valid on any address space for OpenCL.
15291     // Drop address space from actual and expected result types.
15292     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15293       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15294 
15295     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15296       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15297   }
15298 
15299   // Check that the result type is what we expect.
15300   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15301     // Reject even if the type is dependent; an operator delete function is
15302     // required to have a non-dependent result type.
15303     return SemaRef.Diag(
15304                FnDecl->getLocation(),
15305                ResultType->isDependentType()
15306                    ? diag::err_operator_new_delete_dependent_result_type
15307                    : diag::err_operator_new_delete_invalid_result_type)
15308            << FnDecl->getDeclName() << ExpectedResultType;
15309   }
15310 
15311   // A function template must have at least 2 parameters.
15312   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15313     return SemaRef.Diag(FnDecl->getLocation(),
15314                       diag::err_operator_new_delete_template_too_few_parameters)
15315         << FnDecl->getDeclName();
15316 
15317   // The function decl must have at least 1 parameter.
15318   if (FnDecl->getNumParams() == 0)
15319     return SemaRef.Diag(FnDecl->getLocation(),
15320                         diag::err_operator_new_delete_too_few_parameters)
15321       << FnDecl->getDeclName();
15322 
15323   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15324   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15325     // The operator is valid on any address space for OpenCL.
15326     // Drop address space from actual and expected first parameter types.
15327     if (const auto *PtrTy =
15328             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15329       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15330 
15331     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15332       ExpectedFirstParamType =
15333           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15334   }
15335 
15336   // Check that the first parameter type is what we expect.
15337   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15338       ExpectedFirstParamType) {
15339     // The first parameter type is not allowed to be dependent. As a tentative
15340     // DR resolution, we allow a dependent parameter type if it is the right
15341     // type anyway, to allow destroying operator delete in class templates.
15342     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15343                                                    ? DependentParamTypeDiag
15344                                                    : InvalidParamTypeDiag)
15345            << FnDecl->getDeclName() << ExpectedFirstParamType;
15346   }
15347 
15348   return false;
15349 }
15350 
15351 static bool
15352 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15353   // C++ [basic.stc.dynamic.allocation]p1:
15354   //   A program is ill-formed if an allocation function is declared in a
15355   //   namespace scope other than global scope or declared static in global
15356   //   scope.
15357   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15358     return true;
15359 
15360   CanQualType SizeTy =
15361     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15362 
15363   // C++ [basic.stc.dynamic.allocation]p1:
15364   //  The return type shall be void*. The first parameter shall have type
15365   //  std::size_t.
15366   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15367                                   SizeTy,
15368                                   diag::err_operator_new_dependent_param_type,
15369                                   diag::err_operator_new_param_type))
15370     return true;
15371 
15372   // C++ [basic.stc.dynamic.allocation]p1:
15373   //  The first parameter shall not have an associated default argument.
15374   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15375     return SemaRef.Diag(FnDecl->getLocation(),
15376                         diag::err_operator_new_default_arg)
15377       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15378 
15379   return false;
15380 }
15381 
15382 static bool
15383 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15384   // C++ [basic.stc.dynamic.deallocation]p1:
15385   //   A program is ill-formed if deallocation functions are declared in a
15386   //   namespace scope other than global scope or declared static in global
15387   //   scope.
15388   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15389     return true;
15390 
15391   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15392 
15393   // C++ P0722:
15394   //   Within a class C, the first parameter of a destroying operator delete
15395   //   shall be of type C *. The first parameter of any other deallocation
15396   //   function shall be of type void *.
15397   CanQualType ExpectedFirstParamType =
15398       MD && MD->isDestroyingOperatorDelete()
15399           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15400                 SemaRef.Context.getRecordType(MD->getParent())))
15401           : SemaRef.Context.VoidPtrTy;
15402 
15403   // C++ [basic.stc.dynamic.deallocation]p2:
15404   //   Each deallocation function shall return void
15405   if (CheckOperatorNewDeleteTypes(
15406           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15407           diag::err_operator_delete_dependent_param_type,
15408           diag::err_operator_delete_param_type))
15409     return true;
15410 
15411   // C++ P0722:
15412   //   A destroying operator delete shall be a usual deallocation function.
15413   if (MD && !MD->getParent()->isDependentContext() &&
15414       MD->isDestroyingOperatorDelete() &&
15415       !SemaRef.isUsualDeallocationFunction(MD)) {
15416     SemaRef.Diag(MD->getLocation(),
15417                  diag::err_destroying_operator_delete_not_usual);
15418     return true;
15419   }
15420 
15421   return false;
15422 }
15423 
15424 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15425 /// of this overloaded operator is well-formed. If so, returns false;
15426 /// otherwise, emits appropriate diagnostics and returns true.
15427 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15428   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15429          "Expected an overloaded operator declaration");
15430 
15431   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15432 
15433   // C++ [over.oper]p5:
15434   //   The allocation and deallocation functions, operator new,
15435   //   operator new[], operator delete and operator delete[], are
15436   //   described completely in 3.7.3. The attributes and restrictions
15437   //   found in the rest of this subclause do not apply to them unless
15438   //   explicitly stated in 3.7.3.
15439   if (Op == OO_Delete || Op == OO_Array_Delete)
15440     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15441 
15442   if (Op == OO_New || Op == OO_Array_New)
15443     return CheckOperatorNewDeclaration(*this, FnDecl);
15444 
15445   // C++ [over.oper]p6:
15446   //   An operator function shall either be a non-static member
15447   //   function or be a non-member function and have at least one
15448   //   parameter whose type is a class, a reference to a class, an
15449   //   enumeration, or a reference to an enumeration.
15450   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15451     if (MethodDecl->isStatic())
15452       return Diag(FnDecl->getLocation(),
15453                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15454   } else {
15455     bool ClassOrEnumParam = false;
15456     for (auto Param : FnDecl->parameters()) {
15457       QualType ParamType = Param->getType().getNonReferenceType();
15458       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15459           ParamType->isEnumeralType()) {
15460         ClassOrEnumParam = true;
15461         break;
15462       }
15463     }
15464 
15465     if (!ClassOrEnumParam)
15466       return Diag(FnDecl->getLocation(),
15467                   diag::err_operator_overload_needs_class_or_enum)
15468         << FnDecl->getDeclName();
15469   }
15470 
15471   // C++ [over.oper]p8:
15472   //   An operator function cannot have default arguments (8.3.6),
15473   //   except where explicitly stated below.
15474   //
15475   // Only the function-call operator allows default arguments
15476   // (C++ [over.call]p1).
15477   if (Op != OO_Call) {
15478     for (auto Param : FnDecl->parameters()) {
15479       if (Param->hasDefaultArg())
15480         return Diag(Param->getLocation(),
15481                     diag::err_operator_overload_default_arg)
15482           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15483     }
15484   }
15485 
15486   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15487     { false, false, false }
15488 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15489     , { Unary, Binary, MemberOnly }
15490 #include "clang/Basic/OperatorKinds.def"
15491   };
15492 
15493   bool CanBeUnaryOperator = OperatorUses[Op][0];
15494   bool CanBeBinaryOperator = OperatorUses[Op][1];
15495   bool MustBeMemberOperator = OperatorUses[Op][2];
15496 
15497   // C++ [over.oper]p8:
15498   //   [...] Operator functions cannot have more or fewer parameters
15499   //   than the number required for the corresponding operator, as
15500   //   described in the rest of this subclause.
15501   unsigned NumParams = FnDecl->getNumParams()
15502                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15503   if (Op != OO_Call &&
15504       ((NumParams == 1 && !CanBeUnaryOperator) ||
15505        (NumParams == 2 && !CanBeBinaryOperator) ||
15506        (NumParams < 1) || (NumParams > 2))) {
15507     // We have the wrong number of parameters.
15508     unsigned ErrorKind;
15509     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15510       ErrorKind = 2;  // 2 -> unary or binary.
15511     } else if (CanBeUnaryOperator) {
15512       ErrorKind = 0;  // 0 -> unary
15513     } else {
15514       assert(CanBeBinaryOperator &&
15515              "All non-call overloaded operators are unary or binary!");
15516       ErrorKind = 1;  // 1 -> binary
15517     }
15518 
15519     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15520       << FnDecl->getDeclName() << NumParams << ErrorKind;
15521   }
15522 
15523   // Overloaded operators other than operator() cannot be variadic.
15524   if (Op != OO_Call &&
15525       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15526     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15527       << FnDecl->getDeclName();
15528   }
15529 
15530   // Some operators must be non-static member functions.
15531   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15532     return Diag(FnDecl->getLocation(),
15533                 diag::err_operator_overload_must_be_member)
15534       << FnDecl->getDeclName();
15535   }
15536 
15537   // C++ [over.inc]p1:
15538   //   The user-defined function called operator++ implements the
15539   //   prefix and postfix ++ operator. If this function is a member
15540   //   function with no parameters, or a non-member function with one
15541   //   parameter of class or enumeration type, it defines the prefix
15542   //   increment operator ++ for objects of that type. If the function
15543   //   is a member function with one parameter (which shall be of type
15544   //   int) or a non-member function with two parameters (the second
15545   //   of which shall be of type int), it defines the postfix
15546   //   increment operator ++ for objects of that type.
15547   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15548     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15549     QualType ParamType = LastParam->getType();
15550 
15551     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15552         !ParamType->isDependentType())
15553       return Diag(LastParam->getLocation(),
15554                   diag::err_operator_overload_post_incdec_must_be_int)
15555         << LastParam->getType() << (Op == OO_MinusMinus);
15556   }
15557 
15558   return false;
15559 }
15560 
15561 static bool
15562 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15563                                           FunctionTemplateDecl *TpDecl) {
15564   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15565 
15566   // Must have one or two template parameters.
15567   if (TemplateParams->size() == 1) {
15568     NonTypeTemplateParmDecl *PmDecl =
15569         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15570 
15571     // The template parameter must be a char parameter pack.
15572     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15573         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15574       return false;
15575 
15576     // C++20 [over.literal]p5:
15577     //   A string literal operator template is a literal operator template
15578     //   whose template-parameter-list comprises a single non-type
15579     //   template-parameter of class type.
15580     //
15581     // As a DR resolution, we also allow placeholders for deduced class
15582     // template specializations.
15583     if (SemaRef.getLangOpts().CPlusPlus20 &&
15584         !PmDecl->isTemplateParameterPack() &&
15585         (PmDecl->getType()->isRecordType() ||
15586          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15587       return false;
15588   } else if (TemplateParams->size() == 2) {
15589     TemplateTypeParmDecl *PmType =
15590         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15591     NonTypeTemplateParmDecl *PmArgs =
15592         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15593 
15594     // The second template parameter must be a parameter pack with the
15595     // first template parameter as its type.
15596     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15597         PmArgs->isTemplateParameterPack()) {
15598       const TemplateTypeParmType *TArgs =
15599           PmArgs->getType()->getAs<TemplateTypeParmType>();
15600       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15601           TArgs->getIndex() == PmType->getIndex()) {
15602         if (!SemaRef.inTemplateInstantiation())
15603           SemaRef.Diag(TpDecl->getLocation(),
15604                        diag::ext_string_literal_operator_template);
15605         return false;
15606       }
15607     }
15608   }
15609 
15610   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15611                diag::err_literal_operator_template)
15612       << TpDecl->getTemplateParameters()->getSourceRange();
15613   return true;
15614 }
15615 
15616 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15617 /// of this literal operator function is well-formed. If so, returns
15618 /// false; otherwise, emits appropriate diagnostics and returns true.
15619 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15620   if (isa<CXXMethodDecl>(FnDecl)) {
15621     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15622       << FnDecl->getDeclName();
15623     return true;
15624   }
15625 
15626   if (FnDecl->isExternC()) {
15627     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15628     if (const LinkageSpecDecl *LSD =
15629             FnDecl->getDeclContext()->getExternCContext())
15630       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15631     return true;
15632   }
15633 
15634   // This might be the definition of a literal operator template.
15635   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15636 
15637   // This might be a specialization of a literal operator template.
15638   if (!TpDecl)
15639     TpDecl = FnDecl->getPrimaryTemplate();
15640 
15641   // template <char...> type operator "" name() and
15642   // template <class T, T...> type operator "" name() are the only valid
15643   // template signatures, and the only valid signatures with no parameters.
15644   //
15645   // C++20 also allows template <SomeClass T> type operator "" name().
15646   if (TpDecl) {
15647     if (FnDecl->param_size() != 0) {
15648       Diag(FnDecl->getLocation(),
15649            diag::err_literal_operator_template_with_params);
15650       return true;
15651     }
15652 
15653     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15654       return true;
15655 
15656   } else if (FnDecl->param_size() == 1) {
15657     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15658 
15659     QualType ParamType = Param->getType().getUnqualifiedType();
15660 
15661     // Only unsigned long long int, long double, any character type, and const
15662     // char * are allowed as the only parameters.
15663     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15664         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15665         Context.hasSameType(ParamType, Context.CharTy) ||
15666         Context.hasSameType(ParamType, Context.WideCharTy) ||
15667         Context.hasSameType(ParamType, Context.Char8Ty) ||
15668         Context.hasSameType(ParamType, Context.Char16Ty) ||
15669         Context.hasSameType(ParamType, Context.Char32Ty)) {
15670     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15671       QualType InnerType = Ptr->getPointeeType();
15672 
15673       // Pointer parameter must be a const char *.
15674       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15675                                 Context.CharTy) &&
15676             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15677         Diag(Param->getSourceRange().getBegin(),
15678              diag::err_literal_operator_param)
15679             << ParamType << "'const char *'" << Param->getSourceRange();
15680         return true;
15681       }
15682 
15683     } else if (ParamType->isRealFloatingType()) {
15684       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15685           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15686       return true;
15687 
15688     } else if (ParamType->isIntegerType()) {
15689       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15690           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15691       return true;
15692 
15693     } else {
15694       Diag(Param->getSourceRange().getBegin(),
15695            diag::err_literal_operator_invalid_param)
15696           << ParamType << Param->getSourceRange();
15697       return true;
15698     }
15699 
15700   } else if (FnDecl->param_size() == 2) {
15701     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15702 
15703     // First, verify that the first parameter is correct.
15704 
15705     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15706 
15707     // Two parameter function must have a pointer to const as a
15708     // first parameter; let's strip those qualifiers.
15709     const PointerType *PT = FirstParamType->getAs<PointerType>();
15710 
15711     if (!PT) {
15712       Diag((*Param)->getSourceRange().getBegin(),
15713            diag::err_literal_operator_param)
15714           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15715       return true;
15716     }
15717 
15718     QualType PointeeType = PT->getPointeeType();
15719     // First parameter must be const
15720     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15721       Diag((*Param)->getSourceRange().getBegin(),
15722            diag::err_literal_operator_param)
15723           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15724       return true;
15725     }
15726 
15727     QualType InnerType = PointeeType.getUnqualifiedType();
15728     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15729     // const char32_t* are allowed as the first parameter to a two-parameter
15730     // function
15731     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15732           Context.hasSameType(InnerType, Context.WideCharTy) ||
15733           Context.hasSameType(InnerType, Context.Char8Ty) ||
15734           Context.hasSameType(InnerType, Context.Char16Ty) ||
15735           Context.hasSameType(InnerType, Context.Char32Ty))) {
15736       Diag((*Param)->getSourceRange().getBegin(),
15737            diag::err_literal_operator_param)
15738           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15739       return true;
15740     }
15741 
15742     // Move on to the second and final parameter.
15743     ++Param;
15744 
15745     // The second parameter must be a std::size_t.
15746     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15747     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15748       Diag((*Param)->getSourceRange().getBegin(),
15749            diag::err_literal_operator_param)
15750           << SecondParamType << Context.getSizeType()
15751           << (*Param)->getSourceRange();
15752       return true;
15753     }
15754   } else {
15755     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15756     return true;
15757   }
15758 
15759   // Parameters are good.
15760 
15761   // A parameter-declaration-clause containing a default argument is not
15762   // equivalent to any of the permitted forms.
15763   for (auto Param : FnDecl->parameters()) {
15764     if (Param->hasDefaultArg()) {
15765       Diag(Param->getDefaultArgRange().getBegin(),
15766            diag::err_literal_operator_default_argument)
15767         << Param->getDefaultArgRange();
15768       break;
15769     }
15770   }
15771 
15772   StringRef LiteralName
15773     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15774   if (LiteralName[0] != '_' &&
15775       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15776     // C++11 [usrlit.suffix]p1:
15777     //   Literal suffix identifiers that do not start with an underscore
15778     //   are reserved for future standardization.
15779     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15780       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15781   }
15782 
15783   return false;
15784 }
15785 
15786 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15787 /// linkage specification, including the language and (if present)
15788 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15789 /// language string literal. LBraceLoc, if valid, provides the location of
15790 /// the '{' brace. Otherwise, this linkage specification does not
15791 /// have any braces.
15792 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15793                                            Expr *LangStr,
15794                                            SourceLocation LBraceLoc) {
15795   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15796   if (!Lit->isAscii()) {
15797     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15798       << LangStr->getSourceRange();
15799     return nullptr;
15800   }
15801 
15802   StringRef Lang = Lit->getString();
15803   LinkageSpecDecl::LanguageIDs Language;
15804   if (Lang == "C")
15805     Language = LinkageSpecDecl::lang_c;
15806   else if (Lang == "C++")
15807     Language = LinkageSpecDecl::lang_cxx;
15808   else {
15809     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15810       << LangStr->getSourceRange();
15811     return nullptr;
15812   }
15813 
15814   // FIXME: Add all the various semantics of linkage specifications
15815 
15816   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15817                                                LangStr->getExprLoc(), Language,
15818                                                LBraceLoc.isValid());
15819   CurContext->addDecl(D);
15820   PushDeclContext(S, D);
15821   return D;
15822 }
15823 
15824 /// ActOnFinishLinkageSpecification - Complete the definition of
15825 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15826 /// valid, it's the position of the closing '}' brace in a linkage
15827 /// specification that uses braces.
15828 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15829                                             Decl *LinkageSpec,
15830                                             SourceLocation RBraceLoc) {
15831   if (RBraceLoc.isValid()) {
15832     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15833     LSDecl->setRBraceLoc(RBraceLoc);
15834   }
15835   PopDeclContext();
15836   return LinkageSpec;
15837 }
15838 
15839 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15840                                   const ParsedAttributesView &AttrList,
15841                                   SourceLocation SemiLoc) {
15842   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15843   // Attribute declarations appertain to empty declaration so we handle
15844   // them here.
15845   ProcessDeclAttributeList(S, ED, AttrList);
15846 
15847   CurContext->addDecl(ED);
15848   return ED;
15849 }
15850 
15851 /// Perform semantic analysis for the variable declaration that
15852 /// occurs within a C++ catch clause, returning the newly-created
15853 /// variable.
15854 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15855                                          TypeSourceInfo *TInfo,
15856                                          SourceLocation StartLoc,
15857                                          SourceLocation Loc,
15858                                          IdentifierInfo *Name) {
15859   bool Invalid = false;
15860   QualType ExDeclType = TInfo->getType();
15861 
15862   // Arrays and functions decay.
15863   if (ExDeclType->isArrayType())
15864     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15865   else if (ExDeclType->isFunctionType())
15866     ExDeclType = Context.getPointerType(ExDeclType);
15867 
15868   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15869   // The exception-declaration shall not denote a pointer or reference to an
15870   // incomplete type, other than [cv] void*.
15871   // N2844 forbids rvalue references.
15872   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15873     Diag(Loc, diag::err_catch_rvalue_ref);
15874     Invalid = true;
15875   }
15876 
15877   if (ExDeclType->isVariablyModifiedType()) {
15878     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15879     Invalid = true;
15880   }
15881 
15882   QualType BaseType = ExDeclType;
15883   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15884   unsigned DK = diag::err_catch_incomplete;
15885   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15886     BaseType = Ptr->getPointeeType();
15887     Mode = 1;
15888     DK = diag::err_catch_incomplete_ptr;
15889   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15890     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15891     BaseType = Ref->getPointeeType();
15892     Mode = 2;
15893     DK = diag::err_catch_incomplete_ref;
15894   }
15895   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15896       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15897     Invalid = true;
15898 
15899   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15900     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15901     Invalid = true;
15902   }
15903 
15904   if (!Invalid && !ExDeclType->isDependentType() &&
15905       RequireNonAbstractType(Loc, ExDeclType,
15906                              diag::err_abstract_type_in_decl,
15907                              AbstractVariableType))
15908     Invalid = true;
15909 
15910   // Only the non-fragile NeXT runtime currently supports C++ catches
15911   // of ObjC types, and no runtime supports catching ObjC types by value.
15912   if (!Invalid && getLangOpts().ObjC) {
15913     QualType T = ExDeclType;
15914     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15915       T = RT->getPointeeType();
15916 
15917     if (T->isObjCObjectType()) {
15918       Diag(Loc, diag::err_objc_object_catch);
15919       Invalid = true;
15920     } else if (T->isObjCObjectPointerType()) {
15921       // FIXME: should this be a test for macosx-fragile specifically?
15922       if (getLangOpts().ObjCRuntime.isFragile())
15923         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15924     }
15925   }
15926 
15927   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15928                                     ExDeclType, TInfo, SC_None);
15929   ExDecl->setExceptionVariable(true);
15930 
15931   // In ARC, infer 'retaining' for variables of retainable type.
15932   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15933     Invalid = true;
15934 
15935   if (!Invalid && !ExDeclType->isDependentType()) {
15936     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15937       // Insulate this from anything else we might currently be parsing.
15938       EnterExpressionEvaluationContext scope(
15939           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15940 
15941       // C++ [except.handle]p16:
15942       //   The object declared in an exception-declaration or, if the
15943       //   exception-declaration does not specify a name, a temporary (12.2) is
15944       //   copy-initialized (8.5) from the exception object. [...]
15945       //   The object is destroyed when the handler exits, after the destruction
15946       //   of any automatic objects initialized within the handler.
15947       //
15948       // We just pretend to initialize the object with itself, then make sure
15949       // it can be destroyed later.
15950       QualType initType = Context.getExceptionObjectType(ExDeclType);
15951 
15952       InitializedEntity entity =
15953         InitializedEntity::InitializeVariable(ExDecl);
15954       InitializationKind initKind =
15955         InitializationKind::CreateCopy(Loc, SourceLocation());
15956 
15957       Expr *opaqueValue =
15958         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15959       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15960       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15961       if (result.isInvalid())
15962         Invalid = true;
15963       else {
15964         // If the constructor used was non-trivial, set this as the
15965         // "initializer".
15966         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15967         if (!construct->getConstructor()->isTrivial()) {
15968           Expr *init = MaybeCreateExprWithCleanups(construct);
15969           ExDecl->setInit(init);
15970         }
15971 
15972         // And make sure it's destructable.
15973         FinalizeVarWithDestructor(ExDecl, recordType);
15974       }
15975     }
15976   }
15977 
15978   if (Invalid)
15979     ExDecl->setInvalidDecl();
15980 
15981   return ExDecl;
15982 }
15983 
15984 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15985 /// handler.
15986 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15987   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15988   bool Invalid = D.isInvalidType();
15989 
15990   // Check for unexpanded parameter packs.
15991   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15992                                       UPPC_ExceptionType)) {
15993     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15994                                              D.getIdentifierLoc());
15995     Invalid = true;
15996   }
15997 
15998   IdentifierInfo *II = D.getIdentifier();
15999   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16000                                              LookupOrdinaryName,
16001                                              ForVisibleRedeclaration)) {
16002     // The scope should be freshly made just for us. There is just no way
16003     // it contains any previous declaration, except for function parameters in
16004     // a function-try-block's catch statement.
16005     assert(!S->isDeclScope(PrevDecl));
16006     if (isDeclInScope(PrevDecl, CurContext, S)) {
16007       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16008         << D.getIdentifier();
16009       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16010       Invalid = true;
16011     } else if (PrevDecl->isTemplateParameter())
16012       // Maybe we will complain about the shadowed template parameter.
16013       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16014   }
16015 
16016   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16017     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16018       << D.getCXXScopeSpec().getRange();
16019     Invalid = true;
16020   }
16021 
16022   VarDecl *ExDecl = BuildExceptionDeclaration(
16023       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16024   if (Invalid)
16025     ExDecl->setInvalidDecl();
16026 
16027   // Add the exception declaration into this scope.
16028   if (II)
16029     PushOnScopeChains(ExDecl, S);
16030   else
16031     CurContext->addDecl(ExDecl);
16032 
16033   ProcessDeclAttributes(S, ExDecl, D);
16034   return ExDecl;
16035 }
16036 
16037 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16038                                          Expr *AssertExpr,
16039                                          Expr *AssertMessageExpr,
16040                                          SourceLocation RParenLoc) {
16041   StringLiteral *AssertMessage =
16042       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16043 
16044   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16045     return nullptr;
16046 
16047   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16048                                       AssertMessage, RParenLoc, false);
16049 }
16050 
16051 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16052                                          Expr *AssertExpr,
16053                                          StringLiteral *AssertMessage,
16054                                          SourceLocation RParenLoc,
16055                                          bool Failed) {
16056   assert(AssertExpr != nullptr && "Expected non-null condition");
16057   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16058       !Failed) {
16059     // In a static_assert-declaration, the constant-expression shall be a
16060     // constant expression that can be contextually converted to bool.
16061     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16062     if (Converted.isInvalid())
16063       Failed = true;
16064 
16065     ExprResult FullAssertExpr =
16066         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16067                             /*DiscardedValue*/ false,
16068                             /*IsConstexpr*/ true);
16069     if (FullAssertExpr.isInvalid())
16070       Failed = true;
16071     else
16072       AssertExpr = FullAssertExpr.get();
16073 
16074     llvm::APSInt Cond;
16075     if (!Failed && VerifyIntegerConstantExpression(
16076                        AssertExpr, &Cond,
16077                        diag::err_static_assert_expression_is_not_constant)
16078                        .isInvalid())
16079       Failed = true;
16080 
16081     if (!Failed && !Cond) {
16082       SmallString<256> MsgBuffer;
16083       llvm::raw_svector_ostream Msg(MsgBuffer);
16084       if (AssertMessage)
16085         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16086 
16087       Expr *InnerCond = nullptr;
16088       std::string InnerCondDescription;
16089       std::tie(InnerCond, InnerCondDescription) =
16090         findFailedBooleanCondition(Converted.get());
16091       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16092         // Drill down into concept specialization expressions to see why they
16093         // weren't satisfied.
16094         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16095           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16096         ConstraintSatisfaction Satisfaction;
16097         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16098           DiagnoseUnsatisfiedConstraint(Satisfaction);
16099       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16100                            && !isa<IntegerLiteral>(InnerCond)) {
16101         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16102           << InnerCondDescription << !AssertMessage
16103           << Msg.str() << InnerCond->getSourceRange();
16104       } else {
16105         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16106           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16107       }
16108       Failed = true;
16109     }
16110   } else {
16111     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16112                                                     /*DiscardedValue*/false,
16113                                                     /*IsConstexpr*/true);
16114     if (FullAssertExpr.isInvalid())
16115       Failed = true;
16116     else
16117       AssertExpr = FullAssertExpr.get();
16118   }
16119 
16120   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16121                                         AssertExpr, AssertMessage, RParenLoc,
16122                                         Failed);
16123 
16124   CurContext->addDecl(Decl);
16125   return Decl;
16126 }
16127 
16128 /// Perform semantic analysis of the given friend type declaration.
16129 ///
16130 /// \returns A friend declaration that.
16131 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16132                                       SourceLocation FriendLoc,
16133                                       TypeSourceInfo *TSInfo) {
16134   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16135 
16136   QualType T = TSInfo->getType();
16137   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16138 
16139   // C++03 [class.friend]p2:
16140   //   An elaborated-type-specifier shall be used in a friend declaration
16141   //   for a class.*
16142   //
16143   //   * The class-key of the elaborated-type-specifier is required.
16144   if (!CodeSynthesisContexts.empty()) {
16145     // Do not complain about the form of friend template types during any kind
16146     // of code synthesis. For template instantiation, we will have complained
16147     // when the template was defined.
16148   } else {
16149     if (!T->isElaboratedTypeSpecifier()) {
16150       // If we evaluated the type to a record type, suggest putting
16151       // a tag in front.
16152       if (const RecordType *RT = T->getAs<RecordType>()) {
16153         RecordDecl *RD = RT->getDecl();
16154 
16155         SmallString<16> InsertionText(" ");
16156         InsertionText += RD->getKindName();
16157 
16158         Diag(TypeRange.getBegin(),
16159              getLangOpts().CPlusPlus11 ?
16160                diag::warn_cxx98_compat_unelaborated_friend_type :
16161                diag::ext_unelaborated_friend_type)
16162           << (unsigned) RD->getTagKind()
16163           << T
16164           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16165                                         InsertionText);
16166       } else {
16167         Diag(FriendLoc,
16168              getLangOpts().CPlusPlus11 ?
16169                diag::warn_cxx98_compat_nonclass_type_friend :
16170                diag::ext_nonclass_type_friend)
16171           << T
16172           << TypeRange;
16173       }
16174     } else if (T->getAs<EnumType>()) {
16175       Diag(FriendLoc,
16176            getLangOpts().CPlusPlus11 ?
16177              diag::warn_cxx98_compat_enum_friend :
16178              diag::ext_enum_friend)
16179         << T
16180         << TypeRange;
16181     }
16182 
16183     // C++11 [class.friend]p3:
16184     //   A friend declaration that does not declare a function shall have one
16185     //   of the following forms:
16186     //     friend elaborated-type-specifier ;
16187     //     friend simple-type-specifier ;
16188     //     friend typename-specifier ;
16189     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16190       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16191   }
16192 
16193   //   If the type specifier in a friend declaration designates a (possibly
16194   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16195   //   the friend declaration is ignored.
16196   return FriendDecl::Create(Context, CurContext,
16197                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16198                             FriendLoc);
16199 }
16200 
16201 /// Handle a friend tag declaration where the scope specifier was
16202 /// templated.
16203 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16204                                     unsigned TagSpec, SourceLocation TagLoc,
16205                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16206                                     SourceLocation NameLoc,
16207                                     const ParsedAttributesView &Attr,
16208                                     MultiTemplateParamsArg TempParamLists) {
16209   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16210 
16211   bool IsMemberSpecialization = false;
16212   bool Invalid = false;
16213 
16214   if (TemplateParameterList *TemplateParams =
16215           MatchTemplateParametersToScopeSpecifier(
16216               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16217               IsMemberSpecialization, Invalid)) {
16218     if (TemplateParams->size() > 0) {
16219       // This is a declaration of a class template.
16220       if (Invalid)
16221         return nullptr;
16222 
16223       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16224                                 NameLoc, Attr, TemplateParams, AS_public,
16225                                 /*ModulePrivateLoc=*/SourceLocation(),
16226                                 FriendLoc, TempParamLists.size() - 1,
16227                                 TempParamLists.data()).get();
16228     } else {
16229       // The "template<>" header is extraneous.
16230       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16231         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16232       IsMemberSpecialization = true;
16233     }
16234   }
16235 
16236   if (Invalid) return nullptr;
16237 
16238   bool isAllExplicitSpecializations = true;
16239   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16240     if (TempParamLists[I]->size()) {
16241       isAllExplicitSpecializations = false;
16242       break;
16243     }
16244   }
16245 
16246   // FIXME: don't ignore attributes.
16247 
16248   // If it's explicit specializations all the way down, just forget
16249   // about the template header and build an appropriate non-templated
16250   // friend.  TODO: for source fidelity, remember the headers.
16251   if (isAllExplicitSpecializations) {
16252     if (SS.isEmpty()) {
16253       bool Owned = false;
16254       bool IsDependent = false;
16255       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16256                       Attr, AS_public,
16257                       /*ModulePrivateLoc=*/SourceLocation(),
16258                       MultiTemplateParamsArg(), Owned, IsDependent,
16259                       /*ScopedEnumKWLoc=*/SourceLocation(),
16260                       /*ScopedEnumUsesClassTag=*/false,
16261                       /*UnderlyingType=*/TypeResult(),
16262                       /*IsTypeSpecifier=*/false,
16263                       /*IsTemplateParamOrArg=*/false);
16264     }
16265 
16266     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16267     ElaboratedTypeKeyword Keyword
16268       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16269     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16270                                    *Name, NameLoc);
16271     if (T.isNull())
16272       return nullptr;
16273 
16274     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16275     if (isa<DependentNameType>(T)) {
16276       DependentNameTypeLoc TL =
16277           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16278       TL.setElaboratedKeywordLoc(TagLoc);
16279       TL.setQualifierLoc(QualifierLoc);
16280       TL.setNameLoc(NameLoc);
16281     } else {
16282       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16283       TL.setElaboratedKeywordLoc(TagLoc);
16284       TL.setQualifierLoc(QualifierLoc);
16285       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16286     }
16287 
16288     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16289                                             TSI, FriendLoc, TempParamLists);
16290     Friend->setAccess(AS_public);
16291     CurContext->addDecl(Friend);
16292     return Friend;
16293   }
16294 
16295   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16296 
16297 
16298 
16299   // Handle the case of a templated-scope friend class.  e.g.
16300   //   template <class T> class A<T>::B;
16301   // FIXME: we don't support these right now.
16302   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16303     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16304   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16305   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16306   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16307   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16308   TL.setElaboratedKeywordLoc(TagLoc);
16309   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16310   TL.setNameLoc(NameLoc);
16311 
16312   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16313                                           TSI, FriendLoc, TempParamLists);
16314   Friend->setAccess(AS_public);
16315   Friend->setUnsupportedFriend(true);
16316   CurContext->addDecl(Friend);
16317   return Friend;
16318 }
16319 
16320 /// Handle a friend type declaration.  This works in tandem with
16321 /// ActOnTag.
16322 ///
16323 /// Notes on friend class templates:
16324 ///
16325 /// We generally treat friend class declarations as if they were
16326 /// declaring a class.  So, for example, the elaborated type specifier
16327 /// in a friend declaration is required to obey the restrictions of a
16328 /// class-head (i.e. no typedefs in the scope chain), template
16329 /// parameters are required to match up with simple template-ids, &c.
16330 /// However, unlike when declaring a template specialization, it's
16331 /// okay to refer to a template specialization without an empty
16332 /// template parameter declaration, e.g.
16333 ///   friend class A<T>::B<unsigned>;
16334 /// We permit this as a special case; if there are any template
16335 /// parameters present at all, require proper matching, i.e.
16336 ///   template <> template \<class T> friend class A<int>::B;
16337 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16338                                 MultiTemplateParamsArg TempParams) {
16339   SourceLocation Loc = DS.getBeginLoc();
16340 
16341   assert(DS.isFriendSpecified());
16342   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16343 
16344   // C++ [class.friend]p3:
16345   // A friend declaration that does not declare a function shall have one of
16346   // the following forms:
16347   //     friend elaborated-type-specifier ;
16348   //     friend simple-type-specifier ;
16349   //     friend typename-specifier ;
16350   //
16351   // Any declaration with a type qualifier does not have that form. (It's
16352   // legal to specify a qualified type as a friend, you just can't write the
16353   // keywords.)
16354   if (DS.getTypeQualifiers()) {
16355     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16356       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16357     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16358       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16359     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16360       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16361     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16362       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16363     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16364       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16365   }
16366 
16367   // Try to convert the decl specifier to a type.  This works for
16368   // friend templates because ActOnTag never produces a ClassTemplateDecl
16369   // for a TUK_Friend.
16370   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16371   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16372   QualType T = TSI->getType();
16373   if (TheDeclarator.isInvalidType())
16374     return nullptr;
16375 
16376   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16377     return nullptr;
16378 
16379   // This is definitely an error in C++98.  It's probably meant to
16380   // be forbidden in C++0x, too, but the specification is just
16381   // poorly written.
16382   //
16383   // The problem is with declarations like the following:
16384   //   template <T> friend A<T>::foo;
16385   // where deciding whether a class C is a friend or not now hinges
16386   // on whether there exists an instantiation of A that causes
16387   // 'foo' to equal C.  There are restrictions on class-heads
16388   // (which we declare (by fiat) elaborated friend declarations to
16389   // be) that makes this tractable.
16390   //
16391   // FIXME: handle "template <> friend class A<T>;", which
16392   // is possibly well-formed?  Who even knows?
16393   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16394     Diag(Loc, diag::err_tagless_friend_type_template)
16395       << DS.getSourceRange();
16396     return nullptr;
16397   }
16398 
16399   // C++98 [class.friend]p1: A friend of a class is a function
16400   //   or class that is not a member of the class . . .
16401   // This is fixed in DR77, which just barely didn't make the C++03
16402   // deadline.  It's also a very silly restriction that seriously
16403   // affects inner classes and which nobody else seems to implement;
16404   // thus we never diagnose it, not even in -pedantic.
16405   //
16406   // But note that we could warn about it: it's always useless to
16407   // friend one of your own members (it's not, however, worthless to
16408   // friend a member of an arbitrary specialization of your template).
16409 
16410   Decl *D;
16411   if (!TempParams.empty())
16412     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16413                                    TempParams,
16414                                    TSI,
16415                                    DS.getFriendSpecLoc());
16416   else
16417     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16418 
16419   if (!D)
16420     return nullptr;
16421 
16422   D->setAccess(AS_public);
16423   CurContext->addDecl(D);
16424 
16425   return D;
16426 }
16427 
16428 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16429                                         MultiTemplateParamsArg TemplateParams) {
16430   const DeclSpec &DS = D.getDeclSpec();
16431 
16432   assert(DS.isFriendSpecified());
16433   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16434 
16435   SourceLocation Loc = D.getIdentifierLoc();
16436   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16437 
16438   // C++ [class.friend]p1
16439   //   A friend of a class is a function or class....
16440   // Note that this sees through typedefs, which is intended.
16441   // It *doesn't* see through dependent types, which is correct
16442   // according to [temp.arg.type]p3:
16443   //   If a declaration acquires a function type through a
16444   //   type dependent on a template-parameter and this causes
16445   //   a declaration that does not use the syntactic form of a
16446   //   function declarator to have a function type, the program
16447   //   is ill-formed.
16448   if (!TInfo->getType()->isFunctionType()) {
16449     Diag(Loc, diag::err_unexpected_friend);
16450 
16451     // It might be worthwhile to try to recover by creating an
16452     // appropriate declaration.
16453     return nullptr;
16454   }
16455 
16456   // C++ [namespace.memdef]p3
16457   //  - If a friend declaration in a non-local class first declares a
16458   //    class or function, the friend class or function is a member
16459   //    of the innermost enclosing namespace.
16460   //  - The name of the friend is not found by simple name lookup
16461   //    until a matching declaration is provided in that namespace
16462   //    scope (either before or after the class declaration granting
16463   //    friendship).
16464   //  - If a friend function is called, its name may be found by the
16465   //    name lookup that considers functions from namespaces and
16466   //    classes associated with the types of the function arguments.
16467   //  - When looking for a prior declaration of a class or a function
16468   //    declared as a friend, scopes outside the innermost enclosing
16469   //    namespace scope are not considered.
16470 
16471   CXXScopeSpec &SS = D.getCXXScopeSpec();
16472   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16473   assert(NameInfo.getName());
16474 
16475   // Check for unexpanded parameter packs.
16476   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16477       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16478       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16479     return nullptr;
16480 
16481   // The context we found the declaration in, or in which we should
16482   // create the declaration.
16483   DeclContext *DC;
16484   Scope *DCScope = S;
16485   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16486                         ForExternalRedeclaration);
16487 
16488   // There are five cases here.
16489   //   - There's no scope specifier and we're in a local class. Only look
16490   //     for functions declared in the immediately-enclosing block scope.
16491   // We recover from invalid scope qualifiers as if they just weren't there.
16492   FunctionDecl *FunctionContainingLocalClass = nullptr;
16493   if ((SS.isInvalid() || !SS.isSet()) &&
16494       (FunctionContainingLocalClass =
16495            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16496     // C++11 [class.friend]p11:
16497     //   If a friend declaration appears in a local class and the name
16498     //   specified is an unqualified name, a prior declaration is
16499     //   looked up without considering scopes that are outside the
16500     //   innermost enclosing non-class scope. For a friend function
16501     //   declaration, if there is no prior declaration, the program is
16502     //   ill-formed.
16503 
16504     // Find the innermost enclosing non-class scope. This is the block
16505     // scope containing the local class definition (or for a nested class,
16506     // the outer local class).
16507     DCScope = S->getFnParent();
16508 
16509     // Look up the function name in the scope.
16510     Previous.clear(LookupLocalFriendName);
16511     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16512 
16513     if (!Previous.empty()) {
16514       // All possible previous declarations must have the same context:
16515       // either they were declared at block scope or they are members of
16516       // one of the enclosing local classes.
16517       DC = Previous.getRepresentativeDecl()->getDeclContext();
16518     } else {
16519       // This is ill-formed, but provide the context that we would have
16520       // declared the function in, if we were permitted to, for error recovery.
16521       DC = FunctionContainingLocalClass;
16522     }
16523     adjustContextForLocalExternDecl(DC);
16524 
16525     // C++ [class.friend]p6:
16526     //   A function can be defined in a friend declaration of a class if and
16527     //   only if the class is a non-local class (9.8), the function name is
16528     //   unqualified, and the function has namespace scope.
16529     if (D.isFunctionDefinition()) {
16530       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16531     }
16532 
16533   //   - There's no scope specifier, in which case we just go to the
16534   //     appropriate scope and look for a function or function template
16535   //     there as appropriate.
16536   } else if (SS.isInvalid() || !SS.isSet()) {
16537     // C++11 [namespace.memdef]p3:
16538     //   If the name in a friend declaration is neither qualified nor
16539     //   a template-id and the declaration is a function or an
16540     //   elaborated-type-specifier, the lookup to determine whether
16541     //   the entity has been previously declared shall not consider
16542     //   any scopes outside the innermost enclosing namespace.
16543     bool isTemplateId =
16544         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16545 
16546     // Find the appropriate context according to the above.
16547     DC = CurContext;
16548 
16549     // Skip class contexts.  If someone can cite chapter and verse
16550     // for this behavior, that would be nice --- it's what GCC and
16551     // EDG do, and it seems like a reasonable intent, but the spec
16552     // really only says that checks for unqualified existing
16553     // declarations should stop at the nearest enclosing namespace,
16554     // not that they should only consider the nearest enclosing
16555     // namespace.
16556     while (DC->isRecord())
16557       DC = DC->getParent();
16558 
16559     DeclContext *LookupDC = DC;
16560     while (LookupDC->isTransparentContext())
16561       LookupDC = LookupDC->getParent();
16562 
16563     while (true) {
16564       LookupQualifiedName(Previous, LookupDC);
16565 
16566       if (!Previous.empty()) {
16567         DC = LookupDC;
16568         break;
16569       }
16570 
16571       if (isTemplateId) {
16572         if (isa<TranslationUnitDecl>(LookupDC)) break;
16573       } else {
16574         if (LookupDC->isFileContext()) break;
16575       }
16576       LookupDC = LookupDC->getParent();
16577     }
16578 
16579     DCScope = getScopeForDeclContext(S, DC);
16580 
16581   //   - There's a non-dependent scope specifier, in which case we
16582   //     compute it and do a previous lookup there for a function
16583   //     or function template.
16584   } else if (!SS.getScopeRep()->isDependent()) {
16585     DC = computeDeclContext(SS);
16586     if (!DC) return nullptr;
16587 
16588     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16589 
16590     LookupQualifiedName(Previous, DC);
16591 
16592     // C++ [class.friend]p1: A friend of a class is a function or
16593     //   class that is not a member of the class . . .
16594     if (DC->Equals(CurContext))
16595       Diag(DS.getFriendSpecLoc(),
16596            getLangOpts().CPlusPlus11 ?
16597              diag::warn_cxx98_compat_friend_is_member :
16598              diag::err_friend_is_member);
16599 
16600     if (D.isFunctionDefinition()) {
16601       // C++ [class.friend]p6:
16602       //   A function can be defined in a friend declaration of a class if and
16603       //   only if the class is a non-local class (9.8), the function name is
16604       //   unqualified, and the function has namespace scope.
16605       //
16606       // FIXME: We should only do this if the scope specifier names the
16607       // innermost enclosing namespace; otherwise the fixit changes the
16608       // meaning of the code.
16609       SemaDiagnosticBuilder DB
16610         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16611 
16612       DB << SS.getScopeRep();
16613       if (DC->isFileContext())
16614         DB << FixItHint::CreateRemoval(SS.getRange());
16615       SS.clear();
16616     }
16617 
16618   //   - There's a scope specifier that does not match any template
16619   //     parameter lists, in which case we use some arbitrary context,
16620   //     create a method or method template, and wait for instantiation.
16621   //   - There's a scope specifier that does match some template
16622   //     parameter lists, which we don't handle right now.
16623   } else {
16624     if (D.isFunctionDefinition()) {
16625       // C++ [class.friend]p6:
16626       //   A function can be defined in a friend declaration of a class if and
16627       //   only if the class is a non-local class (9.8), the function name is
16628       //   unqualified, and the function has namespace scope.
16629       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16630         << SS.getScopeRep();
16631     }
16632 
16633     DC = CurContext;
16634     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16635   }
16636 
16637   if (!DC->isRecord()) {
16638     int DiagArg = -1;
16639     switch (D.getName().getKind()) {
16640     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16641     case UnqualifiedIdKind::IK_ConstructorName:
16642       DiagArg = 0;
16643       break;
16644     case UnqualifiedIdKind::IK_DestructorName:
16645       DiagArg = 1;
16646       break;
16647     case UnqualifiedIdKind::IK_ConversionFunctionId:
16648       DiagArg = 2;
16649       break;
16650     case UnqualifiedIdKind::IK_DeductionGuideName:
16651       DiagArg = 3;
16652       break;
16653     case UnqualifiedIdKind::IK_Identifier:
16654     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16655     case UnqualifiedIdKind::IK_LiteralOperatorId:
16656     case UnqualifiedIdKind::IK_OperatorFunctionId:
16657     case UnqualifiedIdKind::IK_TemplateId:
16658       break;
16659     }
16660     // This implies that it has to be an operator or function.
16661     if (DiagArg >= 0) {
16662       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16663       return nullptr;
16664     }
16665   }
16666 
16667   // FIXME: This is an egregious hack to cope with cases where the scope stack
16668   // does not contain the declaration context, i.e., in an out-of-line
16669   // definition of a class.
16670   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16671   if (!DCScope) {
16672     FakeDCScope.setEntity(DC);
16673     DCScope = &FakeDCScope;
16674   }
16675 
16676   bool AddToScope = true;
16677   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16678                                           TemplateParams, AddToScope);
16679   if (!ND) return nullptr;
16680 
16681   assert(ND->getLexicalDeclContext() == CurContext);
16682 
16683   // If we performed typo correction, we might have added a scope specifier
16684   // and changed the decl context.
16685   DC = ND->getDeclContext();
16686 
16687   // Add the function declaration to the appropriate lookup tables,
16688   // adjusting the redeclarations list as necessary.  We don't
16689   // want to do this yet if the friending class is dependent.
16690   //
16691   // Also update the scope-based lookup if the target context's
16692   // lookup context is in lexical scope.
16693   if (!CurContext->isDependentContext()) {
16694     DC = DC->getRedeclContext();
16695     DC->makeDeclVisibleInContext(ND);
16696     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16697       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16698   }
16699 
16700   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16701                                        D.getIdentifierLoc(), ND,
16702                                        DS.getFriendSpecLoc());
16703   FrD->setAccess(AS_public);
16704   CurContext->addDecl(FrD);
16705 
16706   if (ND->isInvalidDecl()) {
16707     FrD->setInvalidDecl();
16708   } else {
16709     if (DC->isRecord()) CheckFriendAccess(ND);
16710 
16711     FunctionDecl *FD;
16712     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16713       FD = FTD->getTemplatedDecl();
16714     else
16715       FD = cast<FunctionDecl>(ND);
16716 
16717     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16718     // default argument expression, that declaration shall be a definition
16719     // and shall be the only declaration of the function or function
16720     // template in the translation unit.
16721     if (functionDeclHasDefaultArgument(FD)) {
16722       // We can't look at FD->getPreviousDecl() because it may not have been set
16723       // if we're in a dependent context. If the function is known to be a
16724       // redeclaration, we will have narrowed Previous down to the right decl.
16725       if (D.isRedeclaration()) {
16726         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16727         Diag(Previous.getRepresentativeDecl()->getLocation(),
16728              diag::note_previous_declaration);
16729       } else if (!D.isFunctionDefinition())
16730         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16731     }
16732 
16733     // Mark templated-scope function declarations as unsupported.
16734     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16735       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16736         << SS.getScopeRep() << SS.getRange()
16737         << cast<CXXRecordDecl>(CurContext);
16738       FrD->setUnsupportedFriend(true);
16739     }
16740   }
16741 
16742   return ND;
16743 }
16744 
16745 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16746   AdjustDeclIfTemplate(Dcl);
16747 
16748   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16749   if (!Fn) {
16750     Diag(DelLoc, diag::err_deleted_non_function);
16751     return;
16752   }
16753 
16754   // Deleted function does not have a body.
16755   Fn->setWillHaveBody(false);
16756 
16757   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16758     // Don't consider the implicit declaration we generate for explicit
16759     // specializations. FIXME: Do not generate these implicit declarations.
16760     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16761          Prev->getPreviousDecl()) &&
16762         !Prev->isDefined()) {
16763       Diag(DelLoc, diag::err_deleted_decl_not_first);
16764       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16765            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16766                               : diag::note_previous_declaration);
16767       // We can't recover from this; the declaration might have already
16768       // been used.
16769       Fn->setInvalidDecl();
16770       return;
16771     }
16772 
16773     // To maintain the invariant that functions are only deleted on their first
16774     // declaration, mark the implicitly-instantiated declaration of the
16775     // explicitly-specialized function as deleted instead of marking the
16776     // instantiated redeclaration.
16777     Fn = Fn->getCanonicalDecl();
16778   }
16779 
16780   // dllimport/dllexport cannot be deleted.
16781   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16782     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16783     Fn->setInvalidDecl();
16784   }
16785 
16786   // C++11 [basic.start.main]p3:
16787   //   A program that defines main as deleted [...] is ill-formed.
16788   if (Fn->isMain())
16789     Diag(DelLoc, diag::err_deleted_main);
16790 
16791   // C++11 [dcl.fct.def.delete]p4:
16792   //  A deleted function is implicitly inline.
16793   Fn->setImplicitlyInline();
16794   Fn->setDeletedAsWritten();
16795 }
16796 
16797 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16798   if (!Dcl || Dcl->isInvalidDecl())
16799     return;
16800 
16801   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16802   if (!FD) {
16803     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16804       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16805         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16806         return;
16807       }
16808     }
16809 
16810     Diag(DefaultLoc, diag::err_default_special_members)
16811         << getLangOpts().CPlusPlus20;
16812     return;
16813   }
16814 
16815   // Reject if this can't possibly be a defaultable function.
16816   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16817   if (!DefKind &&
16818       // A dependent function that doesn't locally look defaultable can
16819       // still instantiate to a defaultable function if it's a constructor
16820       // or assignment operator.
16821       (!FD->isDependentContext() ||
16822        (!isa<CXXConstructorDecl>(FD) &&
16823         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16824     Diag(DefaultLoc, diag::err_default_special_members)
16825         << getLangOpts().CPlusPlus20;
16826     return;
16827   }
16828 
16829   if (DefKind.isComparison() &&
16830       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16831     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16832         << (int)DefKind.asComparison();
16833     return;
16834   }
16835 
16836   // Issue compatibility warning. We already warned if the operator is
16837   // 'operator<=>' when parsing the '<=>' token.
16838   if (DefKind.isComparison() &&
16839       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16840     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16841                          ? diag::warn_cxx17_compat_defaulted_comparison
16842                          : diag::ext_defaulted_comparison);
16843   }
16844 
16845   FD->setDefaulted();
16846   FD->setExplicitlyDefaulted();
16847 
16848   // Defer checking functions that are defaulted in a dependent context.
16849   if (FD->isDependentContext())
16850     return;
16851 
16852   // Unset that we will have a body for this function. We might not,
16853   // if it turns out to be trivial, and we don't need this marking now
16854   // that we've marked it as defaulted.
16855   FD->setWillHaveBody(false);
16856 
16857   // If this definition appears within the record, do the checking when
16858   // the record is complete. This is always the case for a defaulted
16859   // comparison.
16860   if (DefKind.isComparison())
16861     return;
16862   auto *MD = cast<CXXMethodDecl>(FD);
16863 
16864   const FunctionDecl *Primary = FD;
16865   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16866     // Ask the template instantiation pattern that actually had the
16867     // '= default' on it.
16868     Primary = Pattern;
16869 
16870   // If the method was defaulted on its first declaration, we will have
16871   // already performed the checking in CheckCompletedCXXClass. Such a
16872   // declaration doesn't trigger an implicit definition.
16873   if (Primary->getCanonicalDecl()->isDefaulted())
16874     return;
16875 
16876   // FIXME: Once we support defining comparisons out of class, check for a
16877   // defaulted comparison here.
16878   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16879     MD->setInvalidDecl();
16880   else
16881     DefineDefaultedFunction(*this, MD, DefaultLoc);
16882 }
16883 
16884 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16885   for (Stmt *SubStmt : S->children()) {
16886     if (!SubStmt)
16887       continue;
16888     if (isa<ReturnStmt>(SubStmt))
16889       Self.Diag(SubStmt->getBeginLoc(),
16890                 diag::err_return_in_constructor_handler);
16891     if (!isa<Expr>(SubStmt))
16892       SearchForReturnInStmt(Self, SubStmt);
16893   }
16894 }
16895 
16896 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16897   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16898     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16899     SearchForReturnInStmt(*this, Handler);
16900   }
16901 }
16902 
16903 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16904                                              const CXXMethodDecl *Old) {
16905   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16906   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16907 
16908   if (OldFT->hasExtParameterInfos()) {
16909     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16910       // A parameter of the overriding method should be annotated with noescape
16911       // if the corresponding parameter of the overridden method is annotated.
16912       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16913           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16914         Diag(New->getParamDecl(I)->getLocation(),
16915              diag::warn_overriding_method_missing_noescape);
16916         Diag(Old->getParamDecl(I)->getLocation(),
16917              diag::note_overridden_marked_noescape);
16918       }
16919   }
16920 
16921   // Virtual overrides must have the same code_seg.
16922   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16923   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16924   if ((NewCSA || OldCSA) &&
16925       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16926     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16927     Diag(Old->getLocation(), diag::note_previous_declaration);
16928     return true;
16929   }
16930 
16931   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16932 
16933   // If the calling conventions match, everything is fine
16934   if (NewCC == OldCC)
16935     return false;
16936 
16937   // If the calling conventions mismatch because the new function is static,
16938   // suppress the calling convention mismatch error; the error about static
16939   // function override (err_static_overrides_virtual from
16940   // Sema::CheckFunctionDeclaration) is more clear.
16941   if (New->getStorageClass() == SC_Static)
16942     return false;
16943 
16944   Diag(New->getLocation(),
16945        diag::err_conflicting_overriding_cc_attributes)
16946     << New->getDeclName() << New->getType() << Old->getType();
16947   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16948   return true;
16949 }
16950 
16951 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16952                                              const CXXMethodDecl *Old) {
16953   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16954   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16955 
16956   if (Context.hasSameType(NewTy, OldTy) ||
16957       NewTy->isDependentType() || OldTy->isDependentType())
16958     return false;
16959 
16960   // Check if the return types are covariant
16961   QualType NewClassTy, OldClassTy;
16962 
16963   /// Both types must be pointers or references to classes.
16964   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16965     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16966       NewClassTy = NewPT->getPointeeType();
16967       OldClassTy = OldPT->getPointeeType();
16968     }
16969   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16970     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16971       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16972         NewClassTy = NewRT->getPointeeType();
16973         OldClassTy = OldRT->getPointeeType();
16974       }
16975     }
16976   }
16977 
16978   // The return types aren't either both pointers or references to a class type.
16979   if (NewClassTy.isNull()) {
16980     Diag(New->getLocation(),
16981          diag::err_different_return_type_for_overriding_virtual_function)
16982         << New->getDeclName() << NewTy << OldTy
16983         << New->getReturnTypeSourceRange();
16984     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16985         << Old->getReturnTypeSourceRange();
16986 
16987     return true;
16988   }
16989 
16990   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16991     // C++14 [class.virtual]p8:
16992     //   If the class type in the covariant return type of D::f differs from
16993     //   that of B::f, the class type in the return type of D::f shall be
16994     //   complete at the point of declaration of D::f or shall be the class
16995     //   type D.
16996     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16997       if (!RT->isBeingDefined() &&
16998           RequireCompleteType(New->getLocation(), NewClassTy,
16999                               diag::err_covariant_return_incomplete,
17000                               New->getDeclName()))
17001         return true;
17002     }
17003 
17004     // Check if the new class derives from the old class.
17005     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17006       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17007           << New->getDeclName() << NewTy << OldTy
17008           << New->getReturnTypeSourceRange();
17009       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17010           << Old->getReturnTypeSourceRange();
17011       return true;
17012     }
17013 
17014     // Check if we the conversion from derived to base is valid.
17015     if (CheckDerivedToBaseConversion(
17016             NewClassTy, OldClassTy,
17017             diag::err_covariant_return_inaccessible_base,
17018             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17019             New->getLocation(), New->getReturnTypeSourceRange(),
17020             New->getDeclName(), nullptr)) {
17021       // FIXME: this note won't trigger for delayed access control
17022       // diagnostics, and it's impossible to get an undelayed error
17023       // here from access control during the original parse because
17024       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17025       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17026           << Old->getReturnTypeSourceRange();
17027       return true;
17028     }
17029   }
17030 
17031   // The qualifiers of the return types must be the same.
17032   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17033     Diag(New->getLocation(),
17034          diag::err_covariant_return_type_different_qualifications)
17035         << New->getDeclName() << NewTy << OldTy
17036         << New->getReturnTypeSourceRange();
17037     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17038         << Old->getReturnTypeSourceRange();
17039     return true;
17040   }
17041 
17042 
17043   // The new class type must have the same or less qualifiers as the old type.
17044   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17045     Diag(New->getLocation(),
17046          diag::err_covariant_return_type_class_type_more_qualified)
17047         << New->getDeclName() << NewTy << OldTy
17048         << New->getReturnTypeSourceRange();
17049     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17050         << Old->getReturnTypeSourceRange();
17051     return true;
17052   }
17053 
17054   return false;
17055 }
17056 
17057 /// Mark the given method pure.
17058 ///
17059 /// \param Method the method to be marked pure.
17060 ///
17061 /// \param InitRange the source range that covers the "0" initializer.
17062 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17063   SourceLocation EndLoc = InitRange.getEnd();
17064   if (EndLoc.isValid())
17065     Method->setRangeEnd(EndLoc);
17066 
17067   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17068     Method->setPure();
17069     return false;
17070   }
17071 
17072   if (!Method->isInvalidDecl())
17073     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17074       << Method->getDeclName() << InitRange;
17075   return true;
17076 }
17077 
17078 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17079   if (D->getFriendObjectKind())
17080     Diag(D->getLocation(), diag::err_pure_friend);
17081   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17082     CheckPureMethod(M, ZeroLoc);
17083   else
17084     Diag(D->getLocation(), diag::err_illegal_initializer);
17085 }
17086 
17087 /// Determine whether the given declaration is a global variable or
17088 /// static data member.
17089 static bool isNonlocalVariable(const Decl *D) {
17090   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17091     return Var->hasGlobalStorage();
17092 
17093   return false;
17094 }
17095 
17096 /// Invoked when we are about to parse an initializer for the declaration
17097 /// 'Dcl'.
17098 ///
17099 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17100 /// static data member of class X, names should be looked up in the scope of
17101 /// class X. If the declaration had a scope specifier, a scope will have
17102 /// been created and passed in for this purpose. Otherwise, S will be null.
17103 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17104   // If there is no declaration, there was an error parsing it.
17105   if (!D || D->isInvalidDecl())
17106     return;
17107 
17108   // We will always have a nested name specifier here, but this declaration
17109   // might not be out of line if the specifier names the current namespace:
17110   //   extern int n;
17111   //   int ::n = 0;
17112   if (S && D->isOutOfLine())
17113     EnterDeclaratorContext(S, D->getDeclContext());
17114 
17115   // If we are parsing the initializer for a static data member, push a
17116   // new expression evaluation context that is associated with this static
17117   // data member.
17118   if (isNonlocalVariable(D))
17119     PushExpressionEvaluationContext(
17120         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17121 }
17122 
17123 /// Invoked after we are finished parsing an initializer for the declaration D.
17124 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17125   // If there is no declaration, there was an error parsing it.
17126   if (!D || D->isInvalidDecl())
17127     return;
17128 
17129   if (isNonlocalVariable(D))
17130     PopExpressionEvaluationContext();
17131 
17132   if (S && D->isOutOfLine())
17133     ExitDeclaratorContext(S);
17134 }
17135 
17136 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17137 /// C++ if/switch/while/for statement.
17138 /// e.g: "if (int x = f()) {...}"
17139 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17140   // C++ 6.4p2:
17141   // The declarator shall not specify a function or an array.
17142   // The type-specifier-seq shall not contain typedef and shall not declare a
17143   // new class or enumeration.
17144   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17145          "Parser allowed 'typedef' as storage class of condition decl.");
17146 
17147   Decl *Dcl = ActOnDeclarator(S, D);
17148   if (!Dcl)
17149     return true;
17150 
17151   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17152     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17153       << D.getSourceRange();
17154     return true;
17155   }
17156 
17157   return Dcl;
17158 }
17159 
17160 void Sema::LoadExternalVTableUses() {
17161   if (!ExternalSource)
17162     return;
17163 
17164   SmallVector<ExternalVTableUse, 4> VTables;
17165   ExternalSource->ReadUsedVTables(VTables);
17166   SmallVector<VTableUse, 4> NewUses;
17167   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17168     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17169       = VTablesUsed.find(VTables[I].Record);
17170     // Even if a definition wasn't required before, it may be required now.
17171     if (Pos != VTablesUsed.end()) {
17172       if (!Pos->second && VTables[I].DefinitionRequired)
17173         Pos->second = true;
17174       continue;
17175     }
17176 
17177     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17178     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17179   }
17180 
17181   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17182 }
17183 
17184 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17185                           bool DefinitionRequired) {
17186   // Ignore any vtable uses in unevaluated operands or for classes that do
17187   // not have a vtable.
17188   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17189       CurContext->isDependentContext() || isUnevaluatedContext())
17190     return;
17191   // Do not mark as used if compiling for the device outside of the target
17192   // region.
17193   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17194       !isInOpenMPDeclareTargetContext() &&
17195       !isInOpenMPTargetExecutionDirective()) {
17196     if (!DefinitionRequired)
17197       MarkVirtualMembersReferenced(Loc, Class);
17198     return;
17199   }
17200 
17201   // Try to insert this class into the map.
17202   LoadExternalVTableUses();
17203   Class = Class->getCanonicalDecl();
17204   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17205     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17206   if (!Pos.second) {
17207     // If we already had an entry, check to see if we are promoting this vtable
17208     // to require a definition. If so, we need to reappend to the VTableUses
17209     // list, since we may have already processed the first entry.
17210     if (DefinitionRequired && !Pos.first->second) {
17211       Pos.first->second = true;
17212     } else {
17213       // Otherwise, we can early exit.
17214       return;
17215     }
17216   } else {
17217     // The Microsoft ABI requires that we perform the destructor body
17218     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17219     // the deleting destructor is emitted with the vtable, not with the
17220     // destructor definition as in the Itanium ABI.
17221     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17222       CXXDestructorDecl *DD = Class->getDestructor();
17223       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17224         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17225           // If this is an out-of-line declaration, marking it referenced will
17226           // not do anything. Manually call CheckDestructor to look up operator
17227           // delete().
17228           ContextRAII SavedContext(*this, DD);
17229           CheckDestructor(DD);
17230         } else {
17231           MarkFunctionReferenced(Loc, Class->getDestructor());
17232         }
17233       }
17234     }
17235   }
17236 
17237   // Local classes need to have their virtual members marked
17238   // immediately. For all other classes, we mark their virtual members
17239   // at the end of the translation unit.
17240   if (Class->isLocalClass())
17241     MarkVirtualMembersReferenced(Loc, Class);
17242   else
17243     VTableUses.push_back(std::make_pair(Class, Loc));
17244 }
17245 
17246 bool Sema::DefineUsedVTables() {
17247   LoadExternalVTableUses();
17248   if (VTableUses.empty())
17249     return false;
17250 
17251   // Note: The VTableUses vector could grow as a result of marking
17252   // the members of a class as "used", so we check the size each
17253   // time through the loop and prefer indices (which are stable) to
17254   // iterators (which are not).
17255   bool DefinedAnything = false;
17256   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17257     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17258     if (!Class)
17259       continue;
17260     TemplateSpecializationKind ClassTSK =
17261         Class->getTemplateSpecializationKind();
17262 
17263     SourceLocation Loc = VTableUses[I].second;
17264 
17265     bool DefineVTable = true;
17266 
17267     // If this class has a key function, but that key function is
17268     // defined in another translation unit, we don't need to emit the
17269     // vtable even though we're using it.
17270     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17271     if (KeyFunction && !KeyFunction->hasBody()) {
17272       // The key function is in another translation unit.
17273       DefineVTable = false;
17274       TemplateSpecializationKind TSK =
17275           KeyFunction->getTemplateSpecializationKind();
17276       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17277              TSK != TSK_ImplicitInstantiation &&
17278              "Instantiations don't have key functions");
17279       (void)TSK;
17280     } else if (!KeyFunction) {
17281       // If we have a class with no key function that is the subject
17282       // of an explicit instantiation declaration, suppress the
17283       // vtable; it will live with the explicit instantiation
17284       // definition.
17285       bool IsExplicitInstantiationDeclaration =
17286           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17287       for (auto R : Class->redecls()) {
17288         TemplateSpecializationKind TSK
17289           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17290         if (TSK == TSK_ExplicitInstantiationDeclaration)
17291           IsExplicitInstantiationDeclaration = true;
17292         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17293           IsExplicitInstantiationDeclaration = false;
17294           break;
17295         }
17296       }
17297 
17298       if (IsExplicitInstantiationDeclaration)
17299         DefineVTable = false;
17300     }
17301 
17302     // The exception specifications for all virtual members may be needed even
17303     // if we are not providing an authoritative form of the vtable in this TU.
17304     // We may choose to emit it available_externally anyway.
17305     if (!DefineVTable) {
17306       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17307       continue;
17308     }
17309 
17310     // Mark all of the virtual members of this class as referenced, so
17311     // that we can build a vtable. Then, tell the AST consumer that a
17312     // vtable for this class is required.
17313     DefinedAnything = true;
17314     MarkVirtualMembersReferenced(Loc, Class);
17315     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17316     if (VTablesUsed[Canonical])
17317       Consumer.HandleVTable(Class);
17318 
17319     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17320     // no key function or the key function is inlined. Don't warn in C++ ABIs
17321     // that lack key functions, since the user won't be able to make one.
17322     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17323         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17324       const FunctionDecl *KeyFunctionDef = nullptr;
17325       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17326                            KeyFunctionDef->isInlined())) {
17327         Diag(Class->getLocation(),
17328              ClassTSK == TSK_ExplicitInstantiationDefinition
17329                  ? diag::warn_weak_template_vtable
17330                  : diag::warn_weak_vtable)
17331             << Class;
17332       }
17333     }
17334   }
17335   VTableUses.clear();
17336 
17337   return DefinedAnything;
17338 }
17339 
17340 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17341                                                  const CXXRecordDecl *RD) {
17342   for (const auto *I : RD->methods())
17343     if (I->isVirtual() && !I->isPure())
17344       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17345 }
17346 
17347 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17348                                         const CXXRecordDecl *RD,
17349                                         bool ConstexprOnly) {
17350   // Mark all functions which will appear in RD's vtable as used.
17351   CXXFinalOverriderMap FinalOverriders;
17352   RD->getFinalOverriders(FinalOverriders);
17353   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17354                                             E = FinalOverriders.end();
17355        I != E; ++I) {
17356     for (OverridingMethods::const_iterator OI = I->second.begin(),
17357                                            OE = I->second.end();
17358          OI != OE; ++OI) {
17359       assert(OI->second.size() > 0 && "no final overrider");
17360       CXXMethodDecl *Overrider = OI->second.front().Method;
17361 
17362       // C++ [basic.def.odr]p2:
17363       //   [...] A virtual member function is used if it is not pure. [...]
17364       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17365         MarkFunctionReferenced(Loc, Overrider);
17366     }
17367   }
17368 
17369   // Only classes that have virtual bases need a VTT.
17370   if (RD->getNumVBases() == 0)
17371     return;
17372 
17373   for (const auto &I : RD->bases()) {
17374     const auto *Base =
17375         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17376     if (Base->getNumVBases() == 0)
17377       continue;
17378     MarkVirtualMembersReferenced(Loc, Base);
17379   }
17380 }
17381 
17382 /// SetIvarInitializers - This routine builds initialization ASTs for the
17383 /// Objective-C implementation whose ivars need be initialized.
17384 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17385   if (!getLangOpts().CPlusPlus)
17386     return;
17387   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17388     SmallVector<ObjCIvarDecl*, 8> ivars;
17389     CollectIvarsToConstructOrDestruct(OID, ivars);
17390     if (ivars.empty())
17391       return;
17392     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17393     for (unsigned i = 0; i < ivars.size(); i++) {
17394       FieldDecl *Field = ivars[i];
17395       if (Field->isInvalidDecl())
17396         continue;
17397 
17398       CXXCtorInitializer *Member;
17399       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17400       InitializationKind InitKind =
17401         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17402 
17403       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17404       ExprResult MemberInit =
17405         InitSeq.Perform(*this, InitEntity, InitKind, None);
17406       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17407       // Note, MemberInit could actually come back empty if no initialization
17408       // is required (e.g., because it would call a trivial default constructor)
17409       if (!MemberInit.get() || MemberInit.isInvalid())
17410         continue;
17411 
17412       Member =
17413         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17414                                          SourceLocation(),
17415                                          MemberInit.getAs<Expr>(),
17416                                          SourceLocation());
17417       AllToInit.push_back(Member);
17418 
17419       // Be sure that the destructor is accessible and is marked as referenced.
17420       if (const RecordType *RecordTy =
17421               Context.getBaseElementType(Field->getType())
17422                   ->getAs<RecordType>()) {
17423         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17424         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17425           MarkFunctionReferenced(Field->getLocation(), Destructor);
17426           CheckDestructorAccess(Field->getLocation(), Destructor,
17427                             PDiag(diag::err_access_dtor_ivar)
17428                               << Context.getBaseElementType(Field->getType()));
17429         }
17430       }
17431     }
17432     ObjCImplementation->setIvarInitializers(Context,
17433                                             AllToInit.data(), AllToInit.size());
17434   }
17435 }
17436 
17437 static
17438 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17439                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17440                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17441                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17442                            Sema &S) {
17443   if (Ctor->isInvalidDecl())
17444     return;
17445 
17446   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17447 
17448   // Target may not be determinable yet, for instance if this is a dependent
17449   // call in an uninstantiated template.
17450   if (Target) {
17451     const FunctionDecl *FNTarget = nullptr;
17452     (void)Target->hasBody(FNTarget);
17453     Target = const_cast<CXXConstructorDecl*>(
17454       cast_or_null<CXXConstructorDecl>(FNTarget));
17455   }
17456 
17457   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17458                      // Avoid dereferencing a null pointer here.
17459                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17460 
17461   if (!Current.insert(Canonical).second)
17462     return;
17463 
17464   // We know that beyond here, we aren't chaining into a cycle.
17465   if (!Target || !Target->isDelegatingConstructor() ||
17466       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17467     Valid.insert(Current.begin(), Current.end());
17468     Current.clear();
17469   // We've hit a cycle.
17470   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17471              Current.count(TCanonical)) {
17472     // If we haven't diagnosed this cycle yet, do so now.
17473     if (!Invalid.count(TCanonical)) {
17474       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17475              diag::warn_delegating_ctor_cycle)
17476         << Ctor;
17477 
17478       // Don't add a note for a function delegating directly to itself.
17479       if (TCanonical != Canonical)
17480         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17481 
17482       CXXConstructorDecl *C = Target;
17483       while (C->getCanonicalDecl() != Canonical) {
17484         const FunctionDecl *FNTarget = nullptr;
17485         (void)C->getTargetConstructor()->hasBody(FNTarget);
17486         assert(FNTarget && "Ctor cycle through bodiless function");
17487 
17488         C = const_cast<CXXConstructorDecl*>(
17489           cast<CXXConstructorDecl>(FNTarget));
17490         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17491       }
17492     }
17493 
17494     Invalid.insert(Current.begin(), Current.end());
17495     Current.clear();
17496   } else {
17497     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17498   }
17499 }
17500 
17501 
17502 void Sema::CheckDelegatingCtorCycles() {
17503   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17504 
17505   for (DelegatingCtorDeclsType::iterator
17506          I = DelegatingCtorDecls.begin(ExternalSource),
17507          E = DelegatingCtorDecls.end();
17508        I != E; ++I)
17509     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17510 
17511   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17512     (*CI)->setInvalidDecl();
17513 }
17514 
17515 namespace {
17516   /// AST visitor that finds references to the 'this' expression.
17517   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17518     Sema &S;
17519 
17520   public:
17521     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17522 
17523     bool VisitCXXThisExpr(CXXThisExpr *E) {
17524       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17525         << E->isImplicit();
17526       return false;
17527     }
17528   };
17529 }
17530 
17531 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17532   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17533   if (!TSInfo)
17534     return false;
17535 
17536   TypeLoc TL = TSInfo->getTypeLoc();
17537   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17538   if (!ProtoTL)
17539     return false;
17540 
17541   // C++11 [expr.prim.general]p3:
17542   //   [The expression this] shall not appear before the optional
17543   //   cv-qualifier-seq and it shall not appear within the declaration of a
17544   //   static member function (although its type and value category are defined
17545   //   within a static member function as they are within a non-static member
17546   //   function). [ Note: this is because declaration matching does not occur
17547   //  until the complete declarator is known. - end note ]
17548   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17549   FindCXXThisExpr Finder(*this);
17550 
17551   // If the return type came after the cv-qualifier-seq, check it now.
17552   if (Proto->hasTrailingReturn() &&
17553       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17554     return true;
17555 
17556   // Check the exception specification.
17557   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17558     return true;
17559 
17560   // Check the trailing requires clause
17561   if (Expr *E = Method->getTrailingRequiresClause())
17562     if (!Finder.TraverseStmt(E))
17563       return true;
17564 
17565   return checkThisInStaticMemberFunctionAttributes(Method);
17566 }
17567 
17568 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17569   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17570   if (!TSInfo)
17571     return false;
17572 
17573   TypeLoc TL = TSInfo->getTypeLoc();
17574   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17575   if (!ProtoTL)
17576     return false;
17577 
17578   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17579   FindCXXThisExpr Finder(*this);
17580 
17581   switch (Proto->getExceptionSpecType()) {
17582   case EST_Unparsed:
17583   case EST_Uninstantiated:
17584   case EST_Unevaluated:
17585   case EST_BasicNoexcept:
17586   case EST_NoThrow:
17587   case EST_DynamicNone:
17588   case EST_MSAny:
17589   case EST_None:
17590     break;
17591 
17592   case EST_DependentNoexcept:
17593   case EST_NoexceptFalse:
17594   case EST_NoexceptTrue:
17595     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17596       return true;
17597     LLVM_FALLTHROUGH;
17598 
17599   case EST_Dynamic:
17600     for (const auto &E : Proto->exceptions()) {
17601       if (!Finder.TraverseType(E))
17602         return true;
17603     }
17604     break;
17605   }
17606 
17607   return false;
17608 }
17609 
17610 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17611   FindCXXThisExpr Finder(*this);
17612 
17613   // Check attributes.
17614   for (const auto *A : Method->attrs()) {
17615     // FIXME: This should be emitted by tblgen.
17616     Expr *Arg = nullptr;
17617     ArrayRef<Expr *> Args;
17618     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17619       Arg = G->getArg();
17620     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17621       Arg = G->getArg();
17622     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17623       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17624     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17625       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17626     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17627       Arg = ETLF->getSuccessValue();
17628       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17629     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17630       Arg = STLF->getSuccessValue();
17631       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17632     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17633       Arg = LR->getArg();
17634     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17635       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17636     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17637       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17638     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17639       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17640     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17641       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17642     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17643       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17644 
17645     if (Arg && !Finder.TraverseStmt(Arg))
17646       return true;
17647 
17648     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17649       if (!Finder.TraverseStmt(Args[I]))
17650         return true;
17651     }
17652   }
17653 
17654   return false;
17655 }
17656 
17657 void Sema::checkExceptionSpecification(
17658     bool IsTopLevel, ExceptionSpecificationType EST,
17659     ArrayRef<ParsedType> DynamicExceptions,
17660     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17661     SmallVectorImpl<QualType> &Exceptions,
17662     FunctionProtoType::ExceptionSpecInfo &ESI) {
17663   Exceptions.clear();
17664   ESI.Type = EST;
17665   if (EST == EST_Dynamic) {
17666     Exceptions.reserve(DynamicExceptions.size());
17667     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17668       // FIXME: Preserve type source info.
17669       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17670 
17671       if (IsTopLevel) {
17672         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17673         collectUnexpandedParameterPacks(ET, Unexpanded);
17674         if (!Unexpanded.empty()) {
17675           DiagnoseUnexpandedParameterPacks(
17676               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17677               Unexpanded);
17678           continue;
17679         }
17680       }
17681 
17682       // Check that the type is valid for an exception spec, and
17683       // drop it if not.
17684       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17685         Exceptions.push_back(ET);
17686     }
17687     ESI.Exceptions = Exceptions;
17688     return;
17689   }
17690 
17691   if (isComputedNoexcept(EST)) {
17692     assert((NoexceptExpr->isTypeDependent() ||
17693             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17694             Context.BoolTy) &&
17695            "Parser should have made sure that the expression is boolean");
17696     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17697       ESI.Type = EST_BasicNoexcept;
17698       return;
17699     }
17700 
17701     ESI.NoexceptExpr = NoexceptExpr;
17702     return;
17703   }
17704 }
17705 
17706 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17707              ExceptionSpecificationType EST,
17708              SourceRange SpecificationRange,
17709              ArrayRef<ParsedType> DynamicExceptions,
17710              ArrayRef<SourceRange> DynamicExceptionRanges,
17711              Expr *NoexceptExpr) {
17712   if (!MethodD)
17713     return;
17714 
17715   // Dig out the method we're referring to.
17716   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17717     MethodD = FunTmpl->getTemplatedDecl();
17718 
17719   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17720   if (!Method)
17721     return;
17722 
17723   // Check the exception specification.
17724   llvm::SmallVector<QualType, 4> Exceptions;
17725   FunctionProtoType::ExceptionSpecInfo ESI;
17726   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17727                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17728                               ESI);
17729 
17730   // Update the exception specification on the function type.
17731   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17732 
17733   if (Method->isStatic())
17734     checkThisInStaticMemberFunctionExceptionSpec(Method);
17735 
17736   if (Method->isVirtual()) {
17737     // Check overrides, which we previously had to delay.
17738     for (const CXXMethodDecl *O : Method->overridden_methods())
17739       CheckOverridingFunctionExceptionSpec(Method, O);
17740   }
17741 }
17742 
17743 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17744 ///
17745 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17746                                        SourceLocation DeclStart, Declarator &D,
17747                                        Expr *BitWidth,
17748                                        InClassInitStyle InitStyle,
17749                                        AccessSpecifier AS,
17750                                        const ParsedAttr &MSPropertyAttr) {
17751   IdentifierInfo *II = D.getIdentifier();
17752   if (!II) {
17753     Diag(DeclStart, diag::err_anonymous_property);
17754     return nullptr;
17755   }
17756   SourceLocation Loc = D.getIdentifierLoc();
17757 
17758   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17759   QualType T = TInfo->getType();
17760   if (getLangOpts().CPlusPlus) {
17761     CheckExtraCXXDefaultArguments(D);
17762 
17763     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17764                                         UPPC_DataMemberType)) {
17765       D.setInvalidType();
17766       T = Context.IntTy;
17767       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17768     }
17769   }
17770 
17771   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17772 
17773   if (D.getDeclSpec().isInlineSpecified())
17774     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17775         << getLangOpts().CPlusPlus17;
17776   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17777     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17778          diag::err_invalid_thread)
17779       << DeclSpec::getSpecifierName(TSCS);
17780 
17781   // Check to see if this name was declared as a member previously
17782   NamedDecl *PrevDecl = nullptr;
17783   LookupResult Previous(*this, II, Loc, LookupMemberName,
17784                         ForVisibleRedeclaration);
17785   LookupName(Previous, S);
17786   switch (Previous.getResultKind()) {
17787   case LookupResult::Found:
17788   case LookupResult::FoundUnresolvedValue:
17789     PrevDecl = Previous.getAsSingle<NamedDecl>();
17790     break;
17791 
17792   case LookupResult::FoundOverloaded:
17793     PrevDecl = Previous.getRepresentativeDecl();
17794     break;
17795 
17796   case LookupResult::NotFound:
17797   case LookupResult::NotFoundInCurrentInstantiation:
17798   case LookupResult::Ambiguous:
17799     break;
17800   }
17801 
17802   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17803     // Maybe we will complain about the shadowed template parameter.
17804     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17805     // Just pretend that we didn't see the previous declaration.
17806     PrevDecl = nullptr;
17807   }
17808 
17809   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17810     PrevDecl = nullptr;
17811 
17812   SourceLocation TSSL = D.getBeginLoc();
17813   MSPropertyDecl *NewPD =
17814       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17815                              MSPropertyAttr.getPropertyDataGetter(),
17816                              MSPropertyAttr.getPropertyDataSetter());
17817   ProcessDeclAttributes(TUScope, NewPD, D);
17818   NewPD->setAccess(AS);
17819 
17820   if (NewPD->isInvalidDecl())
17821     Record->setInvalidDecl();
17822 
17823   if (D.getDeclSpec().isModulePrivateSpecified())
17824     NewPD->setModulePrivate();
17825 
17826   if (NewPD->isInvalidDecl() && PrevDecl) {
17827     // Don't introduce NewFD into scope; there's already something
17828     // with the same name in the same scope.
17829   } else if (II) {
17830     PushOnScopeChains(NewPD, S);
17831   } else
17832     Record->addDecl(NewPD);
17833 
17834   return NewPD;
17835 }
17836 
17837 void Sema::ActOnStartFunctionDeclarationDeclarator(
17838     Declarator &Declarator, unsigned TemplateParameterDepth) {
17839   auto &Info = InventedParameterInfos.emplace_back();
17840   TemplateParameterList *ExplicitParams = nullptr;
17841   ArrayRef<TemplateParameterList *> ExplicitLists =
17842       Declarator.getTemplateParameterLists();
17843   if (!ExplicitLists.empty()) {
17844     bool IsMemberSpecialization, IsInvalid;
17845     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17846         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17847         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17848         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17849         /*SuppressDiagnostic=*/true);
17850   }
17851   if (ExplicitParams) {
17852     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17853     for (NamedDecl *Param : *ExplicitParams)
17854       Info.TemplateParams.push_back(Param);
17855     Info.NumExplicitTemplateParams = ExplicitParams->size();
17856   } else {
17857     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17858     Info.NumExplicitTemplateParams = 0;
17859   }
17860 }
17861 
17862 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17863   auto &FSI = InventedParameterInfos.back();
17864   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17865     if (FSI.NumExplicitTemplateParams != 0) {
17866       TemplateParameterList *ExplicitParams =
17867           Declarator.getTemplateParameterLists().back();
17868       Declarator.setInventedTemplateParameterList(
17869           TemplateParameterList::Create(
17870               Context, ExplicitParams->getTemplateLoc(),
17871               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17872               ExplicitParams->getRAngleLoc(),
17873               ExplicitParams->getRequiresClause()));
17874     } else {
17875       Declarator.setInventedTemplateParameterList(
17876           TemplateParameterList::Create(
17877               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17878               SourceLocation(), /*RequiresClause=*/nullptr));
17879     }
17880   }
17881   InventedParameterInfos.pop_back();
17882 }
17883