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/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <map>
45 #include <set>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55   /// the default argument of a parameter to determine whether it
56   /// contains any ill-formed subexpressions. For example, this will
57   /// diagnose the use of local variables or parameters within the
58   /// default argument expression.
59   class CheckDefaultArgumentVisitor
60     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61     Expr *DefaultArg;
62     Sema *S;
63 
64   public:
65     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66         : DefaultArg(defarg), S(s) {}
67 
68     bool VisitExpr(Expr *Node);
69     bool VisitDeclRefExpr(DeclRefExpr *DRE);
70     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71     bool VisitLambdaExpr(LambdaExpr *Lambda);
72     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73   };
74 
75   /// VisitExpr - Visit all of the children of this expression.
76   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77     bool IsInvalid = false;
78     for (Stmt *SubStmt : Node->children())
79       IsInvalid |= Visit(SubStmt);
80     return IsInvalid;
81   }
82 
83   /// VisitDeclRefExpr - Visit a reference to a declaration, to
84   /// determine whether this declaration can be used in the default
85   /// argument expression.
86   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87     NamedDecl *Decl = DRE->getDecl();
88     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89       // C++ [dcl.fct.default]p9
90       //   Default arguments are evaluated each time the function is
91       //   called. The order of evaluation of function arguments is
92       //   unspecified. Consequently, parameters of a function shall not
93       //   be used in default argument expressions, even if they are not
94       //   evaluated. Parameters of a function declared before a default
95       //   argument expression are in scope and can hide namespace and
96       //   class member names.
97       return S->Diag(DRE->getBeginLoc(),
98                      diag::err_param_default_argument_references_param)
99              << Param->getDeclName() << DefaultArg->getSourceRange();
100     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101       // C++ [dcl.fct.default]p7
102       //   Local variables shall not be used in default argument
103       //   expressions.
104       if (VDecl->isLocalVarDecl())
105         return S->Diag(DRE->getBeginLoc(),
106                        diag::err_param_default_argument_references_local)
107                << VDecl->getDeclName() << DefaultArg->getSourceRange();
108     }
109 
110     return false;
111   }
112 
113   /// VisitCXXThisExpr - Visit a C++ "this" expression.
114   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115     // C++ [dcl.fct.default]p8:
116     //   The keyword this shall not be used in a default argument of a
117     //   member function.
118     return S->Diag(ThisE->getBeginLoc(),
119                    diag::err_param_default_argument_references_this)
120            << ThisE->getSourceRange();
121   }
122 
123   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124     bool Invalid = false;
125     for (PseudoObjectExpr::semantics_iterator
126            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127       Expr *E = *i;
128 
129       // Look through bindings.
130       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131         E = OVE->getSourceExpr();
132         assert(E && "pseudo-object binding without source expression?");
133       }
134 
135       Invalid |= Visit(E);
136     }
137     return Invalid;
138   }
139 
140   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141     // C++11 [expr.lambda.prim]p13:
142     //   A lambda-expression appearing in a default argument shall not
143     //   implicitly or explicitly capture any entity.
144     if (Lambda->capture_begin() == Lambda->capture_end())
145       return false;
146 
147     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171     EST = EST_BasicNoexcept;
172 
173   switch (EST) {
174   case EST_Unparsed:
175   case EST_Uninstantiated:
176   case EST_Unevaluated:
177     llvm_unreachable("should not see unresolved exception specs here");
178 
179   // If this function can throw any exceptions, make a note of that.
180   case EST_MSAny:
181   case EST_None:
182     // FIXME: Whichever we see last of MSAny and None determines our result.
183     // We should make a consistent, order-independent choice here.
184     ClearExceptions();
185     ComputedEST = EST;
186     return;
187   case EST_NoexceptFalse:
188     ClearExceptions();
189     ComputedEST = EST_None;
190     return;
191   // FIXME: If the call to this decl is using any of its default arguments, we
192   // need to search them for potentially-throwing calls.
193   // If this function has a basic noexcept, it doesn't affect the outcome.
194   case EST_BasicNoexcept:
195   case EST_NoexceptTrue:
196   case EST_NoThrow:
197     return;
198   // If we're still at noexcept(true) and there's a throw() callee,
199   // change to that specification.
200   case EST_DynamicNone:
201     if (ComputedEST == EST_BasicNoexcept)
202       ComputedEST = EST_DynamicNone;
203     return;
204   case EST_DependentNoexcept:
205     llvm_unreachable(
206         "should not generate implicit declarations for dependent cases");
207   case EST_Dynamic:
208     break;
209   }
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
221   if (!S || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(S))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // C++11 [dcl.fct.default]p3
322   //   A default argument expression [...] shall not be specified for a
323   //   parameter pack.
324   if (Param->isParameterPack()) {
325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326         << DefaultArg->getSourceRange();
327     return;
328   }
329 
330   // Check that the default argument is well-formed
331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332   if (DefaultArgChecker.Visit(DefaultArg)) {
333     Param->setInvalidDecl();
334     return;
335   }
336 
337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 }
339 
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345                                              SourceLocation EqualLoc,
346                                              SourceLocation ArgLoc) {
347   if (!param)
348     return;
349 
350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
351   Param->setUnparsedDefaultArg();
352   UnparsedDefaultArgLocs[Param] = ArgLoc;
353 }
354 
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358                                           SourceLocation EqualLoc) {
359   if (!param)
360     return;
361 
362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
363   Param->setInvalidDecl();
364   UnparsedDefaultArgLocs.erase(Param);
365   Param->setDefaultArg(new(Context)
366                        OpaqueValueExpr(EqualLoc,
367                                        Param->getType().getNonReferenceType(),
368                                        VK_RValue));
369 }
370 
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377   // C++ [dcl.fct.default]p3
378   //   A default argument expression shall be specified only in the
379   //   parameter-declaration-clause of a function declaration or in a
380   //   template-parameter (14.1). It shall not be specified for a
381   //   parameter pack. If it is specified in a
382   //   parameter-declaration-clause, it shall not occur within a
383   //   declarator or abstract-declarator of a parameter-declaration.
384   bool MightBeFunction = D.isFunctionDeclarationContext();
385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386     DeclaratorChunk &chunk = D.getTypeObject(i);
387     if (chunk.Kind == DeclaratorChunk::Function) {
388       if (MightBeFunction) {
389         // This is a function declaration. It can have default arguments, but
390         // keep looking in case its return type is a function type with default
391         // arguments.
392         MightBeFunction = false;
393         continue;
394       }
395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396            ++argIdx) {
397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398         if (Param->hasUnparsedDefaultArg()) {
399           std::unique_ptr<CachedTokens> Toks =
400               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401           SourceRange SR;
402           if (Toks->size() > 1)
403             SR = SourceRange((*Toks)[1].getLocation(),
404                              Toks->back().getLocation());
405           else
406             SR = UnparsedDefaultArgLocs[Param];
407           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408             << SR;
409         } else if (Param->getDefaultArg()) {
410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411             << Param->getDefaultArg()->getSourceRange();
412           Param->setDefaultArg(nullptr);
413         }
414       }
415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
416       MightBeFunction = false;
417     }
418   }
419 }
420 
421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424     if (!PVD->hasDefaultArg())
425       return false;
426     if (!PVD->hasInheritedDefaultArg())
427       return true;
428   }
429   return false;
430 }
431 
432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
433 /// function, once we already know that they have the same
434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435 /// error, false otherwise.
436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437                                 Scope *S) {
438   bool Invalid = false;
439 
440   // The declaration context corresponding to the scope is the semantic
441   // parent, unless this is a local function declaration, in which case
442   // it is that surrounding function.
443   DeclContext *ScopeDC = New->isLocalExternDecl()
444                              ? New->getLexicalDeclContext()
445                              : New->getDeclContext();
446 
447   // Find the previous declaration for the purpose of default arguments.
448   FunctionDecl *PrevForDefaultArgs = Old;
449   for (/**/; PrevForDefaultArgs;
450        // Don't bother looking back past the latest decl if this is a local
451        // extern declaration; nothing else could work.
452        PrevForDefaultArgs = New->isLocalExternDecl()
453                                 ? nullptr
454                                 : PrevForDefaultArgs->getPreviousDecl()) {
455     // Ignore hidden declarations.
456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457       continue;
458 
459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460         !New->isCXXClassMember()) {
461       // Ignore default arguments of old decl if they are not in
462       // the same scope and this is not an out-of-line definition of
463       // a member function.
464       continue;
465     }
466 
467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468       // If only one of these is a local function declaration, then they are
469       // declared in different scopes, even though isDeclInScope may think
470       // they're in the same scope. (If both are local, the scope check is
471       // sufficient, and if neither is local, then they are in the same scope.)
472       continue;
473     }
474 
475     // We found the right previous declaration.
476     break;
477   }
478 
479   // C++ [dcl.fct.default]p4:
480   //   For non-template functions, default arguments can be added in
481   //   later declarations of a function in the same
482   //   scope. Declarations in different scopes have completely
483   //   distinct sets of default arguments. That is, declarations in
484   //   inner scopes do not acquire default arguments from
485   //   declarations in outer scopes, and vice versa. In a given
486   //   function declaration, all parameters subsequent to a
487   //   parameter with a default argument shall have default
488   //   arguments supplied in this or previous declarations. A
489   //   default argument shall not be redefined by a later
490   //   declaration (not even to the same value).
491   //
492   // C++ [dcl.fct.default]p6:
493   //   Except for member functions of class templates, the default arguments
494   //   in a member function definition that appears outside of the class
495   //   definition are added to the set of default arguments provided by the
496   //   member function declaration in the class definition.
497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
498                                        ? PrevForDefaultArgs->getNumParams()
499                                        : 0;
500        p < NumParams; ++p) {
501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502     ParmVarDecl *NewParam = New->getParamDecl(p);
503 
504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505     bool NewParamHasDfl = NewParam->hasDefaultArg();
506 
507     if (OldParamHasDfl && NewParamHasDfl) {
508       unsigned DiagDefaultParamID =
509         diag::err_param_default_argument_redefinition;
510 
511       // MSVC accepts that default parameters be redefined for member functions
512       // of template class. The new default parameter's value is ignored.
513       Invalid = true;
514       if (getLangOpts().MicrosoftExt) {
515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
517           // Merge the old default argument into the new parameter.
518           NewParam->setHasInheritedDefaultArg();
519           if (OldParam->hasUninstantiatedDefaultArg())
520             NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522           else
523             NewParam->setDefaultArg(OldParam->getInit());
524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525           Invalid = false;
526         }
527       }
528 
529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530       // hint here. Alternatively, we could walk the type-source information
531       // for NewParam to find the last source location in the type... but it
532       // isn't worth the effort right now. This is the kind of test case that
533       // is hard to get right:
534       //   int f(int);
535       //   void g(int (*fp)(int) = f);
536       //   void g(int (*fp)(int) = &f);
537       Diag(NewParam->getLocation(), DiagDefaultParamID)
538         << NewParam->getDefaultArgRange();
539 
540       // Look for the function declaration where the default argument was
541       // actually written, which may be a declaration prior to Old.
542       for (auto Older = PrevForDefaultArgs;
543            OldParam->hasInheritedDefaultArg(); /**/) {
544         Older = Older->getPreviousDecl();
545         OldParam = Older->getParamDecl(p);
546       }
547 
548       Diag(OldParam->getLocation(), diag::note_previous_definition)
549         << OldParam->getDefaultArgRange();
550     } else if (OldParamHasDfl) {
551       // Merge the old default argument into the new parameter unless the new
552       // function is a friend declaration in a template class. In the latter
553       // case the default arguments will be inherited when the friend
554       // declaration will be instantiated.
555       if (New->getFriendObjectKind() == Decl::FOK_None ||
556           !New->getLexicalDeclContext()->isDependentContext()) {
557         // It's important to use getInit() here;  getDefaultArg()
558         // strips off any top-level ExprWithCleanups.
559         NewParam->setHasInheritedDefaultArg();
560         if (OldParam->hasUnparsedDefaultArg())
561           NewParam->setUnparsedDefaultArg();
562         else if (OldParam->hasUninstantiatedDefaultArg())
563           NewParam->setUninstantiatedDefaultArg(
564                                        OldParam->getUninstantiatedDefaultArg());
565         else
566           NewParam->setDefaultArg(OldParam->getInit());
567       }
568     } else if (NewParamHasDfl) {
569       if (New->getDescribedFunctionTemplate()) {
570         // Paragraph 4, quoted above, only applies to non-template functions.
571         Diag(NewParam->getLocation(),
572              diag::err_param_default_argument_template_redecl)
573           << NewParam->getDefaultArgRange();
574         Diag(PrevForDefaultArgs->getLocation(),
575              diag::note_template_prev_declaration)
576             << false;
577       } else if (New->getTemplateSpecializationKind()
578                    != TSK_ImplicitInstantiation &&
579                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
580         // C++ [temp.expr.spec]p21:
581         //   Default function arguments shall not be specified in a declaration
582         //   or a definition for one of the following explicit specializations:
583         //     - the explicit specialization of a function template;
584         //     - the explicit specialization of a member function template;
585         //     - the explicit specialization of a member function of a class
586         //       template where the class template specialization to which the
587         //       member function specialization belongs is implicitly
588         //       instantiated.
589         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
591           << New->getDeclName()
592           << NewParam->getDefaultArgRange();
593       } else if (New->getDeclContext()->isDependentContext()) {
594         // C++ [dcl.fct.default]p6 (DR217):
595         //   Default arguments for a member function of a class template shall
596         //   be specified on the initial declaration of the member function
597         //   within the class template.
598         //
599         // Reading the tea leaves a bit in DR217 and its reference to DR205
600         // leads me to the conclusion that one cannot add default function
601         // arguments for an out-of-line definition of a member function of a
602         // dependent type.
603         int WhichKind = 2;
604         if (CXXRecordDecl *Record
605               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
606           if (Record->getDescribedClassTemplate())
607             WhichKind = 0;
608           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
609             WhichKind = 1;
610           else
611             WhichKind = 2;
612         }
613 
614         Diag(NewParam->getLocation(),
615              diag::err_param_default_argument_member_template_redecl)
616           << WhichKind
617           << NewParam->getDefaultArgRange();
618       }
619     }
620   }
621 
622   // DR1344: If a default argument is added outside a class definition and that
623   // default argument makes the function a special member function, the program
624   // is ill-formed. This can only happen for constructors.
625   if (isa<CXXConstructorDecl>(New) &&
626       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
627     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
628                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
629     if (NewSM != OldSM) {
630       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
631       assert(NewParam->hasDefaultArg());
632       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
633         << NewParam->getDefaultArgRange() << NewSM;
634       Diag(Old->getLocation(), diag::note_previous_declaration);
635     }
636   }
637 
638   const FunctionDecl *Def;
639   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
640   // template has a constexpr specifier then all its declarations shall
641   // contain the constexpr specifier.
642   if (New->getConstexprKind() != Old->getConstexprKind()) {
643     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
644         << New << New->getConstexprKind() << Old->getConstexprKind();
645     Diag(Old->getLocation(), diag::note_previous_declaration);
646     Invalid = true;
647   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
648              Old->isDefined(Def) &&
649              // If a friend function is inlined but does not have 'inline'
650              // specifier, it is a definition. Do not report attribute conflict
651              // in this case, redefinition will be diagnosed later.
652              (New->isInlineSpecified() ||
653               New->getFriendObjectKind() == Decl::FOK_None)) {
654     // C++11 [dcl.fcn.spec]p4:
655     //   If the definition of a function appears in a translation unit before its
656     //   first declaration as inline, the program is ill-formed.
657     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
658     Diag(Def->getLocation(), diag::note_previous_definition);
659     Invalid = true;
660   }
661 
662   // C++17 [temp.deduct.guide]p3:
663   //   Two deduction guide declarations in the same translation unit
664   //   for the same class template shall not have equivalent
665   //   parameter-declaration-clauses.
666   if (isa<CXXDeductionGuideDecl>(New) &&
667       !New->isFunctionTemplateSpecialization()) {
668     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
669     Diag(Old->getLocation(), diag::note_previous_declaration);
670   }
671 
672   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673   // argument expression, that declaration shall be a definition and shall be
674   // the only declaration of the function or function template in the
675   // translation unit.
676   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677       functionDeclHasDefaultArgument(Old)) {
678     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679     Diag(Old->getLocation(), diag::note_previous_declaration);
680     Invalid = true;
681   }
682 
683   return Invalid;
684 }
685 
686 NamedDecl *
687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688                                    MultiTemplateParamsArg TemplateParamLists) {
689   assert(D.isDecompositionDeclarator());
690   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
691 
692   // The syntax only allows a decomposition declarator as a simple-declaration,
693   // a for-range-declaration, or a condition in Clang, but we parse it in more
694   // cases than that.
695   if (!D.mayHaveDecompositionDeclarator()) {
696     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697       << Decomp.getSourceRange();
698     return nullptr;
699   }
700 
701   if (!TemplateParamLists.empty()) {
702     // FIXME: There's no rule against this, but there are also no rules that
703     // would actually make it usable, so we reject it for now.
704     Diag(TemplateParamLists.front()->getTemplateLoc(),
705          diag::err_decomp_decl_template);
706     return nullptr;
707   }
708 
709   Diag(Decomp.getLSquareLoc(),
710        !getLangOpts().CPlusPlus17
711            ? diag::ext_decomp_decl
712            : D.getContext() == DeclaratorContext::ConditionContext
713                  ? diag::ext_decomp_decl_cond
714                  : diag::warn_cxx14_compat_decomp_decl)
715       << Decomp.getSourceRange();
716 
717   // The semantic context is always just the current context.
718   DeclContext *const DC = CurContext;
719 
720   // C++17 [dcl.dcl]/8:
721   //   The decl-specifier-seq shall contain only the type-specifier auto
722   //   and cv-qualifiers.
723   // C++2a [dcl.dcl]/8:
724   //   If decl-specifier-seq contains any decl-specifier other than static,
725   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
726   auto &DS = D.getDeclSpec();
727   {
728     SmallVector<StringRef, 8> BadSpecifiers;
729     SmallVector<SourceLocation, 8> BadSpecifierLocs;
730     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
731     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
732     if (auto SCS = DS.getStorageClassSpec()) {
733       if (SCS == DeclSpec::SCS_static) {
734         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
735         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
736       } else {
737         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
738         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
739       }
740     }
741     if (auto TSCS = DS.getThreadStorageClassSpec()) {
742       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
743       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
744     }
745     if (DS.hasConstexprSpecifier()) {
746       BadSpecifiers.push_back(
747           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
748       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
749     }
750     if (DS.isInlineSpecified()) {
751       BadSpecifiers.push_back("inline");
752       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
753     }
754     if (!BadSpecifiers.empty()) {
755       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
756       Err << (int)BadSpecifiers.size()
757           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
758       // Don't add FixItHints to remove the specifiers; we do still respect
759       // them when building the underlying variable.
760       for (auto Loc : BadSpecifierLocs)
761         Err << SourceRange(Loc, Loc);
762     } else if (!CPlusPlus20Specifiers.empty()) {
763       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
764                          getLangOpts().CPlusPlus20
765                              ? diag::warn_cxx17_compat_decomp_decl_spec
766                              : diag::ext_decomp_decl_spec);
767       Warn << (int)CPlusPlus20Specifiers.size()
768            << llvm::join(CPlusPlus20Specifiers.begin(),
769                          CPlusPlus20Specifiers.end(), " ");
770       for (auto Loc : CPlusPlus20SpecifierLocs)
771         Warn << SourceRange(Loc, Loc);
772     }
773     // We can't recover from it being declared as a typedef.
774     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
775       return nullptr;
776   }
777 
778   // C++2a [dcl.struct.bind]p1:
779   //   A cv that includes volatile is deprecated
780   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
781       getLangOpts().CPlusPlus20)
782     Diag(DS.getVolatileSpecLoc(),
783          diag::warn_deprecated_volatile_structured_binding);
784 
785   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
786   QualType R = TInfo->getType();
787 
788   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
789                                       UPPC_DeclarationType))
790     D.setInvalidType();
791 
792   // The syntax only allows a single ref-qualifier prior to the decomposition
793   // declarator. No other declarator chunks are permitted. Also check the type
794   // specifier here.
795   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
796       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
797       (D.getNumTypeObjects() == 1 &&
798        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
799     Diag(Decomp.getLSquareLoc(),
800          (D.hasGroupingParens() ||
801           (D.getNumTypeObjects() &&
802            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
803              ? diag::err_decomp_decl_parens
804              : diag::err_decomp_decl_type)
805         << R;
806 
807     // In most cases, there's no actual problem with an explicitly-specified
808     // type, but a function type won't work here, and ActOnVariableDeclarator
809     // shouldn't be called for such a type.
810     if (R->isFunctionType())
811       D.setInvalidType();
812   }
813 
814   // Build the BindingDecls.
815   SmallVector<BindingDecl*, 8> Bindings;
816 
817   // Build the BindingDecls.
818   for (auto &B : D.getDecompositionDeclarator().bindings()) {
819     // Check for name conflicts.
820     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
821     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
822                           ForVisibleRedeclaration);
823     LookupName(Previous, S,
824                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
825 
826     // It's not permitted to shadow a template parameter name.
827     if (Previous.isSingleResult() &&
828         Previous.getFoundDecl()->isTemplateParameter()) {
829       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
830                                       Previous.getFoundDecl());
831       Previous.clear();
832     }
833 
834     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
835                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
836     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
837                          /*AllowInlineNamespace*/false);
838     if (!Previous.empty()) {
839       auto *Old = Previous.getRepresentativeDecl();
840       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
841       Diag(Old->getLocation(), diag::note_previous_definition);
842     }
843 
844     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
845     PushOnScopeChains(BD, S, true);
846     Bindings.push_back(BD);
847     ParsingInitForAutoVars.insert(BD);
848   }
849 
850   // There are no prior lookup results for the variable itself, because it
851   // is unnamed.
852   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
853                                Decomp.getLSquareLoc());
854   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
855                         ForVisibleRedeclaration);
856 
857   // Build the variable that holds the non-decomposed object.
858   bool AddToScope = true;
859   NamedDecl *New =
860       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
861                               MultiTemplateParamsArg(), AddToScope, Bindings);
862   if (AddToScope) {
863     S->AddDecl(New);
864     CurContext->addHiddenDecl(New);
865   }
866 
867   if (isInOpenMPDeclareTargetContext())
868     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
869 
870   return New;
871 }
872 
873 static bool checkSimpleDecomposition(
874     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
875     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
876     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
877   if ((int64_t)Bindings.size() != NumElems) {
878     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
879         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
880         << (NumElems < Bindings.size());
881     return true;
882   }
883 
884   unsigned I = 0;
885   for (auto *B : Bindings) {
886     SourceLocation Loc = B->getLocation();
887     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
888     if (E.isInvalid())
889       return true;
890     E = GetInit(Loc, E.get(), I++);
891     if (E.isInvalid())
892       return true;
893     B->setBinding(ElemType, E.get());
894   }
895 
896   return false;
897 }
898 
899 static bool checkArrayLikeDecomposition(Sema &S,
900                                         ArrayRef<BindingDecl *> Bindings,
901                                         ValueDecl *Src, QualType DecompType,
902                                         const llvm::APSInt &NumElems,
903                                         QualType ElemType) {
904   return checkSimpleDecomposition(
905       S, Bindings, Src, DecompType, NumElems, ElemType,
906       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
907         ExprResult E = S.ActOnIntegerConstant(Loc, I);
908         if (E.isInvalid())
909           return ExprError();
910         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
911       });
912 }
913 
914 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
915                                     ValueDecl *Src, QualType DecompType,
916                                     const ConstantArrayType *CAT) {
917   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
918                                      llvm::APSInt(CAT->getSize()),
919                                      CAT->getElementType());
920 }
921 
922 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
923                                      ValueDecl *Src, QualType DecompType,
924                                      const VectorType *VT) {
925   return checkArrayLikeDecomposition(
926       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
927       S.Context.getQualifiedType(VT->getElementType(),
928                                  DecompType.getQualifiers()));
929 }
930 
931 static bool checkComplexDecomposition(Sema &S,
932                                       ArrayRef<BindingDecl *> Bindings,
933                                       ValueDecl *Src, QualType DecompType,
934                                       const ComplexType *CT) {
935   return checkSimpleDecomposition(
936       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
937       S.Context.getQualifiedType(CT->getElementType(),
938                                  DecompType.getQualifiers()),
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
941       });
942 }
943 
944 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
945                                      TemplateArgumentListInfo &Args) {
946   SmallString<128> SS;
947   llvm::raw_svector_ostream OS(SS);
948   bool First = true;
949   for (auto &Arg : Args.arguments()) {
950     if (!First)
951       OS << ", ";
952     Arg.getArgument().print(PrintingPolicy, OS);
953     First = false;
954   }
955   return std::string(OS.str());
956 }
957 
958 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
959                                      SourceLocation Loc, StringRef Trait,
960                                      TemplateArgumentListInfo &Args,
961                                      unsigned DiagID) {
962   auto DiagnoseMissing = [&] {
963     if (DiagID)
964       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
965                                                Args);
966     return true;
967   };
968 
969   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
970   NamespaceDecl *Std = S.getStdNamespace();
971   if (!Std)
972     return DiagnoseMissing();
973 
974   // Look up the trait itself, within namespace std. We can diagnose various
975   // problems with this lookup even if we've been asked to not diagnose a
976   // missing specialization, because this can only fail if the user has been
977   // declaring their own names in namespace std or we don't support the
978   // standard library implementation in use.
979   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
980                       Loc, Sema::LookupOrdinaryName);
981   if (!S.LookupQualifiedName(Result, Std))
982     return DiagnoseMissing();
983   if (Result.isAmbiguous())
984     return true;
985 
986   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
987   if (!TraitTD) {
988     Result.suppressDiagnostics();
989     NamedDecl *Found = *Result.begin();
990     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
991     S.Diag(Found->getLocation(), diag::note_declared_at);
992     return true;
993   }
994 
995   // Build the template-id.
996   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
997   if (TraitTy.isNull())
998     return true;
999   if (!S.isCompleteType(Loc, TraitTy)) {
1000     if (DiagID)
1001       S.RequireCompleteType(
1002           Loc, TraitTy, DiagID,
1003           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1004     return true;
1005   }
1006 
1007   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1008   assert(RD && "specialization of class template is not a class?");
1009 
1010   // Look up the member of the trait type.
1011   S.LookupQualifiedName(TraitMemberLookup, RD);
1012   return TraitMemberLookup.isAmbiguous();
1013 }
1014 
1015 static TemplateArgumentLoc
1016 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1017                                    uint64_t I) {
1018   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1019   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1020 }
1021 
1022 static TemplateArgumentLoc
1023 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1024   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1025 }
1026 
1027 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1028 
1029 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1030                                llvm::APSInt &Size) {
1031   EnterExpressionEvaluationContext ContextRAII(
1032       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1033 
1034   DeclarationName Value = S.PP.getIdentifierInfo("value");
1035   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1036 
1037   // Form template argument list for tuple_size<T>.
1038   TemplateArgumentListInfo Args(Loc, Loc);
1039   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1040 
1041   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1042   // it's not tuple-like.
1043   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1044       R.empty())
1045     return IsTupleLike::NotTupleLike;
1046 
1047   // If we get this far, we've committed to the tuple interpretation, but
1048   // we can still fail if there actually isn't a usable ::value.
1049 
1050   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1051     LookupResult &R;
1052     TemplateArgumentListInfo &Args;
1053     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1054         : R(R), Args(Args) {}
1055     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1056       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1057           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1058     }
1059   } Diagnoser(R, Args);
1060 
1061   ExprResult E =
1062       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1063   if (E.isInvalid())
1064     return IsTupleLike::Error;
1065 
1066   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1067   if (E.isInvalid())
1068     return IsTupleLike::Error;
1069 
1070   return IsTupleLike::TupleLike;
1071 }
1072 
1073 /// \return std::tuple_element<I, T>::type.
1074 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1075                                         unsigned I, QualType T) {
1076   // Form template argument list for tuple_element<I, T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(
1079       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1080   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1081 
1082   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1083   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1084   if (lookupStdTypeTraitMember(
1085           S, R, Loc, "tuple_element", Args,
1086           diag::err_decomp_decl_std_tuple_element_not_specialized))
1087     return QualType();
1088 
1089   auto *TD = R.getAsSingle<TypeDecl>();
1090   if (!TD) {
1091     R.suppressDiagnostics();
1092     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1093       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1094     if (!R.empty())
1095       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1096     return QualType();
1097   }
1098 
1099   return S.Context.getTypeDeclType(TD);
1100 }
1101 
1102 namespace {
1103 struct BindingDiagnosticTrap {
1104   Sema &S;
1105   DiagnosticErrorTrap Trap;
1106   BindingDecl *BD;
1107 
1108   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1109       : S(S), Trap(S.Diags), BD(BD) {}
1110   ~BindingDiagnosticTrap() {
1111     if (Trap.hasErrorOccurred())
1112       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1113   }
1114 };
1115 }
1116 
1117 static bool checkTupleLikeDecomposition(Sema &S,
1118                                         ArrayRef<BindingDecl *> Bindings,
1119                                         VarDecl *Src, QualType DecompType,
1120                                         const llvm::APSInt &TupleSize) {
1121   if ((int64_t)Bindings.size() != TupleSize) {
1122     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1123         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1124         << (TupleSize < Bindings.size());
1125     return true;
1126   }
1127 
1128   if (Bindings.empty())
1129     return false;
1130 
1131   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1132 
1133   // [dcl.decomp]p3:
1134   //   The unqualified-id get is looked up in the scope of E by class member
1135   //   access lookup ...
1136   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1137   bool UseMemberGet = false;
1138   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1139     if (auto *RD = DecompType->getAsCXXRecordDecl())
1140       S.LookupQualifiedName(MemberGet, RD);
1141     if (MemberGet.isAmbiguous())
1142       return true;
1143     //   ... and if that finds at least one declaration that is a function
1144     //   template whose first template parameter is a non-type parameter ...
1145     for (NamedDecl *D : MemberGet) {
1146       if (FunctionTemplateDecl *FTD =
1147               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1148         TemplateParameterList *TPL = FTD->getTemplateParameters();
1149         if (TPL->size() != 0 &&
1150             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1151           //   ... the initializer is e.get<i>().
1152           UseMemberGet = true;
1153           break;
1154         }
1155       }
1156     }
1157   }
1158 
1159   unsigned I = 0;
1160   for (auto *B : Bindings) {
1161     BindingDiagnosticTrap Trap(S, B);
1162     SourceLocation Loc = B->getLocation();
1163 
1164     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1165     if (E.isInvalid())
1166       return true;
1167 
1168     //   e is an lvalue if the type of the entity is an lvalue reference and
1169     //   an xvalue otherwise
1170     if (!Src->getType()->isLValueReferenceType())
1171       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1172                                    E.get(), nullptr, VK_XValue);
1173 
1174     TemplateArgumentListInfo Args(Loc, Loc);
1175     Args.addArgument(
1176         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1177 
1178     if (UseMemberGet) {
1179       //   if [lookup of member get] finds at least one declaration, the
1180       //   initializer is e.get<i-1>().
1181       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1182                                      CXXScopeSpec(), SourceLocation(), nullptr,
1183                                      MemberGet, &Args, nullptr);
1184       if (E.isInvalid())
1185         return true;
1186 
1187       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1188     } else {
1189       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1190       //   in the associated namespaces.
1191       Expr *Get = UnresolvedLookupExpr::Create(
1192           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1193           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1194           UnresolvedSetIterator(), UnresolvedSetIterator());
1195 
1196       Expr *Arg = E.get();
1197       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1198     }
1199     if (E.isInvalid())
1200       return true;
1201     Expr *Init = E.get();
1202 
1203     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1204     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1205     if (T.isNull())
1206       return true;
1207 
1208     //   each vi is a variable of type "reference to T" initialized with the
1209     //   initializer, where the reference is an lvalue reference if the
1210     //   initializer is an lvalue and an rvalue reference otherwise
1211     QualType RefType =
1212         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1213     if (RefType.isNull())
1214       return true;
1215     auto *RefVD = VarDecl::Create(
1216         S.Context, Src->getDeclContext(), Loc, Loc,
1217         B->getDeclName().getAsIdentifierInfo(), RefType,
1218         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1219     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1220     RefVD->setTSCSpec(Src->getTSCSpec());
1221     RefVD->setImplicit();
1222     if (Src->isInlineSpecified())
1223       RefVD->setInlineSpecified();
1224     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1225 
1226     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1227     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1228     InitializationSequence Seq(S, Entity, Kind, Init);
1229     E = Seq.Perform(S, Entity, Kind, Init);
1230     if (E.isInvalid())
1231       return true;
1232     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1233     if (E.isInvalid())
1234       return true;
1235     RefVD->setInit(E.get());
1236     if (!E.get()->isValueDependent())
1237       RefVD->checkInitIsICE();
1238 
1239     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1240                                    DeclarationNameInfo(B->getDeclName(), Loc),
1241                                    RefVD);
1242     if (E.isInvalid())
1243       return true;
1244 
1245     B->setBinding(T, E.get());
1246     I++;
1247   }
1248 
1249   return false;
1250 }
1251 
1252 /// Find the base class to decompose in a built-in decomposition of a class type.
1253 /// This base class search is, unfortunately, not quite like any other that we
1254 /// perform anywhere else in C++.
1255 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1256                                                 const CXXRecordDecl *RD,
1257                                                 CXXCastPath &BasePath) {
1258   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1259                           CXXBasePath &Path) {
1260     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1261   };
1262 
1263   const CXXRecordDecl *ClassWithFields = nullptr;
1264   AccessSpecifier AS = AS_public;
1265   if (RD->hasDirectFields())
1266     // [dcl.decomp]p4:
1267     //   Otherwise, all of E's non-static data members shall be public direct
1268     //   members of E ...
1269     ClassWithFields = RD;
1270   else {
1271     //   ... or of ...
1272     CXXBasePaths Paths;
1273     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1274     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1275       // If no classes have fields, just decompose RD itself. (This will work
1276       // if and only if zero bindings were provided.)
1277       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1278     }
1279 
1280     CXXBasePath *BestPath = nullptr;
1281     for (auto &P : Paths) {
1282       if (!BestPath)
1283         BestPath = &P;
1284       else if (!S.Context.hasSameType(P.back().Base->getType(),
1285                                       BestPath->back().Base->getType())) {
1286         //   ... the same ...
1287         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1288           << false << RD << BestPath->back().Base->getType()
1289           << P.back().Base->getType();
1290         return DeclAccessPair();
1291       } else if (P.Access < BestPath->Access) {
1292         BestPath = &P;
1293       }
1294     }
1295 
1296     //   ... unambiguous ...
1297     QualType BaseType = BestPath->back().Base->getType();
1298     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1299       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1300         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1301       return DeclAccessPair();
1302     }
1303 
1304     //   ... [accessible, implied by other rules] base class of E.
1305     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1306                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1307     AS = BestPath->Access;
1308 
1309     ClassWithFields = BaseType->getAsCXXRecordDecl();
1310     S.BuildBasePathArray(Paths, BasePath);
1311   }
1312 
1313   // The above search did not check whether the selected class itself has base
1314   // classes with fields, so check that now.
1315   CXXBasePaths Paths;
1316   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1317     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1318       << (ClassWithFields == RD) << RD << ClassWithFields
1319       << Paths.front().back().Base->getType();
1320     return DeclAccessPair();
1321   }
1322 
1323   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1324 }
1325 
1326 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1327                                      ValueDecl *Src, QualType DecompType,
1328                                      const CXXRecordDecl *OrigRD) {
1329   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1330                             diag::err_incomplete_type))
1331     return true;
1332 
1333   CXXCastPath BasePath;
1334   DeclAccessPair BasePair =
1335       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1336   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1337   if (!RD)
1338     return true;
1339   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1340                                                  DecompType.getQualifiers());
1341 
1342   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1343     unsigned NumFields =
1344         std::count_if(RD->field_begin(), RD->field_end(),
1345                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1346     assert(Bindings.size() != NumFields);
1347     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1348         << DecompType << (unsigned)Bindings.size() << NumFields
1349         << (NumFields < Bindings.size());
1350     return true;
1351   };
1352 
1353   //   all of E's non-static data members shall be [...] well-formed
1354   //   when named as e.name in the context of the structured binding,
1355   //   E shall not have an anonymous union member, ...
1356   unsigned I = 0;
1357   for (auto *FD : RD->fields()) {
1358     if (FD->isUnnamedBitfield())
1359       continue;
1360 
1361     if (FD->isAnonymousStructOrUnion()) {
1362       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1363         << DecompType << FD->getType()->isUnionType();
1364       S.Diag(FD->getLocation(), diag::note_declared_at);
1365       return true;
1366     }
1367 
1368     // We have a real field to bind.
1369     if (I >= Bindings.size())
1370       return DiagnoseBadNumberOfBindings();
1371     auto *B = Bindings[I++];
1372     SourceLocation Loc = B->getLocation();
1373 
1374     // The field must be accessible in the context of the structured binding.
1375     // We already checked that the base class is accessible.
1376     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1377     // const_cast here.
1378     S.CheckStructuredBindingMemberAccess(
1379         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1380         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1381                                      BasePair.getAccess(), FD->getAccess())));
1382 
1383     // Initialize the binding to Src.FD.
1384     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1385     if (E.isInvalid())
1386       return true;
1387     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1388                             VK_LValue, &BasePath);
1389     if (E.isInvalid())
1390       return true;
1391     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1392                                   CXXScopeSpec(), FD,
1393                                   DeclAccessPair::make(FD, FD->getAccess()),
1394                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1395     if (E.isInvalid())
1396       return true;
1397 
1398     // If the type of the member is T, the referenced type is cv T, where cv is
1399     // the cv-qualification of the decomposition expression.
1400     //
1401     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1402     // 'const' to the type of the field.
1403     Qualifiers Q = DecompType.getQualifiers();
1404     if (FD->isMutable())
1405       Q.removeConst();
1406     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1407   }
1408 
1409   if (I != Bindings.size())
1410     return DiagnoseBadNumberOfBindings();
1411 
1412   return false;
1413 }
1414 
1415 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1416   QualType DecompType = DD->getType();
1417 
1418   // If the type of the decomposition is dependent, then so is the type of
1419   // each binding.
1420   if (DecompType->isDependentType()) {
1421     for (auto *B : DD->bindings())
1422       B->setType(Context.DependentTy);
1423     return;
1424   }
1425 
1426   DecompType = DecompType.getNonReferenceType();
1427   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1428 
1429   // C++1z [dcl.decomp]/2:
1430   //   If E is an array type [...]
1431   // As an extension, we also support decomposition of built-in complex and
1432   // vector types.
1433   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1434     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1435       DD->setInvalidDecl();
1436     return;
1437   }
1438   if (auto *VT = DecompType->getAs<VectorType>()) {
1439     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1440       DD->setInvalidDecl();
1441     return;
1442   }
1443   if (auto *CT = DecompType->getAs<ComplexType>()) {
1444     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1445       DD->setInvalidDecl();
1446     return;
1447   }
1448 
1449   // C++1z [dcl.decomp]/3:
1450   //   if the expression std::tuple_size<E>::value is a well-formed integral
1451   //   constant expression, [...]
1452   llvm::APSInt TupleSize(32);
1453   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1454   case IsTupleLike::Error:
1455     DD->setInvalidDecl();
1456     return;
1457 
1458   case IsTupleLike::TupleLike:
1459     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1460       DD->setInvalidDecl();
1461     return;
1462 
1463   case IsTupleLike::NotTupleLike:
1464     break;
1465   }
1466 
1467   // C++1z [dcl.dcl]/8:
1468   //   [E shall be of array or non-union class type]
1469   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1470   if (!RD || RD->isUnion()) {
1471     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1472         << DD << !RD << DecompType;
1473     DD->setInvalidDecl();
1474     return;
1475   }
1476 
1477   // C++1z [dcl.decomp]/4:
1478   //   all of E's non-static data members shall be [...] direct members of
1479   //   E or of the same unambiguous public base class of E, ...
1480   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1481     DD->setInvalidDecl();
1482 }
1483 
1484 /// Merge the exception specifications of two variable declarations.
1485 ///
1486 /// This is called when there's a redeclaration of a VarDecl. The function
1487 /// checks if the redeclaration might have an exception specification and
1488 /// validates compatibility and merges the specs if necessary.
1489 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1490   // Shortcut if exceptions are disabled.
1491   if (!getLangOpts().CXXExceptions)
1492     return;
1493 
1494   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1495          "Should only be called if types are otherwise the same.");
1496 
1497   QualType NewType = New->getType();
1498   QualType OldType = Old->getType();
1499 
1500   // We're only interested in pointers and references to functions, as well
1501   // as pointers to member functions.
1502   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1503     NewType = R->getPointeeType();
1504     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1505   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1506     NewType = P->getPointeeType();
1507     OldType = OldType->castAs<PointerType>()->getPointeeType();
1508   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1509     NewType = M->getPointeeType();
1510     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1511   }
1512 
1513   if (!NewType->isFunctionProtoType())
1514     return;
1515 
1516   // There's lots of special cases for functions. For function pointers, system
1517   // libraries are hopefully not as broken so that we don't need these
1518   // workarounds.
1519   if (CheckEquivalentExceptionSpec(
1520         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1521         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1522     New->setInvalidDecl();
1523   }
1524 }
1525 
1526 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1527 /// function declaration are well-formed according to C++
1528 /// [dcl.fct.default].
1529 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1530   unsigned NumParams = FD->getNumParams();
1531   unsigned p;
1532 
1533   // Find first parameter with a default argument
1534   for (p = 0; p < NumParams; ++p) {
1535     ParmVarDecl *Param = FD->getParamDecl(p);
1536     if (Param->hasDefaultArg())
1537       break;
1538   }
1539 
1540   // C++11 [dcl.fct.default]p4:
1541   //   In a given function declaration, each parameter subsequent to a parameter
1542   //   with a default argument shall have a default argument supplied in this or
1543   //   a previous declaration or shall be a function parameter pack. A default
1544   //   argument shall not be redefined by a later declaration (not even to the
1545   //   same value).
1546   unsigned LastMissingDefaultArg = 0;
1547   for (; p < NumParams; ++p) {
1548     ParmVarDecl *Param = FD->getParamDecl(p);
1549     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1550       if (Param->isInvalidDecl())
1551         /* We already complained about this parameter. */;
1552       else if (Param->getIdentifier())
1553         Diag(Param->getLocation(),
1554              diag::err_param_default_argument_missing_name)
1555           << Param->getIdentifier();
1556       else
1557         Diag(Param->getLocation(),
1558              diag::err_param_default_argument_missing);
1559 
1560       LastMissingDefaultArg = p;
1561     }
1562   }
1563 
1564   if (LastMissingDefaultArg > 0) {
1565     // Some default arguments were missing. Clear out all of the
1566     // default arguments up to (and including) the last missing
1567     // default argument, so that we leave the function parameters
1568     // in a semantically valid state.
1569     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1570       ParmVarDecl *Param = FD->getParamDecl(p);
1571       if (Param->hasDefaultArg()) {
1572         Param->setDefaultArg(nullptr);
1573       }
1574     }
1575   }
1576 }
1577 
1578 /// Check that the given type is a literal type. Issue a diagnostic if not,
1579 /// if Kind is Diagnose.
1580 /// \return \c true if a problem has been found (and optionally diagnosed).
1581 template <typename... Ts>
1582 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1583                              SourceLocation Loc, QualType T, unsigned DiagID,
1584                              Ts &&...DiagArgs) {
1585   if (T->isDependentType())
1586     return false;
1587 
1588   switch (Kind) {
1589   case Sema::CheckConstexprKind::Diagnose:
1590     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1591                                       std::forward<Ts>(DiagArgs)...);
1592 
1593   case Sema::CheckConstexprKind::CheckValid:
1594     return !T->isLiteralType(SemaRef.Context);
1595   }
1596 
1597   llvm_unreachable("unknown CheckConstexprKind");
1598 }
1599 
1600 /// Determine whether a destructor cannot be constexpr due to
1601 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1602                                                const CXXDestructorDecl *DD,
1603                                                Sema::CheckConstexprKind Kind) {
1604   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1605     const CXXRecordDecl *RD =
1606         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1607     if (!RD || RD->hasConstexprDestructor())
1608       return true;
1609 
1610     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1611       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1612           << DD->getConstexprKind() << !FD
1613           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1614       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1615           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1616     }
1617     return false;
1618   };
1619 
1620   const CXXRecordDecl *RD = DD->getParent();
1621   for (const CXXBaseSpecifier &B : RD->bases())
1622     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1623       return false;
1624   for (const FieldDecl *FD : RD->fields())
1625     if (!Check(FD->getLocation(), FD->getType(), FD))
1626       return false;
1627   return true;
1628 }
1629 
1630 /// Check whether a function's parameter types are all literal types. If so,
1631 /// return true. If not, produce a suitable diagnostic and return false.
1632 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1633                                          const FunctionDecl *FD,
1634                                          Sema::CheckConstexprKind Kind) {
1635   unsigned ArgIndex = 0;
1636   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1637   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1638                                               e = FT->param_type_end();
1639        i != e; ++i, ++ArgIndex) {
1640     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1641     SourceLocation ParamLoc = PD->getLocation();
1642     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1643                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1644                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1645                          FD->isConsteval()))
1646       return false;
1647   }
1648   return true;
1649 }
1650 
1651 /// Check whether a function's return type is a literal type. If so, return
1652 /// true. If not, produce a suitable diagnostic and return false.
1653 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1654                                      Sema::CheckConstexprKind Kind) {
1655   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1656                        diag::err_constexpr_non_literal_return,
1657                        FD->isConsteval()))
1658     return false;
1659   return true;
1660 }
1661 
1662 /// Get diagnostic %select index for tag kind for
1663 /// record diagnostic message.
1664 /// WARNING: Indexes apply to particular diagnostics only!
1665 ///
1666 /// \returns diagnostic %select index.
1667 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1668   switch (Tag) {
1669   case TTK_Struct: return 0;
1670   case TTK_Interface: return 1;
1671   case TTK_Class:  return 2;
1672   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1673   }
1674 }
1675 
1676 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1677                                        Stmt *Body,
1678                                        Sema::CheckConstexprKind Kind);
1679 
1680 // Check whether a function declaration satisfies the requirements of a
1681 // constexpr function definition or a constexpr constructor definition. If so,
1682 // return true. If not, produce appropriate diagnostics (unless asked not to by
1683 // Kind) and return false.
1684 //
1685 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1686 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1687                                             CheckConstexprKind Kind) {
1688   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1689   if (MD && MD->isInstance()) {
1690     // C++11 [dcl.constexpr]p4:
1691     //  The definition of a constexpr constructor shall satisfy the following
1692     //  constraints:
1693     //  - the class shall not have any virtual base classes;
1694     //
1695     // FIXME: This only applies to constructors and destructors, not arbitrary
1696     // member functions.
1697     const CXXRecordDecl *RD = MD->getParent();
1698     if (RD->getNumVBases()) {
1699       if (Kind == CheckConstexprKind::CheckValid)
1700         return false;
1701 
1702       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1703         << isa<CXXConstructorDecl>(NewFD)
1704         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1705       for (const auto &I : RD->vbases())
1706         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1707             << I.getSourceRange();
1708       return false;
1709     }
1710   }
1711 
1712   if (!isa<CXXConstructorDecl>(NewFD)) {
1713     // C++11 [dcl.constexpr]p3:
1714     //  The definition of a constexpr function shall satisfy the following
1715     //  constraints:
1716     // - it shall not be virtual; (removed in C++20)
1717     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1718     if (Method && Method->isVirtual()) {
1719       if (getLangOpts().CPlusPlus20) {
1720         if (Kind == CheckConstexprKind::Diagnose)
1721           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1722       } else {
1723         if (Kind == CheckConstexprKind::CheckValid)
1724           return false;
1725 
1726         Method = Method->getCanonicalDecl();
1727         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1728 
1729         // If it's not obvious why this function is virtual, find an overridden
1730         // function which uses the 'virtual' keyword.
1731         const CXXMethodDecl *WrittenVirtual = Method;
1732         while (!WrittenVirtual->isVirtualAsWritten())
1733           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1734         if (WrittenVirtual != Method)
1735           Diag(WrittenVirtual->getLocation(),
1736                diag::note_overridden_virtual_function);
1737         return false;
1738       }
1739     }
1740 
1741     // - its return type shall be a literal type;
1742     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1743       return false;
1744   }
1745 
1746   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1747     // A destructor can be constexpr only if the defaulted destructor could be;
1748     // we don't need to check the members and bases if we already know they all
1749     // have constexpr destructors.
1750     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1751       if (Kind == CheckConstexprKind::CheckValid)
1752         return false;
1753       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1754         return false;
1755     }
1756   }
1757 
1758   // - each of its parameter types shall be a literal type;
1759   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1760     return false;
1761 
1762   Stmt *Body = NewFD->getBody();
1763   assert(Body &&
1764          "CheckConstexprFunctionDefinition called on function with no body");
1765   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1766 }
1767 
1768 /// Check the given declaration statement is legal within a constexpr function
1769 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1770 ///
1771 /// \return true if the body is OK (maybe only as an extension), false if we
1772 ///         have diagnosed a problem.
1773 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1774                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1775                                    Sema::CheckConstexprKind Kind) {
1776   // C++11 [dcl.constexpr]p3 and p4:
1777   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1778   //  contain only
1779   for (const auto *DclIt : DS->decls()) {
1780     switch (DclIt->getKind()) {
1781     case Decl::StaticAssert:
1782     case Decl::Using:
1783     case Decl::UsingShadow:
1784     case Decl::UsingDirective:
1785     case Decl::UnresolvedUsingTypename:
1786     case Decl::UnresolvedUsingValue:
1787       //   - static_assert-declarations
1788       //   - using-declarations,
1789       //   - using-directives,
1790       continue;
1791 
1792     case Decl::Typedef:
1793     case Decl::TypeAlias: {
1794       //   - typedef declarations and alias-declarations that do not define
1795       //     classes or enumerations,
1796       const auto *TN = cast<TypedefNameDecl>(DclIt);
1797       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1798         // Don't allow variably-modified types in constexpr functions.
1799         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1800           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1801           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1802             << TL.getSourceRange() << TL.getType()
1803             << isa<CXXConstructorDecl>(Dcl);
1804         }
1805         return false;
1806       }
1807       continue;
1808     }
1809 
1810     case Decl::Enum:
1811     case Decl::CXXRecord:
1812       // C++1y allows types to be defined, not just declared.
1813       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1814         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1815           SemaRef.Diag(DS->getBeginLoc(),
1816                        SemaRef.getLangOpts().CPlusPlus14
1817                            ? diag::warn_cxx11_compat_constexpr_type_definition
1818                            : diag::ext_constexpr_type_definition)
1819               << isa<CXXConstructorDecl>(Dcl);
1820         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1821           return false;
1822         }
1823       }
1824       continue;
1825 
1826     case Decl::EnumConstant:
1827     case Decl::IndirectField:
1828     case Decl::ParmVar:
1829       // These can only appear with other declarations which are banned in
1830       // C++11 and permitted in C++1y, so ignore them.
1831       continue;
1832 
1833     case Decl::Var:
1834     case Decl::Decomposition: {
1835       // C++1y [dcl.constexpr]p3 allows anything except:
1836       //   a definition of a variable of non-literal type or of static or
1837       //   thread storage duration or [before C++2a] for which no
1838       //   initialization is performed.
1839       const auto *VD = cast<VarDecl>(DclIt);
1840       if (VD->isThisDeclarationADefinition()) {
1841         if (VD->isStaticLocal()) {
1842           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1843             SemaRef.Diag(VD->getLocation(),
1844                          diag::err_constexpr_local_var_static)
1845               << isa<CXXConstructorDecl>(Dcl)
1846               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1847           }
1848           return false;
1849         }
1850         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1851                              diag::err_constexpr_local_var_non_literal_type,
1852                              isa<CXXConstructorDecl>(Dcl)))
1853           return false;
1854         if (!VD->getType()->isDependentType() &&
1855             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1856           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1857             SemaRef.Diag(
1858                 VD->getLocation(),
1859                 SemaRef.getLangOpts().CPlusPlus20
1860                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1861                     : diag::ext_constexpr_local_var_no_init)
1862                 << isa<CXXConstructorDecl>(Dcl);
1863           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1864             return false;
1865           }
1866           continue;
1867         }
1868       }
1869       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1870         SemaRef.Diag(VD->getLocation(),
1871                      SemaRef.getLangOpts().CPlusPlus14
1872                       ? diag::warn_cxx11_compat_constexpr_local_var
1873                       : diag::ext_constexpr_local_var)
1874           << isa<CXXConstructorDecl>(Dcl);
1875       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1876         return false;
1877       }
1878       continue;
1879     }
1880 
1881     case Decl::NamespaceAlias:
1882     case Decl::Function:
1883       // These are disallowed in C++11 and permitted in C++1y. Allow them
1884       // everywhere as an extension.
1885       if (!Cxx1yLoc.isValid())
1886         Cxx1yLoc = DS->getBeginLoc();
1887       continue;
1888 
1889     default:
1890       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1891         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1892             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1893       }
1894       return false;
1895     }
1896   }
1897 
1898   return true;
1899 }
1900 
1901 /// Check that the given field is initialized within a constexpr constructor.
1902 ///
1903 /// \param Dcl The constexpr constructor being checked.
1904 /// \param Field The field being checked. This may be a member of an anonymous
1905 ///        struct or union nested within the class being checked.
1906 /// \param Inits All declarations, including anonymous struct/union members and
1907 ///        indirect members, for which any initialization was provided.
1908 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1909 ///        multiple notes for different members to the same error.
1910 /// \param Kind Whether we're diagnosing a constructor as written or determining
1911 ///        whether the formal requirements are satisfied.
1912 /// \return \c false if we're checking for validity and the constructor does
1913 ///         not satisfy the requirements on a constexpr constructor.
1914 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1915                                           const FunctionDecl *Dcl,
1916                                           FieldDecl *Field,
1917                                           llvm::SmallSet<Decl*, 16> &Inits,
1918                                           bool &Diagnosed,
1919                                           Sema::CheckConstexprKind Kind) {
1920   // In C++20 onwards, there's nothing to check for validity.
1921   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1922       SemaRef.getLangOpts().CPlusPlus20)
1923     return true;
1924 
1925   if (Field->isInvalidDecl())
1926     return true;
1927 
1928   if (Field->isUnnamedBitfield())
1929     return true;
1930 
1931   // Anonymous unions with no variant members and empty anonymous structs do not
1932   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1933   // indirect fields don't need initializing.
1934   if (Field->isAnonymousStructOrUnion() &&
1935       (Field->getType()->isUnionType()
1936            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1937            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1938     return true;
1939 
1940   if (!Inits.count(Field)) {
1941     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942       if (!Diagnosed) {
1943         SemaRef.Diag(Dcl->getLocation(),
1944                      SemaRef.getLangOpts().CPlusPlus20
1945                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1946                          : diag::ext_constexpr_ctor_missing_init);
1947         Diagnosed = true;
1948       }
1949       SemaRef.Diag(Field->getLocation(),
1950                    diag::note_constexpr_ctor_missing_init);
1951     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1952       return false;
1953     }
1954   } else if (Field->isAnonymousStructOrUnion()) {
1955     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1956     for (auto *I : RD->fields())
1957       // If an anonymous union contains an anonymous struct of which any member
1958       // is initialized, all members must be initialized.
1959       if (!RD->isUnion() || Inits.count(I))
1960         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1961                                            Kind))
1962           return false;
1963   }
1964   return true;
1965 }
1966 
1967 /// Check the provided statement is allowed in a constexpr function
1968 /// definition.
1969 static bool
1970 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1971                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1972                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1973                            Sema::CheckConstexprKind Kind) {
1974   // - its function-body shall be [...] a compound-statement that contains only
1975   switch (S->getStmtClass()) {
1976   case Stmt::NullStmtClass:
1977     //   - null statements,
1978     return true;
1979 
1980   case Stmt::DeclStmtClass:
1981     //   - static_assert-declarations
1982     //   - using-declarations,
1983     //   - using-directives,
1984     //   - typedef declarations and alias-declarations that do not define
1985     //     classes or enumerations,
1986     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1987       return false;
1988     return true;
1989 
1990   case Stmt::ReturnStmtClass:
1991     //   - and exactly one return statement;
1992     if (isa<CXXConstructorDecl>(Dcl)) {
1993       // C++1y allows return statements in constexpr constructors.
1994       if (!Cxx1yLoc.isValid())
1995         Cxx1yLoc = S->getBeginLoc();
1996       return true;
1997     }
1998 
1999     ReturnStmts.push_back(S->getBeginLoc());
2000     return true;
2001 
2002   case Stmt::CompoundStmtClass: {
2003     // C++1y allows compound-statements.
2004     if (!Cxx1yLoc.isValid())
2005       Cxx1yLoc = S->getBeginLoc();
2006 
2007     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2008     for (auto *BodyIt : CompStmt->body()) {
2009       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2010                                       Cxx1yLoc, Cxx2aLoc, Kind))
2011         return false;
2012     }
2013     return true;
2014   }
2015 
2016   case Stmt::AttributedStmtClass:
2017     if (!Cxx1yLoc.isValid())
2018       Cxx1yLoc = S->getBeginLoc();
2019     return true;
2020 
2021   case Stmt::IfStmtClass: {
2022     // C++1y allows if-statements.
2023     if (!Cxx1yLoc.isValid())
2024       Cxx1yLoc = S->getBeginLoc();
2025 
2026     IfStmt *If = cast<IfStmt>(S);
2027     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2028                                     Cxx1yLoc, Cxx2aLoc, Kind))
2029       return false;
2030     if (If->getElse() &&
2031         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2032                                     Cxx1yLoc, Cxx2aLoc, Kind))
2033       return false;
2034     return true;
2035   }
2036 
2037   case Stmt::WhileStmtClass:
2038   case Stmt::DoStmtClass:
2039   case Stmt::ForStmtClass:
2040   case Stmt::CXXForRangeStmtClass:
2041   case Stmt::ContinueStmtClass:
2042     // C++1y allows all of these. We don't allow them as extensions in C++11,
2043     // because they don't make sense without variable mutation.
2044     if (!SemaRef.getLangOpts().CPlusPlus14)
2045       break;
2046     if (!Cxx1yLoc.isValid())
2047       Cxx1yLoc = S->getBeginLoc();
2048     for (Stmt *SubStmt : S->children())
2049       if (SubStmt &&
2050           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2051                                       Cxx1yLoc, Cxx2aLoc, Kind))
2052         return false;
2053     return true;
2054 
2055   case Stmt::SwitchStmtClass:
2056   case Stmt::CaseStmtClass:
2057   case Stmt::DefaultStmtClass:
2058   case Stmt::BreakStmtClass:
2059     // C++1y allows switch-statements, and since they don't need variable
2060     // mutation, we can reasonably allow them in C++11 as an extension.
2061     if (!Cxx1yLoc.isValid())
2062       Cxx1yLoc = S->getBeginLoc();
2063     for (Stmt *SubStmt : S->children())
2064       if (SubStmt &&
2065           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2066                                       Cxx1yLoc, Cxx2aLoc, Kind))
2067         return false;
2068     return true;
2069 
2070   case Stmt::GCCAsmStmtClass:
2071   case Stmt::MSAsmStmtClass:
2072     // C++2a allows inline assembly statements.
2073   case Stmt::CXXTryStmtClass:
2074     if (Cxx2aLoc.isInvalid())
2075       Cxx2aLoc = S->getBeginLoc();
2076     for (Stmt *SubStmt : S->children()) {
2077       if (SubStmt &&
2078           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2079                                       Cxx1yLoc, Cxx2aLoc, Kind))
2080         return false;
2081     }
2082     return true;
2083 
2084   case Stmt::CXXCatchStmtClass:
2085     // Do not bother checking the language mode (already covered by the
2086     // try block check).
2087     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2088                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2089                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2090       return false;
2091     return true;
2092 
2093   default:
2094     if (!isa<Expr>(S))
2095       break;
2096 
2097     // C++1y allows expression-statements.
2098     if (!Cxx1yLoc.isValid())
2099       Cxx1yLoc = S->getBeginLoc();
2100     return true;
2101   }
2102 
2103   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2104     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2105         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2106   }
2107   return false;
2108 }
2109 
2110 /// Check the body for the given constexpr function declaration only contains
2111 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2112 ///
2113 /// \return true if the body is OK, false if we have found or diagnosed a
2114 /// problem.
2115 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2116                                        Stmt *Body,
2117                                        Sema::CheckConstexprKind Kind) {
2118   SmallVector<SourceLocation, 4> ReturnStmts;
2119 
2120   if (isa<CXXTryStmt>(Body)) {
2121     // C++11 [dcl.constexpr]p3:
2122     //  The definition of a constexpr function shall satisfy the following
2123     //  constraints: [...]
2124     // - its function-body shall be = delete, = default, or a
2125     //   compound-statement
2126     //
2127     // C++11 [dcl.constexpr]p4:
2128     //  In the definition of a constexpr constructor, [...]
2129     // - its function-body shall not be a function-try-block;
2130     //
2131     // This restriction is lifted in C++2a, as long as inner statements also
2132     // apply the general constexpr rules.
2133     switch (Kind) {
2134     case Sema::CheckConstexprKind::CheckValid:
2135       if (!SemaRef.getLangOpts().CPlusPlus20)
2136         return false;
2137       break;
2138 
2139     case Sema::CheckConstexprKind::Diagnose:
2140       SemaRef.Diag(Body->getBeginLoc(),
2141            !SemaRef.getLangOpts().CPlusPlus20
2142                ? diag::ext_constexpr_function_try_block_cxx20
2143                : diag::warn_cxx17_compat_constexpr_function_try_block)
2144           << isa<CXXConstructorDecl>(Dcl);
2145       break;
2146     }
2147   }
2148 
2149   // - its function-body shall be [...] a compound-statement that contains only
2150   //   [... list of cases ...]
2151   //
2152   // Note that walking the children here is enough to properly check for
2153   // CompoundStmt and CXXTryStmt body.
2154   SourceLocation Cxx1yLoc, Cxx2aLoc;
2155   for (Stmt *SubStmt : Body->children()) {
2156     if (SubStmt &&
2157         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2158                                     Cxx1yLoc, Cxx2aLoc, Kind))
2159       return false;
2160   }
2161 
2162   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2163     // If this is only valid as an extension, report that we don't satisfy the
2164     // constraints of the current language.
2165     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2166         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2167       return false;
2168   } else if (Cxx2aLoc.isValid()) {
2169     SemaRef.Diag(Cxx2aLoc,
2170          SemaRef.getLangOpts().CPlusPlus20
2171            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2172            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2173       << isa<CXXConstructorDecl>(Dcl);
2174   } else if (Cxx1yLoc.isValid()) {
2175     SemaRef.Diag(Cxx1yLoc,
2176          SemaRef.getLangOpts().CPlusPlus14
2177            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2178            : diag::ext_constexpr_body_invalid_stmt)
2179       << isa<CXXConstructorDecl>(Dcl);
2180   }
2181 
2182   if (const CXXConstructorDecl *Constructor
2183         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2184     const CXXRecordDecl *RD = Constructor->getParent();
2185     // DR1359:
2186     // - every non-variant non-static data member and base class sub-object
2187     //   shall be initialized;
2188     // DR1460:
2189     // - if the class is a union having variant members, exactly one of them
2190     //   shall be initialized;
2191     if (RD->isUnion()) {
2192       if (Constructor->getNumCtorInitializers() == 0 &&
2193           RD->hasVariantMembers()) {
2194         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2195           SemaRef.Diag(
2196               Dcl->getLocation(),
2197               SemaRef.getLangOpts().CPlusPlus20
2198                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2199                   : diag::ext_constexpr_union_ctor_no_init);
2200         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2201           return false;
2202         }
2203       }
2204     } else if (!Constructor->isDependentContext() &&
2205                !Constructor->isDelegatingConstructor()) {
2206       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2207 
2208       // Skip detailed checking if we have enough initializers, and we would
2209       // allow at most one initializer per member.
2210       bool AnyAnonStructUnionMembers = false;
2211       unsigned Fields = 0;
2212       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2213            E = RD->field_end(); I != E; ++I, ++Fields) {
2214         if (I->isAnonymousStructOrUnion()) {
2215           AnyAnonStructUnionMembers = true;
2216           break;
2217         }
2218       }
2219       // DR1460:
2220       // - if the class is a union-like class, but is not a union, for each of
2221       //   its anonymous union members having variant members, exactly one of
2222       //   them shall be initialized;
2223       if (AnyAnonStructUnionMembers ||
2224           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2225         // Check initialization of non-static data members. Base classes are
2226         // always initialized so do not need to be checked. Dependent bases
2227         // might not have initializers in the member initializer list.
2228         llvm::SmallSet<Decl*, 16> Inits;
2229         for (const auto *I: Constructor->inits()) {
2230           if (FieldDecl *FD = I->getMember())
2231             Inits.insert(FD);
2232           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2233             Inits.insert(ID->chain_begin(), ID->chain_end());
2234         }
2235 
2236         bool Diagnosed = false;
2237         for (auto *I : RD->fields())
2238           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2239                                              Kind))
2240             return false;
2241       }
2242     }
2243   } else {
2244     if (ReturnStmts.empty()) {
2245       // C++1y doesn't require constexpr functions to contain a 'return'
2246       // statement. We still do, unless the return type might be void, because
2247       // otherwise if there's no return statement, the function cannot
2248       // be used in a core constant expression.
2249       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2250                 (Dcl->getReturnType()->isVoidType() ||
2251                  Dcl->getReturnType()->isDependentType());
2252       switch (Kind) {
2253       case Sema::CheckConstexprKind::Diagnose:
2254         SemaRef.Diag(Dcl->getLocation(),
2255                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2256                         : diag::err_constexpr_body_no_return)
2257             << Dcl->isConsteval();
2258         if (!OK)
2259           return false;
2260         break;
2261 
2262       case Sema::CheckConstexprKind::CheckValid:
2263         // The formal requirements don't include this rule in C++14, even
2264         // though the "must be able to produce a constant expression" rules
2265         // still imply it in some cases.
2266         if (!SemaRef.getLangOpts().CPlusPlus14)
2267           return false;
2268         break;
2269       }
2270     } else if (ReturnStmts.size() > 1) {
2271       switch (Kind) {
2272       case Sema::CheckConstexprKind::Diagnose:
2273         SemaRef.Diag(
2274             ReturnStmts.back(),
2275             SemaRef.getLangOpts().CPlusPlus14
2276                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2277                 : diag::ext_constexpr_body_multiple_return);
2278         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2279           SemaRef.Diag(ReturnStmts[I],
2280                        diag::note_constexpr_body_previous_return);
2281         break;
2282 
2283       case Sema::CheckConstexprKind::CheckValid:
2284         if (!SemaRef.getLangOpts().CPlusPlus14)
2285           return false;
2286         break;
2287       }
2288     }
2289   }
2290 
2291   // C++11 [dcl.constexpr]p5:
2292   //   if no function argument values exist such that the function invocation
2293   //   substitution would produce a constant expression, the program is
2294   //   ill-formed; no diagnostic required.
2295   // C++11 [dcl.constexpr]p3:
2296   //   - every constructor call and implicit conversion used in initializing the
2297   //     return value shall be one of those allowed in a constant expression.
2298   // C++11 [dcl.constexpr]p4:
2299   //   - every constructor involved in initializing non-static data members and
2300   //     base class sub-objects shall be a constexpr constructor.
2301   //
2302   // Note that this rule is distinct from the "requirements for a constexpr
2303   // function", so is not checked in CheckValid mode.
2304   SmallVector<PartialDiagnosticAt, 8> Diags;
2305   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2306       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2307     SemaRef.Diag(Dcl->getLocation(),
2308                  diag::ext_constexpr_function_never_constant_expr)
2309         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2310     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2311       SemaRef.Diag(Diags[I].first, Diags[I].second);
2312     // Don't return false here: we allow this for compatibility in
2313     // system headers.
2314   }
2315 
2316   return true;
2317 }
2318 
2319 /// Get the class that is directly named by the current context. This is the
2320 /// class for which an unqualified-id in this scope could name a constructor
2321 /// or destructor.
2322 ///
2323 /// If the scope specifier denotes a class, this will be that class.
2324 /// If the scope specifier is empty, this will be the class whose
2325 /// member-specification we are currently within. Otherwise, there
2326 /// is no such class.
2327 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2328   assert(getLangOpts().CPlusPlus && "No class names in C!");
2329 
2330   if (SS && SS->isInvalid())
2331     return nullptr;
2332 
2333   if (SS && SS->isNotEmpty()) {
2334     DeclContext *DC = computeDeclContext(*SS, true);
2335     return dyn_cast_or_null<CXXRecordDecl>(DC);
2336   }
2337 
2338   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2339 }
2340 
2341 /// isCurrentClassName - Determine whether the identifier II is the
2342 /// name of the class type currently being defined. In the case of
2343 /// nested classes, this will only return true if II is the name of
2344 /// the innermost class.
2345 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2346                               const CXXScopeSpec *SS) {
2347   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2348   return CurDecl && &II == CurDecl->getIdentifier();
2349 }
2350 
2351 /// Determine whether the identifier II is a typo for the name of
2352 /// the class type currently being defined. If so, update it to the identifier
2353 /// that should have been used.
2354 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2355   assert(getLangOpts().CPlusPlus && "No class names in C!");
2356 
2357   if (!getLangOpts().SpellChecking)
2358     return false;
2359 
2360   CXXRecordDecl *CurDecl;
2361   if (SS && SS->isSet() && !SS->isInvalid()) {
2362     DeclContext *DC = computeDeclContext(*SS, true);
2363     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2364   } else
2365     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2366 
2367   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2368       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2369           < II->getLength()) {
2370     II = CurDecl->getIdentifier();
2371     return true;
2372   }
2373 
2374   return false;
2375 }
2376 
2377 /// Determine whether the given class is a base class of the given
2378 /// class, including looking at dependent bases.
2379 static bool findCircularInheritance(const CXXRecordDecl *Class,
2380                                     const CXXRecordDecl *Current) {
2381   SmallVector<const CXXRecordDecl*, 8> Queue;
2382 
2383   Class = Class->getCanonicalDecl();
2384   while (true) {
2385     for (const auto &I : Current->bases()) {
2386       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2387       if (!Base)
2388         continue;
2389 
2390       Base = Base->getDefinition();
2391       if (!Base)
2392         continue;
2393 
2394       if (Base->getCanonicalDecl() == Class)
2395         return true;
2396 
2397       Queue.push_back(Base);
2398     }
2399 
2400     if (Queue.empty())
2401       return false;
2402 
2403     Current = Queue.pop_back_val();
2404   }
2405 
2406   return false;
2407 }
2408 
2409 /// Check the validity of a C++ base class specifier.
2410 ///
2411 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2412 /// and returns NULL otherwise.
2413 CXXBaseSpecifier *
2414 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2415                          SourceRange SpecifierRange,
2416                          bool Virtual, AccessSpecifier Access,
2417                          TypeSourceInfo *TInfo,
2418                          SourceLocation EllipsisLoc) {
2419   QualType BaseType = TInfo->getType();
2420 
2421   // C++ [class.union]p1:
2422   //   A union shall not have base classes.
2423   if (Class->isUnion()) {
2424     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2425       << SpecifierRange;
2426     return nullptr;
2427   }
2428 
2429   if (EllipsisLoc.isValid() &&
2430       !TInfo->getType()->containsUnexpandedParameterPack()) {
2431     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2432       << TInfo->getTypeLoc().getSourceRange();
2433     EllipsisLoc = SourceLocation();
2434   }
2435 
2436   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2437 
2438   if (BaseType->isDependentType()) {
2439     // Make sure that we don't have circular inheritance among our dependent
2440     // bases. For non-dependent bases, the check for completeness below handles
2441     // this.
2442     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2443       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2444           ((BaseDecl = BaseDecl->getDefinition()) &&
2445            findCircularInheritance(Class, BaseDecl))) {
2446         Diag(BaseLoc, diag::err_circular_inheritance)
2447           << BaseType << Context.getTypeDeclType(Class);
2448 
2449         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2450           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2451             << BaseType;
2452 
2453         return nullptr;
2454       }
2455     }
2456 
2457     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2458                                           Class->getTagKind() == TTK_Class,
2459                                           Access, TInfo, EllipsisLoc);
2460   }
2461 
2462   // Base specifiers must be record types.
2463   if (!BaseType->isRecordType()) {
2464     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2465     return nullptr;
2466   }
2467 
2468   // C++ [class.union]p1:
2469   //   A union shall not be used as a base class.
2470   if (BaseType->isUnionType()) {
2471     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2472     return nullptr;
2473   }
2474 
2475   // For the MS ABI, propagate DLL attributes to base class templates.
2476   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2477     if (Attr *ClassAttr = getDLLAttr(Class)) {
2478       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2479               BaseType->getAsCXXRecordDecl())) {
2480         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2481                                             BaseLoc);
2482       }
2483     }
2484   }
2485 
2486   // C++ [class.derived]p2:
2487   //   The class-name in a base-specifier shall not be an incompletely
2488   //   defined class.
2489   if (RequireCompleteType(BaseLoc, BaseType,
2490                           diag::err_incomplete_base_class, SpecifierRange)) {
2491     Class->setInvalidDecl();
2492     return nullptr;
2493   }
2494 
2495   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2496   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2497   assert(BaseDecl && "Record type has no declaration");
2498   BaseDecl = BaseDecl->getDefinition();
2499   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2500   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2501   assert(CXXBaseDecl && "Base type is not a C++ type");
2502 
2503   // Microsoft docs say:
2504   // "If a base-class has a code_seg attribute, derived classes must have the
2505   // same attribute."
2506   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2507   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2508   if ((DerivedCSA || BaseCSA) &&
2509       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2510     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2511     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2512       << CXXBaseDecl;
2513     return nullptr;
2514   }
2515 
2516   // A class which contains a flexible array member is not suitable for use as a
2517   // base class:
2518   //   - If the layout determines that a base comes before another base,
2519   //     the flexible array member would index into the subsequent base.
2520   //   - If the layout determines that base comes before the derived class,
2521   //     the flexible array member would index into the derived class.
2522   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2523     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2524       << CXXBaseDecl->getDeclName();
2525     return nullptr;
2526   }
2527 
2528   // C++ [class]p3:
2529   //   If a class is marked final and it appears as a base-type-specifier in
2530   //   base-clause, the program is ill-formed.
2531   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2532     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2533       << CXXBaseDecl->getDeclName()
2534       << FA->isSpelledAsSealed();
2535     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2536         << CXXBaseDecl->getDeclName() << FA->getRange();
2537     return nullptr;
2538   }
2539 
2540   if (BaseDecl->isInvalidDecl())
2541     Class->setInvalidDecl();
2542 
2543   // Create the base specifier.
2544   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2545                                         Class->getTagKind() == TTK_Class,
2546                                         Access, TInfo, EllipsisLoc);
2547 }
2548 
2549 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2550 /// one entry in the base class list of a class specifier, for
2551 /// example:
2552 ///    class foo : public bar, virtual private baz {
2553 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2554 BaseResult
2555 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2556                          ParsedAttributes &Attributes,
2557                          bool Virtual, AccessSpecifier Access,
2558                          ParsedType basetype, SourceLocation BaseLoc,
2559                          SourceLocation EllipsisLoc) {
2560   if (!classdecl)
2561     return true;
2562 
2563   AdjustDeclIfTemplate(classdecl);
2564   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2565   if (!Class)
2566     return true;
2567 
2568   // We haven't yet attached the base specifiers.
2569   Class->setIsParsingBaseSpecifiers();
2570 
2571   // We do not support any C++11 attributes on base-specifiers yet.
2572   // Diagnose any attributes we see.
2573   for (const ParsedAttr &AL : Attributes) {
2574     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2575       continue;
2576     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2577                           ? (unsigned)diag::warn_unknown_attribute_ignored
2578                           : (unsigned)diag::err_base_specifier_attribute)
2579         << AL;
2580   }
2581 
2582   TypeSourceInfo *TInfo = nullptr;
2583   GetTypeFromParser(basetype, &TInfo);
2584 
2585   if (EllipsisLoc.isInvalid() &&
2586       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2587                                       UPPC_BaseType))
2588     return true;
2589 
2590   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2591                                                       Virtual, Access, TInfo,
2592                                                       EllipsisLoc))
2593     return BaseSpec;
2594   else
2595     Class->setInvalidDecl();
2596 
2597   return true;
2598 }
2599 
2600 /// Use small set to collect indirect bases.  As this is only used
2601 /// locally, there's no need to abstract the small size parameter.
2602 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2603 
2604 /// Recursively add the bases of Type.  Don't add Type itself.
2605 static void
2606 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2607                   const QualType &Type)
2608 {
2609   // Even though the incoming type is a base, it might not be
2610   // a class -- it could be a template parm, for instance.
2611   if (auto Rec = Type->getAs<RecordType>()) {
2612     auto Decl = Rec->getAsCXXRecordDecl();
2613 
2614     // Iterate over its bases.
2615     for (const auto &BaseSpec : Decl->bases()) {
2616       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2617         .getUnqualifiedType();
2618       if (Set.insert(Base).second)
2619         // If we've not already seen it, recurse.
2620         NoteIndirectBases(Context, Set, Base);
2621     }
2622   }
2623 }
2624 
2625 /// Performs the actual work of attaching the given base class
2626 /// specifiers to a C++ class.
2627 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2628                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2629  if (Bases.empty())
2630     return false;
2631 
2632   // Used to keep track of which base types we have already seen, so
2633   // that we can properly diagnose redundant direct base types. Note
2634   // that the key is always the unqualified canonical type of the base
2635   // class.
2636   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2637 
2638   // Used to track indirect bases so we can see if a direct base is
2639   // ambiguous.
2640   IndirectBaseSet IndirectBaseTypes;
2641 
2642   // Copy non-redundant base specifiers into permanent storage.
2643   unsigned NumGoodBases = 0;
2644   bool Invalid = false;
2645   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2646     QualType NewBaseType
2647       = Context.getCanonicalType(Bases[idx]->getType());
2648     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2649 
2650     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2651     if (KnownBase) {
2652       // C++ [class.mi]p3:
2653       //   A class shall not be specified as a direct base class of a
2654       //   derived class more than once.
2655       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2656           << KnownBase->getType() << Bases[idx]->getSourceRange();
2657 
2658       // Delete the duplicate base class specifier; we're going to
2659       // overwrite its pointer later.
2660       Context.Deallocate(Bases[idx]);
2661 
2662       Invalid = true;
2663     } else {
2664       // Okay, add this new base class.
2665       KnownBase = Bases[idx];
2666       Bases[NumGoodBases++] = Bases[idx];
2667 
2668       // Note this base's direct & indirect bases, if there could be ambiguity.
2669       if (Bases.size() > 1)
2670         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2671 
2672       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2673         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2674         if (Class->isInterface() &&
2675               (!RD->isInterfaceLike() ||
2676                KnownBase->getAccessSpecifier() != AS_public)) {
2677           // The Microsoft extension __interface does not permit bases that
2678           // are not themselves public interfaces.
2679           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2680               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2681               << RD->getSourceRange();
2682           Invalid = true;
2683         }
2684         if (RD->hasAttr<WeakAttr>())
2685           Class->addAttr(WeakAttr::CreateImplicit(Context));
2686       }
2687     }
2688   }
2689 
2690   // Attach the remaining base class specifiers to the derived class.
2691   Class->setBases(Bases.data(), NumGoodBases);
2692 
2693   // Check that the only base classes that are duplicate are virtual.
2694   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2695     // Check whether this direct base is inaccessible due to ambiguity.
2696     QualType BaseType = Bases[idx]->getType();
2697 
2698     // Skip all dependent types in templates being used as base specifiers.
2699     // Checks below assume that the base specifier is a CXXRecord.
2700     if (BaseType->isDependentType())
2701       continue;
2702 
2703     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2704       .getUnqualifiedType();
2705 
2706     if (IndirectBaseTypes.count(CanonicalBase)) {
2707       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2708                          /*DetectVirtual=*/true);
2709       bool found
2710         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2711       assert(found);
2712       (void)found;
2713 
2714       if (Paths.isAmbiguous(CanonicalBase))
2715         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2716             << BaseType << getAmbiguousPathsDisplayString(Paths)
2717             << Bases[idx]->getSourceRange();
2718       else
2719         assert(Bases[idx]->isVirtual());
2720     }
2721 
2722     // Delete the base class specifier, since its data has been copied
2723     // into the CXXRecordDecl.
2724     Context.Deallocate(Bases[idx]);
2725   }
2726 
2727   return Invalid;
2728 }
2729 
2730 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2731 /// class, after checking whether there are any duplicate base
2732 /// classes.
2733 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2734                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2735   if (!ClassDecl || Bases.empty())
2736     return;
2737 
2738   AdjustDeclIfTemplate(ClassDecl);
2739   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2740 }
2741 
2742 /// Determine whether the type \p Derived is a C++ class that is
2743 /// derived from the type \p Base.
2744 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2745   if (!getLangOpts().CPlusPlus)
2746     return false;
2747 
2748   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2749   if (!DerivedRD)
2750     return false;
2751 
2752   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2753   if (!BaseRD)
2754     return false;
2755 
2756   // If either the base or the derived type is invalid, don't try to
2757   // check whether one is derived from the other.
2758   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2759     return false;
2760 
2761   // FIXME: In a modules build, do we need the entire path to be visible for us
2762   // to be able to use the inheritance relationship?
2763   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2764     return false;
2765 
2766   return DerivedRD->isDerivedFrom(BaseRD);
2767 }
2768 
2769 /// Determine whether the type \p Derived is a C++ class that is
2770 /// derived from the type \p Base.
2771 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2772                          CXXBasePaths &Paths) {
2773   if (!getLangOpts().CPlusPlus)
2774     return false;
2775 
2776   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2777   if (!DerivedRD)
2778     return false;
2779 
2780   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2781   if (!BaseRD)
2782     return false;
2783 
2784   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2785     return false;
2786 
2787   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2788 }
2789 
2790 static void BuildBasePathArray(const CXXBasePath &Path,
2791                                CXXCastPath &BasePathArray) {
2792   // We first go backward and check if we have a virtual base.
2793   // FIXME: It would be better if CXXBasePath had the base specifier for
2794   // the nearest virtual base.
2795   unsigned Start = 0;
2796   for (unsigned I = Path.size(); I != 0; --I) {
2797     if (Path[I - 1].Base->isVirtual()) {
2798       Start = I - 1;
2799       break;
2800     }
2801   }
2802 
2803   // Now add all bases.
2804   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2805     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2806 }
2807 
2808 
2809 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2810                               CXXCastPath &BasePathArray) {
2811   assert(BasePathArray.empty() && "Base path array must be empty!");
2812   assert(Paths.isRecordingPaths() && "Must record paths!");
2813   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2814 }
2815 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2816 /// conversion (where Derived and Base are class types) is
2817 /// well-formed, meaning that the conversion is unambiguous (and
2818 /// that all of the base classes are accessible). Returns true
2819 /// and emits a diagnostic if the code is ill-formed, returns false
2820 /// otherwise. Loc is the location where this routine should point to
2821 /// if there is an error, and Range is the source range to highlight
2822 /// if there is an error.
2823 ///
2824 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2825 /// diagnostic for the respective type of error will be suppressed, but the
2826 /// check for ill-formed code will still be performed.
2827 bool
2828 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2829                                    unsigned InaccessibleBaseID,
2830                                    unsigned AmbiguousBaseConvID,
2831                                    SourceLocation Loc, SourceRange Range,
2832                                    DeclarationName Name,
2833                                    CXXCastPath *BasePath,
2834                                    bool IgnoreAccess) {
2835   // First, determine whether the path from Derived to Base is
2836   // ambiguous. This is slightly more expensive than checking whether
2837   // the Derived to Base conversion exists, because here we need to
2838   // explore multiple paths to determine if there is an ambiguity.
2839   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2840                      /*DetectVirtual=*/false);
2841   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2842   if (!DerivationOkay)
2843     return true;
2844 
2845   const CXXBasePath *Path = nullptr;
2846   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2847     Path = &Paths.front();
2848 
2849   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2850   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2851   // user to access such bases.
2852   if (!Path && getLangOpts().MSVCCompat) {
2853     for (const CXXBasePath &PossiblePath : Paths) {
2854       if (PossiblePath.size() == 1) {
2855         Path = &PossiblePath;
2856         if (AmbiguousBaseConvID)
2857           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2858               << Base << Derived << Range;
2859         break;
2860       }
2861     }
2862   }
2863 
2864   if (Path) {
2865     if (!IgnoreAccess) {
2866       // Check that the base class can be accessed.
2867       switch (
2868           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2869       case AR_inaccessible:
2870         return true;
2871       case AR_accessible:
2872       case AR_dependent:
2873       case AR_delayed:
2874         break;
2875       }
2876     }
2877 
2878     // Build a base path if necessary.
2879     if (BasePath)
2880       ::BuildBasePathArray(*Path, *BasePath);
2881     return false;
2882   }
2883 
2884   if (AmbiguousBaseConvID) {
2885     // We know that the derived-to-base conversion is ambiguous, and
2886     // we're going to produce a diagnostic. Perform the derived-to-base
2887     // search just one more time to compute all of the possible paths so
2888     // that we can print them out. This is more expensive than any of
2889     // the previous derived-to-base checks we've done, but at this point
2890     // performance isn't as much of an issue.
2891     Paths.clear();
2892     Paths.setRecordingPaths(true);
2893     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2894     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2895     (void)StillOkay;
2896 
2897     // Build up a textual representation of the ambiguous paths, e.g.,
2898     // D -> B -> A, that will be used to illustrate the ambiguous
2899     // conversions in the diagnostic. We only print one of the paths
2900     // to each base class subobject.
2901     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2902 
2903     Diag(Loc, AmbiguousBaseConvID)
2904     << Derived << Base << PathDisplayStr << Range << Name;
2905   }
2906   return true;
2907 }
2908 
2909 bool
2910 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2911                                    SourceLocation Loc, SourceRange Range,
2912                                    CXXCastPath *BasePath,
2913                                    bool IgnoreAccess) {
2914   return CheckDerivedToBaseConversion(
2915       Derived, Base, diag::err_upcast_to_inaccessible_base,
2916       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2917       BasePath, IgnoreAccess);
2918 }
2919 
2920 
2921 /// Builds a string representing ambiguous paths from a
2922 /// specific derived class to different subobjects of the same base
2923 /// class.
2924 ///
2925 /// This function builds a string that can be used in error messages
2926 /// to show the different paths that one can take through the
2927 /// inheritance hierarchy to go from the derived class to different
2928 /// subobjects of a base class. The result looks something like this:
2929 /// @code
2930 /// struct D -> struct B -> struct A
2931 /// struct D -> struct C -> struct A
2932 /// @endcode
2933 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2934   std::string PathDisplayStr;
2935   std::set<unsigned> DisplayedPaths;
2936   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2937        Path != Paths.end(); ++Path) {
2938     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2939       // We haven't displayed a path to this particular base
2940       // class subobject yet.
2941       PathDisplayStr += "\n    ";
2942       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2943       for (CXXBasePath::const_iterator Element = Path->begin();
2944            Element != Path->end(); ++Element)
2945         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2946     }
2947   }
2948 
2949   return PathDisplayStr;
2950 }
2951 
2952 //===----------------------------------------------------------------------===//
2953 // C++ class member Handling
2954 //===----------------------------------------------------------------------===//
2955 
2956 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2957 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2958                                 SourceLocation ColonLoc,
2959                                 const ParsedAttributesView &Attrs) {
2960   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2961   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2962                                                   ASLoc, ColonLoc);
2963   CurContext->addHiddenDecl(ASDecl);
2964   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2965 }
2966 
2967 /// CheckOverrideControl - Check C++11 override control semantics.
2968 void Sema::CheckOverrideControl(NamedDecl *D) {
2969   if (D->isInvalidDecl())
2970     return;
2971 
2972   // We only care about "override" and "final" declarations.
2973   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2974     return;
2975 
2976   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2977 
2978   // We can't check dependent instance methods.
2979   if (MD && MD->isInstance() &&
2980       (MD->getParent()->hasAnyDependentBases() ||
2981        MD->getType()->isDependentType()))
2982     return;
2983 
2984   if (MD && !MD->isVirtual()) {
2985     // If we have a non-virtual method, check if if hides a virtual method.
2986     // (In that case, it's most likely the method has the wrong type.)
2987     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2988     FindHiddenVirtualMethods(MD, OverloadedMethods);
2989 
2990     if (!OverloadedMethods.empty()) {
2991       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2992         Diag(OA->getLocation(),
2993              diag::override_keyword_hides_virtual_member_function)
2994           << "override" << (OverloadedMethods.size() > 1);
2995       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2996         Diag(FA->getLocation(),
2997              diag::override_keyword_hides_virtual_member_function)
2998           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2999           << (OverloadedMethods.size() > 1);
3000       }
3001       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3002       MD->setInvalidDecl();
3003       return;
3004     }
3005     // Fall through into the general case diagnostic.
3006     // FIXME: We might want to attempt typo correction here.
3007   }
3008 
3009   if (!MD || !MD->isVirtual()) {
3010     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3011       Diag(OA->getLocation(),
3012            diag::override_keyword_only_allowed_on_virtual_member_functions)
3013         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3014       D->dropAttr<OverrideAttr>();
3015     }
3016     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3017       Diag(FA->getLocation(),
3018            diag::override_keyword_only_allowed_on_virtual_member_functions)
3019         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3020         << FixItHint::CreateRemoval(FA->getLocation());
3021       D->dropAttr<FinalAttr>();
3022     }
3023     return;
3024   }
3025 
3026   // C++11 [class.virtual]p5:
3027   //   If a function is marked with the virt-specifier override and
3028   //   does not override a member function of a base class, the program is
3029   //   ill-formed.
3030   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3031   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3032     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3033       << MD->getDeclName();
3034 }
3035 
3036 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
3037   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3038     return;
3039   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3040   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3041     return;
3042 
3043   SourceLocation Loc = MD->getLocation();
3044   SourceLocation SpellingLoc = Loc;
3045   if (getSourceManager().isMacroArgExpansion(Loc))
3046     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3047   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3048   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3049       return;
3050 
3051   if (MD->size_overridden_methods() > 0) {
3052     unsigned DiagID = isa<CXXDestructorDecl>(MD)
3053                           ? diag::warn_destructor_marked_not_override_overriding
3054                           : diag::warn_function_marked_not_override_overriding;
3055     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3056     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3057     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3058   }
3059 }
3060 
3061 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3062 /// function overrides a virtual member function marked 'final', according to
3063 /// C++11 [class.virtual]p4.
3064 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3065                                                   const CXXMethodDecl *Old) {
3066   FinalAttr *FA = Old->getAttr<FinalAttr>();
3067   if (!FA)
3068     return false;
3069 
3070   Diag(New->getLocation(), diag::err_final_function_overridden)
3071     << New->getDeclName()
3072     << FA->isSpelledAsSealed();
3073   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3074   return true;
3075 }
3076 
3077 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3078   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3079   // FIXME: Destruction of ObjC lifetime types has side-effects.
3080   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3081     return !RD->isCompleteDefinition() ||
3082            !RD->hasTrivialDefaultConstructor() ||
3083            !RD->hasTrivialDestructor();
3084   return false;
3085 }
3086 
3087 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3088   ParsedAttributesView::const_iterator Itr =
3089       llvm::find_if(list, [](const ParsedAttr &AL) {
3090         return AL.isDeclspecPropertyAttribute();
3091       });
3092   if (Itr != list.end())
3093     return &*Itr;
3094   return nullptr;
3095 }
3096 
3097 // Check if there is a field shadowing.
3098 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3099                                       DeclarationName FieldName,
3100                                       const CXXRecordDecl *RD,
3101                                       bool DeclIsField) {
3102   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3103     return;
3104 
3105   // To record a shadowed field in a base
3106   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3107   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3108                            CXXBasePath &Path) {
3109     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3110     // Record an ambiguous path directly
3111     if (Bases.find(Base) != Bases.end())
3112       return true;
3113     for (const auto Field : Base->lookup(FieldName)) {
3114       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3115           Field->getAccess() != AS_private) {
3116         assert(Field->getAccess() != AS_none);
3117         assert(Bases.find(Base) == Bases.end());
3118         Bases[Base] = Field;
3119         return true;
3120       }
3121     }
3122     return false;
3123   };
3124 
3125   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3126                      /*DetectVirtual=*/true);
3127   if (!RD->lookupInBases(FieldShadowed, Paths))
3128     return;
3129 
3130   for (const auto &P : Paths) {
3131     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3132     auto It = Bases.find(Base);
3133     // Skip duplicated bases
3134     if (It == Bases.end())
3135       continue;
3136     auto BaseField = It->second;
3137     assert(BaseField->getAccess() != AS_private);
3138     if (AS_none !=
3139         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3140       Diag(Loc, diag::warn_shadow_field)
3141         << FieldName << RD << Base << DeclIsField;
3142       Diag(BaseField->getLocation(), diag::note_shadow_field);
3143       Bases.erase(It);
3144     }
3145   }
3146 }
3147 
3148 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3149 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3150 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3151 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3152 /// present (but parsing it has been deferred).
3153 NamedDecl *
3154 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3155                                MultiTemplateParamsArg TemplateParameterLists,
3156                                Expr *BW, const VirtSpecifiers &VS,
3157                                InClassInitStyle InitStyle) {
3158   const DeclSpec &DS = D.getDeclSpec();
3159   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3160   DeclarationName Name = NameInfo.getName();
3161   SourceLocation Loc = NameInfo.getLoc();
3162 
3163   // For anonymous bitfields, the location should point to the type.
3164   if (Loc.isInvalid())
3165     Loc = D.getBeginLoc();
3166 
3167   Expr *BitWidth = static_cast<Expr*>(BW);
3168 
3169   assert(isa<CXXRecordDecl>(CurContext));
3170   assert(!DS.isFriendSpecified());
3171 
3172   bool isFunc = D.isDeclarationOfFunction();
3173   const ParsedAttr *MSPropertyAttr =
3174       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3175 
3176   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3177     // The Microsoft extension __interface only permits public member functions
3178     // and prohibits constructors, destructors, operators, non-public member
3179     // functions, static methods and data members.
3180     unsigned InvalidDecl;
3181     bool ShowDeclName = true;
3182     if (!isFunc &&
3183         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3184       InvalidDecl = 0;
3185     else if (!isFunc)
3186       InvalidDecl = 1;
3187     else if (AS != AS_public)
3188       InvalidDecl = 2;
3189     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3190       InvalidDecl = 3;
3191     else switch (Name.getNameKind()) {
3192       case DeclarationName::CXXConstructorName:
3193         InvalidDecl = 4;
3194         ShowDeclName = false;
3195         break;
3196 
3197       case DeclarationName::CXXDestructorName:
3198         InvalidDecl = 5;
3199         ShowDeclName = false;
3200         break;
3201 
3202       case DeclarationName::CXXOperatorName:
3203       case DeclarationName::CXXConversionFunctionName:
3204         InvalidDecl = 6;
3205         break;
3206 
3207       default:
3208         InvalidDecl = 0;
3209         break;
3210     }
3211 
3212     if (InvalidDecl) {
3213       if (ShowDeclName)
3214         Diag(Loc, diag::err_invalid_member_in_interface)
3215           << (InvalidDecl-1) << Name;
3216       else
3217         Diag(Loc, diag::err_invalid_member_in_interface)
3218           << (InvalidDecl-1) << "";
3219       return nullptr;
3220     }
3221   }
3222 
3223   // C++ 9.2p6: A member shall not be declared to have automatic storage
3224   // duration (auto, register) or with the extern storage-class-specifier.
3225   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3226   // data members and cannot be applied to names declared const or static,
3227   // and cannot be applied to reference members.
3228   switch (DS.getStorageClassSpec()) {
3229   case DeclSpec::SCS_unspecified:
3230   case DeclSpec::SCS_typedef:
3231   case DeclSpec::SCS_static:
3232     break;
3233   case DeclSpec::SCS_mutable:
3234     if (isFunc) {
3235       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3236 
3237       // FIXME: It would be nicer if the keyword was ignored only for this
3238       // declarator. Otherwise we could get follow-up errors.
3239       D.getMutableDeclSpec().ClearStorageClassSpecs();
3240     }
3241     break;
3242   default:
3243     Diag(DS.getStorageClassSpecLoc(),
3244          diag::err_storageclass_invalid_for_member);
3245     D.getMutableDeclSpec().ClearStorageClassSpecs();
3246     break;
3247   }
3248 
3249   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3250                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3251                       !isFunc);
3252 
3253   if (DS.hasConstexprSpecifier() && isInstField) {
3254     SemaDiagnosticBuilder B =
3255         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3256     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3257     if (InitStyle == ICIS_NoInit) {
3258       B << 0 << 0;
3259       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3260         B << FixItHint::CreateRemoval(ConstexprLoc);
3261       else {
3262         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3263         D.getMutableDeclSpec().ClearConstexprSpec();
3264         const char *PrevSpec;
3265         unsigned DiagID;
3266         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3267             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3268         (void)Failed;
3269         assert(!Failed && "Making a constexpr member const shouldn't fail");
3270       }
3271     } else {
3272       B << 1;
3273       const char *PrevSpec;
3274       unsigned DiagID;
3275       if (D.getMutableDeclSpec().SetStorageClassSpec(
3276           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3277           Context.getPrintingPolicy())) {
3278         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3279                "This is the only DeclSpec that should fail to be applied");
3280         B << 1;
3281       } else {
3282         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3283         isInstField = false;
3284       }
3285     }
3286   }
3287 
3288   NamedDecl *Member;
3289   if (isInstField) {
3290     CXXScopeSpec &SS = D.getCXXScopeSpec();
3291 
3292     // Data members must have identifiers for names.
3293     if (!Name.isIdentifier()) {
3294       Diag(Loc, diag::err_bad_variable_name)
3295         << Name;
3296       return nullptr;
3297     }
3298 
3299     IdentifierInfo *II = Name.getAsIdentifierInfo();
3300 
3301     // Member field could not be with "template" keyword.
3302     // So TemplateParameterLists should be empty in this case.
3303     if (TemplateParameterLists.size()) {
3304       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3305       if (TemplateParams->size()) {
3306         // There is no such thing as a member field template.
3307         Diag(D.getIdentifierLoc(), diag::err_template_member)
3308             << II
3309             << SourceRange(TemplateParams->getTemplateLoc(),
3310                 TemplateParams->getRAngleLoc());
3311       } else {
3312         // There is an extraneous 'template<>' for this member.
3313         Diag(TemplateParams->getTemplateLoc(),
3314             diag::err_template_member_noparams)
3315             << II
3316             << SourceRange(TemplateParams->getTemplateLoc(),
3317                 TemplateParams->getRAngleLoc());
3318       }
3319       return nullptr;
3320     }
3321 
3322     if (SS.isSet() && !SS.isInvalid()) {
3323       // The user provided a superfluous scope specifier inside a class
3324       // definition:
3325       //
3326       // class X {
3327       //   int X::member;
3328       // };
3329       if (DeclContext *DC = computeDeclContext(SS, false))
3330         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3331                                      D.getName().getKind() ==
3332                                          UnqualifiedIdKind::IK_TemplateId);
3333       else
3334         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3335           << Name << SS.getRange();
3336 
3337       SS.clear();
3338     }
3339 
3340     if (MSPropertyAttr) {
3341       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3342                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3343       if (!Member)
3344         return nullptr;
3345       isInstField = false;
3346     } else {
3347       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3348                                 BitWidth, InitStyle, AS);
3349       if (!Member)
3350         return nullptr;
3351     }
3352 
3353     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3354   } else {
3355     Member = HandleDeclarator(S, D, TemplateParameterLists);
3356     if (!Member)
3357       return nullptr;
3358 
3359     // Non-instance-fields can't have a bitfield.
3360     if (BitWidth) {
3361       if (Member->isInvalidDecl()) {
3362         // don't emit another diagnostic.
3363       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3364         // C++ 9.6p3: A bit-field shall not be a static member.
3365         // "static member 'A' cannot be a bit-field"
3366         Diag(Loc, diag::err_static_not_bitfield)
3367           << Name << BitWidth->getSourceRange();
3368       } else if (isa<TypedefDecl>(Member)) {
3369         // "typedef member 'x' cannot be a bit-field"
3370         Diag(Loc, diag::err_typedef_not_bitfield)
3371           << Name << BitWidth->getSourceRange();
3372       } else {
3373         // A function typedef ("typedef int f(); f a;").
3374         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3375         Diag(Loc, diag::err_not_integral_type_bitfield)
3376           << Name << cast<ValueDecl>(Member)->getType()
3377           << BitWidth->getSourceRange();
3378       }
3379 
3380       BitWidth = nullptr;
3381       Member->setInvalidDecl();
3382     }
3383 
3384     NamedDecl *NonTemplateMember = Member;
3385     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3386       NonTemplateMember = FunTmpl->getTemplatedDecl();
3387     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3388       NonTemplateMember = VarTmpl->getTemplatedDecl();
3389 
3390     Member->setAccess(AS);
3391 
3392     // If we have declared a member function template or static data member
3393     // template, set the access of the templated declaration as well.
3394     if (NonTemplateMember != Member)
3395       NonTemplateMember->setAccess(AS);
3396 
3397     // C++ [temp.deduct.guide]p3:
3398     //   A deduction guide [...] for a member class template [shall be
3399     //   declared] with the same access [as the template].
3400     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3401       auto *TD = DG->getDeducedTemplate();
3402       // Access specifiers are only meaningful if both the template and the
3403       // deduction guide are from the same scope.
3404       if (AS != TD->getAccess() &&
3405           TD->getDeclContext()->getRedeclContext()->Equals(
3406               DG->getDeclContext()->getRedeclContext())) {
3407         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3408         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3409             << TD->getAccess();
3410         const AccessSpecDecl *LastAccessSpec = nullptr;
3411         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3412           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3413             LastAccessSpec = AccessSpec;
3414         }
3415         assert(LastAccessSpec && "differing access with no access specifier");
3416         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3417             << AS;
3418       }
3419     }
3420   }
3421 
3422   if (VS.isOverrideSpecified())
3423     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3424                                          AttributeCommonInfo::AS_Keyword));
3425   if (VS.isFinalSpecified())
3426     Member->addAttr(FinalAttr::Create(
3427         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3428         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3429 
3430   if (VS.getLastLocation().isValid()) {
3431     // Update the end location of a method that has a virt-specifiers.
3432     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3433       MD->setRangeEnd(VS.getLastLocation());
3434   }
3435 
3436   CheckOverrideControl(Member);
3437 
3438   assert((Name || isInstField) && "No identifier for non-field ?");
3439 
3440   if (isInstField) {
3441     FieldDecl *FD = cast<FieldDecl>(Member);
3442     FieldCollector->Add(FD);
3443 
3444     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3445       // Remember all explicit private FieldDecls that have a name, no side
3446       // effects and are not part of a dependent type declaration.
3447       if (!FD->isImplicit() && FD->getDeclName() &&
3448           FD->getAccess() == AS_private &&
3449           !FD->hasAttr<UnusedAttr>() &&
3450           !FD->getParent()->isDependentContext() &&
3451           !InitializationHasSideEffects(*FD))
3452         UnusedPrivateFields.insert(FD);
3453     }
3454   }
3455 
3456   return Member;
3457 }
3458 
3459 namespace {
3460   class UninitializedFieldVisitor
3461       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3462     Sema &S;
3463     // List of Decls to generate a warning on.  Also remove Decls that become
3464     // initialized.
3465     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3466     // List of base classes of the record.  Classes are removed after their
3467     // initializers.
3468     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3469     // Vector of decls to be removed from the Decl set prior to visiting the
3470     // nodes.  These Decls may have been initialized in the prior initializer.
3471     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3472     // If non-null, add a note to the warning pointing back to the constructor.
3473     const CXXConstructorDecl *Constructor;
3474     // Variables to hold state when processing an initializer list.  When
3475     // InitList is true, special case initialization of FieldDecls matching
3476     // InitListFieldDecl.
3477     bool InitList;
3478     FieldDecl *InitListFieldDecl;
3479     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3480 
3481   public:
3482     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3483     UninitializedFieldVisitor(Sema &S,
3484                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3485                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3486       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3487         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3488 
3489     // Returns true if the use of ME is not an uninitialized use.
3490     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3491                                          bool CheckReferenceOnly) {
3492       llvm::SmallVector<FieldDecl*, 4> Fields;
3493       bool ReferenceField = false;
3494       while (ME) {
3495         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3496         if (!FD)
3497           return false;
3498         Fields.push_back(FD);
3499         if (FD->getType()->isReferenceType())
3500           ReferenceField = true;
3501         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3502       }
3503 
3504       // Binding a reference to an uninitialized field is not an
3505       // uninitialized use.
3506       if (CheckReferenceOnly && !ReferenceField)
3507         return true;
3508 
3509       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3510       // Discard the first field since it is the field decl that is being
3511       // initialized.
3512       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3513         UsedFieldIndex.push_back((*I)->getFieldIndex());
3514       }
3515 
3516       for (auto UsedIter = UsedFieldIndex.begin(),
3517                 UsedEnd = UsedFieldIndex.end(),
3518                 OrigIter = InitFieldIndex.begin(),
3519                 OrigEnd = InitFieldIndex.end();
3520            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3521         if (*UsedIter < *OrigIter)
3522           return true;
3523         if (*UsedIter > *OrigIter)
3524           break;
3525       }
3526 
3527       return false;
3528     }
3529 
3530     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3531                           bool AddressOf) {
3532       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3533         return;
3534 
3535       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3536       // or union.
3537       MemberExpr *FieldME = ME;
3538 
3539       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3540 
3541       Expr *Base = ME;
3542       while (MemberExpr *SubME =
3543                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3544 
3545         if (isa<VarDecl>(SubME->getMemberDecl()))
3546           return;
3547 
3548         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3549           if (!FD->isAnonymousStructOrUnion())
3550             FieldME = SubME;
3551 
3552         if (!FieldME->getType().isPODType(S.Context))
3553           AllPODFields = false;
3554 
3555         Base = SubME->getBase();
3556       }
3557 
3558       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3559         return;
3560 
3561       if (AddressOf && AllPODFields)
3562         return;
3563 
3564       ValueDecl* FoundVD = FieldME->getMemberDecl();
3565 
3566       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3567         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3568           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3569         }
3570 
3571         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3572           QualType T = BaseCast->getType();
3573           if (T->isPointerType() &&
3574               BaseClasses.count(T->getPointeeType())) {
3575             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3576                 << T->getPointeeType() << FoundVD;
3577           }
3578         }
3579       }
3580 
3581       if (!Decls.count(FoundVD))
3582         return;
3583 
3584       const bool IsReference = FoundVD->getType()->isReferenceType();
3585 
3586       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3587         // Special checking for initializer lists.
3588         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3589           return;
3590         }
3591       } else {
3592         // Prevent double warnings on use of unbounded references.
3593         if (CheckReferenceOnly && !IsReference)
3594           return;
3595       }
3596 
3597       unsigned diag = IsReference
3598           ? diag::warn_reference_field_is_uninit
3599           : diag::warn_field_is_uninit;
3600       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3601       if (Constructor)
3602         S.Diag(Constructor->getLocation(),
3603                diag::note_uninit_in_this_constructor)
3604           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3605 
3606     }
3607 
3608     void HandleValue(Expr *E, bool AddressOf) {
3609       E = E->IgnoreParens();
3610 
3611       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3612         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3613                          AddressOf /*AddressOf*/);
3614         return;
3615       }
3616 
3617       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3618         Visit(CO->getCond());
3619         HandleValue(CO->getTrueExpr(), AddressOf);
3620         HandleValue(CO->getFalseExpr(), AddressOf);
3621         return;
3622       }
3623 
3624       if (BinaryConditionalOperator *BCO =
3625               dyn_cast<BinaryConditionalOperator>(E)) {
3626         Visit(BCO->getCond());
3627         HandleValue(BCO->getFalseExpr(), AddressOf);
3628         return;
3629       }
3630 
3631       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3632         HandleValue(OVE->getSourceExpr(), AddressOf);
3633         return;
3634       }
3635 
3636       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3637         switch (BO->getOpcode()) {
3638         default:
3639           break;
3640         case(BO_PtrMemD):
3641         case(BO_PtrMemI):
3642           HandleValue(BO->getLHS(), AddressOf);
3643           Visit(BO->getRHS());
3644           return;
3645         case(BO_Comma):
3646           Visit(BO->getLHS());
3647           HandleValue(BO->getRHS(), AddressOf);
3648           return;
3649         }
3650       }
3651 
3652       Visit(E);
3653     }
3654 
3655     void CheckInitListExpr(InitListExpr *ILE) {
3656       InitFieldIndex.push_back(0);
3657       for (auto Child : ILE->children()) {
3658         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3659           CheckInitListExpr(SubList);
3660         } else {
3661           Visit(Child);
3662         }
3663         ++InitFieldIndex.back();
3664       }
3665       InitFieldIndex.pop_back();
3666     }
3667 
3668     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3669                           FieldDecl *Field, const Type *BaseClass) {
3670       // Remove Decls that may have been initialized in the previous
3671       // initializer.
3672       for (ValueDecl* VD : DeclsToRemove)
3673         Decls.erase(VD);
3674       DeclsToRemove.clear();
3675 
3676       Constructor = FieldConstructor;
3677       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3678 
3679       if (ILE && Field) {
3680         InitList = true;
3681         InitListFieldDecl = Field;
3682         InitFieldIndex.clear();
3683         CheckInitListExpr(ILE);
3684       } else {
3685         InitList = false;
3686         Visit(E);
3687       }
3688 
3689       if (Field)
3690         Decls.erase(Field);
3691       if (BaseClass)
3692         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3693     }
3694 
3695     void VisitMemberExpr(MemberExpr *ME) {
3696       // All uses of unbounded reference fields will warn.
3697       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3698     }
3699 
3700     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3701       if (E->getCastKind() == CK_LValueToRValue) {
3702         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3703         return;
3704       }
3705 
3706       Inherited::VisitImplicitCastExpr(E);
3707     }
3708 
3709     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3710       if (E->getConstructor()->isCopyConstructor()) {
3711         Expr *ArgExpr = E->getArg(0);
3712         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3713           if (ILE->getNumInits() == 1)
3714             ArgExpr = ILE->getInit(0);
3715         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3716           if (ICE->getCastKind() == CK_NoOp)
3717             ArgExpr = ICE->getSubExpr();
3718         HandleValue(ArgExpr, false /*AddressOf*/);
3719         return;
3720       }
3721       Inherited::VisitCXXConstructExpr(E);
3722     }
3723 
3724     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3725       Expr *Callee = E->getCallee();
3726       if (isa<MemberExpr>(Callee)) {
3727         HandleValue(Callee, false /*AddressOf*/);
3728         for (auto Arg : E->arguments())
3729           Visit(Arg);
3730         return;
3731       }
3732 
3733       Inherited::VisitCXXMemberCallExpr(E);
3734     }
3735 
3736     void VisitCallExpr(CallExpr *E) {
3737       // Treat std::move as a use.
3738       if (E->isCallToStdMove()) {
3739         HandleValue(E->getArg(0), /*AddressOf=*/false);
3740         return;
3741       }
3742 
3743       Inherited::VisitCallExpr(E);
3744     }
3745 
3746     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3747       Expr *Callee = E->getCallee();
3748 
3749       if (isa<UnresolvedLookupExpr>(Callee))
3750         return Inherited::VisitCXXOperatorCallExpr(E);
3751 
3752       Visit(Callee);
3753       for (auto Arg : E->arguments())
3754         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3755     }
3756 
3757     void VisitBinaryOperator(BinaryOperator *E) {
3758       // If a field assignment is detected, remove the field from the
3759       // uninitiailized field set.
3760       if (E->getOpcode() == BO_Assign)
3761         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3762           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3763             if (!FD->getType()->isReferenceType())
3764               DeclsToRemove.push_back(FD);
3765 
3766       if (E->isCompoundAssignmentOp()) {
3767         HandleValue(E->getLHS(), false /*AddressOf*/);
3768         Visit(E->getRHS());
3769         return;
3770       }
3771 
3772       Inherited::VisitBinaryOperator(E);
3773     }
3774 
3775     void VisitUnaryOperator(UnaryOperator *E) {
3776       if (E->isIncrementDecrementOp()) {
3777         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3778         return;
3779       }
3780       if (E->getOpcode() == UO_AddrOf) {
3781         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3782           HandleValue(ME->getBase(), true /*AddressOf*/);
3783           return;
3784         }
3785       }
3786 
3787       Inherited::VisitUnaryOperator(E);
3788     }
3789   };
3790 
3791   // Diagnose value-uses of fields to initialize themselves, e.g.
3792   //   foo(foo)
3793   // where foo is not also a parameter to the constructor.
3794   // Also diagnose across field uninitialized use such as
3795   //   x(y), y(x)
3796   // TODO: implement -Wuninitialized and fold this into that framework.
3797   static void DiagnoseUninitializedFields(
3798       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3799 
3800     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3801                                            Constructor->getLocation())) {
3802       return;
3803     }
3804 
3805     if (Constructor->isInvalidDecl())
3806       return;
3807 
3808     const CXXRecordDecl *RD = Constructor->getParent();
3809 
3810     if (RD->isDependentContext())
3811       return;
3812 
3813     // Holds fields that are uninitialized.
3814     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3815 
3816     // At the beginning, all fields are uninitialized.
3817     for (auto *I : RD->decls()) {
3818       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3819         UninitializedFields.insert(FD);
3820       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3821         UninitializedFields.insert(IFD->getAnonField());
3822       }
3823     }
3824 
3825     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3826     for (auto I : RD->bases())
3827       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3828 
3829     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3830       return;
3831 
3832     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3833                                                    UninitializedFields,
3834                                                    UninitializedBaseClasses);
3835 
3836     for (const auto *FieldInit : Constructor->inits()) {
3837       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3838         break;
3839 
3840       Expr *InitExpr = FieldInit->getInit();
3841       if (!InitExpr)
3842         continue;
3843 
3844       if (CXXDefaultInitExpr *Default =
3845               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3846         InitExpr = Default->getExpr();
3847         if (!InitExpr)
3848           continue;
3849         // In class initializers will point to the constructor.
3850         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3851                                               FieldInit->getAnyMember(),
3852                                               FieldInit->getBaseClass());
3853       } else {
3854         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3855                                               FieldInit->getAnyMember(),
3856                                               FieldInit->getBaseClass());
3857       }
3858     }
3859   }
3860 } // namespace
3861 
3862 /// Enter a new C++ default initializer scope. After calling this, the
3863 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3864 /// parsing or instantiating the initializer failed.
3865 void Sema::ActOnStartCXXInClassMemberInitializer() {
3866   // Create a synthetic function scope to represent the call to the constructor
3867   // that notionally surrounds a use of this initializer.
3868   PushFunctionScope();
3869 }
3870 
3871 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3872   if (!D.isFunctionDeclarator())
3873     return;
3874   auto &FTI = D.getFunctionTypeInfo();
3875   if (!FTI.Params)
3876     return;
3877   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3878                                                           FTI.NumParams)) {
3879     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3880     if (ParamDecl->getDeclName())
3881       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3882   }
3883 }
3884 
3885 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3886   if (ConstraintExpr.isInvalid())
3887     return ExprError();
3888   return CorrectDelayedTyposInExpr(ConstraintExpr);
3889 }
3890 
3891 /// This is invoked after parsing an in-class initializer for a
3892 /// non-static C++ class member, and after instantiating an in-class initializer
3893 /// in a class template. Such actions are deferred until the class is complete.
3894 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3895                                                   SourceLocation InitLoc,
3896                                                   Expr *InitExpr) {
3897   // Pop the notional constructor scope we created earlier.
3898   PopFunctionScopeInfo(nullptr, D);
3899 
3900   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3901   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3902          "must set init style when field is created");
3903 
3904   if (!InitExpr) {
3905     D->setInvalidDecl();
3906     if (FD)
3907       FD->removeInClassInitializer();
3908     return;
3909   }
3910 
3911   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3912     FD->setInvalidDecl();
3913     FD->removeInClassInitializer();
3914     return;
3915   }
3916 
3917   ExprResult Init = InitExpr;
3918   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3919     InitializedEntity Entity =
3920         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3921     InitializationKind Kind =
3922         FD->getInClassInitStyle() == ICIS_ListInit
3923             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3924                                                    InitExpr->getBeginLoc(),
3925                                                    InitExpr->getEndLoc())
3926             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3927     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3928     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3929     if (Init.isInvalid()) {
3930       FD->setInvalidDecl();
3931       return;
3932     }
3933   }
3934 
3935   // C++11 [class.base.init]p7:
3936   //   The initialization of each base and member constitutes a
3937   //   full-expression.
3938   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3939   if (Init.isInvalid()) {
3940     FD->setInvalidDecl();
3941     return;
3942   }
3943 
3944   InitExpr = Init.get();
3945 
3946   FD->setInClassInitializer(InitExpr);
3947 }
3948 
3949 /// Find the direct and/or virtual base specifiers that
3950 /// correspond to the given base type, for use in base initialization
3951 /// within a constructor.
3952 static bool FindBaseInitializer(Sema &SemaRef,
3953                                 CXXRecordDecl *ClassDecl,
3954                                 QualType BaseType,
3955                                 const CXXBaseSpecifier *&DirectBaseSpec,
3956                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3957   // First, check for a direct base class.
3958   DirectBaseSpec = nullptr;
3959   for (const auto &Base : ClassDecl->bases()) {
3960     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3961       // We found a direct base of this type. That's what we're
3962       // initializing.
3963       DirectBaseSpec = &Base;
3964       break;
3965     }
3966   }
3967 
3968   // Check for a virtual base class.
3969   // FIXME: We might be able to short-circuit this if we know in advance that
3970   // there are no virtual bases.
3971   VirtualBaseSpec = nullptr;
3972   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3973     // We haven't found a base yet; search the class hierarchy for a
3974     // virtual base class.
3975     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3976                        /*DetectVirtual=*/false);
3977     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3978                               SemaRef.Context.getTypeDeclType(ClassDecl),
3979                               BaseType, Paths)) {
3980       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3981            Path != Paths.end(); ++Path) {
3982         if (Path->back().Base->isVirtual()) {
3983           VirtualBaseSpec = Path->back().Base;
3984           break;
3985         }
3986       }
3987     }
3988   }
3989 
3990   return DirectBaseSpec || VirtualBaseSpec;
3991 }
3992 
3993 /// Handle a C++ member initializer using braced-init-list syntax.
3994 MemInitResult
3995 Sema::ActOnMemInitializer(Decl *ConstructorD,
3996                           Scope *S,
3997                           CXXScopeSpec &SS,
3998                           IdentifierInfo *MemberOrBase,
3999                           ParsedType TemplateTypeTy,
4000                           const DeclSpec &DS,
4001                           SourceLocation IdLoc,
4002                           Expr *InitList,
4003                           SourceLocation EllipsisLoc) {
4004   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4005                              DS, IdLoc, InitList,
4006                              EllipsisLoc);
4007 }
4008 
4009 /// Handle a C++ member initializer using parentheses syntax.
4010 MemInitResult
4011 Sema::ActOnMemInitializer(Decl *ConstructorD,
4012                           Scope *S,
4013                           CXXScopeSpec &SS,
4014                           IdentifierInfo *MemberOrBase,
4015                           ParsedType TemplateTypeTy,
4016                           const DeclSpec &DS,
4017                           SourceLocation IdLoc,
4018                           SourceLocation LParenLoc,
4019                           ArrayRef<Expr *> Args,
4020                           SourceLocation RParenLoc,
4021                           SourceLocation EllipsisLoc) {
4022   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4023   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4024                              DS, IdLoc, List, EllipsisLoc);
4025 }
4026 
4027 namespace {
4028 
4029 // Callback to only accept typo corrections that can be a valid C++ member
4030 // intializer: either a non-static field member or a base class.
4031 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4032 public:
4033   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4034       : ClassDecl(ClassDecl) {}
4035 
4036   bool ValidateCandidate(const TypoCorrection &candidate) override {
4037     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4038       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4039         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4040       return isa<TypeDecl>(ND);
4041     }
4042     return false;
4043   }
4044 
4045   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4046     return std::make_unique<MemInitializerValidatorCCC>(*this);
4047   }
4048 
4049 private:
4050   CXXRecordDecl *ClassDecl;
4051 };
4052 
4053 }
4054 
4055 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4056                                              CXXScopeSpec &SS,
4057                                              ParsedType TemplateTypeTy,
4058                                              IdentifierInfo *MemberOrBase) {
4059   if (SS.getScopeRep() || TemplateTypeTy)
4060     return nullptr;
4061   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4062   if (Result.empty())
4063     return nullptr;
4064   ValueDecl *Member;
4065   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4066       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4067     return Member;
4068   return nullptr;
4069 }
4070 
4071 /// Handle a C++ member initializer.
4072 MemInitResult
4073 Sema::BuildMemInitializer(Decl *ConstructorD,
4074                           Scope *S,
4075                           CXXScopeSpec &SS,
4076                           IdentifierInfo *MemberOrBase,
4077                           ParsedType TemplateTypeTy,
4078                           const DeclSpec &DS,
4079                           SourceLocation IdLoc,
4080                           Expr *Init,
4081                           SourceLocation EllipsisLoc) {
4082   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4083   if (!Res.isUsable())
4084     return true;
4085   Init = Res.get();
4086 
4087   if (!ConstructorD)
4088     return true;
4089 
4090   AdjustDeclIfTemplate(ConstructorD);
4091 
4092   CXXConstructorDecl *Constructor
4093     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4094   if (!Constructor) {
4095     // The user wrote a constructor initializer on a function that is
4096     // not a C++ constructor. Ignore the error for now, because we may
4097     // have more member initializers coming; we'll diagnose it just
4098     // once in ActOnMemInitializers.
4099     return true;
4100   }
4101 
4102   CXXRecordDecl *ClassDecl = Constructor->getParent();
4103 
4104   // C++ [class.base.init]p2:
4105   //   Names in a mem-initializer-id are looked up in the scope of the
4106   //   constructor's class and, if not found in that scope, are looked
4107   //   up in the scope containing the constructor's definition.
4108   //   [Note: if the constructor's class contains a member with the
4109   //   same name as a direct or virtual base class of the class, a
4110   //   mem-initializer-id naming the member or base class and composed
4111   //   of a single identifier refers to the class member. A
4112   //   mem-initializer-id for the hidden base class may be specified
4113   //   using a qualified name. ]
4114 
4115   // Look for a member, first.
4116   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4117           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4118     if (EllipsisLoc.isValid())
4119       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4120           << MemberOrBase
4121           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4122 
4123     return BuildMemberInitializer(Member, Init, IdLoc);
4124   }
4125   // It didn't name a member, so see if it names a class.
4126   QualType BaseType;
4127   TypeSourceInfo *TInfo = nullptr;
4128 
4129   if (TemplateTypeTy) {
4130     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4131     if (BaseType.isNull())
4132       return true;
4133   } else if (DS.getTypeSpecType() == TST_decltype) {
4134     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4135   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4136     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4137     return true;
4138   } else {
4139     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4140     LookupParsedName(R, S, &SS);
4141 
4142     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4143     if (!TyD) {
4144       if (R.isAmbiguous()) return true;
4145 
4146       // We don't want access-control diagnostics here.
4147       R.suppressDiagnostics();
4148 
4149       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4150         bool NotUnknownSpecialization = false;
4151         DeclContext *DC = computeDeclContext(SS, false);
4152         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4153           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4154 
4155         if (!NotUnknownSpecialization) {
4156           // When the scope specifier can refer to a member of an unknown
4157           // specialization, we take it as a type name.
4158           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4159                                        SS.getWithLocInContext(Context),
4160                                        *MemberOrBase, IdLoc);
4161           if (BaseType.isNull())
4162             return true;
4163 
4164           TInfo = Context.CreateTypeSourceInfo(BaseType);
4165           DependentNameTypeLoc TL =
4166               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4167           if (!TL.isNull()) {
4168             TL.setNameLoc(IdLoc);
4169             TL.setElaboratedKeywordLoc(SourceLocation());
4170             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4171           }
4172 
4173           R.clear();
4174           R.setLookupName(MemberOrBase);
4175         }
4176       }
4177 
4178       // If no results were found, try to correct typos.
4179       TypoCorrection Corr;
4180       MemInitializerValidatorCCC CCC(ClassDecl);
4181       if (R.empty() && BaseType.isNull() &&
4182           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4183                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4184         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4185           // We have found a non-static data member with a similar
4186           // name to what was typed; complain and initialize that
4187           // member.
4188           diagnoseTypo(Corr,
4189                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4190                          << MemberOrBase << true);
4191           return BuildMemberInitializer(Member, Init, IdLoc);
4192         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4193           const CXXBaseSpecifier *DirectBaseSpec;
4194           const CXXBaseSpecifier *VirtualBaseSpec;
4195           if (FindBaseInitializer(*this, ClassDecl,
4196                                   Context.getTypeDeclType(Type),
4197                                   DirectBaseSpec, VirtualBaseSpec)) {
4198             // We have found a direct or virtual base class with a
4199             // similar name to what was typed; complain and initialize
4200             // that base class.
4201             diagnoseTypo(Corr,
4202                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4203                            << MemberOrBase << false,
4204                          PDiag() /*Suppress note, we provide our own.*/);
4205 
4206             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4207                                                               : VirtualBaseSpec;
4208             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4209                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4210 
4211             TyD = Type;
4212           }
4213         }
4214       }
4215 
4216       if (!TyD && BaseType.isNull()) {
4217         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4218           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4219         return true;
4220       }
4221     }
4222 
4223     if (BaseType.isNull()) {
4224       BaseType = Context.getTypeDeclType(TyD);
4225       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4226       if (SS.isSet()) {
4227         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4228                                              BaseType);
4229         TInfo = Context.CreateTypeSourceInfo(BaseType);
4230         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4231         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4232         TL.setElaboratedKeywordLoc(SourceLocation());
4233         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4234       }
4235     }
4236   }
4237 
4238   if (!TInfo)
4239     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4240 
4241   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4242 }
4243 
4244 MemInitResult
4245 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4246                              SourceLocation IdLoc) {
4247   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4248   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4249   assert((DirectMember || IndirectMember) &&
4250          "Member must be a FieldDecl or IndirectFieldDecl");
4251 
4252   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4253     return true;
4254 
4255   if (Member->isInvalidDecl())
4256     return true;
4257 
4258   MultiExprArg Args;
4259   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4260     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4261   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4262     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4263   } else {
4264     // Template instantiation doesn't reconstruct ParenListExprs for us.
4265     Args = Init;
4266   }
4267 
4268   SourceRange InitRange = Init->getSourceRange();
4269 
4270   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4271     // Can't check initialization for a member of dependent type or when
4272     // any of the arguments are type-dependent expressions.
4273     DiscardCleanupsInEvaluationContext();
4274   } else {
4275     bool InitList = false;
4276     if (isa<InitListExpr>(Init)) {
4277       InitList = true;
4278       Args = Init;
4279     }
4280 
4281     // Initialize the member.
4282     InitializedEntity MemberEntity =
4283       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4284                    : InitializedEntity::InitializeMember(IndirectMember,
4285                                                          nullptr);
4286     InitializationKind Kind =
4287         InitList ? InitializationKind::CreateDirectList(
4288                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4289                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4290                                                     InitRange.getEnd());
4291 
4292     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4293     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4294                                             nullptr);
4295     if (MemberInit.isInvalid())
4296       return true;
4297 
4298     // C++11 [class.base.init]p7:
4299     //   The initialization of each base and member constitutes a
4300     //   full-expression.
4301     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4302                                      /*DiscardedValue*/ false);
4303     if (MemberInit.isInvalid())
4304       return true;
4305 
4306     Init = MemberInit.get();
4307   }
4308 
4309   if (DirectMember) {
4310     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4311                                             InitRange.getBegin(), Init,
4312                                             InitRange.getEnd());
4313   } else {
4314     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4315                                             InitRange.getBegin(), Init,
4316                                             InitRange.getEnd());
4317   }
4318 }
4319 
4320 MemInitResult
4321 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4322                                  CXXRecordDecl *ClassDecl) {
4323   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4324   if (!LangOpts.CPlusPlus11)
4325     return Diag(NameLoc, diag::err_delegating_ctor)
4326       << TInfo->getTypeLoc().getLocalSourceRange();
4327   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4328 
4329   bool InitList = true;
4330   MultiExprArg Args = Init;
4331   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4332     InitList = false;
4333     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4334   }
4335 
4336   SourceRange InitRange = Init->getSourceRange();
4337   // Initialize the object.
4338   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4339                                      QualType(ClassDecl->getTypeForDecl(), 0));
4340   InitializationKind Kind =
4341       InitList ? InitializationKind::CreateDirectList(
4342                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4343                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4344                                                   InitRange.getEnd());
4345   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4346   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4347                                               Args, nullptr);
4348   if (DelegationInit.isInvalid())
4349     return true;
4350 
4351   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4352          "Delegating constructor with no target?");
4353 
4354   // C++11 [class.base.init]p7:
4355   //   The initialization of each base and member constitutes a
4356   //   full-expression.
4357   DelegationInit = ActOnFinishFullExpr(
4358       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4359   if (DelegationInit.isInvalid())
4360     return true;
4361 
4362   // If we are in a dependent context, template instantiation will
4363   // perform this type-checking again. Just save the arguments that we
4364   // received in a ParenListExpr.
4365   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4366   // of the information that we have about the base
4367   // initializer. However, deconstructing the ASTs is a dicey process,
4368   // and this approach is far more likely to get the corner cases right.
4369   if (CurContext->isDependentContext())
4370     DelegationInit = Init;
4371 
4372   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4373                                           DelegationInit.getAs<Expr>(),
4374                                           InitRange.getEnd());
4375 }
4376 
4377 MemInitResult
4378 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4379                            Expr *Init, CXXRecordDecl *ClassDecl,
4380                            SourceLocation EllipsisLoc) {
4381   SourceLocation BaseLoc
4382     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4383 
4384   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4385     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4386              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4387 
4388   // C++ [class.base.init]p2:
4389   //   [...] Unless the mem-initializer-id names a nonstatic data
4390   //   member of the constructor's class or a direct or virtual base
4391   //   of that class, the mem-initializer is ill-formed. A
4392   //   mem-initializer-list can initialize a base class using any
4393   //   name that denotes that base class type.
4394   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4395 
4396   SourceRange InitRange = Init->getSourceRange();
4397   if (EllipsisLoc.isValid()) {
4398     // This is a pack expansion.
4399     if (!BaseType->containsUnexpandedParameterPack())  {
4400       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4401         << SourceRange(BaseLoc, InitRange.getEnd());
4402 
4403       EllipsisLoc = SourceLocation();
4404     }
4405   } else {
4406     // Check for any unexpanded parameter packs.
4407     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4408       return true;
4409 
4410     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4411       return true;
4412   }
4413 
4414   // Check for direct and virtual base classes.
4415   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4416   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4417   if (!Dependent) {
4418     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4419                                        BaseType))
4420       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4421 
4422     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4423                         VirtualBaseSpec);
4424 
4425     // C++ [base.class.init]p2:
4426     // Unless the mem-initializer-id names a nonstatic data member of the
4427     // constructor's class or a direct or virtual base of that class, the
4428     // mem-initializer is ill-formed.
4429     if (!DirectBaseSpec && !VirtualBaseSpec) {
4430       // If the class has any dependent bases, then it's possible that
4431       // one of those types will resolve to the same type as
4432       // BaseType. Therefore, just treat this as a dependent base
4433       // class initialization.  FIXME: Should we try to check the
4434       // initialization anyway? It seems odd.
4435       if (ClassDecl->hasAnyDependentBases())
4436         Dependent = true;
4437       else
4438         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4439           << BaseType << Context.getTypeDeclType(ClassDecl)
4440           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4441     }
4442   }
4443 
4444   if (Dependent) {
4445     DiscardCleanupsInEvaluationContext();
4446 
4447     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4448                                             /*IsVirtual=*/false,
4449                                             InitRange.getBegin(), Init,
4450                                             InitRange.getEnd(), EllipsisLoc);
4451   }
4452 
4453   // C++ [base.class.init]p2:
4454   //   If a mem-initializer-id is ambiguous because it designates both
4455   //   a direct non-virtual base class and an inherited virtual base
4456   //   class, the mem-initializer is ill-formed.
4457   if (DirectBaseSpec && VirtualBaseSpec)
4458     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4459       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4460 
4461   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4462   if (!BaseSpec)
4463     BaseSpec = VirtualBaseSpec;
4464 
4465   // Initialize the base.
4466   bool InitList = true;
4467   MultiExprArg Args = Init;
4468   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4469     InitList = false;
4470     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4471   }
4472 
4473   InitializedEntity BaseEntity =
4474     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4475   InitializationKind Kind =
4476       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4477                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4478                                                   InitRange.getEnd());
4479   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4480   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4481   if (BaseInit.isInvalid())
4482     return true;
4483 
4484   // C++11 [class.base.init]p7:
4485   //   The initialization of each base and member constitutes a
4486   //   full-expression.
4487   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4488                                  /*DiscardedValue*/ false);
4489   if (BaseInit.isInvalid())
4490     return true;
4491 
4492   // If we are in a dependent context, template instantiation will
4493   // perform this type-checking again. Just save the arguments that we
4494   // received in a ParenListExpr.
4495   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4496   // of the information that we have about the base
4497   // initializer. However, deconstructing the ASTs is a dicey process,
4498   // and this approach is far more likely to get the corner cases right.
4499   if (CurContext->isDependentContext())
4500     BaseInit = Init;
4501 
4502   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4503                                           BaseSpec->isVirtual(),
4504                                           InitRange.getBegin(),
4505                                           BaseInit.getAs<Expr>(),
4506                                           InitRange.getEnd(), EllipsisLoc);
4507 }
4508 
4509 // Create a static_cast\<T&&>(expr).
4510 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4511   if (T.isNull()) T = E->getType();
4512   QualType TargetType = SemaRef.BuildReferenceType(
4513       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4514   SourceLocation ExprLoc = E->getBeginLoc();
4515   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4516       TargetType, ExprLoc);
4517 
4518   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4519                                    SourceRange(ExprLoc, ExprLoc),
4520                                    E->getSourceRange()).get();
4521 }
4522 
4523 /// ImplicitInitializerKind - How an implicit base or member initializer should
4524 /// initialize its base or member.
4525 enum ImplicitInitializerKind {
4526   IIK_Default,
4527   IIK_Copy,
4528   IIK_Move,
4529   IIK_Inherit
4530 };
4531 
4532 static bool
4533 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4534                              ImplicitInitializerKind ImplicitInitKind,
4535                              CXXBaseSpecifier *BaseSpec,
4536                              bool IsInheritedVirtualBase,
4537                              CXXCtorInitializer *&CXXBaseInit) {
4538   InitializedEntity InitEntity
4539     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4540                                         IsInheritedVirtualBase);
4541 
4542   ExprResult BaseInit;
4543 
4544   switch (ImplicitInitKind) {
4545   case IIK_Inherit:
4546   case IIK_Default: {
4547     InitializationKind InitKind
4548       = InitializationKind::CreateDefault(Constructor->getLocation());
4549     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4550     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4551     break;
4552   }
4553 
4554   case IIK_Move:
4555   case IIK_Copy: {
4556     bool Moving = ImplicitInitKind == IIK_Move;
4557     ParmVarDecl *Param = Constructor->getParamDecl(0);
4558     QualType ParamType = Param->getType().getNonReferenceType();
4559 
4560     Expr *CopyCtorArg =
4561       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4562                           SourceLocation(), Param, false,
4563                           Constructor->getLocation(), ParamType,
4564                           VK_LValue, nullptr);
4565 
4566     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4567 
4568     // Cast to the base class to avoid ambiguities.
4569     QualType ArgTy =
4570       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4571                                        ParamType.getQualifiers());
4572 
4573     if (Moving) {
4574       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4575     }
4576 
4577     CXXCastPath BasePath;
4578     BasePath.push_back(BaseSpec);
4579     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4580                                             CK_UncheckedDerivedToBase,
4581                                             Moving ? VK_XValue : VK_LValue,
4582                                             &BasePath).get();
4583 
4584     InitializationKind InitKind
4585       = InitializationKind::CreateDirect(Constructor->getLocation(),
4586                                          SourceLocation(), SourceLocation());
4587     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4588     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4589     break;
4590   }
4591   }
4592 
4593   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4594   if (BaseInit.isInvalid())
4595     return true;
4596 
4597   CXXBaseInit =
4598     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4599                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4600                                                         SourceLocation()),
4601                                              BaseSpec->isVirtual(),
4602                                              SourceLocation(),
4603                                              BaseInit.getAs<Expr>(),
4604                                              SourceLocation(),
4605                                              SourceLocation());
4606 
4607   return false;
4608 }
4609 
4610 static bool RefersToRValueRef(Expr *MemRef) {
4611   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4612   return Referenced->getType()->isRValueReferenceType();
4613 }
4614 
4615 static bool
4616 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4617                                ImplicitInitializerKind ImplicitInitKind,
4618                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4619                                CXXCtorInitializer *&CXXMemberInit) {
4620   if (Field->isInvalidDecl())
4621     return true;
4622 
4623   SourceLocation Loc = Constructor->getLocation();
4624 
4625   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4626     bool Moving = ImplicitInitKind == IIK_Move;
4627     ParmVarDecl *Param = Constructor->getParamDecl(0);
4628     QualType ParamType = Param->getType().getNonReferenceType();
4629 
4630     // Suppress copying zero-width bitfields.
4631     if (Field->isZeroLengthBitField(SemaRef.Context))
4632       return false;
4633 
4634     Expr *MemberExprBase =
4635       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4636                           SourceLocation(), Param, false,
4637                           Loc, ParamType, VK_LValue, nullptr);
4638 
4639     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4640 
4641     if (Moving) {
4642       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4643     }
4644 
4645     // Build a reference to this field within the parameter.
4646     CXXScopeSpec SS;
4647     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4648                               Sema::LookupMemberName);
4649     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4650                                   : cast<ValueDecl>(Field), AS_public);
4651     MemberLookup.resolveKind();
4652     ExprResult CtorArg
4653       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4654                                          ParamType, Loc,
4655                                          /*IsArrow=*/false,
4656                                          SS,
4657                                          /*TemplateKWLoc=*/SourceLocation(),
4658                                          /*FirstQualifierInScope=*/nullptr,
4659                                          MemberLookup,
4660                                          /*TemplateArgs=*/nullptr,
4661                                          /*S*/nullptr);
4662     if (CtorArg.isInvalid())
4663       return true;
4664 
4665     // C++11 [class.copy]p15:
4666     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4667     //     with static_cast<T&&>(x.m);
4668     if (RefersToRValueRef(CtorArg.get())) {
4669       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4670     }
4671 
4672     InitializedEntity Entity =
4673         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4674                                                        /*Implicit*/ true)
4675                  : InitializedEntity::InitializeMember(Field, nullptr,
4676                                                        /*Implicit*/ true);
4677 
4678     // Direct-initialize to use the copy constructor.
4679     InitializationKind InitKind =
4680       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4681 
4682     Expr *CtorArgE = CtorArg.getAs<Expr>();
4683     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4684     ExprResult MemberInit =
4685         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4686     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4687     if (MemberInit.isInvalid())
4688       return true;
4689 
4690     if (Indirect)
4691       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4692           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4693     else
4694       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4695           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4696     return false;
4697   }
4698 
4699   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4700          "Unhandled implicit init kind!");
4701 
4702   QualType FieldBaseElementType =
4703     SemaRef.Context.getBaseElementType(Field->getType());
4704 
4705   if (FieldBaseElementType->isRecordType()) {
4706     InitializedEntity InitEntity =
4707         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4708                                                        /*Implicit*/ true)
4709                  : InitializedEntity::InitializeMember(Field, nullptr,
4710                                                        /*Implicit*/ true);
4711     InitializationKind InitKind =
4712       InitializationKind::CreateDefault(Loc);
4713 
4714     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4715     ExprResult MemberInit =
4716       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4717 
4718     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4719     if (MemberInit.isInvalid())
4720       return true;
4721 
4722     if (Indirect)
4723       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4724                                                                Indirect, Loc,
4725                                                                Loc,
4726                                                                MemberInit.get(),
4727                                                                Loc);
4728     else
4729       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4730                                                                Field, Loc, Loc,
4731                                                                MemberInit.get(),
4732                                                                Loc);
4733     return false;
4734   }
4735 
4736   if (!Field->getParent()->isUnion()) {
4737     if (FieldBaseElementType->isReferenceType()) {
4738       SemaRef.Diag(Constructor->getLocation(),
4739                    diag::err_uninitialized_member_in_ctor)
4740       << (int)Constructor->isImplicit()
4741       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4742       << 0 << Field->getDeclName();
4743       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4744       return true;
4745     }
4746 
4747     if (FieldBaseElementType.isConstQualified()) {
4748       SemaRef.Diag(Constructor->getLocation(),
4749                    diag::err_uninitialized_member_in_ctor)
4750       << (int)Constructor->isImplicit()
4751       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4752       << 1 << Field->getDeclName();
4753       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4754       return true;
4755     }
4756   }
4757 
4758   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4759     // ARC and Weak:
4760     //   Default-initialize Objective-C pointers to NULL.
4761     CXXMemberInit
4762       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4763                                                  Loc, Loc,
4764                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4765                                                  Loc);
4766     return false;
4767   }
4768 
4769   // Nothing to initialize.
4770   CXXMemberInit = nullptr;
4771   return false;
4772 }
4773 
4774 namespace {
4775 struct BaseAndFieldInfo {
4776   Sema &S;
4777   CXXConstructorDecl *Ctor;
4778   bool AnyErrorsInInits;
4779   ImplicitInitializerKind IIK;
4780   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4781   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4782   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4783 
4784   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4785     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4786     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4787     if (Ctor->getInheritedConstructor())
4788       IIK = IIK_Inherit;
4789     else if (Generated && Ctor->isCopyConstructor())
4790       IIK = IIK_Copy;
4791     else if (Generated && Ctor->isMoveConstructor())
4792       IIK = IIK_Move;
4793     else
4794       IIK = IIK_Default;
4795   }
4796 
4797   bool isImplicitCopyOrMove() const {
4798     switch (IIK) {
4799     case IIK_Copy:
4800     case IIK_Move:
4801       return true;
4802 
4803     case IIK_Default:
4804     case IIK_Inherit:
4805       return false;
4806     }
4807 
4808     llvm_unreachable("Invalid ImplicitInitializerKind!");
4809   }
4810 
4811   bool addFieldInitializer(CXXCtorInitializer *Init) {
4812     AllToInit.push_back(Init);
4813 
4814     // Check whether this initializer makes the field "used".
4815     if (Init->getInit()->HasSideEffects(S.Context))
4816       S.UnusedPrivateFields.remove(Init->getAnyMember());
4817 
4818     return false;
4819   }
4820 
4821   bool isInactiveUnionMember(FieldDecl *Field) {
4822     RecordDecl *Record = Field->getParent();
4823     if (!Record->isUnion())
4824       return false;
4825 
4826     if (FieldDecl *Active =
4827             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4828       return Active != Field->getCanonicalDecl();
4829 
4830     // In an implicit copy or move constructor, ignore any in-class initializer.
4831     if (isImplicitCopyOrMove())
4832       return true;
4833 
4834     // If there's no explicit initialization, the field is active only if it
4835     // has an in-class initializer...
4836     if (Field->hasInClassInitializer())
4837       return false;
4838     // ... or it's an anonymous struct or union whose class has an in-class
4839     // initializer.
4840     if (!Field->isAnonymousStructOrUnion())
4841       return true;
4842     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4843     return !FieldRD->hasInClassInitializer();
4844   }
4845 
4846   /// Determine whether the given field is, or is within, a union member
4847   /// that is inactive (because there was an initializer given for a different
4848   /// member of the union, or because the union was not initialized at all).
4849   bool isWithinInactiveUnionMember(FieldDecl *Field,
4850                                    IndirectFieldDecl *Indirect) {
4851     if (!Indirect)
4852       return isInactiveUnionMember(Field);
4853 
4854     for (auto *C : Indirect->chain()) {
4855       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4856       if (Field && isInactiveUnionMember(Field))
4857         return true;
4858     }
4859     return false;
4860   }
4861 };
4862 }
4863 
4864 /// Determine whether the given type is an incomplete or zero-lenfgth
4865 /// array type.
4866 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4867   if (T->isIncompleteArrayType())
4868     return true;
4869 
4870   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4871     if (!ArrayT->getSize())
4872       return true;
4873 
4874     T = ArrayT->getElementType();
4875   }
4876 
4877   return false;
4878 }
4879 
4880 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4881                                     FieldDecl *Field,
4882                                     IndirectFieldDecl *Indirect = nullptr) {
4883   if (Field->isInvalidDecl())
4884     return false;
4885 
4886   // Overwhelmingly common case: we have a direct initializer for this field.
4887   if (CXXCtorInitializer *Init =
4888           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4889     return Info.addFieldInitializer(Init);
4890 
4891   // C++11 [class.base.init]p8:
4892   //   if the entity is a non-static data member that has a
4893   //   brace-or-equal-initializer and either
4894   //   -- the constructor's class is a union and no other variant member of that
4895   //      union is designated by a mem-initializer-id or
4896   //   -- the constructor's class is not a union, and, if the entity is a member
4897   //      of an anonymous union, no other member of that union is designated by
4898   //      a mem-initializer-id,
4899   //   the entity is initialized as specified in [dcl.init].
4900   //
4901   // We also apply the same rules to handle anonymous structs within anonymous
4902   // unions.
4903   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4904     return false;
4905 
4906   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4907     ExprResult DIE =
4908         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4909     if (DIE.isInvalid())
4910       return true;
4911 
4912     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4913     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4914 
4915     CXXCtorInitializer *Init;
4916     if (Indirect)
4917       Init = new (SemaRef.Context)
4918           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4919                              SourceLocation(), DIE.get(), SourceLocation());
4920     else
4921       Init = new (SemaRef.Context)
4922           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4923                              SourceLocation(), DIE.get(), SourceLocation());
4924     return Info.addFieldInitializer(Init);
4925   }
4926 
4927   // Don't initialize incomplete or zero-length arrays.
4928   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4929     return false;
4930 
4931   // Don't try to build an implicit initializer if there were semantic
4932   // errors in any of the initializers (and therefore we might be
4933   // missing some that the user actually wrote).
4934   if (Info.AnyErrorsInInits)
4935     return false;
4936 
4937   CXXCtorInitializer *Init = nullptr;
4938   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4939                                      Indirect, Init))
4940     return true;
4941 
4942   if (!Init)
4943     return false;
4944 
4945   return Info.addFieldInitializer(Init);
4946 }
4947 
4948 bool
4949 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4950                                CXXCtorInitializer *Initializer) {
4951   assert(Initializer->isDelegatingInitializer());
4952   Constructor->setNumCtorInitializers(1);
4953   CXXCtorInitializer **initializer =
4954     new (Context) CXXCtorInitializer*[1];
4955   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4956   Constructor->setCtorInitializers(initializer);
4957 
4958   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4959     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4960     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4961   }
4962 
4963   DelegatingCtorDecls.push_back(Constructor);
4964 
4965   DiagnoseUninitializedFields(*this, Constructor);
4966 
4967   return false;
4968 }
4969 
4970 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4971                                ArrayRef<CXXCtorInitializer *> Initializers) {
4972   if (Constructor->isDependentContext()) {
4973     // Just store the initializers as written, they will be checked during
4974     // instantiation.
4975     if (!Initializers.empty()) {
4976       Constructor->setNumCtorInitializers(Initializers.size());
4977       CXXCtorInitializer **baseOrMemberInitializers =
4978         new (Context) CXXCtorInitializer*[Initializers.size()];
4979       memcpy(baseOrMemberInitializers, Initializers.data(),
4980              Initializers.size() * sizeof(CXXCtorInitializer*));
4981       Constructor->setCtorInitializers(baseOrMemberInitializers);
4982     }
4983 
4984     // Let template instantiation know whether we had errors.
4985     if (AnyErrors)
4986       Constructor->setInvalidDecl();
4987 
4988     return false;
4989   }
4990 
4991   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4992 
4993   // We need to build the initializer AST according to order of construction
4994   // and not what user specified in the Initializers list.
4995   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4996   if (!ClassDecl)
4997     return true;
4998 
4999   bool HadError = false;
5000 
5001   for (unsigned i = 0; i < Initializers.size(); i++) {
5002     CXXCtorInitializer *Member = Initializers[i];
5003 
5004     if (Member->isBaseInitializer())
5005       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5006     else {
5007       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5008 
5009       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5010         for (auto *C : F->chain()) {
5011           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5012           if (FD && FD->getParent()->isUnion())
5013             Info.ActiveUnionMember.insert(std::make_pair(
5014                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5015         }
5016       } else if (FieldDecl *FD = Member->getMember()) {
5017         if (FD->getParent()->isUnion())
5018           Info.ActiveUnionMember.insert(std::make_pair(
5019               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5020       }
5021     }
5022   }
5023 
5024   // Keep track of the direct virtual bases.
5025   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5026   for (auto &I : ClassDecl->bases()) {
5027     if (I.isVirtual())
5028       DirectVBases.insert(&I);
5029   }
5030 
5031   // Push virtual bases before others.
5032   for (auto &VBase : ClassDecl->vbases()) {
5033     if (CXXCtorInitializer *Value
5034         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5035       // [class.base.init]p7, per DR257:
5036       //   A mem-initializer where the mem-initializer-id names a virtual base
5037       //   class is ignored during execution of a constructor of any class that
5038       //   is not the most derived class.
5039       if (ClassDecl->isAbstract()) {
5040         // FIXME: Provide a fixit to remove the base specifier. This requires
5041         // tracking the location of the associated comma for a base specifier.
5042         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5043           << VBase.getType() << ClassDecl;
5044         DiagnoseAbstractType(ClassDecl);
5045       }
5046 
5047       Info.AllToInit.push_back(Value);
5048     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5049       // [class.base.init]p8, per DR257:
5050       //   If a given [...] base class is not named by a mem-initializer-id
5051       //   [...] and the entity is not a virtual base class of an abstract
5052       //   class, then [...] the entity is default-initialized.
5053       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5054       CXXCtorInitializer *CXXBaseInit;
5055       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5056                                        &VBase, IsInheritedVirtualBase,
5057                                        CXXBaseInit)) {
5058         HadError = true;
5059         continue;
5060       }
5061 
5062       Info.AllToInit.push_back(CXXBaseInit);
5063     }
5064   }
5065 
5066   // Non-virtual bases.
5067   for (auto &Base : ClassDecl->bases()) {
5068     // Virtuals are in the virtual base list and already constructed.
5069     if (Base.isVirtual())
5070       continue;
5071 
5072     if (CXXCtorInitializer *Value
5073           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5074       Info.AllToInit.push_back(Value);
5075     } else if (!AnyErrors) {
5076       CXXCtorInitializer *CXXBaseInit;
5077       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5078                                        &Base, /*IsInheritedVirtualBase=*/false,
5079                                        CXXBaseInit)) {
5080         HadError = true;
5081         continue;
5082       }
5083 
5084       Info.AllToInit.push_back(CXXBaseInit);
5085     }
5086   }
5087 
5088   // Fields.
5089   for (auto *Mem : ClassDecl->decls()) {
5090     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5091       // C++ [class.bit]p2:
5092       //   A declaration for a bit-field that omits the identifier declares an
5093       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5094       //   initialized.
5095       if (F->isUnnamedBitfield())
5096         continue;
5097 
5098       // If we're not generating the implicit copy/move constructor, then we'll
5099       // handle anonymous struct/union fields based on their individual
5100       // indirect fields.
5101       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5102         continue;
5103 
5104       if (CollectFieldInitializer(*this, Info, F))
5105         HadError = true;
5106       continue;
5107     }
5108 
5109     // Beyond this point, we only consider default initialization.
5110     if (Info.isImplicitCopyOrMove())
5111       continue;
5112 
5113     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5114       if (F->getType()->isIncompleteArrayType()) {
5115         assert(ClassDecl->hasFlexibleArrayMember() &&
5116                "Incomplete array type is not valid");
5117         continue;
5118       }
5119 
5120       // Initialize each field of an anonymous struct individually.
5121       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5122         HadError = true;
5123 
5124       continue;
5125     }
5126   }
5127 
5128   unsigned NumInitializers = Info.AllToInit.size();
5129   if (NumInitializers > 0) {
5130     Constructor->setNumCtorInitializers(NumInitializers);
5131     CXXCtorInitializer **baseOrMemberInitializers =
5132       new (Context) CXXCtorInitializer*[NumInitializers];
5133     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5134            NumInitializers * sizeof(CXXCtorInitializer*));
5135     Constructor->setCtorInitializers(baseOrMemberInitializers);
5136 
5137     // Constructors implicitly reference the base and member
5138     // destructors.
5139     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5140                                            Constructor->getParent());
5141   }
5142 
5143   return HadError;
5144 }
5145 
5146 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5147   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5148     const RecordDecl *RD = RT->getDecl();
5149     if (RD->isAnonymousStructOrUnion()) {
5150       for (auto *Field : RD->fields())
5151         PopulateKeysForFields(Field, IdealInits);
5152       return;
5153     }
5154   }
5155   IdealInits.push_back(Field->getCanonicalDecl());
5156 }
5157 
5158 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5159   return Context.getCanonicalType(BaseType).getTypePtr();
5160 }
5161 
5162 static const void *GetKeyForMember(ASTContext &Context,
5163                                    CXXCtorInitializer *Member) {
5164   if (!Member->isAnyMemberInitializer())
5165     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5166 
5167   return Member->getAnyMember()->getCanonicalDecl();
5168 }
5169 
5170 static void DiagnoseBaseOrMemInitializerOrder(
5171     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5172     ArrayRef<CXXCtorInitializer *> Inits) {
5173   if (Constructor->getDeclContext()->isDependentContext())
5174     return;
5175 
5176   // Don't check initializers order unless the warning is enabled at the
5177   // location of at least one initializer.
5178   bool ShouldCheckOrder = false;
5179   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5180     CXXCtorInitializer *Init = Inits[InitIndex];
5181     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5182                                  Init->getSourceLocation())) {
5183       ShouldCheckOrder = true;
5184       break;
5185     }
5186   }
5187   if (!ShouldCheckOrder)
5188     return;
5189 
5190   // Build the list of bases and members in the order that they'll
5191   // actually be initialized.  The explicit initializers should be in
5192   // this same order but may be missing things.
5193   SmallVector<const void*, 32> IdealInitKeys;
5194 
5195   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5196 
5197   // 1. Virtual bases.
5198   for (const auto &VBase : ClassDecl->vbases())
5199     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5200 
5201   // 2. Non-virtual bases.
5202   for (const auto &Base : ClassDecl->bases()) {
5203     if (Base.isVirtual())
5204       continue;
5205     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5206   }
5207 
5208   // 3. Direct fields.
5209   for (auto *Field : ClassDecl->fields()) {
5210     if (Field->isUnnamedBitfield())
5211       continue;
5212 
5213     PopulateKeysForFields(Field, IdealInitKeys);
5214   }
5215 
5216   unsigned NumIdealInits = IdealInitKeys.size();
5217   unsigned IdealIndex = 0;
5218 
5219   CXXCtorInitializer *PrevInit = nullptr;
5220   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5221     CXXCtorInitializer *Init = Inits[InitIndex];
5222     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5223 
5224     // Scan forward to try to find this initializer in the idealized
5225     // initializers list.
5226     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5227       if (InitKey == IdealInitKeys[IdealIndex])
5228         break;
5229 
5230     // If we didn't find this initializer, it must be because we
5231     // scanned past it on a previous iteration.  That can only
5232     // happen if we're out of order;  emit a warning.
5233     if (IdealIndex == NumIdealInits && PrevInit) {
5234       Sema::SemaDiagnosticBuilder D =
5235         SemaRef.Diag(PrevInit->getSourceLocation(),
5236                      diag::warn_initializer_out_of_order);
5237 
5238       if (PrevInit->isAnyMemberInitializer())
5239         D << 0 << PrevInit->getAnyMember()->getDeclName();
5240       else
5241         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5242 
5243       if (Init->isAnyMemberInitializer())
5244         D << 0 << Init->getAnyMember()->getDeclName();
5245       else
5246         D << 1 << Init->getTypeSourceInfo()->getType();
5247 
5248       // Move back to the initializer's location in the ideal list.
5249       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5250         if (InitKey == IdealInitKeys[IdealIndex])
5251           break;
5252 
5253       assert(IdealIndex < NumIdealInits &&
5254              "initializer not found in initializer list");
5255     }
5256 
5257     PrevInit = Init;
5258   }
5259 }
5260 
5261 namespace {
5262 bool CheckRedundantInit(Sema &S,
5263                         CXXCtorInitializer *Init,
5264                         CXXCtorInitializer *&PrevInit) {
5265   if (!PrevInit) {
5266     PrevInit = Init;
5267     return false;
5268   }
5269 
5270   if (FieldDecl *Field = Init->getAnyMember())
5271     S.Diag(Init->getSourceLocation(),
5272            diag::err_multiple_mem_initialization)
5273       << Field->getDeclName()
5274       << Init->getSourceRange();
5275   else {
5276     const Type *BaseClass = Init->getBaseClass();
5277     assert(BaseClass && "neither field nor base");
5278     S.Diag(Init->getSourceLocation(),
5279            diag::err_multiple_base_initialization)
5280       << QualType(BaseClass, 0)
5281       << Init->getSourceRange();
5282   }
5283   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5284     << 0 << PrevInit->getSourceRange();
5285 
5286   return true;
5287 }
5288 
5289 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5290 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5291 
5292 bool CheckRedundantUnionInit(Sema &S,
5293                              CXXCtorInitializer *Init,
5294                              RedundantUnionMap &Unions) {
5295   FieldDecl *Field = Init->getAnyMember();
5296   RecordDecl *Parent = Field->getParent();
5297   NamedDecl *Child = Field;
5298 
5299   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5300     if (Parent->isUnion()) {
5301       UnionEntry &En = Unions[Parent];
5302       if (En.first && En.first != Child) {
5303         S.Diag(Init->getSourceLocation(),
5304                diag::err_multiple_mem_union_initialization)
5305           << Field->getDeclName()
5306           << Init->getSourceRange();
5307         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5308           << 0 << En.second->getSourceRange();
5309         return true;
5310       }
5311       if (!En.first) {
5312         En.first = Child;
5313         En.second = Init;
5314       }
5315       if (!Parent->isAnonymousStructOrUnion())
5316         return false;
5317     }
5318 
5319     Child = Parent;
5320     Parent = cast<RecordDecl>(Parent->getDeclContext());
5321   }
5322 
5323   return false;
5324 }
5325 }
5326 
5327 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5328 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5329                                 SourceLocation ColonLoc,
5330                                 ArrayRef<CXXCtorInitializer*> MemInits,
5331                                 bool AnyErrors) {
5332   if (!ConstructorDecl)
5333     return;
5334 
5335   AdjustDeclIfTemplate(ConstructorDecl);
5336 
5337   CXXConstructorDecl *Constructor
5338     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5339 
5340   if (!Constructor) {
5341     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5342     return;
5343   }
5344 
5345   // Mapping for the duplicate initializers check.
5346   // For member initializers, this is keyed with a FieldDecl*.
5347   // For base initializers, this is keyed with a Type*.
5348   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5349 
5350   // Mapping for the inconsistent anonymous-union initializers check.
5351   RedundantUnionMap MemberUnions;
5352 
5353   bool HadError = false;
5354   for (unsigned i = 0; i < MemInits.size(); i++) {
5355     CXXCtorInitializer *Init = MemInits[i];
5356 
5357     // Set the source order index.
5358     Init->setSourceOrder(i);
5359 
5360     if (Init->isAnyMemberInitializer()) {
5361       const void *Key = GetKeyForMember(Context, Init);
5362       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5363           CheckRedundantUnionInit(*this, Init, MemberUnions))
5364         HadError = true;
5365     } else if (Init->isBaseInitializer()) {
5366       const void *Key = GetKeyForMember(Context, Init);
5367       if (CheckRedundantInit(*this, Init, Members[Key]))
5368         HadError = true;
5369     } else {
5370       assert(Init->isDelegatingInitializer());
5371       // This must be the only initializer
5372       if (MemInits.size() != 1) {
5373         Diag(Init->getSourceLocation(),
5374              diag::err_delegating_initializer_alone)
5375           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5376         // We will treat this as being the only initializer.
5377       }
5378       SetDelegatingInitializer(Constructor, MemInits[i]);
5379       // Return immediately as the initializer is set.
5380       return;
5381     }
5382   }
5383 
5384   if (HadError)
5385     return;
5386 
5387   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5388 
5389   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5390 
5391   DiagnoseUninitializedFields(*this, Constructor);
5392 }
5393 
5394 void
5395 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5396                                              CXXRecordDecl *ClassDecl) {
5397   // Ignore dependent contexts. Also ignore unions, since their members never
5398   // have destructors implicitly called.
5399   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5400     return;
5401 
5402   // FIXME: all the access-control diagnostics are positioned on the
5403   // field/base declaration.  That's probably good; that said, the
5404   // user might reasonably want to know why the destructor is being
5405   // emitted, and we currently don't say.
5406 
5407   // Non-static data members.
5408   for (auto *Field : ClassDecl->fields()) {
5409     if (Field->isInvalidDecl())
5410       continue;
5411 
5412     // Don't destroy incomplete or zero-length arrays.
5413     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5414       continue;
5415 
5416     QualType FieldType = Context.getBaseElementType(Field->getType());
5417 
5418     const RecordType* RT = FieldType->getAs<RecordType>();
5419     if (!RT)
5420       continue;
5421 
5422     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5423     if (FieldClassDecl->isInvalidDecl())
5424       continue;
5425     if (FieldClassDecl->hasIrrelevantDestructor())
5426       continue;
5427     // The destructor for an implicit anonymous union member is never invoked.
5428     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5429       continue;
5430 
5431     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5432     assert(Dtor && "No dtor found for FieldClassDecl!");
5433     CheckDestructorAccess(Field->getLocation(), Dtor,
5434                           PDiag(diag::err_access_dtor_field)
5435                             << Field->getDeclName()
5436                             << FieldType);
5437 
5438     MarkFunctionReferenced(Location, Dtor);
5439     DiagnoseUseOfDecl(Dtor, Location);
5440   }
5441 
5442   // We only potentially invoke the destructors of potentially constructed
5443   // subobjects.
5444   bool VisitVirtualBases = !ClassDecl->isAbstract();
5445 
5446   // If the destructor exists and has already been marked used in the MS ABI,
5447   // then virtual base destructors have already been checked and marked used.
5448   // Skip checking them again to avoid duplicate diagnostics.
5449   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5450     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5451     if (Dtor && Dtor->isUsed())
5452       VisitVirtualBases = false;
5453   }
5454 
5455   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5456 
5457   // Bases.
5458   for (const auto &Base : ClassDecl->bases()) {
5459     // Bases are always records in a well-formed non-dependent class.
5460     const RecordType *RT = Base.getType()->getAs<RecordType>();
5461 
5462     // Remember direct virtual bases.
5463     if (Base.isVirtual()) {
5464       if (!VisitVirtualBases)
5465         continue;
5466       DirectVirtualBases.insert(RT);
5467     }
5468 
5469     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5470     // If our base class is invalid, we probably can't get its dtor anyway.
5471     if (BaseClassDecl->isInvalidDecl())
5472       continue;
5473     if (BaseClassDecl->hasIrrelevantDestructor())
5474       continue;
5475 
5476     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5477     assert(Dtor && "No dtor found for BaseClassDecl!");
5478 
5479     // FIXME: caret should be on the start of the class name
5480     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5481                           PDiag(diag::err_access_dtor_base)
5482                               << Base.getType() << Base.getSourceRange(),
5483                           Context.getTypeDeclType(ClassDecl));
5484 
5485     MarkFunctionReferenced(Location, Dtor);
5486     DiagnoseUseOfDecl(Dtor, Location);
5487   }
5488 
5489   if (VisitVirtualBases)
5490     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5491                                          &DirectVirtualBases);
5492 }
5493 
5494 void Sema::MarkVirtualBaseDestructorsReferenced(
5495     SourceLocation Location, CXXRecordDecl *ClassDecl,
5496     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5497   // Virtual bases.
5498   for (const auto &VBase : ClassDecl->vbases()) {
5499     // Bases are always records in a well-formed non-dependent class.
5500     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5501 
5502     // Ignore already visited direct virtual bases.
5503     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5504       continue;
5505 
5506     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5507     // If our base class is invalid, we probably can't get its dtor anyway.
5508     if (BaseClassDecl->isInvalidDecl())
5509       continue;
5510     if (BaseClassDecl->hasIrrelevantDestructor())
5511       continue;
5512 
5513     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5514     assert(Dtor && "No dtor found for BaseClassDecl!");
5515     if (CheckDestructorAccess(
5516             ClassDecl->getLocation(), Dtor,
5517             PDiag(diag::err_access_dtor_vbase)
5518                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5519             Context.getTypeDeclType(ClassDecl)) ==
5520         AR_accessible) {
5521       CheckDerivedToBaseConversion(
5522           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5523           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5524           SourceRange(), DeclarationName(), nullptr);
5525     }
5526 
5527     MarkFunctionReferenced(Location, Dtor);
5528     DiagnoseUseOfDecl(Dtor, Location);
5529   }
5530 }
5531 
5532 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5533   if (!CDtorDecl)
5534     return;
5535 
5536   if (CXXConstructorDecl *Constructor
5537       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5538     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5539     DiagnoseUninitializedFields(*this, Constructor);
5540   }
5541 }
5542 
5543 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5544   if (!getLangOpts().CPlusPlus)
5545     return false;
5546 
5547   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5548   if (!RD)
5549     return false;
5550 
5551   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5552   // class template specialization here, but doing so breaks a lot of code.
5553 
5554   // We can't answer whether something is abstract until it has a
5555   // definition. If it's currently being defined, we'll walk back
5556   // over all the declarations when we have a full definition.
5557   const CXXRecordDecl *Def = RD->getDefinition();
5558   if (!Def || Def->isBeingDefined())
5559     return false;
5560 
5561   return RD->isAbstract();
5562 }
5563 
5564 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5565                                   TypeDiagnoser &Diagnoser) {
5566   if (!isAbstractType(Loc, T))
5567     return false;
5568 
5569   T = Context.getBaseElementType(T);
5570   Diagnoser.diagnose(*this, Loc, T);
5571   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5572   return true;
5573 }
5574 
5575 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5576   // Check if we've already emitted the list of pure virtual functions
5577   // for this class.
5578   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5579     return;
5580 
5581   // If the diagnostic is suppressed, don't emit the notes. We're only
5582   // going to emit them once, so try to attach them to a diagnostic we're
5583   // actually going to show.
5584   if (Diags.isLastDiagnosticIgnored())
5585     return;
5586 
5587   CXXFinalOverriderMap FinalOverriders;
5588   RD->getFinalOverriders(FinalOverriders);
5589 
5590   // Keep a set of seen pure methods so we won't diagnose the same method
5591   // more than once.
5592   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5593 
5594   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5595                                    MEnd = FinalOverriders.end();
5596        M != MEnd;
5597        ++M) {
5598     for (OverridingMethods::iterator SO = M->second.begin(),
5599                                   SOEnd = M->second.end();
5600          SO != SOEnd; ++SO) {
5601       // C++ [class.abstract]p4:
5602       //   A class is abstract if it contains or inherits at least one
5603       //   pure virtual function for which the final overrider is pure
5604       //   virtual.
5605 
5606       //
5607       if (SO->second.size() != 1)
5608         continue;
5609 
5610       if (!SO->second.front().Method->isPure())
5611         continue;
5612 
5613       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5614         continue;
5615 
5616       Diag(SO->second.front().Method->getLocation(),
5617            diag::note_pure_virtual_function)
5618         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5619     }
5620   }
5621 
5622   if (!PureVirtualClassDiagSet)
5623     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5624   PureVirtualClassDiagSet->insert(RD);
5625 }
5626 
5627 namespace {
5628 struct AbstractUsageInfo {
5629   Sema &S;
5630   CXXRecordDecl *Record;
5631   CanQualType AbstractType;
5632   bool Invalid;
5633 
5634   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5635     : S(S), Record(Record),
5636       AbstractType(S.Context.getCanonicalType(
5637                    S.Context.getTypeDeclType(Record))),
5638       Invalid(false) {}
5639 
5640   void DiagnoseAbstractType() {
5641     if (Invalid) return;
5642     S.DiagnoseAbstractType(Record);
5643     Invalid = true;
5644   }
5645 
5646   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5647 };
5648 
5649 struct CheckAbstractUsage {
5650   AbstractUsageInfo &Info;
5651   const NamedDecl *Ctx;
5652 
5653   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5654     : Info(Info), Ctx(Ctx) {}
5655 
5656   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5657     switch (TL.getTypeLocClass()) {
5658 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5659 #define TYPELOC(CLASS, PARENT) \
5660     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5661 #include "clang/AST/TypeLocNodes.def"
5662     }
5663   }
5664 
5665   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5666     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5667     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5668       if (!TL.getParam(I))
5669         continue;
5670 
5671       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5672       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5673     }
5674   }
5675 
5676   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5677     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5678   }
5679 
5680   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5681     // Visit the type parameters from a permissive context.
5682     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5683       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5684       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5685         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5686           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5687       // TODO: other template argument types?
5688     }
5689   }
5690 
5691   // Visit pointee types from a permissive context.
5692 #define CheckPolymorphic(Type) \
5693   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5694     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5695   }
5696   CheckPolymorphic(PointerTypeLoc)
5697   CheckPolymorphic(ReferenceTypeLoc)
5698   CheckPolymorphic(MemberPointerTypeLoc)
5699   CheckPolymorphic(BlockPointerTypeLoc)
5700   CheckPolymorphic(AtomicTypeLoc)
5701 
5702   /// Handle all the types we haven't given a more specific
5703   /// implementation for above.
5704   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5705     // Every other kind of type that we haven't called out already
5706     // that has an inner type is either (1) sugar or (2) contains that
5707     // inner type in some way as a subobject.
5708     if (TypeLoc Next = TL.getNextTypeLoc())
5709       return Visit(Next, Sel);
5710 
5711     // If there's no inner type and we're in a permissive context,
5712     // don't diagnose.
5713     if (Sel == Sema::AbstractNone) return;
5714 
5715     // Check whether the type matches the abstract type.
5716     QualType T = TL.getType();
5717     if (T->isArrayType()) {
5718       Sel = Sema::AbstractArrayType;
5719       T = Info.S.Context.getBaseElementType(T);
5720     }
5721     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5722     if (CT != Info.AbstractType) return;
5723 
5724     // It matched; do some magic.
5725     if (Sel == Sema::AbstractArrayType) {
5726       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5727         << T << TL.getSourceRange();
5728     } else {
5729       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5730         << Sel << T << TL.getSourceRange();
5731     }
5732     Info.DiagnoseAbstractType();
5733   }
5734 };
5735 
5736 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5737                                   Sema::AbstractDiagSelID Sel) {
5738   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5739 }
5740 
5741 }
5742 
5743 /// Check for invalid uses of an abstract type in a method declaration.
5744 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5745                                     CXXMethodDecl *MD) {
5746   // No need to do the check on definitions, which require that
5747   // the return/param types be complete.
5748   if (MD->doesThisDeclarationHaveABody())
5749     return;
5750 
5751   // For safety's sake, just ignore it if we don't have type source
5752   // information.  This should never happen for non-implicit methods,
5753   // but...
5754   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5755     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5756 }
5757 
5758 /// Check for invalid uses of an abstract type within a class definition.
5759 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5760                                     CXXRecordDecl *RD) {
5761   for (auto *D : RD->decls()) {
5762     if (D->isImplicit()) continue;
5763 
5764     // Methods and method templates.
5765     if (isa<CXXMethodDecl>(D)) {
5766       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5767     } else if (isa<FunctionTemplateDecl>(D)) {
5768       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5769       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5770 
5771     // Fields and static variables.
5772     } else if (isa<FieldDecl>(D)) {
5773       FieldDecl *FD = cast<FieldDecl>(D);
5774       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5775         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5776     } else if (isa<VarDecl>(D)) {
5777       VarDecl *VD = cast<VarDecl>(D);
5778       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5779         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5780 
5781     // Nested classes and class templates.
5782     } else if (isa<CXXRecordDecl>(D)) {
5783       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5784     } else if (isa<ClassTemplateDecl>(D)) {
5785       CheckAbstractClassUsage(Info,
5786                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5787     }
5788   }
5789 }
5790 
5791 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5792   Attr *ClassAttr = getDLLAttr(Class);
5793   if (!ClassAttr)
5794     return;
5795 
5796   assert(ClassAttr->getKind() == attr::DLLExport);
5797 
5798   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5799 
5800   if (TSK == TSK_ExplicitInstantiationDeclaration)
5801     // Don't go any further if this is just an explicit instantiation
5802     // declaration.
5803     return;
5804 
5805   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5806     S.MarkVTableUsed(Class->getLocation(), Class, true);
5807 
5808   for (Decl *Member : Class->decls()) {
5809     // Defined static variables that are members of an exported base
5810     // class must be marked export too.
5811     auto *VD = dyn_cast<VarDecl>(Member);
5812     if (VD && Member->getAttr<DLLExportAttr>() &&
5813         VD->getStorageClass() == SC_Static &&
5814         TSK == TSK_ImplicitInstantiation)
5815       S.MarkVariableReferenced(VD->getLocation(), VD);
5816 
5817     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5818     if (!MD)
5819       continue;
5820 
5821     if (Member->getAttr<DLLExportAttr>()) {
5822       if (MD->isUserProvided()) {
5823         // Instantiate non-default class member functions ...
5824 
5825         // .. except for certain kinds of template specializations.
5826         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5827           continue;
5828 
5829         S.MarkFunctionReferenced(Class->getLocation(), MD);
5830 
5831         // The function will be passed to the consumer when its definition is
5832         // encountered.
5833       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5834                  MD->isCopyAssignmentOperator() ||
5835                  MD->isMoveAssignmentOperator()) {
5836         // Synthesize and instantiate non-trivial implicit methods, explicitly
5837         // defaulted methods, and the copy and move assignment operators. The
5838         // latter are exported even if they are trivial, because the address of
5839         // an operator can be taken and should compare equal across libraries.
5840         DiagnosticErrorTrap Trap(S.Diags);
5841         S.MarkFunctionReferenced(Class->getLocation(), MD);
5842         if (Trap.hasErrorOccurred()) {
5843           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5844               << Class << !S.getLangOpts().CPlusPlus11;
5845           break;
5846         }
5847 
5848         // There is no later point when we will see the definition of this
5849         // function, so pass it to the consumer now.
5850         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5851       }
5852     }
5853   }
5854 }
5855 
5856 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5857                                                         CXXRecordDecl *Class) {
5858   // Only the MS ABI has default constructor closures, so we don't need to do
5859   // this semantic checking anywhere else.
5860   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5861     return;
5862 
5863   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5864   for (Decl *Member : Class->decls()) {
5865     // Look for exported default constructors.
5866     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5867     if (!CD || !CD->isDefaultConstructor())
5868       continue;
5869     auto *Attr = CD->getAttr<DLLExportAttr>();
5870     if (!Attr)
5871       continue;
5872 
5873     // If the class is non-dependent, mark the default arguments as ODR-used so
5874     // that we can properly codegen the constructor closure.
5875     if (!Class->isDependentContext()) {
5876       for (ParmVarDecl *PD : CD->parameters()) {
5877         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5878         S.DiscardCleanupsInEvaluationContext();
5879       }
5880     }
5881 
5882     if (LastExportedDefaultCtor) {
5883       S.Diag(LastExportedDefaultCtor->getLocation(),
5884              diag::err_attribute_dll_ambiguous_default_ctor)
5885           << Class;
5886       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5887           << CD->getDeclName();
5888       return;
5889     }
5890     LastExportedDefaultCtor = CD;
5891   }
5892 }
5893 
5894 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5895                                                        CXXRecordDecl *Class) {
5896   bool ErrorReported = false;
5897   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5898                                                      ClassTemplateDecl *TD) {
5899     if (ErrorReported)
5900       return;
5901     S.Diag(TD->getLocation(),
5902            diag::err_cuda_device_builtin_surftex_cls_template)
5903         << /*surface*/ 0 << TD;
5904     ErrorReported = true;
5905   };
5906 
5907   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5908   if (!TD) {
5909     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5910     if (!SD) {
5911       S.Diag(Class->getLocation(),
5912              diag::err_cuda_device_builtin_surftex_ref_decl)
5913           << /*surface*/ 0 << Class;
5914       S.Diag(Class->getLocation(),
5915              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5916           << Class;
5917       return;
5918     }
5919     TD = SD->getSpecializedTemplate();
5920   }
5921 
5922   TemplateParameterList *Params = TD->getTemplateParameters();
5923   unsigned N = Params->size();
5924 
5925   if (N != 2) {
5926     reportIllegalClassTemplate(S, TD);
5927     S.Diag(TD->getLocation(),
5928            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5929         << TD << 2;
5930   }
5931   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5932     reportIllegalClassTemplate(S, TD);
5933     S.Diag(TD->getLocation(),
5934            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5935         << TD << /*1st*/ 0 << /*type*/ 0;
5936   }
5937   if (N > 1) {
5938     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5939     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5940       reportIllegalClassTemplate(S, TD);
5941       S.Diag(TD->getLocation(),
5942              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5943           << TD << /*2nd*/ 1 << /*integer*/ 1;
5944     }
5945   }
5946 }
5947 
5948 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5949                                                        CXXRecordDecl *Class) {
5950   bool ErrorReported = false;
5951   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5952                                                      ClassTemplateDecl *TD) {
5953     if (ErrorReported)
5954       return;
5955     S.Diag(TD->getLocation(),
5956            diag::err_cuda_device_builtin_surftex_cls_template)
5957         << /*texture*/ 1 << TD;
5958     ErrorReported = true;
5959   };
5960 
5961   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5962   if (!TD) {
5963     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5964     if (!SD) {
5965       S.Diag(Class->getLocation(),
5966              diag::err_cuda_device_builtin_surftex_ref_decl)
5967           << /*texture*/ 1 << Class;
5968       S.Diag(Class->getLocation(),
5969              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5970           << Class;
5971       return;
5972     }
5973     TD = SD->getSpecializedTemplate();
5974   }
5975 
5976   TemplateParameterList *Params = TD->getTemplateParameters();
5977   unsigned N = Params->size();
5978 
5979   if (N != 3) {
5980     reportIllegalClassTemplate(S, TD);
5981     S.Diag(TD->getLocation(),
5982            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5983         << TD << 3;
5984   }
5985   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5986     reportIllegalClassTemplate(S, TD);
5987     S.Diag(TD->getLocation(),
5988            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5989         << TD << /*1st*/ 0 << /*type*/ 0;
5990   }
5991   if (N > 1) {
5992     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5993     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5994       reportIllegalClassTemplate(S, TD);
5995       S.Diag(TD->getLocation(),
5996              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5997           << TD << /*2nd*/ 1 << /*integer*/ 1;
5998     }
5999   }
6000   if (N > 2) {
6001     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6002     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6003       reportIllegalClassTemplate(S, TD);
6004       S.Diag(TD->getLocation(),
6005              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6006           << TD << /*3rd*/ 2 << /*integer*/ 1;
6007     }
6008   }
6009 }
6010 
6011 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6012   // Mark any compiler-generated routines with the implicit code_seg attribute.
6013   for (auto *Method : Class->methods()) {
6014     if (Method->isUserProvided())
6015       continue;
6016     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6017       Method->addAttr(A);
6018   }
6019 }
6020 
6021 /// Check class-level dllimport/dllexport attribute.
6022 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6023   Attr *ClassAttr = getDLLAttr(Class);
6024 
6025   // MSVC inherits DLL attributes to partial class template specializations.
6026   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6027     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6028       if (Attr *TemplateAttr =
6029               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6030         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6031         A->setInherited(true);
6032         ClassAttr = A;
6033       }
6034     }
6035   }
6036 
6037   if (!ClassAttr)
6038     return;
6039 
6040   if (!Class->isExternallyVisible()) {
6041     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6042         << Class << ClassAttr;
6043     return;
6044   }
6045 
6046   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6047       !ClassAttr->isInherited()) {
6048     // Diagnose dll attributes on members of class with dll attribute.
6049     for (Decl *Member : Class->decls()) {
6050       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6051         continue;
6052       InheritableAttr *MemberAttr = getDLLAttr(Member);
6053       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6054         continue;
6055 
6056       Diag(MemberAttr->getLocation(),
6057              diag::err_attribute_dll_member_of_dll_class)
6058           << MemberAttr << ClassAttr;
6059       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6060       Member->setInvalidDecl();
6061     }
6062   }
6063 
6064   if (Class->getDescribedClassTemplate())
6065     // Don't inherit dll attribute until the template is instantiated.
6066     return;
6067 
6068   // The class is either imported or exported.
6069   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6070 
6071   // Check if this was a dllimport attribute propagated from a derived class to
6072   // a base class template specialization. We don't apply these attributes to
6073   // static data members.
6074   const bool PropagatedImport =
6075       !ClassExported &&
6076       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6077 
6078   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6079 
6080   // Ignore explicit dllexport on explicit class template instantiation
6081   // declarations, except in MinGW mode.
6082   if (ClassExported && !ClassAttr->isInherited() &&
6083       TSK == TSK_ExplicitInstantiationDeclaration &&
6084       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6085     Class->dropAttr<DLLExportAttr>();
6086     return;
6087   }
6088 
6089   // Force declaration of implicit members so they can inherit the attribute.
6090   ForceDeclarationOfImplicitMembers(Class);
6091 
6092   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6093   // seem to be true in practice?
6094 
6095   for (Decl *Member : Class->decls()) {
6096     VarDecl *VD = dyn_cast<VarDecl>(Member);
6097     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6098 
6099     // Only methods and static fields inherit the attributes.
6100     if (!VD && !MD)
6101       continue;
6102 
6103     if (MD) {
6104       // Don't process deleted methods.
6105       if (MD->isDeleted())
6106         continue;
6107 
6108       if (MD->isInlined()) {
6109         // MinGW does not import or export inline methods. But do it for
6110         // template instantiations.
6111         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6112             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6113             TSK != TSK_ExplicitInstantiationDeclaration &&
6114             TSK != TSK_ExplicitInstantiationDefinition)
6115           continue;
6116 
6117         // MSVC versions before 2015 don't export the move assignment operators
6118         // and move constructor, so don't attempt to import/export them if
6119         // we have a definition.
6120         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6121         if ((MD->isMoveAssignmentOperator() ||
6122              (Ctor && Ctor->isMoveConstructor())) &&
6123             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6124           continue;
6125 
6126         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6127         // operator is exported anyway.
6128         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6129             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6130           continue;
6131       }
6132     }
6133 
6134     // Don't apply dllimport attributes to static data members of class template
6135     // instantiations when the attribute is propagated from a derived class.
6136     if (VD && PropagatedImport)
6137       continue;
6138 
6139     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6140       continue;
6141 
6142     if (!getDLLAttr(Member)) {
6143       InheritableAttr *NewAttr = nullptr;
6144 
6145       // Do not export/import inline function when -fno-dllexport-inlines is
6146       // passed. But add attribute for later local static var check.
6147       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6148           TSK != TSK_ExplicitInstantiationDeclaration &&
6149           TSK != TSK_ExplicitInstantiationDefinition) {
6150         if (ClassExported) {
6151           NewAttr = ::new (getASTContext())
6152               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6153         } else {
6154           NewAttr = ::new (getASTContext())
6155               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6156         }
6157       } else {
6158         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6159       }
6160 
6161       NewAttr->setInherited(true);
6162       Member->addAttr(NewAttr);
6163 
6164       if (MD) {
6165         // Propagate DLLAttr to friend re-declarations of MD that have already
6166         // been constructed.
6167         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6168              FD = FD->getPreviousDecl()) {
6169           if (FD->getFriendObjectKind() == Decl::FOK_None)
6170             continue;
6171           assert(!getDLLAttr(FD) &&
6172                  "friend re-decl should not already have a DLLAttr");
6173           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6174           NewAttr->setInherited(true);
6175           FD->addAttr(NewAttr);
6176         }
6177       }
6178     }
6179   }
6180 
6181   if (ClassExported)
6182     DelayedDllExportClasses.push_back(Class);
6183 }
6184 
6185 /// Perform propagation of DLL attributes from a derived class to a
6186 /// templated base class for MS compatibility.
6187 void Sema::propagateDLLAttrToBaseClassTemplate(
6188     CXXRecordDecl *Class, Attr *ClassAttr,
6189     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6190   if (getDLLAttr(
6191           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6192     // If the base class template has a DLL attribute, don't try to change it.
6193     return;
6194   }
6195 
6196   auto TSK = BaseTemplateSpec->getSpecializationKind();
6197   if (!getDLLAttr(BaseTemplateSpec) &&
6198       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6199        TSK == TSK_ImplicitInstantiation)) {
6200     // The template hasn't been instantiated yet (or it has, but only as an
6201     // explicit instantiation declaration or implicit instantiation, which means
6202     // we haven't codegenned any members yet), so propagate the attribute.
6203     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6204     NewAttr->setInherited(true);
6205     BaseTemplateSpec->addAttr(NewAttr);
6206 
6207     // If this was an import, mark that we propagated it from a derived class to
6208     // a base class template specialization.
6209     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6210       ImportAttr->setPropagatedToBaseTemplate();
6211 
6212     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6213     // needs to be run again to work see the new attribute. Otherwise this will
6214     // get run whenever the template is instantiated.
6215     if (TSK != TSK_Undeclared)
6216       checkClassLevelDLLAttribute(BaseTemplateSpec);
6217 
6218     return;
6219   }
6220 
6221   if (getDLLAttr(BaseTemplateSpec)) {
6222     // The template has already been specialized or instantiated with an
6223     // attribute, explicitly or through propagation. We should not try to change
6224     // it.
6225     return;
6226   }
6227 
6228   // The template was previously instantiated or explicitly specialized without
6229   // a dll attribute, It's too late for us to add an attribute, so warn that
6230   // this is unsupported.
6231   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6232       << BaseTemplateSpec->isExplicitSpecialization();
6233   Diag(ClassAttr->getLocation(), diag::note_attribute);
6234   if (BaseTemplateSpec->isExplicitSpecialization()) {
6235     Diag(BaseTemplateSpec->getLocation(),
6236            diag::note_template_class_explicit_specialization_was_here)
6237         << BaseTemplateSpec;
6238   } else {
6239     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6240            diag::note_template_class_instantiation_was_here)
6241         << BaseTemplateSpec;
6242   }
6243 }
6244 
6245 /// Determine the kind of defaulting that would be done for a given function.
6246 ///
6247 /// If the function is both a default constructor and a copy / move constructor
6248 /// (due to having a default argument for the first parameter), this picks
6249 /// CXXDefaultConstructor.
6250 ///
6251 /// FIXME: Check that case is properly handled by all callers.
6252 Sema::DefaultedFunctionKind
6253 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6254   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6255     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6256       if (Ctor->isDefaultConstructor())
6257         return Sema::CXXDefaultConstructor;
6258 
6259       if (Ctor->isCopyConstructor())
6260         return Sema::CXXCopyConstructor;
6261 
6262       if (Ctor->isMoveConstructor())
6263         return Sema::CXXMoveConstructor;
6264     }
6265 
6266     if (MD->isCopyAssignmentOperator())
6267       return Sema::CXXCopyAssignment;
6268 
6269     if (MD->isMoveAssignmentOperator())
6270       return Sema::CXXMoveAssignment;
6271 
6272     if (isa<CXXDestructorDecl>(FD))
6273       return Sema::CXXDestructor;
6274   }
6275 
6276   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6277   case OO_EqualEqual:
6278     return DefaultedComparisonKind::Equal;
6279 
6280   case OO_ExclaimEqual:
6281     return DefaultedComparisonKind::NotEqual;
6282 
6283   case OO_Spaceship:
6284     // No point allowing this if <=> doesn't exist in the current language mode.
6285     if (!getLangOpts().CPlusPlus20)
6286       break;
6287     return DefaultedComparisonKind::ThreeWay;
6288 
6289   case OO_Less:
6290   case OO_LessEqual:
6291   case OO_Greater:
6292   case OO_GreaterEqual:
6293     // No point allowing this if <=> doesn't exist in the current language mode.
6294     if (!getLangOpts().CPlusPlus20)
6295       break;
6296     return DefaultedComparisonKind::Relational;
6297 
6298   default:
6299     break;
6300   }
6301 
6302   // Not defaultable.
6303   return DefaultedFunctionKind();
6304 }
6305 
6306 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6307                                     SourceLocation DefaultLoc) {
6308   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6309   if (DFK.isComparison())
6310     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6311 
6312   switch (DFK.asSpecialMember()) {
6313   case Sema::CXXDefaultConstructor:
6314     S.DefineImplicitDefaultConstructor(DefaultLoc,
6315                                        cast<CXXConstructorDecl>(FD));
6316     break;
6317   case Sema::CXXCopyConstructor:
6318     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6319     break;
6320   case Sema::CXXCopyAssignment:
6321     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6322     break;
6323   case Sema::CXXDestructor:
6324     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6325     break;
6326   case Sema::CXXMoveConstructor:
6327     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6328     break;
6329   case Sema::CXXMoveAssignment:
6330     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6331     break;
6332   case Sema::CXXInvalid:
6333     llvm_unreachable("Invalid special member.");
6334   }
6335 }
6336 
6337 /// Determine whether a type is permitted to be passed or returned in
6338 /// registers, per C++ [class.temporary]p3.
6339 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6340                                TargetInfo::CallingConvKind CCK) {
6341   if (D->isDependentType() || D->isInvalidDecl())
6342     return false;
6343 
6344   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6345   // The PS4 platform ABI follows the behavior of Clang 3.2.
6346   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6347     return !D->hasNonTrivialDestructorForCall() &&
6348            !D->hasNonTrivialCopyConstructorForCall();
6349 
6350   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6351     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6352     bool DtorIsTrivialForCall = false;
6353 
6354     // If a class has at least one non-deleted, trivial copy constructor, it
6355     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6356     //
6357     // Note: This permits classes with non-trivial copy or move ctors to be
6358     // passed in registers, so long as they *also* have a trivial copy ctor,
6359     // which is non-conforming.
6360     if (D->needsImplicitCopyConstructor()) {
6361       if (!D->defaultedCopyConstructorIsDeleted()) {
6362         if (D->hasTrivialCopyConstructor())
6363           CopyCtorIsTrivial = true;
6364         if (D->hasTrivialCopyConstructorForCall())
6365           CopyCtorIsTrivialForCall = true;
6366       }
6367     } else {
6368       for (const CXXConstructorDecl *CD : D->ctors()) {
6369         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6370           if (CD->isTrivial())
6371             CopyCtorIsTrivial = true;
6372           if (CD->isTrivialForCall())
6373             CopyCtorIsTrivialForCall = true;
6374         }
6375       }
6376     }
6377 
6378     if (D->needsImplicitDestructor()) {
6379       if (!D->defaultedDestructorIsDeleted() &&
6380           D->hasTrivialDestructorForCall())
6381         DtorIsTrivialForCall = true;
6382     } else if (const auto *DD = D->getDestructor()) {
6383       if (!DD->isDeleted() && DD->isTrivialForCall())
6384         DtorIsTrivialForCall = true;
6385     }
6386 
6387     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6388     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6389       return true;
6390 
6391     // If a class has a destructor, we'd really like to pass it indirectly
6392     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6393     // impossible for small types, which it will pass in a single register or
6394     // stack slot. Most objects with dtors are large-ish, so handle that early.
6395     // We can't call out all large objects as being indirect because there are
6396     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6397     // how we pass large POD types.
6398 
6399     // Note: This permits small classes with nontrivial destructors to be
6400     // passed in registers, which is non-conforming.
6401     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6402     uint64_t TypeSize = isAArch64 ? 128 : 64;
6403 
6404     if (CopyCtorIsTrivial &&
6405         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6406       return true;
6407     return false;
6408   }
6409 
6410   // Per C++ [class.temporary]p3, the relevant condition is:
6411   //   each copy constructor, move constructor, and destructor of X is
6412   //   either trivial or deleted, and X has at least one non-deleted copy
6413   //   or move constructor
6414   bool HasNonDeletedCopyOrMove = false;
6415 
6416   if (D->needsImplicitCopyConstructor() &&
6417       !D->defaultedCopyConstructorIsDeleted()) {
6418     if (!D->hasTrivialCopyConstructorForCall())
6419       return false;
6420     HasNonDeletedCopyOrMove = true;
6421   }
6422 
6423   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6424       !D->defaultedMoveConstructorIsDeleted()) {
6425     if (!D->hasTrivialMoveConstructorForCall())
6426       return false;
6427     HasNonDeletedCopyOrMove = true;
6428   }
6429 
6430   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6431       !D->hasTrivialDestructorForCall())
6432     return false;
6433 
6434   for (const CXXMethodDecl *MD : D->methods()) {
6435     if (MD->isDeleted())
6436       continue;
6437 
6438     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6439     if (CD && CD->isCopyOrMoveConstructor())
6440       HasNonDeletedCopyOrMove = true;
6441     else if (!isa<CXXDestructorDecl>(MD))
6442       continue;
6443 
6444     if (!MD->isTrivialForCall())
6445       return false;
6446   }
6447 
6448   return HasNonDeletedCopyOrMove;
6449 }
6450 
6451 /// Report an error regarding overriding, along with any relevant
6452 /// overridden methods.
6453 ///
6454 /// \param DiagID the primary error to report.
6455 /// \param MD the overriding method.
6456 static bool
6457 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6458                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6459   bool IssuedDiagnostic = false;
6460   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6461     if (Report(O)) {
6462       if (!IssuedDiagnostic) {
6463         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6464         IssuedDiagnostic = true;
6465       }
6466       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6467     }
6468   }
6469   return IssuedDiagnostic;
6470 }
6471 
6472 /// Perform semantic checks on a class definition that has been
6473 /// completing, introducing implicitly-declared members, checking for
6474 /// abstract types, etc.
6475 ///
6476 /// \param S The scope in which the class was parsed. Null if we didn't just
6477 ///        parse a class definition.
6478 /// \param Record The completed class.
6479 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6480   if (!Record)
6481     return;
6482 
6483   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6484     AbstractUsageInfo Info(*this, Record);
6485     CheckAbstractClassUsage(Info, Record);
6486   }
6487 
6488   // If this is not an aggregate type and has no user-declared constructor,
6489   // complain about any non-static data members of reference or const scalar
6490   // type, since they will never get initializers.
6491   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6492       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6493       !Record->isLambda()) {
6494     bool Complained = false;
6495     for (const auto *F : Record->fields()) {
6496       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6497         continue;
6498 
6499       if (F->getType()->isReferenceType() ||
6500           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6501         if (!Complained) {
6502           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6503             << Record->getTagKind() << Record;
6504           Complained = true;
6505         }
6506 
6507         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6508           << F->getType()->isReferenceType()
6509           << F->getDeclName();
6510       }
6511     }
6512   }
6513 
6514   if (Record->getIdentifier()) {
6515     // C++ [class.mem]p13:
6516     //   If T is the name of a class, then each of the following shall have a
6517     //   name different from T:
6518     //     - every member of every anonymous union that is a member of class T.
6519     //
6520     // C++ [class.mem]p14:
6521     //   In addition, if class T has a user-declared constructor (12.1), every
6522     //   non-static data member of class T shall have a name different from T.
6523     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6524     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6525          ++I) {
6526       NamedDecl *D = (*I)->getUnderlyingDecl();
6527       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6528            Record->hasUserDeclaredConstructor()) ||
6529           isa<IndirectFieldDecl>(D)) {
6530         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6531           << D->getDeclName();
6532         break;
6533       }
6534     }
6535   }
6536 
6537   // Warn if the class has virtual methods but non-virtual public destructor.
6538   if (Record->isPolymorphic() && !Record->isDependentType()) {
6539     CXXDestructorDecl *dtor = Record->getDestructor();
6540     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6541         !Record->hasAttr<FinalAttr>())
6542       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6543            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6544   }
6545 
6546   if (Record->isAbstract()) {
6547     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6548       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6549         << FA->isSpelledAsSealed();
6550       DiagnoseAbstractType(Record);
6551     }
6552   }
6553 
6554   // Warn if the class has a final destructor but is not itself marked final.
6555   if (!Record->hasAttr<FinalAttr>()) {
6556     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6557       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6558         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6559             << FA->isSpelledAsSealed()
6560             << FixItHint::CreateInsertion(
6561                    getLocForEndOfToken(Record->getLocation()),
6562                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6563         Diag(Record->getLocation(),
6564              diag::note_final_dtor_non_final_class_silence)
6565             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6566       }
6567     }
6568   }
6569 
6570   // See if trivial_abi has to be dropped.
6571   if (Record->hasAttr<TrivialABIAttr>())
6572     checkIllFormedTrivialABIStruct(*Record);
6573 
6574   // Set HasTrivialSpecialMemberForCall if the record has attribute
6575   // "trivial_abi".
6576   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6577 
6578   if (HasTrivialABI)
6579     Record->setHasTrivialSpecialMemberForCall();
6580 
6581   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6582   // We check these last because they can depend on the properties of the
6583   // primary comparison functions (==, <=>).
6584   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6585 
6586   // Perform checks that can't be done until we know all the properties of a
6587   // member function (whether it's defaulted, deleted, virtual, overriding,
6588   // ...).
6589   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6590     // A static function cannot override anything.
6591     if (MD->getStorageClass() == SC_Static) {
6592       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6593                           [](const CXXMethodDecl *) { return true; }))
6594         return;
6595     }
6596 
6597     // A deleted function cannot override a non-deleted function and vice
6598     // versa.
6599     if (ReportOverrides(*this,
6600                         MD->isDeleted() ? diag::err_deleted_override
6601                                         : diag::err_non_deleted_override,
6602                         MD, [&](const CXXMethodDecl *V) {
6603                           return MD->isDeleted() != V->isDeleted();
6604                         })) {
6605       if (MD->isDefaulted() && MD->isDeleted())
6606         // Explain why this defaulted function was deleted.
6607         DiagnoseDeletedDefaultedFunction(MD);
6608       return;
6609     }
6610 
6611     // A consteval function cannot override a non-consteval function and vice
6612     // versa.
6613     if (ReportOverrides(*this,
6614                         MD->isConsteval() ? diag::err_consteval_override
6615                                           : diag::err_non_consteval_override,
6616                         MD, [&](const CXXMethodDecl *V) {
6617                           return MD->isConsteval() != V->isConsteval();
6618                         })) {
6619       if (MD->isDefaulted() && MD->isDeleted())
6620         // Explain why this defaulted function was deleted.
6621         DiagnoseDeletedDefaultedFunction(MD);
6622       return;
6623     }
6624   };
6625 
6626   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6627     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6628       return false;
6629 
6630     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6631     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6632         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6633       DefaultedSecondaryComparisons.push_back(FD);
6634       return true;
6635     }
6636 
6637     CheckExplicitlyDefaultedFunction(S, FD);
6638     return false;
6639   };
6640 
6641   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6642     // Check whether the explicitly-defaulted members are valid.
6643     bool Incomplete = CheckForDefaultedFunction(M);
6644 
6645     // Skip the rest of the checks for a member of a dependent class.
6646     if (Record->isDependentType())
6647       return;
6648 
6649     // For an explicitly defaulted or deleted special member, we defer
6650     // determining triviality until the class is complete. That time is now!
6651     CXXSpecialMember CSM = getSpecialMember(M);
6652     if (!M->isImplicit() && !M->isUserProvided()) {
6653       if (CSM != CXXInvalid) {
6654         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6655         // Inform the class that we've finished declaring this member.
6656         Record->finishedDefaultedOrDeletedMember(M);
6657         M->setTrivialForCall(
6658             HasTrivialABI ||
6659             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6660         Record->setTrivialForCallFlags(M);
6661       }
6662     }
6663 
6664     // Set triviality for the purpose of calls if this is a user-provided
6665     // copy/move constructor or destructor.
6666     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6667          CSM == CXXDestructor) && M->isUserProvided()) {
6668       M->setTrivialForCall(HasTrivialABI);
6669       Record->setTrivialForCallFlags(M);
6670     }
6671 
6672     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6673         M->hasAttr<DLLExportAttr>()) {
6674       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6675           M->isTrivial() &&
6676           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6677            CSM == CXXDestructor))
6678         M->dropAttr<DLLExportAttr>();
6679 
6680       if (M->hasAttr<DLLExportAttr>()) {
6681         // Define after any fields with in-class initializers have been parsed.
6682         DelayedDllExportMemberFunctions.push_back(M);
6683       }
6684     }
6685 
6686     // Define defaulted constexpr virtual functions that override a base class
6687     // function right away.
6688     // FIXME: We can defer doing this until the vtable is marked as used.
6689     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6690       DefineDefaultedFunction(*this, M, M->getLocation());
6691 
6692     if (!Incomplete)
6693       CheckCompletedMemberFunction(M);
6694   };
6695 
6696   // Check the destructor before any other member function. We need to
6697   // determine whether it's trivial in order to determine whether the claas
6698   // type is a literal type, which is a prerequisite for determining whether
6699   // other special member functions are valid and whether they're implicitly
6700   // 'constexpr'.
6701   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6702     CompleteMemberFunction(Dtor);
6703 
6704   bool HasMethodWithOverrideControl = false,
6705        HasOverridingMethodWithoutOverrideControl = false;
6706   for (auto *D : Record->decls()) {
6707     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6708       // FIXME: We could do this check for dependent types with non-dependent
6709       // bases.
6710       if (!Record->isDependentType()) {
6711         // See if a method overloads virtual methods in a base
6712         // class without overriding any.
6713         if (!M->isStatic())
6714           DiagnoseHiddenVirtualMethods(M);
6715         if (M->hasAttr<OverrideAttr>())
6716           HasMethodWithOverrideControl = true;
6717         else if (M->size_overridden_methods() > 0)
6718           HasOverridingMethodWithoutOverrideControl = true;
6719       }
6720 
6721       if (!isa<CXXDestructorDecl>(M))
6722         CompleteMemberFunction(M);
6723     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6724       CheckForDefaultedFunction(
6725           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6726     }
6727   }
6728 
6729   if (HasMethodWithOverrideControl &&
6730       HasOverridingMethodWithoutOverrideControl) {
6731     // At least one method has the 'override' control declared.
6732     // Diagnose all other overridden methods which do not have 'override'
6733     // specified on them.
6734     for (auto *M : Record->methods())
6735       DiagnoseAbsenceOfOverrideControl(M);
6736   }
6737 
6738   // Check the defaulted secondary comparisons after any other member functions.
6739   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6740     CheckExplicitlyDefaultedFunction(S, FD);
6741 
6742     // If this is a member function, we deferred checking it until now.
6743     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6744       CheckCompletedMemberFunction(MD);
6745   }
6746 
6747   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6748   // whether this class uses any C++ features that are implemented
6749   // completely differently in MSVC, and if so, emit a diagnostic.
6750   // That diagnostic defaults to an error, but we allow projects to
6751   // map it down to a warning (or ignore it).  It's a fairly common
6752   // practice among users of the ms_struct pragma to mass-annotate
6753   // headers, sweeping up a bunch of types that the project doesn't
6754   // really rely on MSVC-compatible layout for.  We must therefore
6755   // support "ms_struct except for C++ stuff" as a secondary ABI.
6756   if (Record->isMsStruct(Context) &&
6757       (Record->isPolymorphic() || Record->getNumBases())) {
6758     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6759   }
6760 
6761   checkClassLevelDLLAttribute(Record);
6762   checkClassLevelCodeSegAttribute(Record);
6763 
6764   bool ClangABICompat4 =
6765       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6766   TargetInfo::CallingConvKind CCK =
6767       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6768   bool CanPass = canPassInRegisters(*this, Record, CCK);
6769 
6770   // Do not change ArgPassingRestrictions if it has already been set to
6771   // APK_CanNeverPassInRegs.
6772   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6773     Record->setArgPassingRestrictions(CanPass
6774                                           ? RecordDecl::APK_CanPassInRegs
6775                                           : RecordDecl::APK_CannotPassInRegs);
6776 
6777   // If canPassInRegisters returns true despite the record having a non-trivial
6778   // destructor, the record is destructed in the callee. This happens only when
6779   // the record or one of its subobjects has a field annotated with trivial_abi
6780   // or a field qualified with ObjC __strong/__weak.
6781   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6782     Record->setParamDestroyedInCallee(true);
6783   else if (Record->hasNonTrivialDestructor())
6784     Record->setParamDestroyedInCallee(CanPass);
6785 
6786   if (getLangOpts().ForceEmitVTables) {
6787     // If we want to emit all the vtables, we need to mark it as used.  This
6788     // is especially required for cases like vtable assumption loads.
6789     MarkVTableUsed(Record->getInnerLocStart(), Record);
6790   }
6791 
6792   if (getLangOpts().CUDA) {
6793     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6794       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6795     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6796       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6797   }
6798 }
6799 
6800 /// Look up the special member function that would be called by a special
6801 /// member function for a subobject of class type.
6802 ///
6803 /// \param Class The class type of the subobject.
6804 /// \param CSM The kind of special member function.
6805 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6806 /// \param ConstRHS True if this is a copy operation with a const object
6807 ///        on its RHS, that is, if the argument to the outer special member
6808 ///        function is 'const' and this is not a field marked 'mutable'.
6809 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6810     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6811     unsigned FieldQuals, bool ConstRHS) {
6812   unsigned LHSQuals = 0;
6813   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6814     LHSQuals = FieldQuals;
6815 
6816   unsigned RHSQuals = FieldQuals;
6817   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6818     RHSQuals = 0;
6819   else if (ConstRHS)
6820     RHSQuals |= Qualifiers::Const;
6821 
6822   return S.LookupSpecialMember(Class, CSM,
6823                                RHSQuals & Qualifiers::Const,
6824                                RHSQuals & Qualifiers::Volatile,
6825                                false,
6826                                LHSQuals & Qualifiers::Const,
6827                                LHSQuals & Qualifiers::Volatile);
6828 }
6829 
6830 class Sema::InheritedConstructorInfo {
6831   Sema &S;
6832   SourceLocation UseLoc;
6833 
6834   /// A mapping from the base classes through which the constructor was
6835   /// inherited to the using shadow declaration in that base class (or a null
6836   /// pointer if the constructor was declared in that base class).
6837   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6838       InheritedFromBases;
6839 
6840 public:
6841   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6842                            ConstructorUsingShadowDecl *Shadow)
6843       : S(S), UseLoc(UseLoc) {
6844     bool DiagnosedMultipleConstructedBases = false;
6845     CXXRecordDecl *ConstructedBase = nullptr;
6846     UsingDecl *ConstructedBaseUsing = nullptr;
6847 
6848     // Find the set of such base class subobjects and check that there's a
6849     // unique constructed subobject.
6850     for (auto *D : Shadow->redecls()) {
6851       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6852       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6853       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6854 
6855       InheritedFromBases.insert(
6856           std::make_pair(DNominatedBase->getCanonicalDecl(),
6857                          DShadow->getNominatedBaseClassShadowDecl()));
6858       if (DShadow->constructsVirtualBase())
6859         InheritedFromBases.insert(
6860             std::make_pair(DConstructedBase->getCanonicalDecl(),
6861                            DShadow->getConstructedBaseClassShadowDecl()));
6862       else
6863         assert(DNominatedBase == DConstructedBase);
6864 
6865       // [class.inhctor.init]p2:
6866       //   If the constructor was inherited from multiple base class subobjects
6867       //   of type B, the program is ill-formed.
6868       if (!ConstructedBase) {
6869         ConstructedBase = DConstructedBase;
6870         ConstructedBaseUsing = D->getUsingDecl();
6871       } else if (ConstructedBase != DConstructedBase &&
6872                  !Shadow->isInvalidDecl()) {
6873         if (!DiagnosedMultipleConstructedBases) {
6874           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6875               << Shadow->getTargetDecl();
6876           S.Diag(ConstructedBaseUsing->getLocation(),
6877                diag::note_ambiguous_inherited_constructor_using)
6878               << ConstructedBase;
6879           DiagnosedMultipleConstructedBases = true;
6880         }
6881         S.Diag(D->getUsingDecl()->getLocation(),
6882                diag::note_ambiguous_inherited_constructor_using)
6883             << DConstructedBase;
6884       }
6885     }
6886 
6887     if (DiagnosedMultipleConstructedBases)
6888       Shadow->setInvalidDecl();
6889   }
6890 
6891   /// Find the constructor to use for inherited construction of a base class,
6892   /// and whether that base class constructor inherits the constructor from a
6893   /// virtual base class (in which case it won't actually invoke it).
6894   std::pair<CXXConstructorDecl *, bool>
6895   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6896     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6897     if (It == InheritedFromBases.end())
6898       return std::make_pair(nullptr, false);
6899 
6900     // This is an intermediary class.
6901     if (It->second)
6902       return std::make_pair(
6903           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6904           It->second->constructsVirtualBase());
6905 
6906     // This is the base class from which the constructor was inherited.
6907     return std::make_pair(Ctor, false);
6908   }
6909 };
6910 
6911 /// Is the special member function which would be selected to perform the
6912 /// specified operation on the specified class type a constexpr constructor?
6913 static bool
6914 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6915                          Sema::CXXSpecialMember CSM, unsigned Quals,
6916                          bool ConstRHS,
6917                          CXXConstructorDecl *InheritedCtor = nullptr,
6918                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6919   // If we're inheriting a constructor, see if we need to call it for this base
6920   // class.
6921   if (InheritedCtor) {
6922     assert(CSM == Sema::CXXDefaultConstructor);
6923     auto BaseCtor =
6924         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6925     if (BaseCtor)
6926       return BaseCtor->isConstexpr();
6927   }
6928 
6929   if (CSM == Sema::CXXDefaultConstructor)
6930     return ClassDecl->hasConstexprDefaultConstructor();
6931   if (CSM == Sema::CXXDestructor)
6932     return ClassDecl->hasConstexprDestructor();
6933 
6934   Sema::SpecialMemberOverloadResult SMOR =
6935       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6936   if (!SMOR.getMethod())
6937     // A constructor we wouldn't select can't be "involved in initializing"
6938     // anything.
6939     return true;
6940   return SMOR.getMethod()->isConstexpr();
6941 }
6942 
6943 /// Determine whether the specified special member function would be constexpr
6944 /// if it were implicitly defined.
6945 static bool defaultedSpecialMemberIsConstexpr(
6946     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6947     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6948     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6949   if (!S.getLangOpts().CPlusPlus11)
6950     return false;
6951 
6952   // C++11 [dcl.constexpr]p4:
6953   // In the definition of a constexpr constructor [...]
6954   bool Ctor = true;
6955   switch (CSM) {
6956   case Sema::CXXDefaultConstructor:
6957     if (Inherited)
6958       break;
6959     // Since default constructor lookup is essentially trivial (and cannot
6960     // involve, for instance, template instantiation), we compute whether a
6961     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6962     //
6963     // This is important for performance; we need to know whether the default
6964     // constructor is constexpr to determine whether the type is a literal type.
6965     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6966 
6967   case Sema::CXXCopyConstructor:
6968   case Sema::CXXMoveConstructor:
6969     // For copy or move constructors, we need to perform overload resolution.
6970     break;
6971 
6972   case Sema::CXXCopyAssignment:
6973   case Sema::CXXMoveAssignment:
6974     if (!S.getLangOpts().CPlusPlus14)
6975       return false;
6976     // In C++1y, we need to perform overload resolution.
6977     Ctor = false;
6978     break;
6979 
6980   case Sema::CXXDestructor:
6981     return ClassDecl->defaultedDestructorIsConstexpr();
6982 
6983   case Sema::CXXInvalid:
6984     return false;
6985   }
6986 
6987   //   -- if the class is a non-empty union, or for each non-empty anonymous
6988   //      union member of a non-union class, exactly one non-static data member
6989   //      shall be initialized; [DR1359]
6990   //
6991   // If we squint, this is guaranteed, since exactly one non-static data member
6992   // will be initialized (if the constructor isn't deleted), we just don't know
6993   // which one.
6994   if (Ctor && ClassDecl->isUnion())
6995     return CSM == Sema::CXXDefaultConstructor
6996                ? ClassDecl->hasInClassInitializer() ||
6997                      !ClassDecl->hasVariantMembers()
6998                : true;
6999 
7000   //   -- the class shall not have any virtual base classes;
7001   if (Ctor && ClassDecl->getNumVBases())
7002     return false;
7003 
7004   // C++1y [class.copy]p26:
7005   //   -- [the class] is a literal type, and
7006   if (!Ctor && !ClassDecl->isLiteral())
7007     return false;
7008 
7009   //   -- every constructor involved in initializing [...] base class
7010   //      sub-objects shall be a constexpr constructor;
7011   //   -- the assignment operator selected to copy/move each direct base
7012   //      class is a constexpr function, and
7013   for (const auto &B : ClassDecl->bases()) {
7014     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7015     if (!BaseType) continue;
7016 
7017     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7018     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7019                                   InheritedCtor, Inherited))
7020       return false;
7021   }
7022 
7023   //   -- every constructor involved in initializing non-static data members
7024   //      [...] shall be a constexpr constructor;
7025   //   -- every non-static data member and base class sub-object shall be
7026   //      initialized
7027   //   -- for each non-static data member of X that is of class type (or array
7028   //      thereof), the assignment operator selected to copy/move that member is
7029   //      a constexpr function
7030   for (const auto *F : ClassDecl->fields()) {
7031     if (F->isInvalidDecl())
7032       continue;
7033     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7034       continue;
7035     QualType BaseType = S.Context.getBaseElementType(F->getType());
7036     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7037       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7038       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7039                                     BaseType.getCVRQualifiers(),
7040                                     ConstArg && !F->isMutable()))
7041         return false;
7042     } else if (CSM == Sema::CXXDefaultConstructor) {
7043       return false;
7044     }
7045   }
7046 
7047   // All OK, it's constexpr!
7048   return true;
7049 }
7050 
7051 namespace {
7052 /// RAII object to register a defaulted function as having its exception
7053 /// specification computed.
7054 struct ComputingExceptionSpec {
7055   Sema &S;
7056 
7057   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7058       : S(S) {
7059     Sema::CodeSynthesisContext Ctx;
7060     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7061     Ctx.PointOfInstantiation = Loc;
7062     Ctx.Entity = FD;
7063     S.pushCodeSynthesisContext(Ctx);
7064   }
7065   ~ComputingExceptionSpec() {
7066     S.popCodeSynthesisContext();
7067   }
7068 };
7069 }
7070 
7071 static Sema::ImplicitExceptionSpecification
7072 ComputeDefaultedSpecialMemberExceptionSpec(
7073     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7074     Sema::InheritedConstructorInfo *ICI);
7075 
7076 static Sema::ImplicitExceptionSpecification
7077 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7078                                         FunctionDecl *FD,
7079                                         Sema::DefaultedComparisonKind DCK);
7080 
7081 static Sema::ImplicitExceptionSpecification
7082 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7083   auto DFK = S.getDefaultedFunctionKind(FD);
7084   if (DFK.isSpecialMember())
7085     return ComputeDefaultedSpecialMemberExceptionSpec(
7086         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7087   if (DFK.isComparison())
7088     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7089                                                    DFK.asComparison());
7090 
7091   auto *CD = cast<CXXConstructorDecl>(FD);
7092   assert(CD->getInheritedConstructor() &&
7093          "only defaulted functions and inherited constructors have implicit "
7094          "exception specs");
7095   Sema::InheritedConstructorInfo ICI(
7096       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7097   return ComputeDefaultedSpecialMemberExceptionSpec(
7098       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7099 }
7100 
7101 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7102                                                             CXXMethodDecl *MD) {
7103   FunctionProtoType::ExtProtoInfo EPI;
7104 
7105   // Build an exception specification pointing back at this member.
7106   EPI.ExceptionSpec.Type = EST_Unevaluated;
7107   EPI.ExceptionSpec.SourceDecl = MD;
7108 
7109   // Set the calling convention to the default for C++ instance methods.
7110   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7111       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7112                                             /*IsCXXMethod=*/true));
7113   return EPI;
7114 }
7115 
7116 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7117   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7118   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7119     return;
7120 
7121   // Evaluate the exception specification.
7122   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7123   auto ESI = IES.getExceptionSpec();
7124 
7125   // Update the type of the special member to use it.
7126   UpdateExceptionSpec(FD, ESI);
7127 }
7128 
7129 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7130   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7131 
7132   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7133   if (!DefKind) {
7134     assert(FD->getDeclContext()->isDependentContext());
7135     return;
7136   }
7137 
7138   if (DefKind.isSpecialMember()
7139           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7140                                                   DefKind.asSpecialMember())
7141           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7142     FD->setInvalidDecl();
7143 }
7144 
7145 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7146                                                  CXXSpecialMember CSM) {
7147   CXXRecordDecl *RD = MD->getParent();
7148 
7149   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7150          "not an explicitly-defaulted special member");
7151 
7152   // Defer all checking for special members of a dependent type.
7153   if (RD->isDependentType())
7154     return false;
7155 
7156   // Whether this was the first-declared instance of the constructor.
7157   // This affects whether we implicitly add an exception spec and constexpr.
7158   bool First = MD == MD->getCanonicalDecl();
7159 
7160   bool HadError = false;
7161 
7162   // C++11 [dcl.fct.def.default]p1:
7163   //   A function that is explicitly defaulted shall
7164   //     -- be a special member function [...] (checked elsewhere),
7165   //     -- have the same type (except for ref-qualifiers, and except that a
7166   //        copy operation can take a non-const reference) as an implicit
7167   //        declaration, and
7168   //     -- not have default arguments.
7169   // C++2a changes the second bullet to instead delete the function if it's
7170   // defaulted on its first declaration, unless it's "an assignment operator,
7171   // and its return type differs or its parameter type is not a reference".
7172   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7173   bool ShouldDeleteForTypeMismatch = false;
7174   unsigned ExpectedParams = 1;
7175   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7176     ExpectedParams = 0;
7177   if (MD->getNumParams() != ExpectedParams) {
7178     // This checks for default arguments: a copy or move constructor with a
7179     // default argument is classified as a default constructor, and assignment
7180     // operations and destructors can't have default arguments.
7181     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7182       << CSM << MD->getSourceRange();
7183     HadError = true;
7184   } else if (MD->isVariadic()) {
7185     if (DeleteOnTypeMismatch)
7186       ShouldDeleteForTypeMismatch = true;
7187     else {
7188       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7189         << CSM << MD->getSourceRange();
7190       HadError = true;
7191     }
7192   }
7193 
7194   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7195 
7196   bool CanHaveConstParam = false;
7197   if (CSM == CXXCopyConstructor)
7198     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7199   else if (CSM == CXXCopyAssignment)
7200     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7201 
7202   QualType ReturnType = Context.VoidTy;
7203   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7204     // Check for return type matching.
7205     ReturnType = Type->getReturnType();
7206 
7207     QualType DeclType = Context.getTypeDeclType(RD);
7208     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7209     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7210 
7211     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7212       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7213         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7214       HadError = true;
7215     }
7216 
7217     // A defaulted special member cannot have cv-qualifiers.
7218     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7219       if (DeleteOnTypeMismatch)
7220         ShouldDeleteForTypeMismatch = true;
7221       else {
7222         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7223           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7224         HadError = true;
7225       }
7226     }
7227   }
7228 
7229   // Check for parameter type matching.
7230   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7231   bool HasConstParam = false;
7232   if (ExpectedParams && ArgType->isReferenceType()) {
7233     // Argument must be reference to possibly-const T.
7234     QualType ReferentType = ArgType->getPointeeType();
7235     HasConstParam = ReferentType.isConstQualified();
7236 
7237     if (ReferentType.isVolatileQualified()) {
7238       if (DeleteOnTypeMismatch)
7239         ShouldDeleteForTypeMismatch = true;
7240       else {
7241         Diag(MD->getLocation(),
7242              diag::err_defaulted_special_member_volatile_param) << CSM;
7243         HadError = true;
7244       }
7245     }
7246 
7247     if (HasConstParam && !CanHaveConstParam) {
7248       if (DeleteOnTypeMismatch)
7249         ShouldDeleteForTypeMismatch = true;
7250       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7251         Diag(MD->getLocation(),
7252              diag::err_defaulted_special_member_copy_const_param)
7253           << (CSM == CXXCopyAssignment);
7254         // FIXME: Explain why this special member can't be const.
7255         HadError = true;
7256       } else {
7257         Diag(MD->getLocation(),
7258              diag::err_defaulted_special_member_move_const_param)
7259           << (CSM == CXXMoveAssignment);
7260         HadError = true;
7261       }
7262     }
7263   } else if (ExpectedParams) {
7264     // A copy assignment operator can take its argument by value, but a
7265     // defaulted one cannot.
7266     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7267     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7268     HadError = true;
7269   }
7270 
7271   // C++11 [dcl.fct.def.default]p2:
7272   //   An explicitly-defaulted function may be declared constexpr only if it
7273   //   would have been implicitly declared as constexpr,
7274   // Do not apply this rule to members of class templates, since core issue 1358
7275   // makes such functions always instantiate to constexpr functions. For
7276   // functions which cannot be constexpr (for non-constructors in C++11 and for
7277   // destructors in C++14 and C++17), this is checked elsewhere.
7278   //
7279   // FIXME: This should not apply if the member is deleted.
7280   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7281                                                      HasConstParam);
7282   if ((getLangOpts().CPlusPlus20 ||
7283        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7284                                   : isa<CXXConstructorDecl>(MD))) &&
7285       MD->isConstexpr() && !Constexpr &&
7286       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7287     Diag(MD->getBeginLoc(), MD->isConsteval()
7288                                 ? diag::err_incorrect_defaulted_consteval
7289                                 : diag::err_incorrect_defaulted_constexpr)
7290         << CSM;
7291     // FIXME: Explain why the special member can't be constexpr.
7292     HadError = true;
7293   }
7294 
7295   if (First) {
7296     // C++2a [dcl.fct.def.default]p3:
7297     //   If a function is explicitly defaulted on its first declaration, it is
7298     //   implicitly considered to be constexpr if the implicit declaration
7299     //   would be.
7300     MD->setConstexprKind(
7301         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7302                   : CSK_unspecified);
7303 
7304     if (!Type->hasExceptionSpec()) {
7305       // C++2a [except.spec]p3:
7306       //   If a declaration of a function does not have a noexcept-specifier
7307       //   [and] is defaulted on its first declaration, [...] the exception
7308       //   specification is as specified below
7309       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7310       EPI.ExceptionSpec.Type = EST_Unevaluated;
7311       EPI.ExceptionSpec.SourceDecl = MD;
7312       MD->setType(Context.getFunctionType(ReturnType,
7313                                           llvm::makeArrayRef(&ArgType,
7314                                                              ExpectedParams),
7315                                           EPI));
7316     }
7317   }
7318 
7319   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7320     if (First) {
7321       SetDeclDeleted(MD, MD->getLocation());
7322       if (!inTemplateInstantiation() && !HadError) {
7323         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7324         if (ShouldDeleteForTypeMismatch) {
7325           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7326         } else {
7327           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7328         }
7329       }
7330       if (ShouldDeleteForTypeMismatch && !HadError) {
7331         Diag(MD->getLocation(),
7332              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7333       }
7334     } else {
7335       // C++11 [dcl.fct.def.default]p4:
7336       //   [For a] user-provided explicitly-defaulted function [...] if such a
7337       //   function is implicitly defined as deleted, the program is ill-formed.
7338       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7339       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7340       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7341       HadError = true;
7342     }
7343   }
7344 
7345   return HadError;
7346 }
7347 
7348 namespace {
7349 /// Helper class for building and checking a defaulted comparison.
7350 ///
7351 /// Defaulted functions are built in two phases:
7352 ///
7353 ///  * First, the set of operations that the function will perform are
7354 ///    identified, and some of them are checked. If any of the checked
7355 ///    operations is invalid in certain ways, the comparison function is
7356 ///    defined as deleted and no body is built.
7357 ///  * Then, if the function is not defined as deleted, the body is built.
7358 ///
7359 /// This is accomplished by performing two visitation steps over the eventual
7360 /// body of the function.
7361 template<typename Derived, typename ResultList, typename Result,
7362          typename Subobject>
7363 class DefaultedComparisonVisitor {
7364 public:
7365   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7366 
7367   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7368                              DefaultedComparisonKind DCK)
7369       : S(S), RD(RD), FD(FD), DCK(DCK) {
7370     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7371       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7372       // UnresolvedSet to avoid this copy.
7373       Fns.assign(Info->getUnqualifiedLookups().begin(),
7374                  Info->getUnqualifiedLookups().end());
7375     }
7376   }
7377 
7378   ResultList visit() {
7379     // The type of an lvalue naming a parameter of this function.
7380     QualType ParamLvalType =
7381         FD->getParamDecl(0)->getType().getNonReferenceType();
7382 
7383     ResultList Results;
7384 
7385     switch (DCK) {
7386     case DefaultedComparisonKind::None:
7387       llvm_unreachable("not a defaulted comparison");
7388 
7389     case DefaultedComparisonKind::Equal:
7390     case DefaultedComparisonKind::ThreeWay:
7391       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7392       return Results;
7393 
7394     case DefaultedComparisonKind::NotEqual:
7395     case DefaultedComparisonKind::Relational:
7396       Results.add(getDerived().visitExpandedSubobject(
7397           ParamLvalType, getDerived().getCompleteObject()));
7398       return Results;
7399     }
7400     llvm_unreachable("");
7401   }
7402 
7403 protected:
7404   Derived &getDerived() { return static_cast<Derived&>(*this); }
7405 
7406   /// Visit the expanded list of subobjects of the given type, as specified in
7407   /// C++2a [class.compare.default].
7408   ///
7409   /// \return \c true if the ResultList object said we're done, \c false if not.
7410   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7411                        Qualifiers Quals) {
7412     // C++2a [class.compare.default]p4:
7413     //   The direct base class subobjects of C
7414     for (CXXBaseSpecifier &Base : Record->bases())
7415       if (Results.add(getDerived().visitSubobject(
7416               S.Context.getQualifiedType(Base.getType(), Quals),
7417               getDerived().getBase(&Base))))
7418         return true;
7419 
7420     //   followed by the non-static data members of C
7421     for (FieldDecl *Field : Record->fields()) {
7422       // Recursively expand anonymous structs.
7423       if (Field->isAnonymousStructOrUnion()) {
7424         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7425                             Quals))
7426           return true;
7427         continue;
7428       }
7429 
7430       // Figure out the type of an lvalue denoting this field.
7431       Qualifiers FieldQuals = Quals;
7432       if (Field->isMutable())
7433         FieldQuals.removeConst();
7434       QualType FieldType =
7435           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7436 
7437       if (Results.add(getDerived().visitSubobject(
7438               FieldType, getDerived().getField(Field))))
7439         return true;
7440     }
7441 
7442     //   form a list of subobjects.
7443     return false;
7444   }
7445 
7446   Result visitSubobject(QualType Type, Subobject Subobj) {
7447     //   In that list, any subobject of array type is recursively expanded
7448     const ArrayType *AT = S.Context.getAsArrayType(Type);
7449     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7450       return getDerived().visitSubobjectArray(CAT->getElementType(),
7451                                               CAT->getSize(), Subobj);
7452     return getDerived().visitExpandedSubobject(Type, Subobj);
7453   }
7454 
7455   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7456                              Subobject Subobj) {
7457     return getDerived().visitSubobject(Type, Subobj);
7458   }
7459 
7460 protected:
7461   Sema &S;
7462   CXXRecordDecl *RD;
7463   FunctionDecl *FD;
7464   DefaultedComparisonKind DCK;
7465   UnresolvedSet<16> Fns;
7466 };
7467 
7468 /// Information about a defaulted comparison, as determined by
7469 /// DefaultedComparisonAnalyzer.
7470 struct DefaultedComparisonInfo {
7471   bool Deleted = false;
7472   bool Constexpr = true;
7473   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7474 
7475   static DefaultedComparisonInfo deleted() {
7476     DefaultedComparisonInfo Deleted;
7477     Deleted.Deleted = true;
7478     return Deleted;
7479   }
7480 
7481   bool add(const DefaultedComparisonInfo &R) {
7482     Deleted |= R.Deleted;
7483     Constexpr &= R.Constexpr;
7484     Category = commonComparisonType(Category, R.Category);
7485     return Deleted;
7486   }
7487 };
7488 
7489 /// An element in the expanded list of subobjects of a defaulted comparison, as
7490 /// specified in C++2a [class.compare.default]p4.
7491 struct DefaultedComparisonSubobject {
7492   enum { CompleteObject, Member, Base } Kind;
7493   NamedDecl *Decl;
7494   SourceLocation Loc;
7495 };
7496 
7497 /// A visitor over the notional body of a defaulted comparison that determines
7498 /// whether that body would be deleted or constexpr.
7499 class DefaultedComparisonAnalyzer
7500     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7501                                         DefaultedComparisonInfo,
7502                                         DefaultedComparisonInfo,
7503                                         DefaultedComparisonSubobject> {
7504 public:
7505   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7506 
7507 private:
7508   DiagnosticKind Diagnose;
7509 
7510 public:
7511   using Base = DefaultedComparisonVisitor;
7512   using Result = DefaultedComparisonInfo;
7513   using Subobject = DefaultedComparisonSubobject;
7514 
7515   friend Base;
7516 
7517   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7518                               DefaultedComparisonKind DCK,
7519                               DiagnosticKind Diagnose = NoDiagnostics)
7520       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7521 
7522   Result visit() {
7523     if ((DCK == DefaultedComparisonKind::Equal ||
7524          DCK == DefaultedComparisonKind::ThreeWay) &&
7525         RD->hasVariantMembers()) {
7526       // C++2a [class.compare.default]p2 [P2002R0]:
7527       //   A defaulted comparison operator function for class C is defined as
7528       //   deleted if [...] C has variant members.
7529       if (Diagnose == ExplainDeleted) {
7530         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7531           << FD << RD->isUnion() << RD;
7532       }
7533       return Result::deleted();
7534     }
7535 
7536     return Base::visit();
7537   }
7538 
7539 private:
7540   Subobject getCompleteObject() {
7541     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7542   }
7543 
7544   Subobject getBase(CXXBaseSpecifier *Base) {
7545     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7546                      Base->getBaseTypeLoc()};
7547   }
7548 
7549   Subobject getField(FieldDecl *Field) {
7550     return Subobject{Subobject::Member, Field, Field->getLocation()};
7551   }
7552 
7553   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7554     // C++2a [class.compare.default]p2 [P2002R0]:
7555     //   A defaulted <=> or == operator function for class C is defined as
7556     //   deleted if any non-static data member of C is of reference type
7557     if (Type->isReferenceType()) {
7558       if (Diagnose == ExplainDeleted) {
7559         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7560             << FD << RD;
7561       }
7562       return Result::deleted();
7563     }
7564 
7565     // [...] Let xi be an lvalue denoting the ith element [...]
7566     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7567     Expr *Args[] = {&Xi, &Xi};
7568 
7569     // All operators start by trying to apply that same operator recursively.
7570     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7571     assert(OO != OO_None && "not an overloaded operator!");
7572     return visitBinaryOperator(OO, Args, Subobj);
7573   }
7574 
7575   Result
7576   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7577                       Subobject Subobj,
7578                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7579     // Note that there is no need to consider rewritten candidates here if
7580     // we've already found there is no viable 'operator<=>' candidate (and are
7581     // considering synthesizing a '<=>' from '==' and '<').
7582     OverloadCandidateSet CandidateSet(
7583         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7584         OverloadCandidateSet::OperatorRewriteInfo(
7585             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7586 
7587     /// C++2a [class.compare.default]p1 [P2002R0]:
7588     ///   [...] the defaulted function itself is never a candidate for overload
7589     ///   resolution [...]
7590     CandidateSet.exclude(FD);
7591 
7592     if (Args[0]->getType()->isOverloadableType())
7593       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7594     else {
7595       // FIXME: We determine whether this is a valid expression by checking to
7596       // see if there's a viable builtin operator candidate for it. That isn't
7597       // really what the rules ask us to do, but should give the right results.
7598       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7599     }
7600 
7601     Result R;
7602 
7603     OverloadCandidateSet::iterator Best;
7604     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7605     case OR_Success: {
7606       // C++2a [class.compare.secondary]p2 [P2002R0]:
7607       //   The operator function [...] is defined as deleted if [...] the
7608       //   candidate selected by overload resolution is not a rewritten
7609       //   candidate.
7610       if ((DCK == DefaultedComparisonKind::NotEqual ||
7611            DCK == DefaultedComparisonKind::Relational) &&
7612           !Best->RewriteKind) {
7613         if (Diagnose == ExplainDeleted) {
7614           S.Diag(Best->Function->getLocation(),
7615                  diag::note_defaulted_comparison_not_rewritten_callee)
7616               << FD;
7617         }
7618         return Result::deleted();
7619       }
7620 
7621       // Throughout C++2a [class.compare]: if overload resolution does not
7622       // result in a usable function, the candidate function is defined as
7623       // deleted. This requires that we selected an accessible function.
7624       //
7625       // Note that this only considers the access of the function when named
7626       // within the type of the subobject, and not the access path for any
7627       // derived-to-base conversion.
7628       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7629       if (ArgClass && Best->FoundDecl.getDecl() &&
7630           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7631         QualType ObjectType = Subobj.Kind == Subobject::Member
7632                                   ? Args[0]->getType()
7633                                   : S.Context.getRecordType(RD);
7634         if (!S.isMemberAccessibleForDeletion(
7635                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7636                 Diagnose == ExplainDeleted
7637                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7638                           << FD << Subobj.Kind << Subobj.Decl
7639                     : S.PDiag()))
7640           return Result::deleted();
7641       }
7642 
7643       // C++2a [class.compare.default]p3 [P2002R0]:
7644       //   A defaulted comparison function is constexpr-compatible if [...]
7645       //   no overlod resolution performed [...] results in a non-constexpr
7646       //   function.
7647       if (FunctionDecl *BestFD = Best->Function) {
7648         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7649         // If it's not constexpr, explain why not.
7650         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7651           if (Subobj.Kind != Subobject::CompleteObject)
7652             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7653               << Subobj.Kind << Subobj.Decl;
7654           S.Diag(BestFD->getLocation(),
7655                  diag::note_defaulted_comparison_not_constexpr_here);
7656           // Bail out after explaining; we don't want any more notes.
7657           return Result::deleted();
7658         }
7659         R.Constexpr &= BestFD->isConstexpr();
7660       }
7661 
7662       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7663         if (auto *BestFD = Best->Function) {
7664           // If any callee has an undeduced return type, deduce it now.
7665           // FIXME: It's not clear how a failure here should be handled. For
7666           // now, we produce an eager diagnostic, because that is forward
7667           // compatible with most (all?) other reasonable options.
7668           if (BestFD->getReturnType()->isUndeducedType() &&
7669               S.DeduceReturnType(BestFD, FD->getLocation(),
7670                                  /*Diagnose=*/false)) {
7671             // Don't produce a duplicate error when asked to explain why the
7672             // comparison is deleted: we diagnosed that when initially checking
7673             // the defaulted operator.
7674             if (Diagnose == NoDiagnostics) {
7675               S.Diag(
7676                   FD->getLocation(),
7677                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7678                   << Subobj.Kind << Subobj.Decl;
7679               S.Diag(
7680                   Subobj.Loc,
7681                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7682                   << Subobj.Kind << Subobj.Decl;
7683               S.Diag(BestFD->getLocation(),
7684                      diag::note_defaulted_comparison_cannot_deduce_callee)
7685                   << Subobj.Kind << Subobj.Decl;
7686             }
7687             return Result::deleted();
7688           }
7689           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7690               BestFD->getCallResultType())) {
7691             R.Category = Info->Kind;
7692           } else {
7693             if (Diagnose == ExplainDeleted) {
7694               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7695                   << Subobj.Kind << Subobj.Decl
7696                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7697               S.Diag(BestFD->getLocation(),
7698                      diag::note_defaulted_comparison_cannot_deduce_callee)
7699                   << Subobj.Kind << Subobj.Decl;
7700             }
7701             return Result::deleted();
7702           }
7703         } else {
7704           Optional<ComparisonCategoryType> Cat =
7705               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7706           assert(Cat && "no category for builtin comparison?");
7707           R.Category = *Cat;
7708         }
7709       }
7710 
7711       // Note that we might be rewriting to a different operator. That call is
7712       // not considered until we come to actually build the comparison function.
7713       break;
7714     }
7715 
7716     case OR_Ambiguous:
7717       if (Diagnose == ExplainDeleted) {
7718         unsigned Kind = 0;
7719         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7720           Kind = OO == OO_EqualEqual ? 1 : 2;
7721         CandidateSet.NoteCandidates(
7722             PartialDiagnosticAt(
7723                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7724                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7725             S, OCD_AmbiguousCandidates, Args);
7726       }
7727       R = Result::deleted();
7728       break;
7729 
7730     case OR_Deleted:
7731       if (Diagnose == ExplainDeleted) {
7732         if ((DCK == DefaultedComparisonKind::NotEqual ||
7733              DCK == DefaultedComparisonKind::Relational) &&
7734             !Best->RewriteKind) {
7735           S.Diag(Best->Function->getLocation(),
7736                  diag::note_defaulted_comparison_not_rewritten_callee)
7737               << FD;
7738         } else {
7739           S.Diag(Subobj.Loc,
7740                  diag::note_defaulted_comparison_calls_deleted)
7741               << FD << Subobj.Kind << Subobj.Decl;
7742           S.NoteDeletedFunction(Best->Function);
7743         }
7744       }
7745       R = Result::deleted();
7746       break;
7747 
7748     case OR_No_Viable_Function:
7749       // If there's no usable candidate, we're done unless we can rewrite a
7750       // '<=>' in terms of '==' and '<'.
7751       if (OO == OO_Spaceship &&
7752           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7753         // For any kind of comparison category return type, we need a usable
7754         // '==' and a usable '<'.
7755         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7756                                        &CandidateSet)))
7757           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7758         break;
7759       }
7760 
7761       if (Diagnose == ExplainDeleted) {
7762         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7763             << FD << Subobj.Kind << Subobj.Decl;
7764 
7765         // For a three-way comparison, list both the candidates for the
7766         // original operator and the candidates for the synthesized operator.
7767         if (SpaceshipCandidates) {
7768           SpaceshipCandidates->NoteCandidates(
7769               S, Args,
7770               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7771                                                       Args, FD->getLocation()));
7772           S.Diag(Subobj.Loc,
7773                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7774               << (OO == OO_EqualEqual ? 0 : 1);
7775         }
7776 
7777         CandidateSet.NoteCandidates(
7778             S, Args,
7779             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7780                                             FD->getLocation()));
7781       }
7782       R = Result::deleted();
7783       break;
7784     }
7785 
7786     return R;
7787   }
7788 };
7789 
7790 /// A list of statements.
7791 struct StmtListResult {
7792   bool IsInvalid = false;
7793   llvm::SmallVector<Stmt*, 16> Stmts;
7794 
7795   bool add(const StmtResult &S) {
7796     IsInvalid |= S.isInvalid();
7797     if (IsInvalid)
7798       return true;
7799     Stmts.push_back(S.get());
7800     return false;
7801   }
7802 };
7803 
7804 /// A visitor over the notional body of a defaulted comparison that synthesizes
7805 /// the actual body.
7806 class DefaultedComparisonSynthesizer
7807     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7808                                         StmtListResult, StmtResult,
7809                                         std::pair<ExprResult, ExprResult>> {
7810   SourceLocation Loc;
7811   unsigned ArrayDepth = 0;
7812 
7813 public:
7814   using Base = DefaultedComparisonVisitor;
7815   using ExprPair = std::pair<ExprResult, ExprResult>;
7816 
7817   friend Base;
7818 
7819   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7820                                  DefaultedComparisonKind DCK,
7821                                  SourceLocation BodyLoc)
7822       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7823 
7824   /// Build a suitable function body for this defaulted comparison operator.
7825   StmtResult build() {
7826     Sema::CompoundScopeRAII CompoundScope(S);
7827 
7828     StmtListResult Stmts = visit();
7829     if (Stmts.IsInvalid)
7830       return StmtError();
7831 
7832     ExprResult RetVal;
7833     switch (DCK) {
7834     case DefaultedComparisonKind::None:
7835       llvm_unreachable("not a defaulted comparison");
7836 
7837     case DefaultedComparisonKind::Equal: {
7838       // C++2a [class.eq]p3:
7839       //   [...] compar[e] the corresponding elements [...] until the first
7840       //   index i where xi == yi yields [...] false. If no such index exists,
7841       //   V is true. Otherwise, V is false.
7842       //
7843       // Join the comparisons with '&&'s and return the result. Use a right
7844       // fold (traversing the conditions right-to-left), because that
7845       // short-circuits more naturally.
7846       auto OldStmts = std::move(Stmts.Stmts);
7847       Stmts.Stmts.clear();
7848       ExprResult CmpSoFar;
7849       // Finish a particular comparison chain.
7850       auto FinishCmp = [&] {
7851         if (Expr *Prior = CmpSoFar.get()) {
7852           // Convert the last expression to 'return ...;'
7853           if (RetVal.isUnset() && Stmts.Stmts.empty())
7854             RetVal = CmpSoFar;
7855           // Convert any prior comparison to 'if (!(...)) return false;'
7856           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7857             return true;
7858           CmpSoFar = ExprResult();
7859         }
7860         return false;
7861       };
7862       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7863         Expr *E = dyn_cast<Expr>(EAsStmt);
7864         if (!E) {
7865           // Found an array comparison.
7866           if (FinishCmp() || Stmts.add(EAsStmt))
7867             return StmtError();
7868           continue;
7869         }
7870 
7871         if (CmpSoFar.isUnset()) {
7872           CmpSoFar = E;
7873           continue;
7874         }
7875         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7876         if (CmpSoFar.isInvalid())
7877           return StmtError();
7878       }
7879       if (FinishCmp())
7880         return StmtError();
7881       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7882       //   If no such index exists, V is true.
7883       if (RetVal.isUnset())
7884         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7885       break;
7886     }
7887 
7888     case DefaultedComparisonKind::ThreeWay: {
7889       // Per C++2a [class.spaceship]p3, as a fallback add:
7890       // return static_cast<R>(std::strong_ordering::equal);
7891       QualType StrongOrdering = S.CheckComparisonCategoryType(
7892           ComparisonCategoryType::StrongOrdering, Loc,
7893           Sema::ComparisonCategoryUsage::DefaultedOperator);
7894       if (StrongOrdering.isNull())
7895         return StmtError();
7896       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7897                              .getValueInfo(ComparisonCategoryResult::Equal)
7898                              ->VD;
7899       RetVal = getDecl(EqualVD);
7900       if (RetVal.isInvalid())
7901         return StmtError();
7902       RetVal = buildStaticCastToR(RetVal.get());
7903       break;
7904     }
7905 
7906     case DefaultedComparisonKind::NotEqual:
7907     case DefaultedComparisonKind::Relational:
7908       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7909       break;
7910     }
7911 
7912     // Build the final return statement.
7913     if (RetVal.isInvalid())
7914       return StmtError();
7915     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7916     if (ReturnStmt.isInvalid())
7917       return StmtError();
7918     Stmts.Stmts.push_back(ReturnStmt.get());
7919 
7920     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7921   }
7922 
7923 private:
7924   ExprResult getDecl(ValueDecl *VD) {
7925     return S.BuildDeclarationNameExpr(
7926         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7927   }
7928 
7929   ExprResult getParam(unsigned I) {
7930     ParmVarDecl *PD = FD->getParamDecl(I);
7931     return getDecl(PD);
7932   }
7933 
7934   ExprPair getCompleteObject() {
7935     unsigned Param = 0;
7936     ExprResult LHS;
7937     if (isa<CXXMethodDecl>(FD)) {
7938       // LHS is '*this'.
7939       LHS = S.ActOnCXXThis(Loc);
7940       if (!LHS.isInvalid())
7941         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7942     } else {
7943       LHS = getParam(Param++);
7944     }
7945     ExprResult RHS = getParam(Param++);
7946     assert(Param == FD->getNumParams());
7947     return {LHS, RHS};
7948   }
7949 
7950   ExprPair getBase(CXXBaseSpecifier *Base) {
7951     ExprPair Obj = getCompleteObject();
7952     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7953       return {ExprError(), ExprError()};
7954     CXXCastPath Path = {Base};
7955     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7956                                 CK_DerivedToBase, VK_LValue, &Path),
7957             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7958                                 CK_DerivedToBase, VK_LValue, &Path)};
7959   }
7960 
7961   ExprPair getField(FieldDecl *Field) {
7962     ExprPair Obj = getCompleteObject();
7963     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7964       return {ExprError(), ExprError()};
7965 
7966     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
7967     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
7968     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
7969                                       CXXScopeSpec(), Field, Found, NameInfo),
7970             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
7971                                       CXXScopeSpec(), Field, Found, NameInfo)};
7972   }
7973 
7974   // FIXME: When expanding a subobject, register a note in the code synthesis
7975   // stack to say which subobject we're comparing.
7976 
7977   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
7978     if (Cond.isInvalid())
7979       return StmtError();
7980 
7981     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
7982     if (NotCond.isInvalid())
7983       return StmtError();
7984 
7985     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
7986     assert(!False.isInvalid() && "should never fail");
7987     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
7988     if (ReturnFalse.isInvalid())
7989       return StmtError();
7990 
7991     return S.ActOnIfStmt(Loc, false, nullptr,
7992                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
7993                                           Sema::ConditionKind::Boolean),
7994                          ReturnFalse.get(), SourceLocation(), nullptr);
7995   }
7996 
7997   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
7998                                  ExprPair Subobj) {
7999     QualType SizeType = S.Context.getSizeType();
8000     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8001 
8002     // Build 'size_t i$n = 0'.
8003     IdentifierInfo *IterationVarName = nullptr;
8004     {
8005       SmallString<8> Str;
8006       llvm::raw_svector_ostream OS(Str);
8007       OS << "i" << ArrayDepth;
8008       IterationVarName = &S.Context.Idents.get(OS.str());
8009     }
8010     VarDecl *IterationVar = VarDecl::Create(
8011         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8012         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8013     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8014     IterationVar->setInit(
8015         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8016     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8017 
8018     auto IterRef = [&] {
8019       ExprResult Ref = S.BuildDeclarationNameExpr(
8020           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8021           IterationVar);
8022       assert(!Ref.isInvalid() && "can't reference our own variable?");
8023       return Ref.get();
8024     };
8025 
8026     // Build 'i$n != Size'.
8027     ExprResult Cond = S.CreateBuiltinBinOp(
8028         Loc, BO_NE, IterRef(),
8029         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8030     assert(!Cond.isInvalid() && "should never fail");
8031 
8032     // Build '++i$n'.
8033     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8034     assert(!Inc.isInvalid() && "should never fail");
8035 
8036     // Build 'a[i$n]' and 'b[i$n]'.
8037     auto Index = [&](ExprResult E) {
8038       if (E.isInvalid())
8039         return ExprError();
8040       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8041     };
8042     Subobj.first = Index(Subobj.first);
8043     Subobj.second = Index(Subobj.second);
8044 
8045     // Compare the array elements.
8046     ++ArrayDepth;
8047     StmtResult Substmt = visitSubobject(Type, Subobj);
8048     --ArrayDepth;
8049 
8050     if (Substmt.isInvalid())
8051       return StmtError();
8052 
8053     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8054     // For outer levels or for an 'operator<=>' we already have a suitable
8055     // statement that returns as necessary.
8056     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8057       assert(DCK == DefaultedComparisonKind::Equal &&
8058              "should have non-expression statement");
8059       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8060       if (Substmt.isInvalid())
8061         return StmtError();
8062     }
8063 
8064     // Build 'for (...) ...'
8065     return S.ActOnForStmt(Loc, Loc, Init,
8066                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8067                                            Sema::ConditionKind::Boolean),
8068                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8069                           Substmt.get());
8070   }
8071 
8072   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8073     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8074       return StmtError();
8075 
8076     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8077     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8078     ExprResult Op;
8079     if (Type->isOverloadableType())
8080       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8081                                    Obj.second.get(), /*PerformADL=*/true,
8082                                    /*AllowRewrittenCandidates=*/true, FD);
8083     else
8084       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8085     if (Op.isInvalid())
8086       return StmtError();
8087 
8088     switch (DCK) {
8089     case DefaultedComparisonKind::None:
8090       llvm_unreachable("not a defaulted comparison");
8091 
8092     case DefaultedComparisonKind::Equal:
8093       // Per C++2a [class.eq]p2, each comparison is individually contextually
8094       // converted to bool.
8095       Op = S.PerformContextuallyConvertToBool(Op.get());
8096       if (Op.isInvalid())
8097         return StmtError();
8098       return Op.get();
8099 
8100     case DefaultedComparisonKind::ThreeWay: {
8101       // Per C++2a [class.spaceship]p3, form:
8102       //   if (R cmp = static_cast<R>(op); cmp != 0)
8103       //     return cmp;
8104       QualType R = FD->getReturnType();
8105       Op = buildStaticCastToR(Op.get());
8106       if (Op.isInvalid())
8107         return StmtError();
8108 
8109       // R cmp = ...;
8110       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8111       VarDecl *VD =
8112           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8113                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8114       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8115       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8116 
8117       // cmp != 0
8118       ExprResult VDRef = getDecl(VD);
8119       if (VDRef.isInvalid())
8120         return StmtError();
8121       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8122       Expr *Zero =
8123           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8124       ExprResult Comp;
8125       if (VDRef.get()->getType()->isOverloadableType())
8126         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8127                                        true, FD);
8128       else
8129         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8130       if (Comp.isInvalid())
8131         return StmtError();
8132       Sema::ConditionResult Cond = S.ActOnCondition(
8133           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8134       if (Cond.isInvalid())
8135         return StmtError();
8136 
8137       // return cmp;
8138       VDRef = getDecl(VD);
8139       if (VDRef.isInvalid())
8140         return StmtError();
8141       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8142       if (ReturnStmt.isInvalid())
8143         return StmtError();
8144 
8145       // if (...)
8146       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond,
8147                            ReturnStmt.get(), /*ElseLoc=*/SourceLocation(),
8148                            /*Else=*/nullptr);
8149     }
8150 
8151     case DefaultedComparisonKind::NotEqual:
8152     case DefaultedComparisonKind::Relational:
8153       // C++2a [class.compare.secondary]p2:
8154       //   Otherwise, the operator function yields x @ y.
8155       return Op.get();
8156     }
8157     llvm_unreachable("");
8158   }
8159 
8160   /// Build "static_cast<R>(E)".
8161   ExprResult buildStaticCastToR(Expr *E) {
8162     QualType R = FD->getReturnType();
8163     assert(!R->isUndeducedType() && "type should have been deduced already");
8164 
8165     // Don't bother forming a no-op cast in the common case.
8166     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8167       return E;
8168     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8169                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8170                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8171   }
8172 };
8173 }
8174 
8175 /// Perform the unqualified lookups that might be needed to form a defaulted
8176 /// comparison function for the given operator.
8177 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8178                                                   UnresolvedSetImpl &Operators,
8179                                                   OverloadedOperatorKind Op) {
8180   auto Lookup = [&](OverloadedOperatorKind OO) {
8181     Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators);
8182   };
8183 
8184   // Every defaulted operator looks up itself.
8185   Lookup(Op);
8186   // ... and the rewritten form of itself, if any.
8187   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8188     Lookup(ExtraOp);
8189 
8190   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8191   // synthesize a three-way comparison from '<' and '=='. In a dependent
8192   // context, we also need to look up '==' in case we implicitly declare a
8193   // defaulted 'operator=='.
8194   if (Op == OO_Spaceship) {
8195     Lookup(OO_ExclaimEqual);
8196     Lookup(OO_Less);
8197     Lookup(OO_EqualEqual);
8198   }
8199 }
8200 
8201 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8202                                               DefaultedComparisonKind DCK) {
8203   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8204 
8205   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8206   assert(RD && "defaulted comparison is not defaulted in a class");
8207 
8208   // Perform any unqualified lookups we're going to need to default this
8209   // function.
8210   if (S) {
8211     UnresolvedSet<32> Operators;
8212     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8213                                           FD->getOverloadedOperator());
8214     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8215         Context, Operators.pairs()));
8216   }
8217 
8218   // C++2a [class.compare.default]p1:
8219   //   A defaulted comparison operator function for some class C shall be a
8220   //   non-template function declared in the member-specification of C that is
8221   //    -- a non-static const member of C having one parameter of type
8222   //       const C&, or
8223   //    -- a friend of C having two parameters of type const C& or two
8224   //       parameters of type C.
8225   QualType ExpectedParmType1 = Context.getRecordType(RD);
8226   QualType ExpectedParmType2 =
8227       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8228   if (isa<CXXMethodDecl>(FD))
8229     ExpectedParmType1 = ExpectedParmType2;
8230   for (const ParmVarDecl *Param : FD->parameters()) {
8231     if (!Param->getType()->isDependentType() &&
8232         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8233         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8234       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8235       // corresponding defaulted 'operator<=>' already.
8236       if (!FD->isImplicit()) {
8237         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8238             << (int)DCK << Param->getType() << ExpectedParmType1
8239             << !isa<CXXMethodDecl>(FD)
8240             << ExpectedParmType2 << Param->getSourceRange();
8241       }
8242       return true;
8243     }
8244   }
8245   if (FD->getNumParams() == 2 &&
8246       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8247                            FD->getParamDecl(1)->getType())) {
8248     if (!FD->isImplicit()) {
8249       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8250           << (int)DCK
8251           << FD->getParamDecl(0)->getType()
8252           << FD->getParamDecl(0)->getSourceRange()
8253           << FD->getParamDecl(1)->getType()
8254           << FD->getParamDecl(1)->getSourceRange();
8255     }
8256     return true;
8257   }
8258 
8259   // ... non-static const member ...
8260   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8261     assert(!MD->isStatic() && "comparison function cannot be a static member");
8262     if (!MD->isConst()) {
8263       SourceLocation InsertLoc;
8264       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8265         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8266       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8267       // corresponding defaulted 'operator<=>' already.
8268       if (!MD->isImplicit()) {
8269         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8270           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8271       }
8272 
8273       // Add the 'const' to the type to recover.
8274       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8275       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8276       EPI.TypeQuals.addConst();
8277       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8278                                           FPT->getParamTypes(), EPI));
8279     }
8280   } else {
8281     // A non-member function declared in a class must be a friend.
8282     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8283   }
8284 
8285   // C++2a [class.eq]p1, [class.rel]p1:
8286   //   A [defaulted comparison other than <=>] shall have a declared return
8287   //   type bool.
8288   if (DCK != DefaultedComparisonKind::ThreeWay &&
8289       !FD->getDeclaredReturnType()->isDependentType() &&
8290       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8291     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8292         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8293         << FD->getReturnTypeSourceRange();
8294     return true;
8295   }
8296   // C++2a [class.spaceship]p2 [P2002R0]:
8297   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8298   //   R shall not contain a placeholder type.
8299   if (DCK == DefaultedComparisonKind::ThreeWay &&
8300       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8301       !Context.hasSameType(FD->getDeclaredReturnType(),
8302                            Context.getAutoDeductType())) {
8303     Diag(FD->getLocation(),
8304          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8305         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8306         << FD->getReturnTypeSourceRange();
8307     return true;
8308   }
8309 
8310   // For a defaulted function in a dependent class, defer all remaining checks
8311   // until instantiation.
8312   if (RD->isDependentType())
8313     return false;
8314 
8315   // Determine whether the function should be defined as deleted.
8316   DefaultedComparisonInfo Info =
8317       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8318 
8319   bool First = FD == FD->getCanonicalDecl();
8320 
8321   // If we want to delete the function, then do so; there's nothing else to
8322   // check in that case.
8323   if (Info.Deleted) {
8324     if (!First) {
8325       // C++11 [dcl.fct.def.default]p4:
8326       //   [For a] user-provided explicitly-defaulted function [...] if such a
8327       //   function is implicitly defined as deleted, the program is ill-formed.
8328       //
8329       // This is really just a consequence of the general rule that you can
8330       // only delete a function on its first declaration.
8331       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8332           << FD->isImplicit() << (int)DCK;
8333       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8334                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8335           .visit();
8336       return true;
8337     }
8338 
8339     SetDeclDeleted(FD, FD->getLocation());
8340     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8341       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8342           << (int)DCK;
8343       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8344                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8345           .visit();
8346     }
8347     return false;
8348   }
8349 
8350   // C++2a [class.spaceship]p2:
8351   //   The return type is deduced as the common comparison type of R0, R1, ...
8352   if (DCK == DefaultedComparisonKind::ThreeWay &&
8353       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8354     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8355     if (RetLoc.isInvalid())
8356       RetLoc = FD->getBeginLoc();
8357     // FIXME: Should we really care whether we have the complete type and the
8358     // 'enumerator' constants here? A forward declaration seems sufficient.
8359     QualType Cat = CheckComparisonCategoryType(
8360         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8361     if (Cat.isNull())
8362       return true;
8363     Context.adjustDeducedFunctionResultType(
8364         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8365   }
8366 
8367   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8368   //   An explicitly-defaulted function that is not defined as deleted may be
8369   //   declared constexpr or consteval only if it is constexpr-compatible.
8370   // C++2a [class.compare.default]p3 [P2002R0]:
8371   //   A defaulted comparison function is constexpr-compatible if it satisfies
8372   //   the requirements for a constexpr function [...]
8373   // The only relevant requirements are that the parameter and return types are
8374   // literal types. The remaining conditions are checked by the analyzer.
8375   if (FD->isConstexpr()) {
8376     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8377         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8378         !Info.Constexpr) {
8379       Diag(FD->getBeginLoc(),
8380            diag::err_incorrect_defaulted_comparison_constexpr)
8381           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8382       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8383                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8384           .visit();
8385     }
8386   }
8387 
8388   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8389   //   If a constexpr-compatible function is explicitly defaulted on its first
8390   //   declaration, it is implicitly considered to be constexpr.
8391   // FIXME: Only applying this to the first declaration seems problematic, as
8392   // simple reorderings can affect the meaning of the program.
8393   if (First && !FD->isConstexpr() && Info.Constexpr)
8394     FD->setConstexprKind(CSK_constexpr);
8395 
8396   // C++2a [except.spec]p3:
8397   //   If a declaration of a function does not have a noexcept-specifier
8398   //   [and] is defaulted on its first declaration, [...] the exception
8399   //   specification is as specified below
8400   if (FD->getExceptionSpecType() == EST_None) {
8401     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8402     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8403     EPI.ExceptionSpec.Type = EST_Unevaluated;
8404     EPI.ExceptionSpec.SourceDecl = FD;
8405     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8406                                         FPT->getParamTypes(), EPI));
8407   }
8408 
8409   return false;
8410 }
8411 
8412 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8413                                              FunctionDecl *Spaceship) {
8414   Sema::CodeSynthesisContext Ctx;
8415   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8416   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8417   Ctx.Entity = Spaceship;
8418   pushCodeSynthesisContext(Ctx);
8419 
8420   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8421     EqualEqual->setImplicit();
8422 
8423   popCodeSynthesisContext();
8424 }
8425 
8426 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8427                                      DefaultedComparisonKind DCK) {
8428   assert(FD->isDefaulted() && !FD->isDeleted() &&
8429          !FD->doesThisDeclarationHaveABody());
8430   if (FD->willHaveBody() || FD->isInvalidDecl())
8431     return;
8432 
8433   SynthesizedFunctionScope Scope(*this, FD);
8434 
8435   // Add a context note for diagnostics produced after this point.
8436   Scope.addContextNote(UseLoc);
8437 
8438   {
8439     // Build and set up the function body.
8440     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8441     SourceLocation BodyLoc =
8442         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8443     StmtResult Body =
8444         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8445     if (Body.isInvalid()) {
8446       FD->setInvalidDecl();
8447       return;
8448     }
8449     FD->setBody(Body.get());
8450     FD->markUsed(Context);
8451   }
8452 
8453   // The exception specification is needed because we are defining the
8454   // function. Note that this will reuse the body we just built.
8455   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8456 
8457   if (ASTMutationListener *L = getASTMutationListener())
8458     L->CompletedImplicitDefinition(FD);
8459 }
8460 
8461 static Sema::ImplicitExceptionSpecification
8462 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8463                                         FunctionDecl *FD,
8464                                         Sema::DefaultedComparisonKind DCK) {
8465   ComputingExceptionSpec CES(S, FD, Loc);
8466   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8467 
8468   if (FD->isInvalidDecl())
8469     return ExceptSpec;
8470 
8471   // The common case is that we just defined the comparison function. In that
8472   // case, just look at whether the body can throw.
8473   if (FD->hasBody()) {
8474     ExceptSpec.CalledStmt(FD->getBody());
8475   } else {
8476     // Otherwise, build a body so we can check it. This should ideally only
8477     // happen when we're not actually marking the function referenced. (This is
8478     // only really important for efficiency: we don't want to build and throw
8479     // away bodies for comparison functions more than we strictly need to.)
8480 
8481     // Pretend to synthesize the function body in an unevaluated context.
8482     // Note that we can't actually just go ahead and define the function here:
8483     // we are not permitted to mark its callees as referenced.
8484     Sema::SynthesizedFunctionScope Scope(S, FD);
8485     EnterExpressionEvaluationContext Context(
8486         S, Sema::ExpressionEvaluationContext::Unevaluated);
8487 
8488     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8489     SourceLocation BodyLoc =
8490         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8491     StmtResult Body =
8492         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8493     if (!Body.isInvalid())
8494       ExceptSpec.CalledStmt(Body.get());
8495 
8496     // FIXME: Can we hold onto this body and just transform it to potentially
8497     // evaluated when we're asked to define the function rather than rebuilding
8498     // it? Either that, or we should only build the bits of the body that we
8499     // need (the expressions, not the statements).
8500   }
8501 
8502   return ExceptSpec;
8503 }
8504 
8505 void Sema::CheckDelayedMemberExceptionSpecs() {
8506   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8507   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8508 
8509   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8510   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8511 
8512   // Perform any deferred checking of exception specifications for virtual
8513   // destructors.
8514   for (auto &Check : Overriding)
8515     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8516 
8517   // Perform any deferred checking of exception specifications for befriended
8518   // special members.
8519   for (auto &Check : Equivalent)
8520     CheckEquivalentExceptionSpec(Check.second, Check.first);
8521 }
8522 
8523 namespace {
8524 /// CRTP base class for visiting operations performed by a special member
8525 /// function (or inherited constructor).
8526 template<typename Derived>
8527 struct SpecialMemberVisitor {
8528   Sema &S;
8529   CXXMethodDecl *MD;
8530   Sema::CXXSpecialMember CSM;
8531   Sema::InheritedConstructorInfo *ICI;
8532 
8533   // Properties of the special member, computed for convenience.
8534   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8535 
8536   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8537                        Sema::InheritedConstructorInfo *ICI)
8538       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8539     switch (CSM) {
8540     case Sema::CXXDefaultConstructor:
8541     case Sema::CXXCopyConstructor:
8542     case Sema::CXXMoveConstructor:
8543       IsConstructor = true;
8544       break;
8545     case Sema::CXXCopyAssignment:
8546     case Sema::CXXMoveAssignment:
8547       IsAssignment = true;
8548       break;
8549     case Sema::CXXDestructor:
8550       break;
8551     case Sema::CXXInvalid:
8552       llvm_unreachable("invalid special member kind");
8553     }
8554 
8555     if (MD->getNumParams()) {
8556       if (const ReferenceType *RT =
8557               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8558         ConstArg = RT->getPointeeType().isConstQualified();
8559     }
8560   }
8561 
8562   Derived &getDerived() { return static_cast<Derived&>(*this); }
8563 
8564   /// Is this a "move" special member?
8565   bool isMove() const {
8566     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8567   }
8568 
8569   /// Look up the corresponding special member in the given class.
8570   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8571                                              unsigned Quals, bool IsMutable) {
8572     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8573                                        ConstArg && !IsMutable);
8574   }
8575 
8576   /// Look up the constructor for the specified base class to see if it's
8577   /// overridden due to this being an inherited constructor.
8578   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8579     if (!ICI)
8580       return {};
8581     assert(CSM == Sema::CXXDefaultConstructor);
8582     auto *BaseCtor =
8583       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8584     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8585       return MD;
8586     return {};
8587   }
8588 
8589   /// A base or member subobject.
8590   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8591 
8592   /// Get the location to use for a subobject in diagnostics.
8593   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8594     // FIXME: For an indirect virtual base, the direct base leading to
8595     // the indirect virtual base would be a more useful choice.
8596     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8597       return B->getBaseTypeLoc();
8598     else
8599       return Subobj.get<FieldDecl*>()->getLocation();
8600   }
8601 
8602   enum BasesToVisit {
8603     /// Visit all non-virtual (direct) bases.
8604     VisitNonVirtualBases,
8605     /// Visit all direct bases, virtual or not.
8606     VisitDirectBases,
8607     /// Visit all non-virtual bases, and all virtual bases if the class
8608     /// is not abstract.
8609     VisitPotentiallyConstructedBases,
8610     /// Visit all direct or virtual bases.
8611     VisitAllBases
8612   };
8613 
8614   // Visit the bases and members of the class.
8615   bool visit(BasesToVisit Bases) {
8616     CXXRecordDecl *RD = MD->getParent();
8617 
8618     if (Bases == VisitPotentiallyConstructedBases)
8619       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8620 
8621     for (auto &B : RD->bases())
8622       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8623           getDerived().visitBase(&B))
8624         return true;
8625 
8626     if (Bases == VisitAllBases)
8627       for (auto &B : RD->vbases())
8628         if (getDerived().visitBase(&B))
8629           return true;
8630 
8631     for (auto *F : RD->fields())
8632       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8633           getDerived().visitField(F))
8634         return true;
8635 
8636     return false;
8637   }
8638 };
8639 }
8640 
8641 namespace {
8642 struct SpecialMemberDeletionInfo
8643     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8644   bool Diagnose;
8645 
8646   SourceLocation Loc;
8647 
8648   bool AllFieldsAreConst;
8649 
8650   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8651                             Sema::CXXSpecialMember CSM,
8652                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8653       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8654         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8655 
8656   bool inUnion() const { return MD->getParent()->isUnion(); }
8657 
8658   Sema::CXXSpecialMember getEffectiveCSM() {
8659     return ICI ? Sema::CXXInvalid : CSM;
8660   }
8661 
8662   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8663 
8664   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8665   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8666 
8667   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8668   bool shouldDeleteForField(FieldDecl *FD);
8669   bool shouldDeleteForAllConstMembers();
8670 
8671   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8672                                      unsigned Quals);
8673   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8674                                     Sema::SpecialMemberOverloadResult SMOR,
8675                                     bool IsDtorCallInCtor);
8676 
8677   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8678 };
8679 }
8680 
8681 /// Is the given special member inaccessible when used on the given
8682 /// sub-object.
8683 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8684                                              CXXMethodDecl *target) {
8685   /// If we're operating on a base class, the object type is the
8686   /// type of this special member.
8687   QualType objectTy;
8688   AccessSpecifier access = target->getAccess();
8689   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8690     objectTy = S.Context.getTypeDeclType(MD->getParent());
8691     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8692 
8693   // If we're operating on a field, the object type is the type of the field.
8694   } else {
8695     objectTy = S.Context.getTypeDeclType(target->getParent());
8696   }
8697 
8698   return S.isMemberAccessibleForDeletion(
8699       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8700 }
8701 
8702 /// Check whether we should delete a special member due to the implicit
8703 /// definition containing a call to a special member of a subobject.
8704 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8705     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8706     bool IsDtorCallInCtor) {
8707   CXXMethodDecl *Decl = SMOR.getMethod();
8708   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8709 
8710   int DiagKind = -1;
8711 
8712   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8713     DiagKind = !Decl ? 0 : 1;
8714   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8715     DiagKind = 2;
8716   else if (!isAccessible(Subobj, Decl))
8717     DiagKind = 3;
8718   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8719            !Decl->isTrivial()) {
8720     // A member of a union must have a trivial corresponding special member.
8721     // As a weird special case, a destructor call from a union's constructor
8722     // must be accessible and non-deleted, but need not be trivial. Such a
8723     // destructor is never actually called, but is semantically checked as
8724     // if it were.
8725     DiagKind = 4;
8726   }
8727 
8728   if (DiagKind == -1)
8729     return false;
8730 
8731   if (Diagnose) {
8732     if (Field) {
8733       S.Diag(Field->getLocation(),
8734              diag::note_deleted_special_member_class_subobject)
8735         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8736         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8737     } else {
8738       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8739       S.Diag(Base->getBeginLoc(),
8740              diag::note_deleted_special_member_class_subobject)
8741           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8742           << Base->getType() << DiagKind << IsDtorCallInCtor
8743           << /*IsObjCPtr*/false;
8744     }
8745 
8746     if (DiagKind == 1)
8747       S.NoteDeletedFunction(Decl);
8748     // FIXME: Explain inaccessibility if DiagKind == 3.
8749   }
8750 
8751   return true;
8752 }
8753 
8754 /// Check whether we should delete a special member function due to having a
8755 /// direct or virtual base class or non-static data member of class type M.
8756 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8757     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8758   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8759   bool IsMutable = Field && Field->isMutable();
8760 
8761   // C++11 [class.ctor]p5:
8762   // -- any direct or virtual base class, or non-static data member with no
8763   //    brace-or-equal-initializer, has class type M (or array thereof) and
8764   //    either M has no default constructor or overload resolution as applied
8765   //    to M's default constructor results in an ambiguity or in a function
8766   //    that is deleted or inaccessible
8767   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8768   // -- a direct or virtual base class B that cannot be copied/moved because
8769   //    overload resolution, as applied to B's corresponding special member,
8770   //    results in an ambiguity or a function that is deleted or inaccessible
8771   //    from the defaulted special member
8772   // C++11 [class.dtor]p5:
8773   // -- any direct or virtual base class [...] has a type with a destructor
8774   //    that is deleted or inaccessible
8775   if (!(CSM == Sema::CXXDefaultConstructor &&
8776         Field && Field->hasInClassInitializer()) &&
8777       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8778                                    false))
8779     return true;
8780 
8781   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8782   // -- any direct or virtual base class or non-static data member has a
8783   //    type with a destructor that is deleted or inaccessible
8784   if (IsConstructor) {
8785     Sema::SpecialMemberOverloadResult SMOR =
8786         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8787                               false, false, false, false, false);
8788     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8789       return true;
8790   }
8791 
8792   return false;
8793 }
8794 
8795 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8796     FieldDecl *FD, QualType FieldType) {
8797   // The defaulted special functions are defined as deleted if this is a variant
8798   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8799   // type under ARC.
8800   if (!FieldType.hasNonTrivialObjCLifetime())
8801     return false;
8802 
8803   // Don't make the defaulted default constructor defined as deleted if the
8804   // member has an in-class initializer.
8805   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8806     return false;
8807 
8808   if (Diagnose) {
8809     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8810     S.Diag(FD->getLocation(),
8811            diag::note_deleted_special_member_class_subobject)
8812         << getEffectiveCSM() << ParentClass << /*IsField*/true
8813         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8814   }
8815 
8816   return true;
8817 }
8818 
8819 /// Check whether we should delete a special member function due to the class
8820 /// having a particular direct or virtual base class.
8821 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8822   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8823   // If program is correct, BaseClass cannot be null, but if it is, the error
8824   // must be reported elsewhere.
8825   if (!BaseClass)
8826     return false;
8827   // If we have an inheriting constructor, check whether we're calling an
8828   // inherited constructor instead of a default constructor.
8829   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8830   if (auto *BaseCtor = SMOR.getMethod()) {
8831     // Note that we do not check access along this path; other than that,
8832     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8833     // FIXME: Check that the base has a usable destructor! Sink this into
8834     // shouldDeleteForClassSubobject.
8835     if (BaseCtor->isDeleted() && Diagnose) {
8836       S.Diag(Base->getBeginLoc(),
8837              diag::note_deleted_special_member_class_subobject)
8838           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8839           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8840           << /*IsObjCPtr*/false;
8841       S.NoteDeletedFunction(BaseCtor);
8842     }
8843     return BaseCtor->isDeleted();
8844   }
8845   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8846 }
8847 
8848 /// Check whether we should delete a special member function due to the class
8849 /// having a particular non-static data member.
8850 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8851   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8852   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8853 
8854   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8855     return true;
8856 
8857   if (CSM == Sema::CXXDefaultConstructor) {
8858     // For a default constructor, all references must be initialized in-class
8859     // and, if a union, it must have a non-const member.
8860     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8861       if (Diagnose)
8862         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8863           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8864       return true;
8865     }
8866     // C++11 [class.ctor]p5: any non-variant non-static data member of
8867     // const-qualified type (or array thereof) with no
8868     // brace-or-equal-initializer does not have a user-provided default
8869     // constructor.
8870     if (!inUnion() && FieldType.isConstQualified() &&
8871         !FD->hasInClassInitializer() &&
8872         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8873       if (Diagnose)
8874         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8875           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8876       return true;
8877     }
8878 
8879     if (inUnion() && !FieldType.isConstQualified())
8880       AllFieldsAreConst = false;
8881   } else if (CSM == Sema::CXXCopyConstructor) {
8882     // For a copy constructor, data members must not be of rvalue reference
8883     // type.
8884     if (FieldType->isRValueReferenceType()) {
8885       if (Diagnose)
8886         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8887           << MD->getParent() << FD << FieldType;
8888       return true;
8889     }
8890   } else if (IsAssignment) {
8891     // For an assignment operator, data members must not be of reference type.
8892     if (FieldType->isReferenceType()) {
8893       if (Diagnose)
8894         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8895           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8896       return true;
8897     }
8898     if (!FieldRecord && FieldType.isConstQualified()) {
8899       // C++11 [class.copy]p23:
8900       // -- a non-static data member of const non-class type (or array thereof)
8901       if (Diagnose)
8902         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8903           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8904       return true;
8905     }
8906   }
8907 
8908   if (FieldRecord) {
8909     // Some additional restrictions exist on the variant members.
8910     if (!inUnion() && FieldRecord->isUnion() &&
8911         FieldRecord->isAnonymousStructOrUnion()) {
8912       bool AllVariantFieldsAreConst = true;
8913 
8914       // FIXME: Handle anonymous unions declared within anonymous unions.
8915       for (auto *UI : FieldRecord->fields()) {
8916         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8917 
8918         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8919           return true;
8920 
8921         if (!UnionFieldType.isConstQualified())
8922           AllVariantFieldsAreConst = false;
8923 
8924         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8925         if (UnionFieldRecord &&
8926             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8927                                           UnionFieldType.getCVRQualifiers()))
8928           return true;
8929       }
8930 
8931       // At least one member in each anonymous union must be non-const
8932       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8933           !FieldRecord->field_empty()) {
8934         if (Diagnose)
8935           S.Diag(FieldRecord->getLocation(),
8936                  diag::note_deleted_default_ctor_all_const)
8937             << !!ICI << MD->getParent() << /*anonymous union*/1;
8938         return true;
8939       }
8940 
8941       // Don't check the implicit member of the anonymous union type.
8942       // This is technically non-conformant, but sanity demands it.
8943       return false;
8944     }
8945 
8946     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8947                                       FieldType.getCVRQualifiers()))
8948       return true;
8949   }
8950 
8951   return false;
8952 }
8953 
8954 /// C++11 [class.ctor] p5:
8955 ///   A defaulted default constructor for a class X is defined as deleted if
8956 /// X is a union and all of its variant members are of const-qualified type.
8957 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8958   // This is a silly definition, because it gives an empty union a deleted
8959   // default constructor. Don't do that.
8960   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8961     bool AnyFields = false;
8962     for (auto *F : MD->getParent()->fields())
8963       if ((AnyFields = !F->isUnnamedBitfield()))
8964         break;
8965     if (!AnyFields)
8966       return false;
8967     if (Diagnose)
8968       S.Diag(MD->getParent()->getLocation(),
8969              diag::note_deleted_default_ctor_all_const)
8970         << !!ICI << MD->getParent() << /*not anonymous union*/0;
8971     return true;
8972   }
8973   return false;
8974 }
8975 
8976 /// Determine whether a defaulted special member function should be defined as
8977 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
8978 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
8979 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
8980                                      InheritedConstructorInfo *ICI,
8981                                      bool Diagnose) {
8982   if (MD->isInvalidDecl())
8983     return false;
8984   CXXRecordDecl *RD = MD->getParent();
8985   assert(!RD->isDependentType() && "do deletion after instantiation");
8986   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
8987     return false;
8988 
8989   // C++11 [expr.lambda.prim]p19:
8990   //   The closure type associated with a lambda-expression has a
8991   //   deleted (8.4.3) default constructor and a deleted copy
8992   //   assignment operator.
8993   // C++2a adds back these operators if the lambda has no lambda-capture.
8994   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
8995       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
8996     if (Diagnose)
8997       Diag(RD->getLocation(), diag::note_lambda_decl);
8998     return true;
8999   }
9000 
9001   // For an anonymous struct or union, the copy and assignment special members
9002   // will never be used, so skip the check. For an anonymous union declared at
9003   // namespace scope, the constructor and destructor are used.
9004   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9005       RD->isAnonymousStructOrUnion())
9006     return false;
9007 
9008   // C++11 [class.copy]p7, p18:
9009   //   If the class definition declares a move constructor or move assignment
9010   //   operator, an implicitly declared copy constructor or copy assignment
9011   //   operator is defined as deleted.
9012   if (MD->isImplicit() &&
9013       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9014     CXXMethodDecl *UserDeclaredMove = nullptr;
9015 
9016     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9017     // deletion of the corresponding copy operation, not both copy operations.
9018     // MSVC 2015 has adopted the standards conforming behavior.
9019     bool DeletesOnlyMatchingCopy =
9020         getLangOpts().MSVCCompat &&
9021         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9022 
9023     if (RD->hasUserDeclaredMoveConstructor() &&
9024         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9025       if (!Diagnose) return true;
9026 
9027       // Find any user-declared move constructor.
9028       for (auto *I : RD->ctors()) {
9029         if (I->isMoveConstructor()) {
9030           UserDeclaredMove = I;
9031           break;
9032         }
9033       }
9034       assert(UserDeclaredMove);
9035     } else if (RD->hasUserDeclaredMoveAssignment() &&
9036                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9037       if (!Diagnose) return true;
9038 
9039       // Find any user-declared move assignment operator.
9040       for (auto *I : RD->methods()) {
9041         if (I->isMoveAssignmentOperator()) {
9042           UserDeclaredMove = I;
9043           break;
9044         }
9045       }
9046       assert(UserDeclaredMove);
9047     }
9048 
9049     if (UserDeclaredMove) {
9050       Diag(UserDeclaredMove->getLocation(),
9051            diag::note_deleted_copy_user_declared_move)
9052         << (CSM == CXXCopyAssignment) << RD
9053         << UserDeclaredMove->isMoveAssignmentOperator();
9054       return true;
9055     }
9056   }
9057 
9058   // Do access control from the special member function
9059   ContextRAII MethodContext(*this, MD);
9060 
9061   // C++11 [class.dtor]p5:
9062   // -- for a virtual destructor, lookup of the non-array deallocation function
9063   //    results in an ambiguity or in a function that is deleted or inaccessible
9064   if (CSM == CXXDestructor && MD->isVirtual()) {
9065     FunctionDecl *OperatorDelete = nullptr;
9066     DeclarationName Name =
9067       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9068     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9069                                  OperatorDelete, /*Diagnose*/false)) {
9070       if (Diagnose)
9071         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9072       return true;
9073     }
9074   }
9075 
9076   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9077 
9078   // Per DR1611, do not consider virtual bases of constructors of abstract
9079   // classes, since we are not going to construct them.
9080   // Per DR1658, do not consider virtual bases of destructors of abstract
9081   // classes either.
9082   // Per DR2180, for assignment operators we only assign (and thus only
9083   // consider) direct bases.
9084   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9085                                  : SMI.VisitPotentiallyConstructedBases))
9086     return true;
9087 
9088   if (SMI.shouldDeleteForAllConstMembers())
9089     return true;
9090 
9091   if (getLangOpts().CUDA) {
9092     // We should delete the special member in CUDA mode if target inference
9093     // failed.
9094     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9095     // is treated as certain special member, which may not reflect what special
9096     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9097     // expects CSM to match MD, therefore recalculate CSM.
9098     assert(ICI || CSM == getSpecialMember(MD));
9099     auto RealCSM = CSM;
9100     if (ICI)
9101       RealCSM = getSpecialMember(MD);
9102 
9103     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9104                                                    SMI.ConstArg, Diagnose);
9105   }
9106 
9107   return false;
9108 }
9109 
9110 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9111   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9112   assert(DFK && "not a defaultable function");
9113   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9114 
9115   if (DFK.isSpecialMember()) {
9116     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9117                               nullptr, /*Diagnose=*/true);
9118   } else {
9119     DefaultedComparisonAnalyzer(
9120         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9121         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9122         .visit();
9123   }
9124 }
9125 
9126 /// Perform lookup for a special member of the specified kind, and determine
9127 /// whether it is trivial. If the triviality can be determined without the
9128 /// lookup, skip it. This is intended for use when determining whether a
9129 /// special member of a containing object is trivial, and thus does not ever
9130 /// perform overload resolution for default constructors.
9131 ///
9132 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9133 /// member that was most likely to be intended to be trivial, if any.
9134 ///
9135 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9136 /// determine whether the special member is trivial.
9137 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9138                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9139                                      bool ConstRHS,
9140                                      Sema::TrivialABIHandling TAH,
9141                                      CXXMethodDecl **Selected) {
9142   if (Selected)
9143     *Selected = nullptr;
9144 
9145   switch (CSM) {
9146   case Sema::CXXInvalid:
9147     llvm_unreachable("not a special member");
9148 
9149   case Sema::CXXDefaultConstructor:
9150     // C++11 [class.ctor]p5:
9151     //   A default constructor is trivial if:
9152     //    - all the [direct subobjects] have trivial default constructors
9153     //
9154     // Note, no overload resolution is performed in this case.
9155     if (RD->hasTrivialDefaultConstructor())
9156       return true;
9157 
9158     if (Selected) {
9159       // If there's a default constructor which could have been trivial, dig it
9160       // out. Otherwise, if there's any user-provided default constructor, point
9161       // to that as an example of why there's not a trivial one.
9162       CXXConstructorDecl *DefCtor = nullptr;
9163       if (RD->needsImplicitDefaultConstructor())
9164         S.DeclareImplicitDefaultConstructor(RD);
9165       for (auto *CI : RD->ctors()) {
9166         if (!CI->isDefaultConstructor())
9167           continue;
9168         DefCtor = CI;
9169         if (!DefCtor->isUserProvided())
9170           break;
9171       }
9172 
9173       *Selected = DefCtor;
9174     }
9175 
9176     return false;
9177 
9178   case Sema::CXXDestructor:
9179     // C++11 [class.dtor]p5:
9180     //   A destructor is trivial if:
9181     //    - all the direct [subobjects] have trivial destructors
9182     if (RD->hasTrivialDestructor() ||
9183         (TAH == Sema::TAH_ConsiderTrivialABI &&
9184          RD->hasTrivialDestructorForCall()))
9185       return true;
9186 
9187     if (Selected) {
9188       if (RD->needsImplicitDestructor())
9189         S.DeclareImplicitDestructor(RD);
9190       *Selected = RD->getDestructor();
9191     }
9192 
9193     return false;
9194 
9195   case Sema::CXXCopyConstructor:
9196     // C++11 [class.copy]p12:
9197     //   A copy constructor is trivial if:
9198     //    - the constructor selected to copy each direct [subobject] is trivial
9199     if (RD->hasTrivialCopyConstructor() ||
9200         (TAH == Sema::TAH_ConsiderTrivialABI &&
9201          RD->hasTrivialCopyConstructorForCall())) {
9202       if (Quals == Qualifiers::Const)
9203         // We must either select the trivial copy constructor or reach an
9204         // ambiguity; no need to actually perform overload resolution.
9205         return true;
9206     } else if (!Selected) {
9207       return false;
9208     }
9209     // In C++98, we are not supposed to perform overload resolution here, but we
9210     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9211     // cases like B as having a non-trivial copy constructor:
9212     //   struct A { template<typename T> A(T&); };
9213     //   struct B { mutable A a; };
9214     goto NeedOverloadResolution;
9215 
9216   case Sema::CXXCopyAssignment:
9217     // C++11 [class.copy]p25:
9218     //   A copy assignment operator is trivial if:
9219     //    - the assignment operator selected to copy each direct [subobject] is
9220     //      trivial
9221     if (RD->hasTrivialCopyAssignment()) {
9222       if (Quals == Qualifiers::Const)
9223         return true;
9224     } else if (!Selected) {
9225       return false;
9226     }
9227     // In C++98, we are not supposed to perform overload resolution here, but we
9228     // treat that as a language defect.
9229     goto NeedOverloadResolution;
9230 
9231   case Sema::CXXMoveConstructor:
9232   case Sema::CXXMoveAssignment:
9233   NeedOverloadResolution:
9234     Sema::SpecialMemberOverloadResult SMOR =
9235         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9236 
9237     // The standard doesn't describe how to behave if the lookup is ambiguous.
9238     // We treat it as not making the member non-trivial, just like the standard
9239     // mandates for the default constructor. This should rarely matter, because
9240     // the member will also be deleted.
9241     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9242       return true;
9243 
9244     if (!SMOR.getMethod()) {
9245       assert(SMOR.getKind() ==
9246              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9247       return false;
9248     }
9249 
9250     // We deliberately don't check if we found a deleted special member. We're
9251     // not supposed to!
9252     if (Selected)
9253       *Selected = SMOR.getMethod();
9254 
9255     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9256         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9257       return SMOR.getMethod()->isTrivialForCall();
9258     return SMOR.getMethod()->isTrivial();
9259   }
9260 
9261   llvm_unreachable("unknown special method kind");
9262 }
9263 
9264 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9265   for (auto *CI : RD->ctors())
9266     if (!CI->isImplicit())
9267       return CI;
9268 
9269   // Look for constructor templates.
9270   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9271   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9272     if (CXXConstructorDecl *CD =
9273           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9274       return CD;
9275   }
9276 
9277   return nullptr;
9278 }
9279 
9280 /// The kind of subobject we are checking for triviality. The values of this
9281 /// enumeration are used in diagnostics.
9282 enum TrivialSubobjectKind {
9283   /// The subobject is a base class.
9284   TSK_BaseClass,
9285   /// The subobject is a non-static data member.
9286   TSK_Field,
9287   /// The object is actually the complete object.
9288   TSK_CompleteObject
9289 };
9290 
9291 /// Check whether the special member selected for a given type would be trivial.
9292 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9293                                       QualType SubType, bool ConstRHS,
9294                                       Sema::CXXSpecialMember CSM,
9295                                       TrivialSubobjectKind Kind,
9296                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9297   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9298   if (!SubRD)
9299     return true;
9300 
9301   CXXMethodDecl *Selected;
9302   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9303                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9304     return true;
9305 
9306   if (Diagnose) {
9307     if (ConstRHS)
9308       SubType.addConst();
9309 
9310     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9311       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9312         << Kind << SubType.getUnqualifiedType();
9313       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9314         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9315     } else if (!Selected)
9316       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9317         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9318     else if (Selected->isUserProvided()) {
9319       if (Kind == TSK_CompleteObject)
9320         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9321           << Kind << SubType.getUnqualifiedType() << CSM;
9322       else {
9323         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9324           << Kind << SubType.getUnqualifiedType() << CSM;
9325         S.Diag(Selected->getLocation(), diag::note_declared_at);
9326       }
9327     } else {
9328       if (Kind != TSK_CompleteObject)
9329         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9330           << Kind << SubType.getUnqualifiedType() << CSM;
9331 
9332       // Explain why the defaulted or deleted special member isn't trivial.
9333       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9334                                Diagnose);
9335     }
9336   }
9337 
9338   return false;
9339 }
9340 
9341 /// Check whether the members of a class type allow a special member to be
9342 /// trivial.
9343 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9344                                      Sema::CXXSpecialMember CSM,
9345                                      bool ConstArg,
9346                                      Sema::TrivialABIHandling TAH,
9347                                      bool Diagnose) {
9348   for (const auto *FI : RD->fields()) {
9349     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9350       continue;
9351 
9352     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9353 
9354     // Pretend anonymous struct or union members are members of this class.
9355     if (FI->isAnonymousStructOrUnion()) {
9356       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9357                                     CSM, ConstArg, TAH, Diagnose))
9358         return false;
9359       continue;
9360     }
9361 
9362     // C++11 [class.ctor]p5:
9363     //   A default constructor is trivial if [...]
9364     //    -- no non-static data member of its class has a
9365     //       brace-or-equal-initializer
9366     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9367       if (Diagnose)
9368         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9369       return false;
9370     }
9371 
9372     // Objective C ARC 4.3.5:
9373     //   [...] nontrivally ownership-qualified types are [...] not trivially
9374     //   default constructible, copy constructible, move constructible, copy
9375     //   assignable, move assignable, or destructible [...]
9376     if (FieldType.hasNonTrivialObjCLifetime()) {
9377       if (Diagnose)
9378         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9379           << RD << FieldType.getObjCLifetime();
9380       return false;
9381     }
9382 
9383     bool ConstRHS = ConstArg && !FI->isMutable();
9384     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9385                                    CSM, TSK_Field, TAH, Diagnose))
9386       return false;
9387   }
9388 
9389   return true;
9390 }
9391 
9392 /// Diagnose why the specified class does not have a trivial special member of
9393 /// the given kind.
9394 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9395   QualType Ty = Context.getRecordType(RD);
9396 
9397   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9398   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9399                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9400                             /*Diagnose*/true);
9401 }
9402 
9403 /// Determine whether a defaulted or deleted special member function is trivial,
9404 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9405 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9406 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9407                                   TrivialABIHandling TAH, bool Diagnose) {
9408   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9409 
9410   CXXRecordDecl *RD = MD->getParent();
9411 
9412   bool ConstArg = false;
9413 
9414   // C++11 [class.copy]p12, p25: [DR1593]
9415   //   A [special member] is trivial if [...] its parameter-type-list is
9416   //   equivalent to the parameter-type-list of an implicit declaration [...]
9417   switch (CSM) {
9418   case CXXDefaultConstructor:
9419   case CXXDestructor:
9420     // Trivial default constructors and destructors cannot have parameters.
9421     break;
9422 
9423   case CXXCopyConstructor:
9424   case CXXCopyAssignment: {
9425     // Trivial copy operations always have const, non-volatile parameter types.
9426     ConstArg = true;
9427     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9428     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9429     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9430       if (Diagnose)
9431         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9432           << Param0->getSourceRange() << Param0->getType()
9433           << Context.getLValueReferenceType(
9434                Context.getRecordType(RD).withConst());
9435       return false;
9436     }
9437     break;
9438   }
9439 
9440   case CXXMoveConstructor:
9441   case CXXMoveAssignment: {
9442     // Trivial move operations always have non-cv-qualified parameters.
9443     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9444     const RValueReferenceType *RT =
9445       Param0->getType()->getAs<RValueReferenceType>();
9446     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9447       if (Diagnose)
9448         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9449           << Param0->getSourceRange() << Param0->getType()
9450           << Context.getRValueReferenceType(Context.getRecordType(RD));
9451       return false;
9452     }
9453     break;
9454   }
9455 
9456   case CXXInvalid:
9457     llvm_unreachable("not a special member");
9458   }
9459 
9460   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9461     if (Diagnose)
9462       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9463            diag::note_nontrivial_default_arg)
9464         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9465     return false;
9466   }
9467   if (MD->isVariadic()) {
9468     if (Diagnose)
9469       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9470     return false;
9471   }
9472 
9473   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9474   //   A copy/move [constructor or assignment operator] is trivial if
9475   //    -- the [member] selected to copy/move each direct base class subobject
9476   //       is trivial
9477   //
9478   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9479   //   A [default constructor or destructor] is trivial if
9480   //    -- all the direct base classes have trivial [default constructors or
9481   //       destructors]
9482   for (const auto &BI : RD->bases())
9483     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9484                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9485       return false;
9486 
9487   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9488   //   A copy/move [constructor or assignment operator] for a class X is
9489   //   trivial if
9490   //    -- for each non-static data member of X that is of class type (or array
9491   //       thereof), the constructor selected to copy/move that member is
9492   //       trivial
9493   //
9494   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9495   //   A [default constructor or destructor] is trivial if
9496   //    -- for all of the non-static data members of its class that are of class
9497   //       type (or array thereof), each such class has a trivial [default
9498   //       constructor or destructor]
9499   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9500     return false;
9501 
9502   // C++11 [class.dtor]p5:
9503   //   A destructor is trivial if [...]
9504   //    -- the destructor is not virtual
9505   if (CSM == CXXDestructor && MD->isVirtual()) {
9506     if (Diagnose)
9507       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9508     return false;
9509   }
9510 
9511   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9512   //   A [special member] for class X is trivial if [...]
9513   //    -- class X has no virtual functions and no virtual base classes
9514   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9515     if (!Diagnose)
9516       return false;
9517 
9518     if (RD->getNumVBases()) {
9519       // Check for virtual bases. We already know that the corresponding
9520       // member in all bases is trivial, so vbases must all be direct.
9521       CXXBaseSpecifier &BS = *RD->vbases_begin();
9522       assert(BS.isVirtual());
9523       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9524       return false;
9525     }
9526 
9527     // Must have a virtual method.
9528     for (const auto *MI : RD->methods()) {
9529       if (MI->isVirtual()) {
9530         SourceLocation MLoc = MI->getBeginLoc();
9531         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9532         return false;
9533       }
9534     }
9535 
9536     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9537   }
9538 
9539   // Looks like it's trivial!
9540   return true;
9541 }
9542 
9543 namespace {
9544 struct FindHiddenVirtualMethod {
9545   Sema *S;
9546   CXXMethodDecl *Method;
9547   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9548   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9549 
9550 private:
9551   /// Check whether any most overridden method from MD in Methods
9552   static bool CheckMostOverridenMethods(
9553       const CXXMethodDecl *MD,
9554       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9555     if (MD->size_overridden_methods() == 0)
9556       return Methods.count(MD->getCanonicalDecl());
9557     for (const CXXMethodDecl *O : MD->overridden_methods())
9558       if (CheckMostOverridenMethods(O, Methods))
9559         return true;
9560     return false;
9561   }
9562 
9563 public:
9564   /// Member lookup function that determines whether a given C++
9565   /// method overloads virtual methods in a base class without overriding any,
9566   /// to be used with CXXRecordDecl::lookupInBases().
9567   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9568     RecordDecl *BaseRecord =
9569         Specifier->getType()->castAs<RecordType>()->getDecl();
9570 
9571     DeclarationName Name = Method->getDeclName();
9572     assert(Name.getNameKind() == DeclarationName::Identifier);
9573 
9574     bool foundSameNameMethod = false;
9575     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9576     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9577          Path.Decls = Path.Decls.slice(1)) {
9578       NamedDecl *D = Path.Decls.front();
9579       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9580         MD = MD->getCanonicalDecl();
9581         foundSameNameMethod = true;
9582         // Interested only in hidden virtual methods.
9583         if (!MD->isVirtual())
9584           continue;
9585         // If the method we are checking overrides a method from its base
9586         // don't warn about the other overloaded methods. Clang deviates from
9587         // GCC by only diagnosing overloads of inherited virtual functions that
9588         // do not override any other virtual functions in the base. GCC's
9589         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9590         // function from a base class. These cases may be better served by a
9591         // warning (not specific to virtual functions) on call sites when the
9592         // call would select a different function from the base class, were it
9593         // visible.
9594         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9595         if (!S->IsOverload(Method, MD, false))
9596           return true;
9597         // Collect the overload only if its hidden.
9598         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9599           overloadedMethods.push_back(MD);
9600       }
9601     }
9602 
9603     if (foundSameNameMethod)
9604       OverloadedMethods.append(overloadedMethods.begin(),
9605                                overloadedMethods.end());
9606     return foundSameNameMethod;
9607   }
9608 };
9609 } // end anonymous namespace
9610 
9611 /// Add the most overriden methods from MD to Methods
9612 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9613                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9614   if (MD->size_overridden_methods() == 0)
9615     Methods.insert(MD->getCanonicalDecl());
9616   else
9617     for (const CXXMethodDecl *O : MD->overridden_methods())
9618       AddMostOverridenMethods(O, Methods);
9619 }
9620 
9621 /// Check if a method overloads virtual methods in a base class without
9622 /// overriding any.
9623 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9624                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9625   if (!MD->getDeclName().isIdentifier())
9626     return;
9627 
9628   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9629                      /*bool RecordPaths=*/false,
9630                      /*bool DetectVirtual=*/false);
9631   FindHiddenVirtualMethod FHVM;
9632   FHVM.Method = MD;
9633   FHVM.S = this;
9634 
9635   // Keep the base methods that were overridden or introduced in the subclass
9636   // by 'using' in a set. A base method not in this set is hidden.
9637   CXXRecordDecl *DC = MD->getParent();
9638   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9639   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9640     NamedDecl *ND = *I;
9641     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9642       ND = shad->getTargetDecl();
9643     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9644       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9645   }
9646 
9647   if (DC->lookupInBases(FHVM, Paths))
9648     OverloadedMethods = FHVM.OverloadedMethods;
9649 }
9650 
9651 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9652                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9653   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9654     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9655     PartialDiagnostic PD = PDiag(
9656          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9657     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9658     Diag(overloadedMD->getLocation(), PD);
9659   }
9660 }
9661 
9662 /// Diagnose methods which overload virtual methods in a base class
9663 /// without overriding any.
9664 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9665   if (MD->isInvalidDecl())
9666     return;
9667 
9668   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9669     return;
9670 
9671   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9672   FindHiddenVirtualMethods(MD, OverloadedMethods);
9673   if (!OverloadedMethods.empty()) {
9674     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9675       << MD << (OverloadedMethods.size() > 1);
9676 
9677     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9678   }
9679 }
9680 
9681 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9682   auto PrintDiagAndRemoveAttr = [&]() {
9683     // No diagnostics if this is a template instantiation.
9684     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
9685       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9686            diag::ext_cannot_use_trivial_abi) << &RD;
9687     RD.dropAttr<TrivialABIAttr>();
9688   };
9689 
9690   // Ill-formed if the struct has virtual functions.
9691   if (RD.isPolymorphic()) {
9692     PrintDiagAndRemoveAttr();
9693     return;
9694   }
9695 
9696   for (const auto &B : RD.bases()) {
9697     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9698     // virtual base.
9699     if ((!B.getType()->isDependentType() &&
9700          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
9701         B.isVirtual()) {
9702       PrintDiagAndRemoveAttr();
9703       return;
9704     }
9705   }
9706 
9707   for (const auto *FD : RD.fields()) {
9708     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9709     // non-trivial for the purpose of calls.
9710     QualType FT = FD->getType();
9711     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9712       PrintDiagAndRemoveAttr();
9713       return;
9714     }
9715 
9716     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9717       if (!RT->isDependentType() &&
9718           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9719         PrintDiagAndRemoveAttr();
9720         return;
9721       }
9722   }
9723 }
9724 
9725 void Sema::ActOnFinishCXXMemberSpecification(
9726     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9727     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9728   if (!TagDecl)
9729     return;
9730 
9731   AdjustDeclIfTemplate(TagDecl);
9732 
9733   for (const ParsedAttr &AL : AttrList) {
9734     if (AL.getKind() != ParsedAttr::AT_Visibility)
9735       continue;
9736     AL.setInvalid();
9737     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9738   }
9739 
9740   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9741               // strict aliasing violation!
9742               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9743               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9744 
9745   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9746 }
9747 
9748 /// Find the equality comparison functions that should be implicitly declared
9749 /// in a given class definition, per C++2a [class.compare.default]p3.
9750 static void findImplicitlyDeclaredEqualityComparisons(
9751     ASTContext &Ctx, CXXRecordDecl *RD,
9752     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9753   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9754   if (!RD->lookup(EqEq).empty())
9755     // Member operator== explicitly declared: no implicit operator==s.
9756     return;
9757 
9758   // Traverse friends looking for an '==' or a '<=>'.
9759   for (FriendDecl *Friend : RD->friends()) {
9760     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9761     if (!FD) continue;
9762 
9763     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9764       // Friend operator== explicitly declared: no implicit operator==s.
9765       Spaceships.clear();
9766       return;
9767     }
9768 
9769     if (FD->getOverloadedOperator() == OO_Spaceship &&
9770         FD->isExplicitlyDefaulted())
9771       Spaceships.push_back(FD);
9772   }
9773 
9774   // Look for members named 'operator<=>'.
9775   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9776   for (NamedDecl *ND : RD->lookup(Cmp)) {
9777     // Note that we could find a non-function here (either a function template
9778     // or a using-declaration). Neither case results in an implicit
9779     // 'operator=='.
9780     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9781       if (FD->isExplicitlyDefaulted())
9782         Spaceships.push_back(FD);
9783   }
9784 }
9785 
9786 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9787 /// special functions, such as the default constructor, copy
9788 /// constructor, or destructor, to the given C++ class (C++
9789 /// [special]p1).  This routine can only be executed just before the
9790 /// definition of the class is complete.
9791 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9792   if (ClassDecl->needsImplicitDefaultConstructor()) {
9793     ++getASTContext().NumImplicitDefaultConstructors;
9794 
9795     if (ClassDecl->hasInheritedConstructor())
9796       DeclareImplicitDefaultConstructor(ClassDecl);
9797   }
9798 
9799   if (ClassDecl->needsImplicitCopyConstructor()) {
9800     ++getASTContext().NumImplicitCopyConstructors;
9801 
9802     // If the properties or semantics of the copy constructor couldn't be
9803     // determined while the class was being declared, force a declaration
9804     // of it now.
9805     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9806         ClassDecl->hasInheritedConstructor())
9807       DeclareImplicitCopyConstructor(ClassDecl);
9808     // For the MS ABI we need to know whether the copy ctor is deleted. A
9809     // prerequisite for deleting the implicit copy ctor is that the class has a
9810     // move ctor or move assignment that is either user-declared or whose
9811     // semantics are inherited from a subobject. FIXME: We should provide a more
9812     // direct way for CodeGen to ask whether the constructor was deleted.
9813     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9814              (ClassDecl->hasUserDeclaredMoveConstructor() ||
9815               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9816               ClassDecl->hasUserDeclaredMoveAssignment() ||
9817               ClassDecl->needsOverloadResolutionForMoveAssignment()))
9818       DeclareImplicitCopyConstructor(ClassDecl);
9819   }
9820 
9821   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
9822     ++getASTContext().NumImplicitMoveConstructors;
9823 
9824     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9825         ClassDecl->hasInheritedConstructor())
9826       DeclareImplicitMoveConstructor(ClassDecl);
9827   }
9828 
9829   if (ClassDecl->needsImplicitCopyAssignment()) {
9830     ++getASTContext().NumImplicitCopyAssignmentOperators;
9831 
9832     // If we have a dynamic class, then the copy assignment operator may be
9833     // virtual, so we have to declare it immediately. This ensures that, e.g.,
9834     // it shows up in the right place in the vtable and that we diagnose
9835     // problems with the implicit exception specification.
9836     if (ClassDecl->isDynamicClass() ||
9837         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9838         ClassDecl->hasInheritedAssignment())
9839       DeclareImplicitCopyAssignment(ClassDecl);
9840   }
9841 
9842   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9843     ++getASTContext().NumImplicitMoveAssignmentOperators;
9844 
9845     // Likewise for the move assignment operator.
9846     if (ClassDecl->isDynamicClass() ||
9847         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9848         ClassDecl->hasInheritedAssignment())
9849       DeclareImplicitMoveAssignment(ClassDecl);
9850   }
9851 
9852   if (ClassDecl->needsImplicitDestructor()) {
9853     ++getASTContext().NumImplicitDestructors;
9854 
9855     // If we have a dynamic class, then the destructor may be virtual, so we
9856     // have to declare the destructor immediately. This ensures that, e.g., it
9857     // shows up in the right place in the vtable and that we diagnose problems
9858     // with the implicit exception specification.
9859     if (ClassDecl->isDynamicClass() ||
9860         ClassDecl->needsOverloadResolutionForDestructor())
9861       DeclareImplicitDestructor(ClassDecl);
9862   }
9863 
9864   // C++2a [class.compare.default]p3:
9865   //   If the member-specification does not explicitly declare any member or
9866   //   friend named operator==, an == operator function is declared implicitly
9867   //   for each defaulted three-way comparison operator function defined in the
9868   //   member-specification
9869   // FIXME: Consider doing this lazily.
9870   if (getLangOpts().CPlusPlus20) {
9871     llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships;
9872     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9873                                               DefaultedSpaceships);
9874     for (auto *FD : DefaultedSpaceships)
9875       DeclareImplicitEqualityComparison(ClassDecl, FD);
9876   }
9877 }
9878 
9879 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
9880   if (!D)
9881     return 0;
9882 
9883   // The order of template parameters is not important here. All names
9884   // get added to the same scope.
9885   SmallVector<TemplateParameterList *, 4> ParameterLists;
9886 
9887   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9888     D = TD->getTemplatedDecl();
9889 
9890   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9891     ParameterLists.push_back(PSD->getTemplateParameters());
9892 
9893   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9894     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9895       ParameterLists.push_back(DD->getTemplateParameterList(i));
9896 
9897     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9898       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9899         ParameterLists.push_back(FTD->getTemplateParameters());
9900     }
9901   }
9902 
9903   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9904     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9905       ParameterLists.push_back(TD->getTemplateParameterList(i));
9906 
9907     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9908       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9909         ParameterLists.push_back(CTD->getTemplateParameters());
9910     }
9911   }
9912 
9913   unsigned Count = 0;
9914   for (TemplateParameterList *Params : ParameterLists) {
9915     if (Params->size() > 0)
9916       // Ignore explicit specializations; they don't contribute to the template
9917       // depth.
9918       ++Count;
9919     for (NamedDecl *Param : *Params) {
9920       if (Param->getDeclName()) {
9921         S->AddDecl(Param);
9922         IdResolver.AddDecl(Param);
9923       }
9924     }
9925   }
9926 
9927   return Count;
9928 }
9929 
9930 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
9931   if (!RecordD) return;
9932   AdjustDeclIfTemplate(RecordD);
9933   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
9934   PushDeclContext(S, Record);
9935 }
9936 
9937 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
9938   if (!RecordD) return;
9939   PopDeclContext();
9940 }
9941 
9942 /// This is used to implement the constant expression evaluation part of the
9943 /// attribute enable_if extension. There is nothing in standard C++ which would
9944 /// require reentering parameters.
9945 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
9946   if (!Param)
9947     return;
9948 
9949   S->AddDecl(Param);
9950   if (Param->getDeclName())
9951     IdResolver.AddDecl(Param);
9952 }
9953 
9954 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
9955 /// parsing a top-level (non-nested) C++ class, and we are now
9956 /// parsing those parts of the given Method declaration that could
9957 /// not be parsed earlier (C++ [class.mem]p2), such as default
9958 /// arguments. This action should enter the scope of the given
9959 /// Method declaration as if we had just parsed the qualified method
9960 /// name. However, it should not bring the parameters into scope;
9961 /// that will be performed by ActOnDelayedCXXMethodParameter.
9962 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
9963 }
9964 
9965 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
9966 /// C++ method declaration. We're (re-)introducing the given
9967 /// function parameter into scope for use in parsing later parts of
9968 /// the method declaration. For example, we could see an
9969 /// ActOnParamDefaultArgument event for this parameter.
9970 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
9971   if (!ParamD)
9972     return;
9973 
9974   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
9975 
9976   // If this parameter has an unparsed default argument, clear it out
9977   // to make way for the parsed default argument.
9978   if (Param->hasUnparsedDefaultArg())
9979     Param->setDefaultArg(nullptr);
9980 
9981   S->AddDecl(Param);
9982   if (Param->getDeclName())
9983     IdResolver.AddDecl(Param);
9984 }
9985 
9986 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
9987 /// processing the delayed method declaration for Method. The method
9988 /// declaration is now considered finished. There may be a separate
9989 /// ActOnStartOfFunctionDef action later (not necessarily
9990 /// immediately!) for this method, if it was also defined inside the
9991 /// class body.
9992 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
9993   if (!MethodD)
9994     return;
9995 
9996   AdjustDeclIfTemplate(MethodD);
9997 
9998   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
9999 
10000   // Now that we have our default arguments, check the constructor
10001   // again. It could produce additional diagnostics or affect whether
10002   // the class has implicitly-declared destructors, among other
10003   // things.
10004   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10005     CheckConstructor(Constructor);
10006 
10007   // Check the default arguments, which we may have added.
10008   if (!Method->isInvalidDecl())
10009     CheckCXXDefaultArguments(Method);
10010 }
10011 
10012 // Emit the given diagnostic for each non-address-space qualifier.
10013 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10014 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10015   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10016   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10017     bool DiagOccured = false;
10018     FTI.MethodQualifiers->forEachQualifier(
10019         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10020                                    SourceLocation SL) {
10021           // This diagnostic should be emitted on any qualifier except an addr
10022           // space qualifier. However, forEachQualifier currently doesn't visit
10023           // addr space qualifiers, so there's no way to write this condition
10024           // right now; we just diagnose on everything.
10025           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10026           DiagOccured = true;
10027         });
10028     if (DiagOccured)
10029       D.setInvalidType();
10030   }
10031 }
10032 
10033 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10034 /// the well-formedness of the constructor declarator @p D with type @p
10035 /// R. If there are any errors in the declarator, this routine will
10036 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10037 /// will be updated to reflect a well-formed type for the constructor and
10038 /// returned.
10039 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10040                                           StorageClass &SC) {
10041   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10042 
10043   // C++ [class.ctor]p3:
10044   //   A constructor shall not be virtual (10.3) or static (9.4). A
10045   //   constructor can be invoked for a const, volatile or const
10046   //   volatile object. A constructor shall not be declared const,
10047   //   volatile, or const volatile (9.3.2).
10048   if (isVirtual) {
10049     if (!D.isInvalidType())
10050       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10051         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10052         << SourceRange(D.getIdentifierLoc());
10053     D.setInvalidType();
10054   }
10055   if (SC == SC_Static) {
10056     if (!D.isInvalidType())
10057       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10058         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10059         << SourceRange(D.getIdentifierLoc());
10060     D.setInvalidType();
10061     SC = SC_None;
10062   }
10063 
10064   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10065     diagnoseIgnoredQualifiers(
10066         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10067         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10068         D.getDeclSpec().getRestrictSpecLoc(),
10069         D.getDeclSpec().getAtomicSpecLoc());
10070     D.setInvalidType();
10071   }
10072 
10073   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10074 
10075   // C++0x [class.ctor]p4:
10076   //   A constructor shall not be declared with a ref-qualifier.
10077   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10078   if (FTI.hasRefQualifier()) {
10079     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10080       << FTI.RefQualifierIsLValueRef
10081       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10082     D.setInvalidType();
10083   }
10084 
10085   // Rebuild the function type "R" without any type qualifiers (in
10086   // case any of the errors above fired) and with "void" as the
10087   // return type, since constructors don't have return types.
10088   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10089   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10090     return R;
10091 
10092   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10093   EPI.TypeQuals = Qualifiers();
10094   EPI.RefQualifier = RQ_None;
10095 
10096   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10097 }
10098 
10099 /// CheckConstructor - Checks a fully-formed constructor for
10100 /// well-formedness, issuing any diagnostics required. Returns true if
10101 /// the constructor declarator is invalid.
10102 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10103   CXXRecordDecl *ClassDecl
10104     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10105   if (!ClassDecl)
10106     return Constructor->setInvalidDecl();
10107 
10108   // C++ [class.copy]p3:
10109   //   A declaration of a constructor for a class X is ill-formed if
10110   //   its first parameter is of type (optionally cv-qualified) X and
10111   //   either there are no other parameters or else all other
10112   //   parameters have default arguments.
10113   if (!Constructor->isInvalidDecl() &&
10114       ((Constructor->getNumParams() == 1) ||
10115        (Constructor->getNumParams() > 1 &&
10116         Constructor->getParamDecl(1)->hasDefaultArg())) &&
10117       Constructor->getTemplateSpecializationKind()
10118                                               != TSK_ImplicitInstantiation) {
10119     QualType ParamType = Constructor->getParamDecl(0)->getType();
10120     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10121     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10122       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10123       const char *ConstRef
10124         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10125                                                         : " const &";
10126       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10127         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10128 
10129       // FIXME: Rather that making the constructor invalid, we should endeavor
10130       // to fix the type.
10131       Constructor->setInvalidDecl();
10132     }
10133   }
10134 }
10135 
10136 /// CheckDestructor - Checks a fully-formed destructor definition for
10137 /// well-formedness, issuing any diagnostics required.  Returns true
10138 /// on error.
10139 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10140   CXXRecordDecl *RD = Destructor->getParent();
10141 
10142   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10143     SourceLocation Loc;
10144 
10145     if (!Destructor->isImplicit())
10146       Loc = Destructor->getLocation();
10147     else
10148       Loc = RD->getLocation();
10149 
10150     // If we have a virtual destructor, look up the deallocation function
10151     if (FunctionDecl *OperatorDelete =
10152             FindDeallocationFunctionForDestructor(Loc, RD)) {
10153       Expr *ThisArg = nullptr;
10154 
10155       // If the notional 'delete this' expression requires a non-trivial
10156       // conversion from 'this' to the type of a destroying operator delete's
10157       // first parameter, perform that conversion now.
10158       if (OperatorDelete->isDestroyingOperatorDelete()) {
10159         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10160         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10161           // C++ [class.dtor]p13:
10162           //   ... as if for the expression 'delete this' appearing in a
10163           //   non-virtual destructor of the destructor's class.
10164           ContextRAII SwitchContext(*this, Destructor);
10165           ExprResult This =
10166               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10167           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10168           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10169           if (This.isInvalid()) {
10170             // FIXME: Register this as a context note so that it comes out
10171             // in the right order.
10172             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10173             return true;
10174           }
10175           ThisArg = This.get();
10176         }
10177       }
10178 
10179       DiagnoseUseOfDecl(OperatorDelete, Loc);
10180       MarkFunctionReferenced(Loc, OperatorDelete);
10181       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10182     }
10183   }
10184 
10185   return false;
10186 }
10187 
10188 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10189 /// the well-formednes of the destructor declarator @p D with type @p
10190 /// R. If there are any errors in the declarator, this routine will
10191 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10192 /// will be updated to reflect a well-formed type for the destructor and
10193 /// returned.
10194 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10195                                          StorageClass& SC) {
10196   // C++ [class.dtor]p1:
10197   //   [...] A typedef-name that names a class is a class-name
10198   //   (7.1.3); however, a typedef-name that names a class shall not
10199   //   be used as the identifier in the declarator for a destructor
10200   //   declaration.
10201   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10202   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10203     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10204       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10205   else if (const TemplateSpecializationType *TST =
10206              DeclaratorType->getAs<TemplateSpecializationType>())
10207     if (TST->isTypeAlias())
10208       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10209         << DeclaratorType << 1;
10210 
10211   // C++ [class.dtor]p2:
10212   //   A destructor is used to destroy objects of its class type. A
10213   //   destructor takes no parameters, and no return type can be
10214   //   specified for it (not even void). The address of a destructor
10215   //   shall not be taken. A destructor shall not be static. A
10216   //   destructor can be invoked for a const, volatile or const
10217   //   volatile object. A destructor shall not be declared const,
10218   //   volatile or const volatile (9.3.2).
10219   if (SC == SC_Static) {
10220     if (!D.isInvalidType())
10221       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10222         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10223         << SourceRange(D.getIdentifierLoc())
10224         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10225 
10226     SC = SC_None;
10227   }
10228   if (!D.isInvalidType()) {
10229     // Destructors don't have return types, but the parser will
10230     // happily parse something like:
10231     //
10232     //   class X {
10233     //     float ~X();
10234     //   };
10235     //
10236     // The return type will be eliminated later.
10237     if (D.getDeclSpec().hasTypeSpecifier())
10238       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10239         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10240         << SourceRange(D.getIdentifierLoc());
10241     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10242       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10243                                 SourceLocation(),
10244                                 D.getDeclSpec().getConstSpecLoc(),
10245                                 D.getDeclSpec().getVolatileSpecLoc(),
10246                                 D.getDeclSpec().getRestrictSpecLoc(),
10247                                 D.getDeclSpec().getAtomicSpecLoc());
10248       D.setInvalidType();
10249     }
10250   }
10251 
10252   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10253 
10254   // C++0x [class.dtor]p2:
10255   //   A destructor shall not be declared with a ref-qualifier.
10256   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10257   if (FTI.hasRefQualifier()) {
10258     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10259       << FTI.RefQualifierIsLValueRef
10260       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10261     D.setInvalidType();
10262   }
10263 
10264   // Make sure we don't have any parameters.
10265   if (FTIHasNonVoidParameters(FTI)) {
10266     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10267 
10268     // Delete the parameters.
10269     FTI.freeParams();
10270     D.setInvalidType();
10271   }
10272 
10273   // Make sure the destructor isn't variadic.
10274   if (FTI.isVariadic) {
10275     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10276     D.setInvalidType();
10277   }
10278 
10279   // Rebuild the function type "R" without any type qualifiers or
10280   // parameters (in case any of the errors above fired) and with
10281   // "void" as the return type, since destructors don't have return
10282   // types.
10283   if (!D.isInvalidType())
10284     return R;
10285 
10286   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10287   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10288   EPI.Variadic = false;
10289   EPI.TypeQuals = Qualifiers();
10290   EPI.RefQualifier = RQ_None;
10291   return Context.getFunctionType(Context.VoidTy, None, EPI);
10292 }
10293 
10294 static void extendLeft(SourceRange &R, SourceRange Before) {
10295   if (Before.isInvalid())
10296     return;
10297   R.setBegin(Before.getBegin());
10298   if (R.getEnd().isInvalid())
10299     R.setEnd(Before.getEnd());
10300 }
10301 
10302 static void extendRight(SourceRange &R, SourceRange After) {
10303   if (After.isInvalid())
10304     return;
10305   if (R.getBegin().isInvalid())
10306     R.setBegin(After.getBegin());
10307   R.setEnd(After.getEnd());
10308 }
10309 
10310 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10311 /// well-formednes of the conversion function declarator @p D with
10312 /// type @p R. If there are any errors in the declarator, this routine
10313 /// will emit diagnostics and return true. Otherwise, it will return
10314 /// false. Either way, the type @p R will be updated to reflect a
10315 /// well-formed type for the conversion operator.
10316 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10317                                      StorageClass& SC) {
10318   // C++ [class.conv.fct]p1:
10319   //   Neither parameter types nor return type can be specified. The
10320   //   type of a conversion function (8.3.5) is "function taking no
10321   //   parameter returning conversion-type-id."
10322   if (SC == SC_Static) {
10323     if (!D.isInvalidType())
10324       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10325         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10326         << D.getName().getSourceRange();
10327     D.setInvalidType();
10328     SC = SC_None;
10329   }
10330 
10331   TypeSourceInfo *ConvTSI = nullptr;
10332   QualType ConvType =
10333       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10334 
10335   const DeclSpec &DS = D.getDeclSpec();
10336   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10337     // Conversion functions don't have return types, but the parser will
10338     // happily parse something like:
10339     //
10340     //   class X {
10341     //     float operator bool();
10342     //   };
10343     //
10344     // The return type will be changed later anyway.
10345     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10346       << SourceRange(DS.getTypeSpecTypeLoc())
10347       << SourceRange(D.getIdentifierLoc());
10348     D.setInvalidType();
10349   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10350     // It's also plausible that the user writes type qualifiers in the wrong
10351     // place, such as:
10352     //   struct S { const operator int(); };
10353     // FIXME: we could provide a fixit to move the qualifiers onto the
10354     // conversion type.
10355     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10356         << SourceRange(D.getIdentifierLoc()) << 0;
10357     D.setInvalidType();
10358   }
10359 
10360   const auto *Proto = R->castAs<FunctionProtoType>();
10361 
10362   // Make sure we don't have any parameters.
10363   if (Proto->getNumParams() > 0) {
10364     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10365 
10366     // Delete the parameters.
10367     D.getFunctionTypeInfo().freeParams();
10368     D.setInvalidType();
10369   } else if (Proto->isVariadic()) {
10370     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10371     D.setInvalidType();
10372   }
10373 
10374   // Diagnose "&operator bool()" and other such nonsense.  This
10375   // is actually a gcc extension which we don't support.
10376   if (Proto->getReturnType() != ConvType) {
10377     bool NeedsTypedef = false;
10378     SourceRange Before, After;
10379 
10380     // Walk the chunks and extract information on them for our diagnostic.
10381     bool PastFunctionChunk = false;
10382     for (auto &Chunk : D.type_objects()) {
10383       switch (Chunk.Kind) {
10384       case DeclaratorChunk::Function:
10385         if (!PastFunctionChunk) {
10386           if (Chunk.Fun.HasTrailingReturnType) {
10387             TypeSourceInfo *TRT = nullptr;
10388             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10389             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10390           }
10391           PastFunctionChunk = true;
10392           break;
10393         }
10394         LLVM_FALLTHROUGH;
10395       case DeclaratorChunk::Array:
10396         NeedsTypedef = true;
10397         extendRight(After, Chunk.getSourceRange());
10398         break;
10399 
10400       case DeclaratorChunk::Pointer:
10401       case DeclaratorChunk::BlockPointer:
10402       case DeclaratorChunk::Reference:
10403       case DeclaratorChunk::MemberPointer:
10404       case DeclaratorChunk::Pipe:
10405         extendLeft(Before, Chunk.getSourceRange());
10406         break;
10407 
10408       case DeclaratorChunk::Paren:
10409         extendLeft(Before, Chunk.Loc);
10410         extendRight(After, Chunk.EndLoc);
10411         break;
10412       }
10413     }
10414 
10415     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10416                          After.isValid()  ? After.getBegin() :
10417                                             D.getIdentifierLoc();
10418     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10419     DB << Before << After;
10420 
10421     if (!NeedsTypedef) {
10422       DB << /*don't need a typedef*/0;
10423 
10424       // If we can provide a correct fix-it hint, do so.
10425       if (After.isInvalid() && ConvTSI) {
10426         SourceLocation InsertLoc =
10427             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10428         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10429            << FixItHint::CreateInsertionFromRange(
10430                   InsertLoc, CharSourceRange::getTokenRange(Before))
10431            << FixItHint::CreateRemoval(Before);
10432       }
10433     } else if (!Proto->getReturnType()->isDependentType()) {
10434       DB << /*typedef*/1 << Proto->getReturnType();
10435     } else if (getLangOpts().CPlusPlus11) {
10436       DB << /*alias template*/2 << Proto->getReturnType();
10437     } else {
10438       DB << /*might not be fixable*/3;
10439     }
10440 
10441     // Recover by incorporating the other type chunks into the result type.
10442     // Note, this does *not* change the name of the function. This is compatible
10443     // with the GCC extension:
10444     //   struct S { &operator int(); } s;
10445     //   int &r = s.operator int(); // ok in GCC
10446     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10447     ConvType = Proto->getReturnType();
10448   }
10449 
10450   // C++ [class.conv.fct]p4:
10451   //   The conversion-type-id shall not represent a function type nor
10452   //   an array type.
10453   if (ConvType->isArrayType()) {
10454     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10455     ConvType = Context.getPointerType(ConvType);
10456     D.setInvalidType();
10457   } else if (ConvType->isFunctionType()) {
10458     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10459     ConvType = Context.getPointerType(ConvType);
10460     D.setInvalidType();
10461   }
10462 
10463   // Rebuild the function type "R" without any parameters (in case any
10464   // of the errors above fired) and with the conversion type as the
10465   // return type.
10466   if (D.isInvalidType())
10467     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10468 
10469   // C++0x explicit conversion operators.
10470   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10471     Diag(DS.getExplicitSpecLoc(),
10472          getLangOpts().CPlusPlus11
10473              ? diag::warn_cxx98_compat_explicit_conversion_functions
10474              : diag::ext_explicit_conversion_functions)
10475         << SourceRange(DS.getExplicitSpecRange());
10476 }
10477 
10478 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10479 /// the declaration of the given C++ conversion function. This routine
10480 /// is responsible for recording the conversion function in the C++
10481 /// class, if possible.
10482 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10483   assert(Conversion && "Expected to receive a conversion function declaration");
10484 
10485   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10486 
10487   // Make sure we aren't redeclaring the conversion function.
10488   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10489   // C++ [class.conv.fct]p1:
10490   //   [...] A conversion function is never used to convert a
10491   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10492   //   same object type (or a reference to it), to a (possibly
10493   //   cv-qualified) base class of that type (or a reference to it),
10494   //   or to (possibly cv-qualified) void.
10495   QualType ClassType
10496     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10497   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10498     ConvType = ConvTypeRef->getPointeeType();
10499   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10500       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10501     /* Suppress diagnostics for instantiations. */;
10502   else if (Conversion->size_overridden_methods() != 0)
10503     /* Suppress diagnostics for overriding virtual function in a base class. */;
10504   else if (ConvType->isRecordType()) {
10505     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10506     if (ConvType == ClassType)
10507       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10508         << ClassType;
10509     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10510       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10511         <<  ClassType << ConvType;
10512   } else if (ConvType->isVoidType()) {
10513     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10514       << ClassType << ConvType;
10515   }
10516 
10517   if (FunctionTemplateDecl *ConversionTemplate
10518                                 = Conversion->getDescribedFunctionTemplate())
10519     return ConversionTemplate;
10520 
10521   return Conversion;
10522 }
10523 
10524 namespace {
10525 /// Utility class to accumulate and print a diagnostic listing the invalid
10526 /// specifier(s) on a declaration.
10527 struct BadSpecifierDiagnoser {
10528   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10529       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10530   ~BadSpecifierDiagnoser() {
10531     Diagnostic << Specifiers;
10532   }
10533 
10534   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10535     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10536   }
10537   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10538     return check(SpecLoc,
10539                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10540   }
10541   void check(SourceLocation SpecLoc, const char *Spec) {
10542     if (SpecLoc.isInvalid()) return;
10543     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10544     if (!Specifiers.empty()) Specifiers += " ";
10545     Specifiers += Spec;
10546   }
10547 
10548   Sema &S;
10549   Sema::SemaDiagnosticBuilder Diagnostic;
10550   std::string Specifiers;
10551 };
10552 }
10553 
10554 /// Check the validity of a declarator that we parsed for a deduction-guide.
10555 /// These aren't actually declarators in the grammar, so we need to check that
10556 /// the user didn't specify any pieces that are not part of the deduction-guide
10557 /// grammar.
10558 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10559                                          StorageClass &SC) {
10560   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10561   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10562   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10563 
10564   // C++ [temp.deduct.guide]p3:
10565   //   A deduction-gide shall be declared in the same scope as the
10566   //   corresponding class template.
10567   if (!CurContext->getRedeclContext()->Equals(
10568           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10569     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10570       << GuidedTemplateDecl;
10571     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10572   }
10573 
10574   auto &DS = D.getMutableDeclSpec();
10575   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10576   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10577       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10578       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10579     BadSpecifierDiagnoser Diagnoser(
10580         *this, D.getIdentifierLoc(),
10581         diag::err_deduction_guide_invalid_specifier);
10582 
10583     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10584     DS.ClearStorageClassSpecs();
10585     SC = SC_None;
10586 
10587     // 'explicit' is permitted.
10588     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10589     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10590     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10591     DS.ClearConstexprSpec();
10592 
10593     Diagnoser.check(DS.getConstSpecLoc(), "const");
10594     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10595     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10596     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10597     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10598     DS.ClearTypeQualifiers();
10599 
10600     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10601     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10602     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10603     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10604     DS.ClearTypeSpecType();
10605   }
10606 
10607   if (D.isInvalidType())
10608     return;
10609 
10610   // Check the declarator is simple enough.
10611   bool FoundFunction = false;
10612   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10613     if (Chunk.Kind == DeclaratorChunk::Paren)
10614       continue;
10615     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10616       Diag(D.getDeclSpec().getBeginLoc(),
10617            diag::err_deduction_guide_with_complex_decl)
10618           << D.getSourceRange();
10619       break;
10620     }
10621     if (!Chunk.Fun.hasTrailingReturnType()) {
10622       Diag(D.getName().getBeginLoc(),
10623            diag::err_deduction_guide_no_trailing_return_type);
10624       break;
10625     }
10626 
10627     // Check that the return type is written as a specialization of
10628     // the template specified as the deduction-guide's name.
10629     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10630     TypeSourceInfo *TSI = nullptr;
10631     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10632     assert(TSI && "deduction guide has valid type but invalid return type?");
10633     bool AcceptableReturnType = false;
10634     bool MightInstantiateToSpecialization = false;
10635     if (auto RetTST =
10636             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10637       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10638       bool TemplateMatches =
10639           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10640       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10641         AcceptableReturnType = true;
10642       else {
10643         // This could still instantiate to the right type, unless we know it
10644         // names the wrong class template.
10645         auto *TD = SpecifiedName.getAsTemplateDecl();
10646         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10647                                              !TemplateMatches);
10648       }
10649     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10650       MightInstantiateToSpecialization = true;
10651     }
10652 
10653     if (!AcceptableReturnType) {
10654       Diag(TSI->getTypeLoc().getBeginLoc(),
10655            diag::err_deduction_guide_bad_trailing_return_type)
10656           << GuidedTemplate << TSI->getType()
10657           << MightInstantiateToSpecialization
10658           << TSI->getTypeLoc().getSourceRange();
10659     }
10660 
10661     // Keep going to check that we don't have any inner declarator pieces (we
10662     // could still have a function returning a pointer to a function).
10663     FoundFunction = true;
10664   }
10665 
10666   if (D.isFunctionDefinition())
10667     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10668 }
10669 
10670 //===----------------------------------------------------------------------===//
10671 // Namespace Handling
10672 //===----------------------------------------------------------------------===//
10673 
10674 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10675 /// reopened.
10676 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10677                                             SourceLocation Loc,
10678                                             IdentifierInfo *II, bool *IsInline,
10679                                             NamespaceDecl *PrevNS) {
10680   assert(*IsInline != PrevNS->isInline());
10681 
10682   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10683   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10684   // inline namespaces, with the intention of bringing names into namespace std.
10685   //
10686   // We support this just well enough to get that case working; this is not
10687   // sufficient to support reopening namespaces as inline in general.
10688   if (*IsInline && II && II->getName().startswith("__atomic") &&
10689       S.getSourceManager().isInSystemHeader(Loc)) {
10690     // Mark all prior declarations of the namespace as inline.
10691     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10692          NS = NS->getPreviousDecl())
10693       NS->setInline(*IsInline);
10694     // Patch up the lookup table for the containing namespace. This isn't really
10695     // correct, but it's good enough for this particular case.
10696     for (auto *I : PrevNS->decls())
10697       if (auto *ND = dyn_cast<NamedDecl>(I))
10698         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10699     return;
10700   }
10701 
10702   if (PrevNS->isInline())
10703     // The user probably just forgot the 'inline', so suggest that it
10704     // be added back.
10705     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10706       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10707   else
10708     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10709 
10710   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10711   *IsInline = PrevNS->isInline();
10712 }
10713 
10714 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10715 /// definition.
10716 Decl *Sema::ActOnStartNamespaceDef(
10717     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10718     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10719     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10720   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10721   // For anonymous namespace, take the location of the left brace.
10722   SourceLocation Loc = II ? IdentLoc : LBrace;
10723   bool IsInline = InlineLoc.isValid();
10724   bool IsInvalid = false;
10725   bool IsStd = false;
10726   bool AddToKnown = false;
10727   Scope *DeclRegionScope = NamespcScope->getParent();
10728 
10729   NamespaceDecl *PrevNS = nullptr;
10730   if (II) {
10731     // C++ [namespace.def]p2:
10732     //   The identifier in an original-namespace-definition shall not
10733     //   have been previously defined in the declarative region in
10734     //   which the original-namespace-definition appears. The
10735     //   identifier in an original-namespace-definition is the name of
10736     //   the namespace. Subsequently in that declarative region, it is
10737     //   treated as an original-namespace-name.
10738     //
10739     // Since namespace names are unique in their scope, and we don't
10740     // look through using directives, just look for any ordinary names
10741     // as if by qualified name lookup.
10742     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10743                    ForExternalRedeclaration);
10744     LookupQualifiedName(R, CurContext->getRedeclContext());
10745     NamedDecl *PrevDecl =
10746         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10747     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10748 
10749     if (PrevNS) {
10750       // This is an extended namespace definition.
10751       if (IsInline != PrevNS->isInline())
10752         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10753                                         &IsInline, PrevNS);
10754     } else if (PrevDecl) {
10755       // This is an invalid name redefinition.
10756       Diag(Loc, diag::err_redefinition_different_kind)
10757         << II;
10758       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10759       IsInvalid = true;
10760       // Continue on to push Namespc as current DeclContext and return it.
10761     } else if (II->isStr("std") &&
10762                CurContext->getRedeclContext()->isTranslationUnit()) {
10763       // This is the first "real" definition of the namespace "std", so update
10764       // our cache of the "std" namespace to point at this definition.
10765       PrevNS = getStdNamespace();
10766       IsStd = true;
10767       AddToKnown = !IsInline;
10768     } else {
10769       // We've seen this namespace for the first time.
10770       AddToKnown = !IsInline;
10771     }
10772   } else {
10773     // Anonymous namespaces.
10774 
10775     // Determine whether the parent already has an anonymous namespace.
10776     DeclContext *Parent = CurContext->getRedeclContext();
10777     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10778       PrevNS = TU->getAnonymousNamespace();
10779     } else {
10780       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10781       PrevNS = ND->getAnonymousNamespace();
10782     }
10783 
10784     if (PrevNS && IsInline != PrevNS->isInline())
10785       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10786                                       &IsInline, PrevNS);
10787   }
10788 
10789   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10790                                                  StartLoc, Loc, II, PrevNS);
10791   if (IsInvalid)
10792     Namespc->setInvalidDecl();
10793 
10794   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10795   AddPragmaAttributes(DeclRegionScope, Namespc);
10796 
10797   // FIXME: Should we be merging attributes?
10798   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10799     PushNamespaceVisibilityAttr(Attr, Loc);
10800 
10801   if (IsStd)
10802     StdNamespace = Namespc;
10803   if (AddToKnown)
10804     KnownNamespaces[Namespc] = false;
10805 
10806   if (II) {
10807     PushOnScopeChains(Namespc, DeclRegionScope);
10808   } else {
10809     // Link the anonymous namespace into its parent.
10810     DeclContext *Parent = CurContext->getRedeclContext();
10811     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10812       TU->setAnonymousNamespace(Namespc);
10813     } else {
10814       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10815     }
10816 
10817     CurContext->addDecl(Namespc);
10818 
10819     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10820     //   behaves as if it were replaced by
10821     //     namespace unique { /* empty body */ }
10822     //     using namespace unique;
10823     //     namespace unique { namespace-body }
10824     //   where all occurrences of 'unique' in a translation unit are
10825     //   replaced by the same identifier and this identifier differs
10826     //   from all other identifiers in the entire program.
10827 
10828     // We just create the namespace with an empty name and then add an
10829     // implicit using declaration, just like the standard suggests.
10830     //
10831     // CodeGen enforces the "universally unique" aspect by giving all
10832     // declarations semantically contained within an anonymous
10833     // namespace internal linkage.
10834 
10835     if (!PrevNS) {
10836       UD = UsingDirectiveDecl::Create(Context, Parent,
10837                                       /* 'using' */ LBrace,
10838                                       /* 'namespace' */ SourceLocation(),
10839                                       /* qualifier */ NestedNameSpecifierLoc(),
10840                                       /* identifier */ SourceLocation(),
10841                                       Namespc,
10842                                       /* Ancestor */ Parent);
10843       UD->setImplicit();
10844       Parent->addDecl(UD);
10845     }
10846   }
10847 
10848   ActOnDocumentableDecl(Namespc);
10849 
10850   // Although we could have an invalid decl (i.e. the namespace name is a
10851   // redefinition), push it as current DeclContext and try to continue parsing.
10852   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10853   // for the namespace has the declarations that showed up in that particular
10854   // namespace definition.
10855   PushDeclContext(NamespcScope, Namespc);
10856   return Namespc;
10857 }
10858 
10859 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10860 /// is a namespace alias, returns the namespace it points to.
10861 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10862   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10863     return AD->getNamespace();
10864   return dyn_cast_or_null<NamespaceDecl>(D);
10865 }
10866 
10867 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10868 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10869 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10870   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10871   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10872   Namespc->setRBraceLoc(RBrace);
10873   PopDeclContext();
10874   if (Namespc->hasAttr<VisibilityAttr>())
10875     PopPragmaVisibility(true, RBrace);
10876   // If this namespace contains an export-declaration, export it now.
10877   if (DeferredExportedNamespaces.erase(Namespc))
10878     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10879 }
10880 
10881 CXXRecordDecl *Sema::getStdBadAlloc() const {
10882   return cast_or_null<CXXRecordDecl>(
10883                                   StdBadAlloc.get(Context.getExternalSource()));
10884 }
10885 
10886 EnumDecl *Sema::getStdAlignValT() const {
10887   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10888 }
10889 
10890 NamespaceDecl *Sema::getStdNamespace() const {
10891   return cast_or_null<NamespaceDecl>(
10892                                  StdNamespace.get(Context.getExternalSource()));
10893 }
10894 
10895 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10896   if (!StdExperimentalNamespaceCache) {
10897     if (auto Std = getStdNamespace()) {
10898       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10899                           SourceLocation(), LookupNamespaceName);
10900       if (!LookupQualifiedName(Result, Std) ||
10901           !(StdExperimentalNamespaceCache =
10902                 Result.getAsSingle<NamespaceDecl>()))
10903         Result.suppressDiagnostics();
10904     }
10905   }
10906   return StdExperimentalNamespaceCache;
10907 }
10908 
10909 namespace {
10910 
10911 enum UnsupportedSTLSelect {
10912   USS_InvalidMember,
10913   USS_MissingMember,
10914   USS_NonTrivial,
10915   USS_Other
10916 };
10917 
10918 struct InvalidSTLDiagnoser {
10919   Sema &S;
10920   SourceLocation Loc;
10921   QualType TyForDiags;
10922 
10923   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
10924                       const VarDecl *VD = nullptr) {
10925     {
10926       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
10927                << TyForDiags << ((int)Sel);
10928       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
10929         assert(!Name.empty());
10930         D << Name;
10931       }
10932     }
10933     if (Sel == USS_InvalidMember) {
10934       S.Diag(VD->getLocation(), diag::note_var_declared_here)
10935           << VD << VD->getSourceRange();
10936     }
10937     return QualType();
10938   }
10939 };
10940 } // namespace
10941 
10942 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
10943                                            SourceLocation Loc,
10944                                            ComparisonCategoryUsage Usage) {
10945   assert(getLangOpts().CPlusPlus &&
10946          "Looking for comparison category type outside of C++.");
10947 
10948   // Use an elaborated type for diagnostics which has a name containing the
10949   // prepended 'std' namespace but not any inline namespace names.
10950   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
10951     auto *NNS =
10952         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
10953     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
10954   };
10955 
10956   // Check if we've already successfully checked the comparison category type
10957   // before. If so, skip checking it again.
10958   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
10959   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
10960     // The only thing we need to check is that the type has a reachable
10961     // definition in the current context.
10962     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
10963       return QualType();
10964 
10965     return Info->getType();
10966   }
10967 
10968   // If lookup failed
10969   if (!Info) {
10970     std::string NameForDiags = "std::";
10971     NameForDiags += ComparisonCategories::getCategoryString(Kind);
10972     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
10973         << NameForDiags << (int)Usage;
10974     return QualType();
10975   }
10976 
10977   assert(Info->Kind == Kind);
10978   assert(Info->Record);
10979 
10980   // Update the Record decl in case we encountered a forward declaration on our
10981   // first pass. FIXME: This is a bit of a hack.
10982   if (Info->Record->hasDefinition())
10983     Info->Record = Info->Record->getDefinition();
10984 
10985   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
10986     return QualType();
10987 
10988   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
10989 
10990   if (!Info->Record->isTriviallyCopyable())
10991     return UnsupportedSTLError(USS_NonTrivial);
10992 
10993   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
10994     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
10995     // Tolerate empty base classes.
10996     if (Base->isEmpty())
10997       continue;
10998     // Reject STL implementations which have at least one non-empty base.
10999     return UnsupportedSTLError();
11000   }
11001 
11002   // Check that the STL has implemented the types using a single integer field.
11003   // This expectation allows better codegen for builtin operators. We require:
11004   //   (1) The class has exactly one field.
11005   //   (2) The field is an integral or enumeration type.
11006   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11007   if (std::distance(FIt, FEnd) != 1 ||
11008       !FIt->getType()->isIntegralOrEnumerationType()) {
11009     return UnsupportedSTLError();
11010   }
11011 
11012   // Build each of the require values and store them in Info.
11013   for (ComparisonCategoryResult CCR :
11014        ComparisonCategories::getPossibleResultsForType(Kind)) {
11015     StringRef MemName = ComparisonCategories::getResultString(CCR);
11016     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11017 
11018     if (!ValInfo)
11019       return UnsupportedSTLError(USS_MissingMember, MemName);
11020 
11021     VarDecl *VD = ValInfo->VD;
11022     assert(VD && "should not be null!");
11023 
11024     // Attempt to diagnose reasons why the STL definition of this type
11025     // might be foobar, including it failing to be a constant expression.
11026     // TODO Handle more ways the lookup or result can be invalid.
11027     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11028         !VD->checkInitIsICE())
11029       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11030 
11031     // Attempt to evaluate the var decl as a constant expression and extract
11032     // the value of its first field as a ICE. If this fails, the STL
11033     // implementation is not supported.
11034     if (!ValInfo->hasValidIntValue())
11035       return UnsupportedSTLError();
11036 
11037     MarkVariableReferenced(Loc, VD);
11038   }
11039 
11040   // We've successfully built the required types and expressions. Update
11041   // the cache and return the newly cached value.
11042   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11043   return Info->getType();
11044 }
11045 
11046 /// Retrieve the special "std" namespace, which may require us to
11047 /// implicitly define the namespace.
11048 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11049   if (!StdNamespace) {
11050     // The "std" namespace has not yet been defined, so build one implicitly.
11051     StdNamespace = NamespaceDecl::Create(Context,
11052                                          Context.getTranslationUnitDecl(),
11053                                          /*Inline=*/false,
11054                                          SourceLocation(), SourceLocation(),
11055                                          &PP.getIdentifierTable().get("std"),
11056                                          /*PrevDecl=*/nullptr);
11057     getStdNamespace()->setImplicit(true);
11058   }
11059 
11060   return getStdNamespace();
11061 }
11062 
11063 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11064   assert(getLangOpts().CPlusPlus &&
11065          "Looking for std::initializer_list outside of C++.");
11066 
11067   // We're looking for implicit instantiations of
11068   // template <typename E> class std::initializer_list.
11069 
11070   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11071     return false;
11072 
11073   ClassTemplateDecl *Template = nullptr;
11074   const TemplateArgument *Arguments = nullptr;
11075 
11076   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11077 
11078     ClassTemplateSpecializationDecl *Specialization =
11079         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11080     if (!Specialization)
11081       return false;
11082 
11083     Template = Specialization->getSpecializedTemplate();
11084     Arguments = Specialization->getTemplateArgs().data();
11085   } else if (const TemplateSpecializationType *TST =
11086                  Ty->getAs<TemplateSpecializationType>()) {
11087     Template = dyn_cast_or_null<ClassTemplateDecl>(
11088         TST->getTemplateName().getAsTemplateDecl());
11089     Arguments = TST->getArgs();
11090   }
11091   if (!Template)
11092     return false;
11093 
11094   if (!StdInitializerList) {
11095     // Haven't recognized std::initializer_list yet, maybe this is it.
11096     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11097     if (TemplateClass->getIdentifier() !=
11098             &PP.getIdentifierTable().get("initializer_list") ||
11099         !getStdNamespace()->InEnclosingNamespaceSetOf(
11100             TemplateClass->getDeclContext()))
11101       return false;
11102     // This is a template called std::initializer_list, but is it the right
11103     // template?
11104     TemplateParameterList *Params = Template->getTemplateParameters();
11105     if (Params->getMinRequiredArguments() != 1)
11106       return false;
11107     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11108       return false;
11109 
11110     // It's the right template.
11111     StdInitializerList = Template;
11112   }
11113 
11114   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11115     return false;
11116 
11117   // This is an instance of std::initializer_list. Find the argument type.
11118   if (Element)
11119     *Element = Arguments[0].getAsType();
11120   return true;
11121 }
11122 
11123 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11124   NamespaceDecl *Std = S.getStdNamespace();
11125   if (!Std) {
11126     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11127     return nullptr;
11128   }
11129 
11130   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11131                       Loc, Sema::LookupOrdinaryName);
11132   if (!S.LookupQualifiedName(Result, Std)) {
11133     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11134     return nullptr;
11135   }
11136   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11137   if (!Template) {
11138     Result.suppressDiagnostics();
11139     // We found something weird. Complain about the first thing we found.
11140     NamedDecl *Found = *Result.begin();
11141     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11142     return nullptr;
11143   }
11144 
11145   // We found some template called std::initializer_list. Now verify that it's
11146   // correct.
11147   TemplateParameterList *Params = Template->getTemplateParameters();
11148   if (Params->getMinRequiredArguments() != 1 ||
11149       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11150     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11151     return nullptr;
11152   }
11153 
11154   return Template;
11155 }
11156 
11157 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11158   if (!StdInitializerList) {
11159     StdInitializerList = LookupStdInitializerList(*this, Loc);
11160     if (!StdInitializerList)
11161       return QualType();
11162   }
11163 
11164   TemplateArgumentListInfo Args(Loc, Loc);
11165   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11166                                        Context.getTrivialTypeSourceInfo(Element,
11167                                                                         Loc)));
11168   return Context.getCanonicalType(
11169       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11170 }
11171 
11172 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11173   // C++ [dcl.init.list]p2:
11174   //   A constructor is an initializer-list constructor if its first parameter
11175   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11176   //   std::initializer_list<E> for some type E, and either there are no other
11177   //   parameters or else all other parameters have default arguments.
11178   if (Ctor->getNumParams() < 1 ||
11179       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
11180     return false;
11181 
11182   QualType ArgType = Ctor->getParamDecl(0)->getType();
11183   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11184     ArgType = RT->getPointeeType().getUnqualifiedType();
11185 
11186   return isStdInitializerList(ArgType, nullptr);
11187 }
11188 
11189 /// Determine whether a using statement is in a context where it will be
11190 /// apply in all contexts.
11191 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11192   switch (CurContext->getDeclKind()) {
11193     case Decl::TranslationUnit:
11194       return true;
11195     case Decl::LinkageSpec:
11196       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11197     default:
11198       return false;
11199   }
11200 }
11201 
11202 namespace {
11203 
11204 // Callback to only accept typo corrections that are namespaces.
11205 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11206 public:
11207   bool ValidateCandidate(const TypoCorrection &candidate) override {
11208     if (NamedDecl *ND = candidate.getCorrectionDecl())
11209       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11210     return false;
11211   }
11212 
11213   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11214     return std::make_unique<NamespaceValidatorCCC>(*this);
11215   }
11216 };
11217 
11218 }
11219 
11220 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11221                                        CXXScopeSpec &SS,
11222                                        SourceLocation IdentLoc,
11223                                        IdentifierInfo *Ident) {
11224   R.clear();
11225   NamespaceValidatorCCC CCC{};
11226   if (TypoCorrection Corrected =
11227           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11228                         Sema::CTK_ErrorRecovery)) {
11229     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11230       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11231       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11232                               Ident->getName().equals(CorrectedStr);
11233       S.diagnoseTypo(Corrected,
11234                      S.PDiag(diag::err_using_directive_member_suggest)
11235                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11236                      S.PDiag(diag::note_namespace_defined_here));
11237     } else {
11238       S.diagnoseTypo(Corrected,
11239                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11240                      S.PDiag(diag::note_namespace_defined_here));
11241     }
11242     R.addDecl(Corrected.getFoundDecl());
11243     return true;
11244   }
11245   return false;
11246 }
11247 
11248 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11249                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11250                                 SourceLocation IdentLoc,
11251                                 IdentifierInfo *NamespcName,
11252                                 const ParsedAttributesView &AttrList) {
11253   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11254   assert(NamespcName && "Invalid NamespcName.");
11255   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11256 
11257   // This can only happen along a recovery path.
11258   while (S->isTemplateParamScope())
11259     S = S->getParent();
11260   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11261 
11262   UsingDirectiveDecl *UDir = nullptr;
11263   NestedNameSpecifier *Qualifier = nullptr;
11264   if (SS.isSet())
11265     Qualifier = SS.getScopeRep();
11266 
11267   // Lookup namespace name.
11268   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11269   LookupParsedName(R, S, &SS);
11270   if (R.isAmbiguous())
11271     return nullptr;
11272 
11273   if (R.empty()) {
11274     R.clear();
11275     // Allow "using namespace std;" or "using namespace ::std;" even if
11276     // "std" hasn't been defined yet, for GCC compatibility.
11277     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11278         NamespcName->isStr("std")) {
11279       Diag(IdentLoc, diag::ext_using_undefined_std);
11280       R.addDecl(getOrCreateStdNamespace());
11281       R.resolveKind();
11282     }
11283     // Otherwise, attempt typo correction.
11284     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11285   }
11286 
11287   if (!R.empty()) {
11288     NamedDecl *Named = R.getRepresentativeDecl();
11289     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11290     assert(NS && "expected namespace decl");
11291 
11292     // The use of a nested name specifier may trigger deprecation warnings.
11293     DiagnoseUseOfDecl(Named, IdentLoc);
11294 
11295     // C++ [namespace.udir]p1:
11296     //   A using-directive specifies that the names in the nominated
11297     //   namespace can be used in the scope in which the
11298     //   using-directive appears after the using-directive. During
11299     //   unqualified name lookup (3.4.1), the names appear as if they
11300     //   were declared in the nearest enclosing namespace which
11301     //   contains both the using-directive and the nominated
11302     //   namespace. [Note: in this context, "contains" means "contains
11303     //   directly or indirectly". ]
11304 
11305     // Find enclosing context containing both using-directive and
11306     // nominated namespace.
11307     DeclContext *CommonAncestor = NS;
11308     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11309       CommonAncestor = CommonAncestor->getParent();
11310 
11311     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11312                                       SS.getWithLocInContext(Context),
11313                                       IdentLoc, Named, CommonAncestor);
11314 
11315     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11316         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11317       Diag(IdentLoc, diag::warn_using_directive_in_header);
11318     }
11319 
11320     PushUsingDirective(S, UDir);
11321   } else {
11322     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11323   }
11324 
11325   if (UDir)
11326     ProcessDeclAttributeList(S, UDir, AttrList);
11327 
11328   return UDir;
11329 }
11330 
11331 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11332   // If the scope has an associated entity and the using directive is at
11333   // namespace or translation unit scope, add the UsingDirectiveDecl into
11334   // its lookup structure so qualified name lookup can find it.
11335   DeclContext *Ctx = S->getEntity();
11336   if (Ctx && !Ctx->isFunctionOrMethod())
11337     Ctx->addDecl(UDir);
11338   else
11339     // Otherwise, it is at block scope. The using-directives will affect lookup
11340     // only to the end of the scope.
11341     S->PushUsingDirective(UDir);
11342 }
11343 
11344 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11345                                   SourceLocation UsingLoc,
11346                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11347                                   UnqualifiedId &Name,
11348                                   SourceLocation EllipsisLoc,
11349                                   const ParsedAttributesView &AttrList) {
11350   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11351 
11352   if (SS.isEmpty()) {
11353     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11354     return nullptr;
11355   }
11356 
11357   switch (Name.getKind()) {
11358   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11359   case UnqualifiedIdKind::IK_Identifier:
11360   case UnqualifiedIdKind::IK_OperatorFunctionId:
11361   case UnqualifiedIdKind::IK_LiteralOperatorId:
11362   case UnqualifiedIdKind::IK_ConversionFunctionId:
11363     break;
11364 
11365   case UnqualifiedIdKind::IK_ConstructorName:
11366   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11367     // C++11 inheriting constructors.
11368     Diag(Name.getBeginLoc(),
11369          getLangOpts().CPlusPlus11
11370              ? diag::warn_cxx98_compat_using_decl_constructor
11371              : diag::err_using_decl_constructor)
11372         << SS.getRange();
11373 
11374     if (getLangOpts().CPlusPlus11) break;
11375 
11376     return nullptr;
11377 
11378   case UnqualifiedIdKind::IK_DestructorName:
11379     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11380     return nullptr;
11381 
11382   case UnqualifiedIdKind::IK_TemplateId:
11383     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11384         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11385     return nullptr;
11386 
11387   case UnqualifiedIdKind::IK_DeductionGuideName:
11388     llvm_unreachable("cannot parse qualified deduction guide name");
11389   }
11390 
11391   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11392   DeclarationName TargetName = TargetNameInfo.getName();
11393   if (!TargetName)
11394     return nullptr;
11395 
11396   // Warn about access declarations.
11397   if (UsingLoc.isInvalid()) {
11398     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11399                                  ? diag::err_access_decl
11400                                  : diag::warn_access_decl_deprecated)
11401         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11402   }
11403 
11404   if (EllipsisLoc.isInvalid()) {
11405     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11406         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11407       return nullptr;
11408   } else {
11409     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11410         !TargetNameInfo.containsUnexpandedParameterPack()) {
11411       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11412         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11413       EllipsisLoc = SourceLocation();
11414     }
11415   }
11416 
11417   NamedDecl *UD =
11418       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11419                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11420                             /*IsInstantiation*/false);
11421   if (UD)
11422     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11423 
11424   return UD;
11425 }
11426 
11427 /// Determine whether a using declaration considers the given
11428 /// declarations as "equivalent", e.g., if they are redeclarations of
11429 /// the same entity or are both typedefs of the same type.
11430 static bool
11431 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11432   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11433     return true;
11434 
11435   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11436     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11437       return Context.hasSameType(TD1->getUnderlyingType(),
11438                                  TD2->getUnderlyingType());
11439 
11440   return false;
11441 }
11442 
11443 
11444 /// Determines whether to create a using shadow decl for a particular
11445 /// decl, given the set of decls existing prior to this using lookup.
11446 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11447                                 const LookupResult &Previous,
11448                                 UsingShadowDecl *&PrevShadow) {
11449   // Diagnose finding a decl which is not from a base class of the
11450   // current class.  We do this now because there are cases where this
11451   // function will silently decide not to build a shadow decl, which
11452   // will pre-empt further diagnostics.
11453   //
11454   // We don't need to do this in C++11 because we do the check once on
11455   // the qualifier.
11456   //
11457   // FIXME: diagnose the following if we care enough:
11458   //   struct A { int foo; };
11459   //   struct B : A { using A::foo; };
11460   //   template <class T> struct C : A {};
11461   //   template <class T> struct D : C<T> { using B::foo; } // <---
11462   // This is invalid (during instantiation) in C++03 because B::foo
11463   // resolves to the using decl in B, which is not a base class of D<T>.
11464   // We can't diagnose it immediately because C<T> is an unknown
11465   // specialization.  The UsingShadowDecl in D<T> then points directly
11466   // to A::foo, which will look well-formed when we instantiate.
11467   // The right solution is to not collapse the shadow-decl chain.
11468   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11469     DeclContext *OrigDC = Orig->getDeclContext();
11470 
11471     // Handle enums and anonymous structs.
11472     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11473     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11474     while (OrigRec->isAnonymousStructOrUnion())
11475       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11476 
11477     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11478       if (OrigDC == CurContext) {
11479         Diag(Using->getLocation(),
11480              diag::err_using_decl_nested_name_specifier_is_current_class)
11481           << Using->getQualifierLoc().getSourceRange();
11482         Diag(Orig->getLocation(), diag::note_using_decl_target);
11483         Using->setInvalidDecl();
11484         return true;
11485       }
11486 
11487       Diag(Using->getQualifierLoc().getBeginLoc(),
11488            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11489         << Using->getQualifier()
11490         << cast<CXXRecordDecl>(CurContext)
11491         << Using->getQualifierLoc().getSourceRange();
11492       Diag(Orig->getLocation(), diag::note_using_decl_target);
11493       Using->setInvalidDecl();
11494       return true;
11495     }
11496   }
11497 
11498   if (Previous.empty()) return false;
11499 
11500   NamedDecl *Target = Orig;
11501   if (isa<UsingShadowDecl>(Target))
11502     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11503 
11504   // If the target happens to be one of the previous declarations, we
11505   // don't have a conflict.
11506   //
11507   // FIXME: but we might be increasing its access, in which case we
11508   // should redeclare it.
11509   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11510   bool FoundEquivalentDecl = false;
11511   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11512          I != E; ++I) {
11513     NamedDecl *D = (*I)->getUnderlyingDecl();
11514     // We can have UsingDecls in our Previous results because we use the same
11515     // LookupResult for checking whether the UsingDecl itself is a valid
11516     // redeclaration.
11517     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11518       continue;
11519 
11520     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11521       // C++ [class.mem]p19:
11522       //   If T is the name of a class, then [every named member other than
11523       //   a non-static data member] shall have a name different from T
11524       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11525           !isa<IndirectFieldDecl>(Target) &&
11526           !isa<UnresolvedUsingValueDecl>(Target) &&
11527           DiagnoseClassNameShadow(
11528               CurContext,
11529               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11530         return true;
11531     }
11532 
11533     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11534       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11535         PrevShadow = Shadow;
11536       FoundEquivalentDecl = true;
11537     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11538       // We don't conflict with an existing using shadow decl of an equivalent
11539       // declaration, but we're not a redeclaration of it.
11540       FoundEquivalentDecl = true;
11541     }
11542 
11543     if (isVisible(D))
11544       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11545   }
11546 
11547   if (FoundEquivalentDecl)
11548     return false;
11549 
11550   if (FunctionDecl *FD = Target->getAsFunction()) {
11551     NamedDecl *OldDecl = nullptr;
11552     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11553                           /*IsForUsingDecl*/ true)) {
11554     case Ovl_Overload:
11555       return false;
11556 
11557     case Ovl_NonFunction:
11558       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11559       break;
11560 
11561     // We found a decl with the exact signature.
11562     case Ovl_Match:
11563       // If we're in a record, we want to hide the target, so we
11564       // return true (without a diagnostic) to tell the caller not to
11565       // build a shadow decl.
11566       if (CurContext->isRecord())
11567         return true;
11568 
11569       // If we're not in a record, this is an error.
11570       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11571       break;
11572     }
11573 
11574     Diag(Target->getLocation(), diag::note_using_decl_target);
11575     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11576     Using->setInvalidDecl();
11577     return true;
11578   }
11579 
11580   // Target is not a function.
11581 
11582   if (isa<TagDecl>(Target)) {
11583     // No conflict between a tag and a non-tag.
11584     if (!Tag) return false;
11585 
11586     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11587     Diag(Target->getLocation(), diag::note_using_decl_target);
11588     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11589     Using->setInvalidDecl();
11590     return true;
11591   }
11592 
11593   // No conflict between a tag and a non-tag.
11594   if (!NonTag) return false;
11595 
11596   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11597   Diag(Target->getLocation(), diag::note_using_decl_target);
11598   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11599   Using->setInvalidDecl();
11600   return true;
11601 }
11602 
11603 /// Determine whether a direct base class is a virtual base class.
11604 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11605   if (!Derived->getNumVBases())
11606     return false;
11607   for (auto &B : Derived->bases())
11608     if (B.getType()->getAsCXXRecordDecl() == Base)
11609       return B.isVirtual();
11610   llvm_unreachable("not a direct base class");
11611 }
11612 
11613 /// Builds a shadow declaration corresponding to a 'using' declaration.
11614 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11615                                             UsingDecl *UD,
11616                                             NamedDecl *Orig,
11617                                             UsingShadowDecl *PrevDecl) {
11618   // If we resolved to another shadow declaration, just coalesce them.
11619   NamedDecl *Target = Orig;
11620   if (isa<UsingShadowDecl>(Target)) {
11621     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11622     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11623   }
11624 
11625   NamedDecl *NonTemplateTarget = Target;
11626   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11627     NonTemplateTarget = TargetTD->getTemplatedDecl();
11628 
11629   UsingShadowDecl *Shadow;
11630   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11631     bool IsVirtualBase =
11632         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11633                             UD->getQualifier()->getAsRecordDecl());
11634     Shadow = ConstructorUsingShadowDecl::Create(
11635         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11636   } else {
11637     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11638                                      Target);
11639   }
11640   UD->addShadowDecl(Shadow);
11641 
11642   Shadow->setAccess(UD->getAccess());
11643   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11644     Shadow->setInvalidDecl();
11645 
11646   Shadow->setPreviousDecl(PrevDecl);
11647 
11648   if (S)
11649     PushOnScopeChains(Shadow, S);
11650   else
11651     CurContext->addDecl(Shadow);
11652 
11653 
11654   return Shadow;
11655 }
11656 
11657 /// Hides a using shadow declaration.  This is required by the current
11658 /// using-decl implementation when a resolvable using declaration in a
11659 /// class is followed by a declaration which would hide or override
11660 /// one or more of the using decl's targets; for example:
11661 ///
11662 ///   struct Base { void foo(int); };
11663 ///   struct Derived : Base {
11664 ///     using Base::foo;
11665 ///     void foo(int);
11666 ///   };
11667 ///
11668 /// The governing language is C++03 [namespace.udecl]p12:
11669 ///
11670 ///   When a using-declaration brings names from a base class into a
11671 ///   derived class scope, member functions in the derived class
11672 ///   override and/or hide member functions with the same name and
11673 ///   parameter types in a base class (rather than conflicting).
11674 ///
11675 /// There are two ways to implement this:
11676 ///   (1) optimistically create shadow decls when they're not hidden
11677 ///       by existing declarations, or
11678 ///   (2) don't create any shadow decls (or at least don't make them
11679 ///       visible) until we've fully parsed/instantiated the class.
11680 /// The problem with (1) is that we might have to retroactively remove
11681 /// a shadow decl, which requires several O(n) operations because the
11682 /// decl structures are (very reasonably) not designed for removal.
11683 /// (2) avoids this but is very fiddly and phase-dependent.
11684 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11685   if (Shadow->getDeclName().getNameKind() ==
11686         DeclarationName::CXXConversionFunctionName)
11687     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11688 
11689   // Remove it from the DeclContext...
11690   Shadow->getDeclContext()->removeDecl(Shadow);
11691 
11692   // ...and the scope, if applicable...
11693   if (S) {
11694     S->RemoveDecl(Shadow);
11695     IdResolver.RemoveDecl(Shadow);
11696   }
11697 
11698   // ...and the using decl.
11699   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11700 
11701   // TODO: complain somehow if Shadow was used.  It shouldn't
11702   // be possible for this to happen, because...?
11703 }
11704 
11705 /// Find the base specifier for a base class with the given type.
11706 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11707                                                 QualType DesiredBase,
11708                                                 bool &AnyDependentBases) {
11709   // Check whether the named type is a direct base class.
11710   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11711     .getUnqualifiedType();
11712   for (auto &Base : Derived->bases()) {
11713     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11714     if (CanonicalDesiredBase == BaseType)
11715       return &Base;
11716     if (BaseType->isDependentType())
11717       AnyDependentBases = true;
11718   }
11719   return nullptr;
11720 }
11721 
11722 namespace {
11723 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11724 public:
11725   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11726                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11727       : HasTypenameKeyword(HasTypenameKeyword),
11728         IsInstantiation(IsInstantiation), OldNNS(NNS),
11729         RequireMemberOf(RequireMemberOf) {}
11730 
11731   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11732     NamedDecl *ND = Candidate.getCorrectionDecl();
11733 
11734     // Keywords are not valid here.
11735     if (!ND || isa<NamespaceDecl>(ND))
11736       return false;
11737 
11738     // Completely unqualified names are invalid for a 'using' declaration.
11739     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11740       return false;
11741 
11742     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11743     // reject.
11744 
11745     if (RequireMemberOf) {
11746       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11747       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11748         // No-one ever wants a using-declaration to name an injected-class-name
11749         // of a base class, unless they're declaring an inheriting constructor.
11750         ASTContext &Ctx = ND->getASTContext();
11751         if (!Ctx.getLangOpts().CPlusPlus11)
11752           return false;
11753         QualType FoundType = Ctx.getRecordType(FoundRecord);
11754 
11755         // Check that the injected-class-name is named as a member of its own
11756         // type; we don't want to suggest 'using Derived::Base;', since that
11757         // means something else.
11758         NestedNameSpecifier *Specifier =
11759             Candidate.WillReplaceSpecifier()
11760                 ? Candidate.getCorrectionSpecifier()
11761                 : OldNNS;
11762         if (!Specifier->getAsType() ||
11763             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11764           return false;
11765 
11766         // Check that this inheriting constructor declaration actually names a
11767         // direct base class of the current class.
11768         bool AnyDependentBases = false;
11769         if (!findDirectBaseWithType(RequireMemberOf,
11770                                     Ctx.getRecordType(FoundRecord),
11771                                     AnyDependentBases) &&
11772             !AnyDependentBases)
11773           return false;
11774       } else {
11775         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11776         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11777           return false;
11778 
11779         // FIXME: Check that the base class member is accessible?
11780       }
11781     } else {
11782       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11783       if (FoundRecord && FoundRecord->isInjectedClassName())
11784         return false;
11785     }
11786 
11787     if (isa<TypeDecl>(ND))
11788       return HasTypenameKeyword || !IsInstantiation;
11789 
11790     return !HasTypenameKeyword;
11791   }
11792 
11793   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11794     return std::make_unique<UsingValidatorCCC>(*this);
11795   }
11796 
11797 private:
11798   bool HasTypenameKeyword;
11799   bool IsInstantiation;
11800   NestedNameSpecifier *OldNNS;
11801   CXXRecordDecl *RequireMemberOf;
11802 };
11803 } // end anonymous namespace
11804 
11805 /// Builds a using declaration.
11806 ///
11807 /// \param IsInstantiation - Whether this call arises from an
11808 ///   instantiation of an unresolved using declaration.  We treat
11809 ///   the lookup differently for these declarations.
11810 NamedDecl *Sema::BuildUsingDeclaration(
11811     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11812     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11813     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11814     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11815   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11816   SourceLocation IdentLoc = NameInfo.getLoc();
11817   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11818 
11819   // FIXME: We ignore attributes for now.
11820 
11821   // For an inheriting constructor declaration, the name of the using
11822   // declaration is the name of a constructor in this class, not in the
11823   // base class.
11824   DeclarationNameInfo UsingName = NameInfo;
11825   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11826     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11827       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11828           Context.getCanonicalType(Context.getRecordType(RD))));
11829 
11830   // Do the redeclaration lookup in the current scope.
11831   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11832                         ForVisibleRedeclaration);
11833   Previous.setHideTags(false);
11834   if (S) {
11835     LookupName(Previous, S);
11836 
11837     // It is really dumb that we have to do this.
11838     LookupResult::Filter F = Previous.makeFilter();
11839     while (F.hasNext()) {
11840       NamedDecl *D = F.next();
11841       if (!isDeclInScope(D, CurContext, S))
11842         F.erase();
11843       // If we found a local extern declaration that's not ordinarily visible,
11844       // and this declaration is being added to a non-block scope, ignore it.
11845       // We're only checking for scope conflicts here, not also for violations
11846       // of the linkage rules.
11847       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11848                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11849         F.erase();
11850     }
11851     F.done();
11852   } else {
11853     assert(IsInstantiation && "no scope in non-instantiation");
11854     if (CurContext->isRecord())
11855       LookupQualifiedName(Previous, CurContext);
11856     else {
11857       // No redeclaration check is needed here; in non-member contexts we
11858       // diagnosed all possible conflicts with other using-declarations when
11859       // building the template:
11860       //
11861       // For a dependent non-type using declaration, the only valid case is
11862       // if we instantiate to a single enumerator. We check for conflicts
11863       // between shadow declarations we introduce, and we check in the template
11864       // definition for conflicts between a non-type using declaration and any
11865       // other declaration, which together covers all cases.
11866       //
11867       // A dependent typename using declaration will never successfully
11868       // instantiate, since it will always name a class member, so we reject
11869       // that in the template definition.
11870     }
11871   }
11872 
11873   // Check for invalid redeclarations.
11874   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11875                                   SS, IdentLoc, Previous))
11876     return nullptr;
11877 
11878   // Check for bad qualifiers.
11879   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11880                               IdentLoc))
11881     return nullptr;
11882 
11883   DeclContext *LookupContext = computeDeclContext(SS);
11884   NamedDecl *D;
11885   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11886   if (!LookupContext || EllipsisLoc.isValid()) {
11887     if (HasTypenameKeyword) {
11888       // FIXME: not all declaration name kinds are legal here
11889       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11890                                               UsingLoc, TypenameLoc,
11891                                               QualifierLoc,
11892                                               IdentLoc, NameInfo.getName(),
11893                                               EllipsisLoc);
11894     } else {
11895       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11896                                            QualifierLoc, NameInfo, EllipsisLoc);
11897     }
11898     D->setAccess(AS);
11899     CurContext->addDecl(D);
11900     return D;
11901   }
11902 
11903   auto Build = [&](bool Invalid) {
11904     UsingDecl *UD =
11905         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11906                           UsingName, HasTypenameKeyword);
11907     UD->setAccess(AS);
11908     CurContext->addDecl(UD);
11909     UD->setInvalidDecl(Invalid);
11910     return UD;
11911   };
11912   auto BuildInvalid = [&]{ return Build(true); };
11913   auto BuildValid = [&]{ return Build(false); };
11914 
11915   if (RequireCompleteDeclContext(SS, LookupContext))
11916     return BuildInvalid();
11917 
11918   // Look up the target name.
11919   LookupResult R(*this, NameInfo, LookupOrdinaryName);
11920 
11921   // Unlike most lookups, we don't always want to hide tag
11922   // declarations: tag names are visible through the using declaration
11923   // even if hidden by ordinary names, *except* in a dependent context
11924   // where it's important for the sanity of two-phase lookup.
11925   if (!IsInstantiation)
11926     R.setHideTags(false);
11927 
11928   // For the purposes of this lookup, we have a base object type
11929   // equal to that of the current context.
11930   if (CurContext->isRecord()) {
11931     R.setBaseObjectType(
11932                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
11933   }
11934 
11935   LookupQualifiedName(R, LookupContext);
11936 
11937   // Try to correct typos if possible. If constructor name lookup finds no
11938   // results, that means the named class has no explicit constructors, and we
11939   // suppressed declaring implicit ones (probably because it's dependent or
11940   // invalid).
11941   if (R.empty() &&
11942       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
11943     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
11944     // it will believe that glibc provides a ::gets in cases where it does not,
11945     // and will try to pull it into namespace std with a using-declaration.
11946     // Just ignore the using-declaration in that case.
11947     auto *II = NameInfo.getName().getAsIdentifierInfo();
11948     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
11949         CurContext->isStdNamespace() &&
11950         isa<TranslationUnitDecl>(LookupContext) &&
11951         getSourceManager().isInSystemHeader(UsingLoc))
11952       return nullptr;
11953     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
11954                           dyn_cast<CXXRecordDecl>(CurContext));
11955     if (TypoCorrection Corrected =
11956             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
11957                         CTK_ErrorRecovery)) {
11958       // We reject candidates where DroppedSpecifier == true, hence the
11959       // literal '0' below.
11960       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
11961                                 << NameInfo.getName() << LookupContext << 0
11962                                 << SS.getRange());
11963 
11964       // If we picked a correction with no attached Decl we can't do anything
11965       // useful with it, bail out.
11966       NamedDecl *ND = Corrected.getCorrectionDecl();
11967       if (!ND)
11968         return BuildInvalid();
11969 
11970       // If we corrected to an inheriting constructor, handle it as one.
11971       auto *RD = dyn_cast<CXXRecordDecl>(ND);
11972       if (RD && RD->isInjectedClassName()) {
11973         // The parent of the injected class name is the class itself.
11974         RD = cast<CXXRecordDecl>(RD->getParent());
11975 
11976         // Fix up the information we'll use to build the using declaration.
11977         if (Corrected.WillReplaceSpecifier()) {
11978           NestedNameSpecifierLocBuilder Builder;
11979           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
11980                               QualifierLoc.getSourceRange());
11981           QualifierLoc = Builder.getWithLocInContext(Context);
11982         }
11983 
11984         // In this case, the name we introduce is the name of a derived class
11985         // constructor.
11986         auto *CurClass = cast<CXXRecordDecl>(CurContext);
11987         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11988             Context.getCanonicalType(Context.getRecordType(CurClass))));
11989         UsingName.setNamedTypeInfo(nullptr);
11990         for (auto *Ctor : LookupConstructors(RD))
11991           R.addDecl(Ctor);
11992         R.resolveKind();
11993       } else {
11994         // FIXME: Pick up all the declarations if we found an overloaded
11995         // function.
11996         UsingName.setName(ND->getDeclName());
11997         R.addDecl(ND);
11998       }
11999     } else {
12000       Diag(IdentLoc, diag::err_no_member)
12001         << NameInfo.getName() << LookupContext << SS.getRange();
12002       return BuildInvalid();
12003     }
12004   }
12005 
12006   if (R.isAmbiguous())
12007     return BuildInvalid();
12008 
12009   if (HasTypenameKeyword) {
12010     // If we asked for a typename and got a non-type decl, error out.
12011     if (!R.getAsSingle<TypeDecl>()) {
12012       Diag(IdentLoc, diag::err_using_typename_non_type);
12013       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12014         Diag((*I)->getUnderlyingDecl()->getLocation(),
12015              diag::note_using_decl_target);
12016       return BuildInvalid();
12017     }
12018   } else {
12019     // If we asked for a non-typename and we got a type, error out,
12020     // but only if this is an instantiation of an unresolved using
12021     // decl.  Otherwise just silently find the type name.
12022     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12023       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12024       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12025       return BuildInvalid();
12026     }
12027   }
12028 
12029   // C++14 [namespace.udecl]p6:
12030   // A using-declaration shall not name a namespace.
12031   if (R.getAsSingle<NamespaceDecl>()) {
12032     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12033       << SS.getRange();
12034     return BuildInvalid();
12035   }
12036 
12037   // C++14 [namespace.udecl]p7:
12038   // A using-declaration shall not name a scoped enumerator.
12039   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12040     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12041       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12042         << SS.getRange();
12043       return BuildInvalid();
12044     }
12045   }
12046 
12047   UsingDecl *UD = BuildValid();
12048 
12049   // Some additional rules apply to inheriting constructors.
12050   if (UsingName.getName().getNameKind() ==
12051         DeclarationName::CXXConstructorName) {
12052     // Suppress access diagnostics; the access check is instead performed at the
12053     // point of use for an inheriting constructor.
12054     R.suppressDiagnostics();
12055     if (CheckInheritingConstructorUsingDecl(UD))
12056       return UD;
12057   }
12058 
12059   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12060     UsingShadowDecl *PrevDecl = nullptr;
12061     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12062       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12063   }
12064 
12065   return UD;
12066 }
12067 
12068 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12069                                     ArrayRef<NamedDecl *> Expansions) {
12070   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12071          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12072          isa<UsingPackDecl>(InstantiatedFrom));
12073 
12074   auto *UPD =
12075       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12076   UPD->setAccess(InstantiatedFrom->getAccess());
12077   CurContext->addDecl(UPD);
12078   return UPD;
12079 }
12080 
12081 /// Additional checks for a using declaration referring to a constructor name.
12082 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12083   assert(!UD->hasTypename() && "expecting a constructor name");
12084 
12085   const Type *SourceType = UD->getQualifier()->getAsType();
12086   assert(SourceType &&
12087          "Using decl naming constructor doesn't have type in scope spec.");
12088   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12089 
12090   // Check whether the named type is a direct base class.
12091   bool AnyDependentBases = false;
12092   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12093                                       AnyDependentBases);
12094   if (!Base && !AnyDependentBases) {
12095     Diag(UD->getUsingLoc(),
12096          diag::err_using_decl_constructor_not_in_direct_base)
12097       << UD->getNameInfo().getSourceRange()
12098       << QualType(SourceType, 0) << TargetClass;
12099     UD->setInvalidDecl();
12100     return true;
12101   }
12102 
12103   if (Base)
12104     Base->setInheritConstructors();
12105 
12106   return false;
12107 }
12108 
12109 /// Checks that the given using declaration is not an invalid
12110 /// redeclaration.  Note that this is checking only for the using decl
12111 /// itself, not for any ill-formedness among the UsingShadowDecls.
12112 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12113                                        bool HasTypenameKeyword,
12114                                        const CXXScopeSpec &SS,
12115                                        SourceLocation NameLoc,
12116                                        const LookupResult &Prev) {
12117   NestedNameSpecifier *Qual = SS.getScopeRep();
12118 
12119   // C++03 [namespace.udecl]p8:
12120   // C++0x [namespace.udecl]p10:
12121   //   A using-declaration is a declaration and can therefore be used
12122   //   repeatedly where (and only where) multiple declarations are
12123   //   allowed.
12124   //
12125   // That's in non-member contexts.
12126   if (!CurContext->getRedeclContext()->isRecord()) {
12127     // A dependent qualifier outside a class can only ever resolve to an
12128     // enumeration type. Therefore it conflicts with any other non-type
12129     // declaration in the same scope.
12130     // FIXME: How should we check for dependent type-type conflicts at block
12131     // scope?
12132     if (Qual->isDependent() && !HasTypenameKeyword) {
12133       for (auto *D : Prev) {
12134         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12135           bool OldCouldBeEnumerator =
12136               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12137           Diag(NameLoc,
12138                OldCouldBeEnumerator ? diag::err_redefinition
12139                                     : diag::err_redefinition_different_kind)
12140               << Prev.getLookupName();
12141           Diag(D->getLocation(), diag::note_previous_definition);
12142           return true;
12143         }
12144       }
12145     }
12146     return false;
12147   }
12148 
12149   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12150     NamedDecl *D = *I;
12151 
12152     bool DTypename;
12153     NestedNameSpecifier *DQual;
12154     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12155       DTypename = UD->hasTypename();
12156       DQual = UD->getQualifier();
12157     } else if (UnresolvedUsingValueDecl *UD
12158                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12159       DTypename = false;
12160       DQual = UD->getQualifier();
12161     } else if (UnresolvedUsingTypenameDecl *UD
12162                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12163       DTypename = true;
12164       DQual = UD->getQualifier();
12165     } else continue;
12166 
12167     // using decls differ if one says 'typename' and the other doesn't.
12168     // FIXME: non-dependent using decls?
12169     if (HasTypenameKeyword != DTypename) continue;
12170 
12171     // using decls differ if they name different scopes (but note that
12172     // template instantiation can cause this check to trigger when it
12173     // didn't before instantiation).
12174     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12175         Context.getCanonicalNestedNameSpecifier(DQual))
12176       continue;
12177 
12178     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12179     Diag(D->getLocation(), diag::note_using_decl) << 1;
12180     return true;
12181   }
12182 
12183   return false;
12184 }
12185 
12186 
12187 /// Checks that the given nested-name qualifier used in a using decl
12188 /// in the current context is appropriately related to the current
12189 /// scope.  If an error is found, diagnoses it and returns true.
12190 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12191                                    bool HasTypename,
12192                                    const CXXScopeSpec &SS,
12193                                    const DeclarationNameInfo &NameInfo,
12194                                    SourceLocation NameLoc) {
12195   DeclContext *NamedContext = computeDeclContext(SS);
12196 
12197   if (!CurContext->isRecord()) {
12198     // C++03 [namespace.udecl]p3:
12199     // C++0x [namespace.udecl]p8:
12200     //   A using-declaration for a class member shall be a member-declaration.
12201 
12202     // If we weren't able to compute a valid scope, it might validly be a
12203     // dependent class scope or a dependent enumeration unscoped scope. If
12204     // we have a 'typename' keyword, the scope must resolve to a class type.
12205     if ((HasTypename && !NamedContext) ||
12206         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12207       auto *RD = NamedContext
12208                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12209                      : nullptr;
12210       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12211         RD = nullptr;
12212 
12213       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12214         << SS.getRange();
12215 
12216       // If we have a complete, non-dependent source type, try to suggest a
12217       // way to get the same effect.
12218       if (!RD)
12219         return true;
12220 
12221       // Find what this using-declaration was referring to.
12222       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12223       R.setHideTags(false);
12224       R.suppressDiagnostics();
12225       LookupQualifiedName(R, RD);
12226 
12227       if (R.getAsSingle<TypeDecl>()) {
12228         if (getLangOpts().CPlusPlus11) {
12229           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12230           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12231             << 0 // alias declaration
12232             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12233                                           NameInfo.getName().getAsString() +
12234                                               " = ");
12235         } else {
12236           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12237           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12238           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12239             << 1 // typedef declaration
12240             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12241             << FixItHint::CreateInsertion(
12242                    InsertLoc, " " + NameInfo.getName().getAsString());
12243         }
12244       } else if (R.getAsSingle<VarDecl>()) {
12245         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12246         // repeating the type of the static data member here.
12247         FixItHint FixIt;
12248         if (getLangOpts().CPlusPlus11) {
12249           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12250           FixIt = FixItHint::CreateReplacement(
12251               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12252         }
12253 
12254         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12255           << 2 // reference declaration
12256           << FixIt;
12257       } else if (R.getAsSingle<EnumConstantDecl>()) {
12258         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12259         // repeating the type of the enumeration here, and we can't do so if
12260         // the type is anonymous.
12261         FixItHint FixIt;
12262         if (getLangOpts().CPlusPlus11) {
12263           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12264           FixIt = FixItHint::CreateReplacement(
12265               UsingLoc,
12266               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12267         }
12268 
12269         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12270           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12271           << FixIt;
12272       }
12273       return true;
12274     }
12275 
12276     // Otherwise, this might be valid.
12277     return false;
12278   }
12279 
12280   // The current scope is a record.
12281 
12282   // If the named context is dependent, we can't decide much.
12283   if (!NamedContext) {
12284     // FIXME: in C++0x, we can diagnose if we can prove that the
12285     // nested-name-specifier does not refer to a base class, which is
12286     // still possible in some cases.
12287 
12288     // Otherwise we have to conservatively report that things might be
12289     // okay.
12290     return false;
12291   }
12292 
12293   if (!NamedContext->isRecord()) {
12294     // Ideally this would point at the last name in the specifier,
12295     // but we don't have that level of source info.
12296     Diag(SS.getRange().getBegin(),
12297          diag::err_using_decl_nested_name_specifier_is_not_class)
12298       << SS.getScopeRep() << SS.getRange();
12299     return true;
12300   }
12301 
12302   if (!NamedContext->isDependentContext() &&
12303       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12304     return true;
12305 
12306   if (getLangOpts().CPlusPlus11) {
12307     // C++11 [namespace.udecl]p3:
12308     //   In a using-declaration used as a member-declaration, the
12309     //   nested-name-specifier shall name a base class of the class
12310     //   being defined.
12311 
12312     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12313                                  cast<CXXRecordDecl>(NamedContext))) {
12314       if (CurContext == NamedContext) {
12315         Diag(NameLoc,
12316              diag::err_using_decl_nested_name_specifier_is_current_class)
12317           << SS.getRange();
12318         return true;
12319       }
12320 
12321       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12322         Diag(SS.getRange().getBegin(),
12323              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12324           << SS.getScopeRep()
12325           << cast<CXXRecordDecl>(CurContext)
12326           << SS.getRange();
12327       }
12328       return true;
12329     }
12330 
12331     return false;
12332   }
12333 
12334   // C++03 [namespace.udecl]p4:
12335   //   A using-declaration used as a member-declaration shall refer
12336   //   to a member of a base class of the class being defined [etc.].
12337 
12338   // Salient point: SS doesn't have to name a base class as long as
12339   // lookup only finds members from base classes.  Therefore we can
12340   // diagnose here only if we can prove that that can't happen,
12341   // i.e. if the class hierarchies provably don't intersect.
12342 
12343   // TODO: it would be nice if "definitely valid" results were cached
12344   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12345   // need to be repeated.
12346 
12347   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12348   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12349     Bases.insert(Base);
12350     return true;
12351   };
12352 
12353   // Collect all bases. Return false if we find a dependent base.
12354   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12355     return false;
12356 
12357   // Returns true if the base is dependent or is one of the accumulated base
12358   // classes.
12359   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12360     return !Bases.count(Base);
12361   };
12362 
12363   // Return false if the class has a dependent base or if it or one
12364   // of its bases is present in the base set of the current context.
12365   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12366       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12367     return false;
12368 
12369   Diag(SS.getRange().getBegin(),
12370        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12371     << SS.getScopeRep()
12372     << cast<CXXRecordDecl>(CurContext)
12373     << SS.getRange();
12374 
12375   return true;
12376 }
12377 
12378 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12379                                   MultiTemplateParamsArg TemplateParamLists,
12380                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12381                                   const ParsedAttributesView &AttrList,
12382                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12383   // Skip up to the relevant declaration scope.
12384   while (S->isTemplateParamScope())
12385     S = S->getParent();
12386   assert((S->getFlags() & Scope::DeclScope) &&
12387          "got alias-declaration outside of declaration scope");
12388 
12389   if (Type.isInvalid())
12390     return nullptr;
12391 
12392   bool Invalid = false;
12393   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12394   TypeSourceInfo *TInfo = nullptr;
12395   GetTypeFromParser(Type.get(), &TInfo);
12396 
12397   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12398     return nullptr;
12399 
12400   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12401                                       UPPC_DeclarationType)) {
12402     Invalid = true;
12403     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12404                                              TInfo->getTypeLoc().getBeginLoc());
12405   }
12406 
12407   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12408                         TemplateParamLists.size()
12409                             ? forRedeclarationInCurContext()
12410                             : ForVisibleRedeclaration);
12411   LookupName(Previous, S);
12412 
12413   // Warn about shadowing the name of a template parameter.
12414   if (Previous.isSingleResult() &&
12415       Previous.getFoundDecl()->isTemplateParameter()) {
12416     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12417     Previous.clear();
12418   }
12419 
12420   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12421          "name in alias declaration must be an identifier");
12422   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12423                                                Name.StartLocation,
12424                                                Name.Identifier, TInfo);
12425 
12426   NewTD->setAccess(AS);
12427 
12428   if (Invalid)
12429     NewTD->setInvalidDecl();
12430 
12431   ProcessDeclAttributeList(S, NewTD, AttrList);
12432   AddPragmaAttributes(S, NewTD);
12433 
12434   CheckTypedefForVariablyModifiedType(S, NewTD);
12435   Invalid |= NewTD->isInvalidDecl();
12436 
12437   bool Redeclaration = false;
12438 
12439   NamedDecl *NewND;
12440   if (TemplateParamLists.size()) {
12441     TypeAliasTemplateDecl *OldDecl = nullptr;
12442     TemplateParameterList *OldTemplateParams = nullptr;
12443 
12444     if (TemplateParamLists.size() != 1) {
12445       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12446         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12447          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12448     }
12449     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12450 
12451     // Check that we can declare a template here.
12452     if (CheckTemplateDeclScope(S, TemplateParams))
12453       return nullptr;
12454 
12455     // Only consider previous declarations in the same scope.
12456     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12457                          /*ExplicitInstantiationOrSpecialization*/false);
12458     if (!Previous.empty()) {
12459       Redeclaration = true;
12460 
12461       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12462       if (!OldDecl && !Invalid) {
12463         Diag(UsingLoc, diag::err_redefinition_different_kind)
12464           << Name.Identifier;
12465 
12466         NamedDecl *OldD = Previous.getRepresentativeDecl();
12467         if (OldD->getLocation().isValid())
12468           Diag(OldD->getLocation(), diag::note_previous_definition);
12469 
12470         Invalid = true;
12471       }
12472 
12473       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12474         if (TemplateParameterListsAreEqual(TemplateParams,
12475                                            OldDecl->getTemplateParameters(),
12476                                            /*Complain=*/true,
12477                                            TPL_TemplateMatch))
12478           OldTemplateParams =
12479               OldDecl->getMostRecentDecl()->getTemplateParameters();
12480         else
12481           Invalid = true;
12482 
12483         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12484         if (!Invalid &&
12485             !Context.hasSameType(OldTD->getUnderlyingType(),
12486                                  NewTD->getUnderlyingType())) {
12487           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12488           // but we can't reasonably accept it.
12489           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12490             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12491           if (OldTD->getLocation().isValid())
12492             Diag(OldTD->getLocation(), diag::note_previous_definition);
12493           Invalid = true;
12494         }
12495       }
12496     }
12497 
12498     // Merge any previous default template arguments into our parameters,
12499     // and check the parameter list.
12500     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12501                                    TPC_TypeAliasTemplate))
12502       return nullptr;
12503 
12504     TypeAliasTemplateDecl *NewDecl =
12505       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12506                                     Name.Identifier, TemplateParams,
12507                                     NewTD);
12508     NewTD->setDescribedAliasTemplate(NewDecl);
12509 
12510     NewDecl->setAccess(AS);
12511 
12512     if (Invalid)
12513       NewDecl->setInvalidDecl();
12514     else if (OldDecl) {
12515       NewDecl->setPreviousDecl(OldDecl);
12516       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12517     }
12518 
12519     NewND = NewDecl;
12520   } else {
12521     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12522       setTagNameForLinkagePurposes(TD, NewTD);
12523       handleTagNumbering(TD, S);
12524     }
12525     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12526     NewND = NewTD;
12527   }
12528 
12529   PushOnScopeChains(NewND, S);
12530   ActOnDocumentableDecl(NewND);
12531   return NewND;
12532 }
12533 
12534 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12535                                    SourceLocation AliasLoc,
12536                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12537                                    SourceLocation IdentLoc,
12538                                    IdentifierInfo *Ident) {
12539 
12540   // Lookup the namespace name.
12541   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12542   LookupParsedName(R, S, &SS);
12543 
12544   if (R.isAmbiguous())
12545     return nullptr;
12546 
12547   if (R.empty()) {
12548     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12549       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12550       return nullptr;
12551     }
12552   }
12553   assert(!R.isAmbiguous() && !R.empty());
12554   NamedDecl *ND = R.getRepresentativeDecl();
12555 
12556   // Check if we have a previous declaration with the same name.
12557   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12558                      ForVisibleRedeclaration);
12559   LookupName(PrevR, S);
12560 
12561   // Check we're not shadowing a template parameter.
12562   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12563     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12564     PrevR.clear();
12565   }
12566 
12567   // Filter out any other lookup result from an enclosing scope.
12568   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12569                        /*AllowInlineNamespace*/false);
12570 
12571   // Find the previous declaration and check that we can redeclare it.
12572   NamespaceAliasDecl *Prev = nullptr;
12573   if (PrevR.isSingleResult()) {
12574     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12575     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12576       // We already have an alias with the same name that points to the same
12577       // namespace; check that it matches.
12578       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12579         Prev = AD;
12580       } else if (isVisible(PrevDecl)) {
12581         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12582           << Alias;
12583         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12584           << AD->getNamespace();
12585         return nullptr;
12586       }
12587     } else if (isVisible(PrevDecl)) {
12588       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12589                             ? diag::err_redefinition
12590                             : diag::err_redefinition_different_kind;
12591       Diag(AliasLoc, DiagID) << Alias;
12592       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12593       return nullptr;
12594     }
12595   }
12596 
12597   // The use of a nested name specifier may trigger deprecation warnings.
12598   DiagnoseUseOfDecl(ND, IdentLoc);
12599 
12600   NamespaceAliasDecl *AliasDecl =
12601     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12602                                Alias, SS.getWithLocInContext(Context),
12603                                IdentLoc, ND);
12604   if (Prev)
12605     AliasDecl->setPreviousDecl(Prev);
12606 
12607   PushOnScopeChains(AliasDecl, S);
12608   return AliasDecl;
12609 }
12610 
12611 namespace {
12612 struct SpecialMemberExceptionSpecInfo
12613     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12614   SourceLocation Loc;
12615   Sema::ImplicitExceptionSpecification ExceptSpec;
12616 
12617   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12618                                  Sema::CXXSpecialMember CSM,
12619                                  Sema::InheritedConstructorInfo *ICI,
12620                                  SourceLocation Loc)
12621       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12622 
12623   bool visitBase(CXXBaseSpecifier *Base);
12624   bool visitField(FieldDecl *FD);
12625 
12626   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12627                            unsigned Quals);
12628 
12629   void visitSubobjectCall(Subobject Subobj,
12630                           Sema::SpecialMemberOverloadResult SMOR);
12631 };
12632 }
12633 
12634 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12635   auto *RT = Base->getType()->getAs<RecordType>();
12636   if (!RT)
12637     return false;
12638 
12639   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12640   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12641   if (auto *BaseCtor = SMOR.getMethod()) {
12642     visitSubobjectCall(Base, BaseCtor);
12643     return false;
12644   }
12645 
12646   visitClassSubobject(BaseClass, Base, 0);
12647   return false;
12648 }
12649 
12650 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12651   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12652     Expr *E = FD->getInClassInitializer();
12653     if (!E)
12654       // FIXME: It's a little wasteful to build and throw away a
12655       // CXXDefaultInitExpr here.
12656       // FIXME: We should have a single context note pointing at Loc, and
12657       // this location should be MD->getLocation() instead, since that's
12658       // the location where we actually use the default init expression.
12659       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12660     if (E)
12661       ExceptSpec.CalledExpr(E);
12662   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12663                             ->getAs<RecordType>()) {
12664     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12665                         FD->getType().getCVRQualifiers());
12666   }
12667   return false;
12668 }
12669 
12670 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12671                                                          Subobject Subobj,
12672                                                          unsigned Quals) {
12673   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12674   bool IsMutable = Field && Field->isMutable();
12675   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12676 }
12677 
12678 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12679     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12680   // Note, if lookup fails, it doesn't matter what exception specification we
12681   // choose because the special member will be deleted.
12682   if (CXXMethodDecl *MD = SMOR.getMethod())
12683     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12684 }
12685 
12686 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12687   llvm::APSInt Result;
12688   ExprResult Converted = CheckConvertedConstantExpression(
12689       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12690   ExplicitSpec.setExpr(Converted.get());
12691   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12692     ExplicitSpec.setKind(Result.getBoolValue()
12693                              ? ExplicitSpecKind::ResolvedTrue
12694                              : ExplicitSpecKind::ResolvedFalse);
12695     return true;
12696   }
12697   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12698   return false;
12699 }
12700 
12701 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12702   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12703   if (!ExplicitExpr->isTypeDependent())
12704     tryResolveExplicitSpecifier(ES);
12705   return ES;
12706 }
12707 
12708 static Sema::ImplicitExceptionSpecification
12709 ComputeDefaultedSpecialMemberExceptionSpec(
12710     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12711     Sema::InheritedConstructorInfo *ICI) {
12712   ComputingExceptionSpec CES(S, MD, Loc);
12713 
12714   CXXRecordDecl *ClassDecl = MD->getParent();
12715 
12716   // C++ [except.spec]p14:
12717   //   An implicitly declared special member function (Clause 12) shall have an
12718   //   exception-specification. [...]
12719   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12720   if (ClassDecl->isInvalidDecl())
12721     return Info.ExceptSpec;
12722 
12723   // FIXME: If this diagnostic fires, we're probably missing a check for
12724   // attempting to resolve an exception specification before it's known
12725   // at a higher level.
12726   if (S.RequireCompleteType(MD->getLocation(),
12727                             S.Context.getRecordType(ClassDecl),
12728                             diag::err_exception_spec_incomplete_type))
12729     return Info.ExceptSpec;
12730 
12731   // C++1z [except.spec]p7:
12732   //   [Look for exceptions thrown by] a constructor selected [...] to
12733   //   initialize a potentially constructed subobject,
12734   // C++1z [except.spec]p8:
12735   //   The exception specification for an implicitly-declared destructor, or a
12736   //   destructor without a noexcept-specifier, is potentially-throwing if and
12737   //   only if any of the destructors for any of its potentially constructed
12738   //   subojects is potentially throwing.
12739   // FIXME: We respect the first rule but ignore the "potentially constructed"
12740   // in the second rule to resolve a core issue (no number yet) that would have
12741   // us reject:
12742   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12743   //   struct B : A {};
12744   //   struct C : B { void f(); };
12745   // ... due to giving B::~B() a non-throwing exception specification.
12746   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12747                                 : Info.VisitAllBases);
12748 
12749   return Info.ExceptSpec;
12750 }
12751 
12752 namespace {
12753 /// RAII object to register a special member as being currently declared.
12754 struct DeclaringSpecialMember {
12755   Sema &S;
12756   Sema::SpecialMemberDecl D;
12757   Sema::ContextRAII SavedContext;
12758   bool WasAlreadyBeingDeclared;
12759 
12760   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12761       : S(S), D(RD, CSM), SavedContext(S, RD) {
12762     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12763     if (WasAlreadyBeingDeclared)
12764       // This almost never happens, but if it does, ensure that our cache
12765       // doesn't contain a stale result.
12766       S.SpecialMemberCache.clear();
12767     else {
12768       // Register a note to be produced if we encounter an error while
12769       // declaring the special member.
12770       Sema::CodeSynthesisContext Ctx;
12771       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12772       // FIXME: We don't have a location to use here. Using the class's
12773       // location maintains the fiction that we declare all special members
12774       // with the class, but (1) it's not clear that lying about that helps our
12775       // users understand what's going on, and (2) there may be outer contexts
12776       // on the stack (some of which are relevant) and printing them exposes
12777       // our lies.
12778       Ctx.PointOfInstantiation = RD->getLocation();
12779       Ctx.Entity = RD;
12780       Ctx.SpecialMember = CSM;
12781       S.pushCodeSynthesisContext(Ctx);
12782     }
12783   }
12784   ~DeclaringSpecialMember() {
12785     if (!WasAlreadyBeingDeclared) {
12786       S.SpecialMembersBeingDeclared.erase(D);
12787       S.popCodeSynthesisContext();
12788     }
12789   }
12790 
12791   /// Are we already trying to declare this special member?
12792   bool isAlreadyBeingDeclared() const {
12793     return WasAlreadyBeingDeclared;
12794   }
12795 };
12796 }
12797 
12798 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12799   // Look up any existing declarations, but don't trigger declaration of all
12800   // implicit special members with this name.
12801   DeclarationName Name = FD->getDeclName();
12802   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12803                  ForExternalRedeclaration);
12804   for (auto *D : FD->getParent()->lookup(Name))
12805     if (auto *Acceptable = R.getAcceptableDecl(D))
12806       R.addDecl(Acceptable);
12807   R.resolveKind();
12808   R.suppressDiagnostics();
12809 
12810   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12811 }
12812 
12813 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12814                                           QualType ResultTy,
12815                                           ArrayRef<QualType> Args) {
12816   // Build an exception specification pointing back at this constructor.
12817   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12818 
12819   LangAS AS = getDefaultCXXMethodAddrSpace();
12820   if (AS != LangAS::Default) {
12821     EPI.TypeQuals.addAddressSpace(AS);
12822   }
12823 
12824   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12825   SpecialMem->setType(QT);
12826 }
12827 
12828 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12829                                                      CXXRecordDecl *ClassDecl) {
12830   // C++ [class.ctor]p5:
12831   //   A default constructor for a class X is a constructor of class X
12832   //   that can be called without an argument. If there is no
12833   //   user-declared constructor for class X, a default constructor is
12834   //   implicitly declared. An implicitly-declared default constructor
12835   //   is an inline public member of its class.
12836   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12837          "Should not build implicit default constructor!");
12838 
12839   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12840   if (DSM.isAlreadyBeingDeclared())
12841     return nullptr;
12842 
12843   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12844                                                      CXXDefaultConstructor,
12845                                                      false);
12846 
12847   // Create the actual constructor declaration.
12848   CanQualType ClassType
12849     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12850   SourceLocation ClassLoc = ClassDecl->getLocation();
12851   DeclarationName Name
12852     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12853   DeclarationNameInfo NameInfo(Name, ClassLoc);
12854   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12855       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12856       /*TInfo=*/nullptr, ExplicitSpecifier(),
12857       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12858       Constexpr ? CSK_constexpr : CSK_unspecified);
12859   DefaultCon->setAccess(AS_public);
12860   DefaultCon->setDefaulted();
12861 
12862   if (getLangOpts().CUDA) {
12863     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12864                                             DefaultCon,
12865                                             /* ConstRHS */ false,
12866                                             /* Diagnose */ false);
12867   }
12868 
12869   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12870 
12871   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12872   // constructors is easy to compute.
12873   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12874 
12875   // Note that we have declared this constructor.
12876   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12877 
12878   Scope *S = getScopeForContext(ClassDecl);
12879   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12880 
12881   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12882     SetDeclDeleted(DefaultCon, ClassLoc);
12883 
12884   if (S)
12885     PushOnScopeChains(DefaultCon, S, false);
12886   ClassDecl->addDecl(DefaultCon);
12887 
12888   return DefaultCon;
12889 }
12890 
12891 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12892                                             CXXConstructorDecl *Constructor) {
12893   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12894           !Constructor->doesThisDeclarationHaveABody() &&
12895           !Constructor->isDeleted()) &&
12896     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12897   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12898     return;
12899 
12900   CXXRecordDecl *ClassDecl = Constructor->getParent();
12901   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12902 
12903   SynthesizedFunctionScope Scope(*this, Constructor);
12904 
12905   // The exception specification is needed because we are defining the
12906   // function.
12907   ResolveExceptionSpec(CurrentLocation,
12908                        Constructor->getType()->castAs<FunctionProtoType>());
12909   MarkVTableUsed(CurrentLocation, ClassDecl);
12910 
12911   // Add a context note for diagnostics produced after this point.
12912   Scope.addContextNote(CurrentLocation);
12913 
12914   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12915     Constructor->setInvalidDecl();
12916     return;
12917   }
12918 
12919   SourceLocation Loc = Constructor->getEndLoc().isValid()
12920                            ? Constructor->getEndLoc()
12921                            : Constructor->getLocation();
12922   Constructor->setBody(new (Context) CompoundStmt(Loc));
12923   Constructor->markUsed(Context);
12924 
12925   if (ASTMutationListener *L = getASTMutationListener()) {
12926     L->CompletedImplicitDefinition(Constructor);
12927   }
12928 
12929   DiagnoseUninitializedFields(*this, Constructor);
12930 }
12931 
12932 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
12933   // Perform any delayed checks on exception specifications.
12934   CheckDelayedMemberExceptionSpecs();
12935 }
12936 
12937 /// Find or create the fake constructor we synthesize to model constructing an
12938 /// object of a derived class via a constructor of a base class.
12939 CXXConstructorDecl *
12940 Sema::findInheritingConstructor(SourceLocation Loc,
12941                                 CXXConstructorDecl *BaseCtor,
12942                                 ConstructorUsingShadowDecl *Shadow) {
12943   CXXRecordDecl *Derived = Shadow->getParent();
12944   SourceLocation UsingLoc = Shadow->getLocation();
12945 
12946   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
12947   // For now we use the name of the base class constructor as a member of the
12948   // derived class to indicate a (fake) inherited constructor name.
12949   DeclarationName Name = BaseCtor->getDeclName();
12950 
12951   // Check to see if we already have a fake constructor for this inherited
12952   // constructor call.
12953   for (NamedDecl *Ctor : Derived->lookup(Name))
12954     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
12955                                ->getInheritedConstructor()
12956                                .getConstructor(),
12957                            BaseCtor))
12958       return cast<CXXConstructorDecl>(Ctor);
12959 
12960   DeclarationNameInfo NameInfo(Name, UsingLoc);
12961   TypeSourceInfo *TInfo =
12962       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
12963   FunctionProtoTypeLoc ProtoLoc =
12964       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
12965 
12966   // Check the inherited constructor is valid and find the list of base classes
12967   // from which it was inherited.
12968   InheritedConstructorInfo ICI(*this, Loc, Shadow);
12969 
12970   bool Constexpr =
12971       BaseCtor->isConstexpr() &&
12972       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
12973                                         false, BaseCtor, &ICI);
12974 
12975   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
12976       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
12977       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
12978       /*isImplicitlyDeclared=*/true,
12979       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
12980       InheritedConstructor(Shadow, BaseCtor),
12981       BaseCtor->getTrailingRequiresClause());
12982   if (Shadow->isInvalidDecl())
12983     DerivedCtor->setInvalidDecl();
12984 
12985   // Build an unevaluated exception specification for this fake constructor.
12986   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
12987   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12988   EPI.ExceptionSpec.Type = EST_Unevaluated;
12989   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
12990   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
12991                                                FPT->getParamTypes(), EPI));
12992 
12993   // Build the parameter declarations.
12994   SmallVector<ParmVarDecl *, 16> ParamDecls;
12995   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
12996     TypeSourceInfo *TInfo =
12997         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
12998     ParmVarDecl *PD = ParmVarDecl::Create(
12999         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13000         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13001     PD->setScopeInfo(0, I);
13002     PD->setImplicit();
13003     // Ensure attributes are propagated onto parameters (this matters for
13004     // format, pass_object_size, ...).
13005     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13006     ParamDecls.push_back(PD);
13007     ProtoLoc.setParam(I, PD);
13008   }
13009 
13010   // Set up the new constructor.
13011   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13012   DerivedCtor->setAccess(BaseCtor->getAccess());
13013   DerivedCtor->setParams(ParamDecls);
13014   Derived->addDecl(DerivedCtor);
13015 
13016   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13017     SetDeclDeleted(DerivedCtor, UsingLoc);
13018 
13019   return DerivedCtor;
13020 }
13021 
13022 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13023   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13024                                Ctor->getInheritedConstructor().getShadowDecl());
13025   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13026                             /*Diagnose*/true);
13027 }
13028 
13029 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13030                                        CXXConstructorDecl *Constructor) {
13031   CXXRecordDecl *ClassDecl = Constructor->getParent();
13032   assert(Constructor->getInheritedConstructor() &&
13033          !Constructor->doesThisDeclarationHaveABody() &&
13034          !Constructor->isDeleted());
13035   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13036     return;
13037 
13038   // Initializations are performed "as if by a defaulted default constructor",
13039   // so enter the appropriate scope.
13040   SynthesizedFunctionScope Scope(*this, Constructor);
13041 
13042   // The exception specification is needed because we are defining the
13043   // function.
13044   ResolveExceptionSpec(CurrentLocation,
13045                        Constructor->getType()->castAs<FunctionProtoType>());
13046   MarkVTableUsed(CurrentLocation, ClassDecl);
13047 
13048   // Add a context note for diagnostics produced after this point.
13049   Scope.addContextNote(CurrentLocation);
13050 
13051   ConstructorUsingShadowDecl *Shadow =
13052       Constructor->getInheritedConstructor().getShadowDecl();
13053   CXXConstructorDecl *InheritedCtor =
13054       Constructor->getInheritedConstructor().getConstructor();
13055 
13056   // [class.inhctor.init]p1:
13057   //   initialization proceeds as if a defaulted default constructor is used to
13058   //   initialize the D object and each base class subobject from which the
13059   //   constructor was inherited
13060 
13061   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13062   CXXRecordDecl *RD = Shadow->getParent();
13063   SourceLocation InitLoc = Shadow->getLocation();
13064 
13065   // Build explicit initializers for all base classes from which the
13066   // constructor was inherited.
13067   SmallVector<CXXCtorInitializer*, 8> Inits;
13068   for (bool VBase : {false, true}) {
13069     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13070       if (B.isVirtual() != VBase)
13071         continue;
13072 
13073       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13074       if (!BaseRD)
13075         continue;
13076 
13077       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13078       if (!BaseCtor.first)
13079         continue;
13080 
13081       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13082       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13083           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13084 
13085       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13086       Inits.push_back(new (Context) CXXCtorInitializer(
13087           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13088           SourceLocation()));
13089     }
13090   }
13091 
13092   // We now proceed as if for a defaulted default constructor, with the relevant
13093   // initializers replaced.
13094 
13095   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13096     Constructor->setInvalidDecl();
13097     return;
13098   }
13099 
13100   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13101   Constructor->markUsed(Context);
13102 
13103   if (ASTMutationListener *L = getASTMutationListener()) {
13104     L->CompletedImplicitDefinition(Constructor);
13105   }
13106 
13107   DiagnoseUninitializedFields(*this, Constructor);
13108 }
13109 
13110 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13111   // C++ [class.dtor]p2:
13112   //   If a class has no user-declared destructor, a destructor is
13113   //   declared implicitly. An implicitly-declared destructor is an
13114   //   inline public member of its class.
13115   assert(ClassDecl->needsImplicitDestructor());
13116 
13117   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13118   if (DSM.isAlreadyBeingDeclared())
13119     return nullptr;
13120 
13121   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13122                                                      CXXDestructor,
13123                                                      false);
13124 
13125   // Create the actual destructor declaration.
13126   CanQualType ClassType
13127     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13128   SourceLocation ClassLoc = ClassDecl->getLocation();
13129   DeclarationName Name
13130     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13131   DeclarationNameInfo NameInfo(Name, ClassLoc);
13132   CXXDestructorDecl *Destructor =
13133       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13134                                 QualType(), nullptr, /*isInline=*/true,
13135                                 /*isImplicitlyDeclared=*/true,
13136                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13137   Destructor->setAccess(AS_public);
13138   Destructor->setDefaulted();
13139 
13140   if (getLangOpts().CUDA) {
13141     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13142                                             Destructor,
13143                                             /* ConstRHS */ false,
13144                                             /* Diagnose */ false);
13145   }
13146 
13147   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13148 
13149   // We don't need to use SpecialMemberIsTrivial here; triviality for
13150   // destructors is easy to compute.
13151   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13152   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13153                                 ClassDecl->hasTrivialDestructorForCall());
13154 
13155   // Note that we have declared this destructor.
13156   ++getASTContext().NumImplicitDestructorsDeclared;
13157 
13158   Scope *S = getScopeForContext(ClassDecl);
13159   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13160 
13161   // We can't check whether an implicit destructor is deleted before we complete
13162   // the definition of the class, because its validity depends on the alignment
13163   // of the class. We'll check this from ActOnFields once the class is complete.
13164   if (ClassDecl->isCompleteDefinition() &&
13165       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13166     SetDeclDeleted(Destructor, ClassLoc);
13167 
13168   // Introduce this destructor into its scope.
13169   if (S)
13170     PushOnScopeChains(Destructor, S, false);
13171   ClassDecl->addDecl(Destructor);
13172 
13173   return Destructor;
13174 }
13175 
13176 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13177                                     CXXDestructorDecl *Destructor) {
13178   assert((Destructor->isDefaulted() &&
13179           !Destructor->doesThisDeclarationHaveABody() &&
13180           !Destructor->isDeleted()) &&
13181          "DefineImplicitDestructor - call it for implicit default dtor");
13182   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13183     return;
13184 
13185   CXXRecordDecl *ClassDecl = Destructor->getParent();
13186   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13187 
13188   SynthesizedFunctionScope Scope(*this, Destructor);
13189 
13190   // The exception specification is needed because we are defining the
13191   // function.
13192   ResolveExceptionSpec(CurrentLocation,
13193                        Destructor->getType()->castAs<FunctionProtoType>());
13194   MarkVTableUsed(CurrentLocation, ClassDecl);
13195 
13196   // Add a context note for diagnostics produced after this point.
13197   Scope.addContextNote(CurrentLocation);
13198 
13199   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13200                                          Destructor->getParent());
13201 
13202   if (CheckDestructor(Destructor)) {
13203     Destructor->setInvalidDecl();
13204     return;
13205   }
13206 
13207   SourceLocation Loc = Destructor->getEndLoc().isValid()
13208                            ? Destructor->getEndLoc()
13209                            : Destructor->getLocation();
13210   Destructor->setBody(new (Context) CompoundStmt(Loc));
13211   Destructor->markUsed(Context);
13212 
13213   if (ASTMutationListener *L = getASTMutationListener()) {
13214     L->CompletedImplicitDefinition(Destructor);
13215   }
13216 }
13217 
13218 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13219                                           CXXDestructorDecl *Destructor) {
13220   if (Destructor->isInvalidDecl())
13221     return;
13222 
13223   CXXRecordDecl *ClassDecl = Destructor->getParent();
13224   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13225          "implicit complete dtors unneeded outside MS ABI");
13226   assert(ClassDecl->getNumVBases() > 0 &&
13227          "complete dtor only exists for classes with vbases");
13228 
13229   SynthesizedFunctionScope Scope(*this, Destructor);
13230 
13231   // Add a context note for diagnostics produced after this point.
13232   Scope.addContextNote(CurrentLocation);
13233 
13234   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13235 }
13236 
13237 /// Perform any semantic analysis which needs to be delayed until all
13238 /// pending class member declarations have been parsed.
13239 void Sema::ActOnFinishCXXMemberDecls() {
13240   // If the context is an invalid C++ class, just suppress these checks.
13241   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13242     if (Record->isInvalidDecl()) {
13243       DelayedOverridingExceptionSpecChecks.clear();
13244       DelayedEquivalentExceptionSpecChecks.clear();
13245       return;
13246     }
13247     checkForMultipleExportedDefaultConstructors(*this, Record);
13248   }
13249 }
13250 
13251 void Sema::ActOnFinishCXXNonNestedClass() {
13252   referenceDLLExportedClassMethods();
13253 
13254   if (!DelayedDllExportMemberFunctions.empty()) {
13255     SmallVector<CXXMethodDecl*, 4> WorkList;
13256     std::swap(DelayedDllExportMemberFunctions, WorkList);
13257     for (CXXMethodDecl *M : WorkList) {
13258       DefineDefaultedFunction(*this, M, M->getLocation());
13259 
13260       // Pass the method to the consumer to get emitted. This is not necessary
13261       // for explicit instantiation definitions, as they will get emitted
13262       // anyway.
13263       if (M->getParent()->getTemplateSpecializationKind() !=
13264           TSK_ExplicitInstantiationDefinition)
13265         ActOnFinishInlineFunctionDef(M);
13266     }
13267   }
13268 }
13269 
13270 void Sema::referenceDLLExportedClassMethods() {
13271   if (!DelayedDllExportClasses.empty()) {
13272     // Calling ReferenceDllExportedMembers might cause the current function to
13273     // be called again, so use a local copy of DelayedDllExportClasses.
13274     SmallVector<CXXRecordDecl *, 4> WorkList;
13275     std::swap(DelayedDllExportClasses, WorkList);
13276     for (CXXRecordDecl *Class : WorkList)
13277       ReferenceDllExportedMembers(*this, Class);
13278   }
13279 }
13280 
13281 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13282   assert(getLangOpts().CPlusPlus11 &&
13283          "adjusting dtor exception specs was introduced in c++11");
13284 
13285   if (Destructor->isDependentContext())
13286     return;
13287 
13288   // C++11 [class.dtor]p3:
13289   //   A declaration of a destructor that does not have an exception-
13290   //   specification is implicitly considered to have the same exception-
13291   //   specification as an implicit declaration.
13292   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13293   if (DtorType->hasExceptionSpec())
13294     return;
13295 
13296   // Replace the destructor's type, building off the existing one. Fortunately,
13297   // the only thing of interest in the destructor type is its extended info.
13298   // The return and arguments are fixed.
13299   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13300   EPI.ExceptionSpec.Type = EST_Unevaluated;
13301   EPI.ExceptionSpec.SourceDecl = Destructor;
13302   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13303 
13304   // FIXME: If the destructor has a body that could throw, and the newly created
13305   // spec doesn't allow exceptions, we should emit a warning, because this
13306   // change in behavior can break conforming C++03 programs at runtime.
13307   // However, we don't have a body or an exception specification yet, so it
13308   // needs to be done somewhere else.
13309 }
13310 
13311 namespace {
13312 /// An abstract base class for all helper classes used in building the
13313 //  copy/move operators. These classes serve as factory functions and help us
13314 //  avoid using the same Expr* in the AST twice.
13315 class ExprBuilder {
13316   ExprBuilder(const ExprBuilder&) = delete;
13317   ExprBuilder &operator=(const ExprBuilder&) = delete;
13318 
13319 protected:
13320   static Expr *assertNotNull(Expr *E) {
13321     assert(E && "Expression construction must not fail.");
13322     return E;
13323   }
13324 
13325 public:
13326   ExprBuilder() {}
13327   virtual ~ExprBuilder() {}
13328 
13329   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13330 };
13331 
13332 class RefBuilder: public ExprBuilder {
13333   VarDecl *Var;
13334   QualType VarType;
13335 
13336 public:
13337   Expr *build(Sema &S, SourceLocation Loc) const override {
13338     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13339   }
13340 
13341   RefBuilder(VarDecl *Var, QualType VarType)
13342       : Var(Var), VarType(VarType) {}
13343 };
13344 
13345 class ThisBuilder: public ExprBuilder {
13346 public:
13347   Expr *build(Sema &S, SourceLocation Loc) const override {
13348     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13349   }
13350 };
13351 
13352 class CastBuilder: public ExprBuilder {
13353   const ExprBuilder &Builder;
13354   QualType Type;
13355   ExprValueKind Kind;
13356   const CXXCastPath &Path;
13357 
13358 public:
13359   Expr *build(Sema &S, SourceLocation Loc) const override {
13360     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13361                                              CK_UncheckedDerivedToBase, Kind,
13362                                              &Path).get());
13363   }
13364 
13365   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13366               const CXXCastPath &Path)
13367       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13368 };
13369 
13370 class DerefBuilder: public ExprBuilder {
13371   const ExprBuilder &Builder;
13372 
13373 public:
13374   Expr *build(Sema &S, SourceLocation Loc) const override {
13375     return assertNotNull(
13376         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13377   }
13378 
13379   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13380 };
13381 
13382 class MemberBuilder: public ExprBuilder {
13383   const ExprBuilder &Builder;
13384   QualType Type;
13385   CXXScopeSpec SS;
13386   bool IsArrow;
13387   LookupResult &MemberLookup;
13388 
13389 public:
13390   Expr *build(Sema &S, SourceLocation Loc) const override {
13391     return assertNotNull(S.BuildMemberReferenceExpr(
13392         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13393         nullptr, MemberLookup, nullptr, nullptr).get());
13394   }
13395 
13396   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13397                 LookupResult &MemberLookup)
13398       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13399         MemberLookup(MemberLookup) {}
13400 };
13401 
13402 class MoveCastBuilder: public ExprBuilder {
13403   const ExprBuilder &Builder;
13404 
13405 public:
13406   Expr *build(Sema &S, SourceLocation Loc) const override {
13407     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13408   }
13409 
13410   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13411 };
13412 
13413 class LvalueConvBuilder: public ExprBuilder {
13414   const ExprBuilder &Builder;
13415 
13416 public:
13417   Expr *build(Sema &S, SourceLocation Loc) const override {
13418     return assertNotNull(
13419         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13420   }
13421 
13422   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13423 };
13424 
13425 class SubscriptBuilder: public ExprBuilder {
13426   const ExprBuilder &Base;
13427   const ExprBuilder &Index;
13428 
13429 public:
13430   Expr *build(Sema &S, SourceLocation Loc) const override {
13431     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13432         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13433   }
13434 
13435   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13436       : Base(Base), Index(Index) {}
13437 };
13438 
13439 } // end anonymous namespace
13440 
13441 /// When generating a defaulted copy or move assignment operator, if a field
13442 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13443 /// do so. This optimization only applies for arrays of scalars, and for arrays
13444 /// of class type where the selected copy/move-assignment operator is trivial.
13445 static StmtResult
13446 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13447                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13448   // Compute the size of the memory buffer to be copied.
13449   QualType SizeType = S.Context.getSizeType();
13450   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13451                    S.Context.getTypeSizeInChars(T).getQuantity());
13452 
13453   // Take the address of the field references for "from" and "to". We
13454   // directly construct UnaryOperators here because semantic analysis
13455   // does not permit us to take the address of an xvalue.
13456   Expr *From = FromB.build(S, Loc);
13457   From = UnaryOperator::Create(
13458       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13459       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatures);
13460   Expr *To = ToB.build(S, Loc);
13461   To = UnaryOperator::Create(S.Context, To, UO_AddrOf,
13462                              S.Context.getPointerType(To->getType()), VK_RValue,
13463                              OK_Ordinary, Loc, false, S.CurFPFeatures);
13464 
13465   const Type *E = T->getBaseElementTypeUnsafe();
13466   bool NeedsCollectableMemCpy =
13467       E->isRecordType() &&
13468       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13469 
13470   // Create a reference to the __builtin_objc_memmove_collectable function
13471   StringRef MemCpyName = NeedsCollectableMemCpy ?
13472     "__builtin_objc_memmove_collectable" :
13473     "__builtin_memcpy";
13474   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13475                  Sema::LookupOrdinaryName);
13476   S.LookupName(R, S.TUScope, true);
13477 
13478   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13479   if (!MemCpy)
13480     // Something went horribly wrong earlier, and we will have complained
13481     // about it.
13482     return StmtError();
13483 
13484   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13485                                             VK_RValue, Loc, nullptr);
13486   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13487 
13488   Expr *CallArgs[] = {
13489     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13490   };
13491   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13492                                     Loc, CallArgs, Loc);
13493 
13494   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13495   return Call.getAs<Stmt>();
13496 }
13497 
13498 /// Builds a statement that copies/moves the given entity from \p From to
13499 /// \c To.
13500 ///
13501 /// This routine is used to copy/move the members of a class with an
13502 /// implicitly-declared copy/move assignment operator. When the entities being
13503 /// copied are arrays, this routine builds for loops to copy them.
13504 ///
13505 /// \param S The Sema object used for type-checking.
13506 ///
13507 /// \param Loc The location where the implicit copy/move is being generated.
13508 ///
13509 /// \param T The type of the expressions being copied/moved. Both expressions
13510 /// must have this type.
13511 ///
13512 /// \param To The expression we are copying/moving to.
13513 ///
13514 /// \param From The expression we are copying/moving from.
13515 ///
13516 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13517 /// Otherwise, it's a non-static member subobject.
13518 ///
13519 /// \param Copying Whether we're copying or moving.
13520 ///
13521 /// \param Depth Internal parameter recording the depth of the recursion.
13522 ///
13523 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13524 /// if a memcpy should be used instead.
13525 static StmtResult
13526 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13527                                  const ExprBuilder &To, const ExprBuilder &From,
13528                                  bool CopyingBaseSubobject, bool Copying,
13529                                  unsigned Depth = 0) {
13530   // C++11 [class.copy]p28:
13531   //   Each subobject is assigned in the manner appropriate to its type:
13532   //
13533   //     - if the subobject is of class type, as if by a call to operator= with
13534   //       the subobject as the object expression and the corresponding
13535   //       subobject of x as a single function argument (as if by explicit
13536   //       qualification; that is, ignoring any possible virtual overriding
13537   //       functions in more derived classes);
13538   //
13539   // C++03 [class.copy]p13:
13540   //     - if the subobject is of class type, the copy assignment operator for
13541   //       the class is used (as if by explicit qualification; that is,
13542   //       ignoring any possible virtual overriding functions in more derived
13543   //       classes);
13544   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13545     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13546 
13547     // Look for operator=.
13548     DeclarationName Name
13549       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13550     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13551     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13552 
13553     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13554     // operator.
13555     if (!S.getLangOpts().CPlusPlus11) {
13556       LookupResult::Filter F = OpLookup.makeFilter();
13557       while (F.hasNext()) {
13558         NamedDecl *D = F.next();
13559         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13560           if (Method->isCopyAssignmentOperator() ||
13561               (!Copying && Method->isMoveAssignmentOperator()))
13562             continue;
13563 
13564         F.erase();
13565       }
13566       F.done();
13567     }
13568 
13569     // Suppress the protected check (C++ [class.protected]) for each of the
13570     // assignment operators we found. This strange dance is required when
13571     // we're assigning via a base classes's copy-assignment operator. To
13572     // ensure that we're getting the right base class subobject (without
13573     // ambiguities), we need to cast "this" to that subobject type; to
13574     // ensure that we don't go through the virtual call mechanism, we need
13575     // to qualify the operator= name with the base class (see below). However,
13576     // this means that if the base class has a protected copy assignment
13577     // operator, the protected member access check will fail. So, we
13578     // rewrite "protected" access to "public" access in this case, since we
13579     // know by construction that we're calling from a derived class.
13580     if (CopyingBaseSubobject) {
13581       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13582            L != LEnd; ++L) {
13583         if (L.getAccess() == AS_protected)
13584           L.setAccess(AS_public);
13585       }
13586     }
13587 
13588     // Create the nested-name-specifier that will be used to qualify the
13589     // reference to operator=; this is required to suppress the virtual
13590     // call mechanism.
13591     CXXScopeSpec SS;
13592     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13593     SS.MakeTrivial(S.Context,
13594                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13595                                                CanonicalT),
13596                    Loc);
13597 
13598     // Create the reference to operator=.
13599     ExprResult OpEqualRef
13600       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13601                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13602                                    /*FirstQualifierInScope=*/nullptr,
13603                                    OpLookup,
13604                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13605                                    /*SuppressQualifierCheck=*/true);
13606     if (OpEqualRef.isInvalid())
13607       return StmtError();
13608 
13609     // Build the call to the assignment operator.
13610 
13611     Expr *FromInst = From.build(S, Loc);
13612     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13613                                                   OpEqualRef.getAs<Expr>(),
13614                                                   Loc, FromInst, Loc);
13615     if (Call.isInvalid())
13616       return StmtError();
13617 
13618     // If we built a call to a trivial 'operator=' while copying an array,
13619     // bail out. We'll replace the whole shebang with a memcpy.
13620     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13621     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13622       return StmtResult((Stmt*)nullptr);
13623 
13624     // Convert to an expression-statement, and clean up any produced
13625     // temporaries.
13626     return S.ActOnExprStmt(Call);
13627   }
13628 
13629   //     - if the subobject is of scalar type, the built-in assignment
13630   //       operator is used.
13631   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13632   if (!ArrayTy) {
13633     ExprResult Assignment = S.CreateBuiltinBinOp(
13634         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13635     if (Assignment.isInvalid())
13636       return StmtError();
13637     return S.ActOnExprStmt(Assignment);
13638   }
13639 
13640   //     - if the subobject is an array, each element is assigned, in the
13641   //       manner appropriate to the element type;
13642 
13643   // Construct a loop over the array bounds, e.g.,
13644   //
13645   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13646   //
13647   // that will copy each of the array elements.
13648   QualType SizeType = S.Context.getSizeType();
13649 
13650   // Create the iteration variable.
13651   IdentifierInfo *IterationVarName = nullptr;
13652   {
13653     SmallString<8> Str;
13654     llvm::raw_svector_ostream OS(Str);
13655     OS << "__i" << Depth;
13656     IterationVarName = &S.Context.Idents.get(OS.str());
13657   }
13658   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13659                                           IterationVarName, SizeType,
13660                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13661                                           SC_None);
13662 
13663   // Initialize the iteration variable to zero.
13664   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13665   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13666 
13667   // Creates a reference to the iteration variable.
13668   RefBuilder IterationVarRef(IterationVar, SizeType);
13669   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13670 
13671   // Create the DeclStmt that holds the iteration variable.
13672   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13673 
13674   // Subscript the "from" and "to" expressions with the iteration variable.
13675   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13676   MoveCastBuilder FromIndexMove(FromIndexCopy);
13677   const ExprBuilder *FromIndex;
13678   if (Copying)
13679     FromIndex = &FromIndexCopy;
13680   else
13681     FromIndex = &FromIndexMove;
13682 
13683   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13684 
13685   // Build the copy/move for an individual element of the array.
13686   StmtResult Copy =
13687     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13688                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13689                                      Copying, Depth + 1);
13690   // Bail out if copying fails or if we determined that we should use memcpy.
13691   if (Copy.isInvalid() || !Copy.get())
13692     return Copy;
13693 
13694   // Create the comparison against the array bound.
13695   llvm::APInt Upper
13696     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13697   Expr *Comparison = BinaryOperator::Create(
13698       S.Context, IterationVarRefRVal.build(S, Loc),
13699       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13700       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatures);
13701 
13702   // Create the pre-increment of the iteration variable. We can determine
13703   // whether the increment will overflow based on the value of the array
13704   // bound.
13705   Expr *Increment = UnaryOperator::Create(
13706       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13707       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatures);
13708 
13709   // Construct the loop that copies all elements of this array.
13710   return S.ActOnForStmt(
13711       Loc, Loc, InitStmt,
13712       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13713       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13714 }
13715 
13716 static StmtResult
13717 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13718                       const ExprBuilder &To, const ExprBuilder &From,
13719                       bool CopyingBaseSubobject, bool Copying) {
13720   // Maybe we should use a memcpy?
13721   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13722       T.isTriviallyCopyableType(S.Context))
13723     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13724 
13725   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13726                                                      CopyingBaseSubobject,
13727                                                      Copying, 0));
13728 
13729   // If we ended up picking a trivial assignment operator for an array of a
13730   // non-trivially-copyable class type, just emit a memcpy.
13731   if (!Result.isInvalid() && !Result.get())
13732     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13733 
13734   return Result;
13735 }
13736 
13737 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13738   // Note: The following rules are largely analoguous to the copy
13739   // constructor rules. Note that virtual bases are not taken into account
13740   // for determining the argument type of the operator. Note also that
13741   // operators taking an object instead of a reference are allowed.
13742   assert(ClassDecl->needsImplicitCopyAssignment());
13743 
13744   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13745   if (DSM.isAlreadyBeingDeclared())
13746     return nullptr;
13747 
13748   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13749   LangAS AS = getDefaultCXXMethodAddrSpace();
13750   if (AS != LangAS::Default)
13751     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13752   QualType RetType = Context.getLValueReferenceType(ArgType);
13753   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13754   if (Const)
13755     ArgType = ArgType.withConst();
13756 
13757   ArgType = Context.getLValueReferenceType(ArgType);
13758 
13759   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13760                                                      CXXCopyAssignment,
13761                                                      Const);
13762 
13763   //   An implicitly-declared copy assignment operator is an inline public
13764   //   member of its class.
13765   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13766   SourceLocation ClassLoc = ClassDecl->getLocation();
13767   DeclarationNameInfo NameInfo(Name, ClassLoc);
13768   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13769       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13770       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13771       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13772       SourceLocation());
13773   CopyAssignment->setAccess(AS_public);
13774   CopyAssignment->setDefaulted();
13775   CopyAssignment->setImplicit();
13776 
13777   if (getLangOpts().CUDA) {
13778     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13779                                             CopyAssignment,
13780                                             /* ConstRHS */ Const,
13781                                             /* Diagnose */ false);
13782   }
13783 
13784   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13785 
13786   // Add the parameter to the operator.
13787   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13788                                                ClassLoc, ClassLoc,
13789                                                /*Id=*/nullptr, ArgType,
13790                                                /*TInfo=*/nullptr, SC_None,
13791                                                nullptr);
13792   CopyAssignment->setParams(FromParam);
13793 
13794   CopyAssignment->setTrivial(
13795     ClassDecl->needsOverloadResolutionForCopyAssignment()
13796       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13797       : ClassDecl->hasTrivialCopyAssignment());
13798 
13799   // Note that we have added this copy-assignment operator.
13800   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13801 
13802   Scope *S = getScopeForContext(ClassDecl);
13803   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13804 
13805   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
13806     SetDeclDeleted(CopyAssignment, ClassLoc);
13807 
13808   if (S)
13809     PushOnScopeChains(CopyAssignment, S, false);
13810   ClassDecl->addDecl(CopyAssignment);
13811 
13812   return CopyAssignment;
13813 }
13814 
13815 /// Diagnose an implicit copy operation for a class which is odr-used, but
13816 /// which is deprecated because the class has a user-declared copy constructor,
13817 /// copy assignment operator, or destructor.
13818 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13819   assert(CopyOp->isImplicit());
13820 
13821   CXXRecordDecl *RD = CopyOp->getParent();
13822   CXXMethodDecl *UserDeclaredOperation = nullptr;
13823 
13824   // In Microsoft mode, assignment operations don't affect constructors and
13825   // vice versa.
13826   if (RD->hasUserDeclaredDestructor()) {
13827     UserDeclaredOperation = RD->getDestructor();
13828   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13829              RD->hasUserDeclaredCopyConstructor() &&
13830              !S.getLangOpts().MSVCCompat) {
13831     // Find any user-declared copy constructor.
13832     for (auto *I : RD->ctors()) {
13833       if (I->isCopyConstructor()) {
13834         UserDeclaredOperation = I;
13835         break;
13836       }
13837     }
13838     assert(UserDeclaredOperation);
13839   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13840              RD->hasUserDeclaredCopyAssignment() &&
13841              !S.getLangOpts().MSVCCompat) {
13842     // Find any user-declared move assignment operator.
13843     for (auto *I : RD->methods()) {
13844       if (I->isCopyAssignmentOperator()) {
13845         UserDeclaredOperation = I;
13846         break;
13847       }
13848     }
13849     assert(UserDeclaredOperation);
13850   }
13851 
13852   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13853     S.Diag(UserDeclaredOperation->getLocation(),
13854            isa<CXXDestructorDecl>(UserDeclaredOperation)
13855                ? diag::warn_deprecated_copy_dtor_operation
13856                : diag::warn_deprecated_copy_operation)
13857         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13858   }
13859 }
13860 
13861 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13862                                         CXXMethodDecl *CopyAssignOperator) {
13863   assert((CopyAssignOperator->isDefaulted() &&
13864           CopyAssignOperator->isOverloadedOperator() &&
13865           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13866           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13867           !CopyAssignOperator->isDeleted()) &&
13868          "DefineImplicitCopyAssignment called for wrong function");
13869   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13870     return;
13871 
13872   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13873   if (ClassDecl->isInvalidDecl()) {
13874     CopyAssignOperator->setInvalidDecl();
13875     return;
13876   }
13877 
13878   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13879 
13880   // The exception specification is needed because we are defining the
13881   // function.
13882   ResolveExceptionSpec(CurrentLocation,
13883                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13884 
13885   // Add a context note for diagnostics produced after this point.
13886   Scope.addContextNote(CurrentLocation);
13887 
13888   // C++11 [class.copy]p18:
13889   //   The [definition of an implicitly declared copy assignment operator] is
13890   //   deprecated if the class has a user-declared copy constructor or a
13891   //   user-declared destructor.
13892   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13893     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13894 
13895   // C++0x [class.copy]p30:
13896   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13897   //   for a non-union class X performs memberwise copy assignment of its
13898   //   subobjects. The direct base classes of X are assigned first, in the
13899   //   order of their declaration in the base-specifier-list, and then the
13900   //   immediate non-static data members of X are assigned, in the order in
13901   //   which they were declared in the class definition.
13902 
13903   // The statements that form the synthesized function body.
13904   SmallVector<Stmt*, 8> Statements;
13905 
13906   // The parameter for the "other" object, which we are copying from.
13907   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13908   Qualifiers OtherQuals = Other->getType().getQualifiers();
13909   QualType OtherRefType = Other->getType();
13910   if (const LValueReferenceType *OtherRef
13911                                 = OtherRefType->getAs<LValueReferenceType>()) {
13912     OtherRefType = OtherRef->getPointeeType();
13913     OtherQuals = OtherRefType.getQualifiers();
13914   }
13915 
13916   // Our location for everything implicitly-generated.
13917   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
13918                            ? CopyAssignOperator->getEndLoc()
13919                            : CopyAssignOperator->getLocation();
13920 
13921   // Builds a DeclRefExpr for the "other" object.
13922   RefBuilder OtherRef(Other, OtherRefType);
13923 
13924   // Builds the "this" pointer.
13925   ThisBuilder This;
13926 
13927   // Assign base classes.
13928   bool Invalid = false;
13929   for (auto &Base : ClassDecl->bases()) {
13930     // Form the assignment:
13931     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
13932     QualType BaseType = Base.getType().getUnqualifiedType();
13933     if (!BaseType->isRecordType()) {
13934       Invalid = true;
13935       continue;
13936     }
13937 
13938     CXXCastPath BasePath;
13939     BasePath.push_back(&Base);
13940 
13941     // Construct the "from" expression, which is an implicit cast to the
13942     // appropriately-qualified base type.
13943     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
13944                      VK_LValue, BasePath);
13945 
13946     // Dereference "this".
13947     DerefBuilder DerefThis(This);
13948     CastBuilder To(DerefThis,
13949                    Context.getQualifiedType(
13950                        BaseType, CopyAssignOperator->getMethodQualifiers()),
13951                    VK_LValue, BasePath);
13952 
13953     // Build the copy.
13954     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
13955                                             To, From,
13956                                             /*CopyingBaseSubobject=*/true,
13957                                             /*Copying=*/true);
13958     if (Copy.isInvalid()) {
13959       CopyAssignOperator->setInvalidDecl();
13960       return;
13961     }
13962 
13963     // Success! Record the copy.
13964     Statements.push_back(Copy.getAs<Expr>());
13965   }
13966 
13967   // Assign non-static members.
13968   for (auto *Field : ClassDecl->fields()) {
13969     // FIXME: We should form some kind of AST representation for the implied
13970     // memcpy in a union copy operation.
13971     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
13972       continue;
13973 
13974     if (Field->isInvalidDecl()) {
13975       Invalid = true;
13976       continue;
13977     }
13978 
13979     // Check for members of reference type; we can't copy those.
13980     if (Field->getType()->isReferenceType()) {
13981       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
13982         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
13983       Diag(Field->getLocation(), diag::note_declared_at);
13984       Invalid = true;
13985       continue;
13986     }
13987 
13988     // Check for members of const-qualified, non-class type.
13989     QualType BaseType = Context.getBaseElementType(Field->getType());
13990     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
13991       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
13992         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
13993       Diag(Field->getLocation(), diag::note_declared_at);
13994       Invalid = true;
13995       continue;
13996     }
13997 
13998     // Suppress assigning zero-width bitfields.
13999     if (Field->isZeroLengthBitField(Context))
14000       continue;
14001 
14002     QualType FieldType = Field->getType().getNonReferenceType();
14003     if (FieldType->isIncompleteArrayType()) {
14004       assert(ClassDecl->hasFlexibleArrayMember() &&
14005              "Incomplete array type is not valid");
14006       continue;
14007     }
14008 
14009     // Build references to the field in the object we're copying from and to.
14010     CXXScopeSpec SS; // Intentionally empty
14011     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14012                               LookupMemberName);
14013     MemberLookup.addDecl(Field);
14014     MemberLookup.resolveKind();
14015 
14016     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14017 
14018     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14019 
14020     // Build the copy of this field.
14021     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14022                                             To, From,
14023                                             /*CopyingBaseSubobject=*/false,
14024                                             /*Copying=*/true);
14025     if (Copy.isInvalid()) {
14026       CopyAssignOperator->setInvalidDecl();
14027       return;
14028     }
14029 
14030     // Success! Record the copy.
14031     Statements.push_back(Copy.getAs<Stmt>());
14032   }
14033 
14034   if (!Invalid) {
14035     // Add a "return *this;"
14036     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14037 
14038     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14039     if (Return.isInvalid())
14040       Invalid = true;
14041     else
14042       Statements.push_back(Return.getAs<Stmt>());
14043   }
14044 
14045   if (Invalid) {
14046     CopyAssignOperator->setInvalidDecl();
14047     return;
14048   }
14049 
14050   StmtResult Body;
14051   {
14052     CompoundScopeRAII CompoundScope(*this);
14053     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14054                              /*isStmtExpr=*/false);
14055     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14056   }
14057   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14058   CopyAssignOperator->markUsed(Context);
14059 
14060   if (ASTMutationListener *L = getASTMutationListener()) {
14061     L->CompletedImplicitDefinition(CopyAssignOperator);
14062   }
14063 }
14064 
14065 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14066   assert(ClassDecl->needsImplicitMoveAssignment());
14067 
14068   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14069   if (DSM.isAlreadyBeingDeclared())
14070     return nullptr;
14071 
14072   // Note: The following rules are largely analoguous to the move
14073   // constructor rules.
14074 
14075   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14076   LangAS AS = getDefaultCXXMethodAddrSpace();
14077   if (AS != LangAS::Default)
14078     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14079   QualType RetType = Context.getLValueReferenceType(ArgType);
14080   ArgType = Context.getRValueReferenceType(ArgType);
14081 
14082   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14083                                                      CXXMoveAssignment,
14084                                                      false);
14085 
14086   //   An implicitly-declared move assignment operator is an inline public
14087   //   member of its class.
14088   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14089   SourceLocation ClassLoc = ClassDecl->getLocation();
14090   DeclarationNameInfo NameInfo(Name, ClassLoc);
14091   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14092       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14093       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14094       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14095       SourceLocation());
14096   MoveAssignment->setAccess(AS_public);
14097   MoveAssignment->setDefaulted();
14098   MoveAssignment->setImplicit();
14099 
14100   if (getLangOpts().CUDA) {
14101     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14102                                             MoveAssignment,
14103                                             /* ConstRHS */ false,
14104                                             /* Diagnose */ false);
14105   }
14106 
14107   // Build an exception specification pointing back at this member.
14108   FunctionProtoType::ExtProtoInfo EPI =
14109       getImplicitMethodEPI(*this, MoveAssignment);
14110   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14111 
14112   // Add the parameter to the operator.
14113   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14114                                                ClassLoc, ClassLoc,
14115                                                /*Id=*/nullptr, ArgType,
14116                                                /*TInfo=*/nullptr, SC_None,
14117                                                nullptr);
14118   MoveAssignment->setParams(FromParam);
14119 
14120   MoveAssignment->setTrivial(
14121     ClassDecl->needsOverloadResolutionForMoveAssignment()
14122       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14123       : ClassDecl->hasTrivialMoveAssignment());
14124 
14125   // Note that we have added this copy-assignment operator.
14126   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14127 
14128   Scope *S = getScopeForContext(ClassDecl);
14129   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14130 
14131   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14132     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14133     SetDeclDeleted(MoveAssignment, ClassLoc);
14134   }
14135 
14136   if (S)
14137     PushOnScopeChains(MoveAssignment, S, false);
14138   ClassDecl->addDecl(MoveAssignment);
14139 
14140   return MoveAssignment;
14141 }
14142 
14143 /// Check if we're implicitly defining a move assignment operator for a class
14144 /// with virtual bases. Such a move assignment might move-assign the virtual
14145 /// base multiple times.
14146 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14147                                                SourceLocation CurrentLocation) {
14148   assert(!Class->isDependentContext() && "should not define dependent move");
14149 
14150   // Only a virtual base could get implicitly move-assigned multiple times.
14151   // Only a non-trivial move assignment can observe this. We only want to
14152   // diagnose if we implicitly define an assignment operator that assigns
14153   // two base classes, both of which move-assign the same virtual base.
14154   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14155       Class->getNumBases() < 2)
14156     return;
14157 
14158   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14159   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14160   VBaseMap VBases;
14161 
14162   for (auto &BI : Class->bases()) {
14163     Worklist.push_back(&BI);
14164     while (!Worklist.empty()) {
14165       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14166       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14167 
14168       // If the base has no non-trivial move assignment operators,
14169       // we don't care about moves from it.
14170       if (!Base->hasNonTrivialMoveAssignment())
14171         continue;
14172 
14173       // If there's nothing virtual here, skip it.
14174       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14175         continue;
14176 
14177       // If we're not actually going to call a move assignment for this base,
14178       // or the selected move assignment is trivial, skip it.
14179       Sema::SpecialMemberOverloadResult SMOR =
14180         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14181                               /*ConstArg*/false, /*VolatileArg*/false,
14182                               /*RValueThis*/true, /*ConstThis*/false,
14183                               /*VolatileThis*/false);
14184       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14185           !SMOR.getMethod()->isMoveAssignmentOperator())
14186         continue;
14187 
14188       if (BaseSpec->isVirtual()) {
14189         // We're going to move-assign this virtual base, and its move
14190         // assignment operator is not trivial. If this can happen for
14191         // multiple distinct direct bases of Class, diagnose it. (If it
14192         // only happens in one base, we'll diagnose it when synthesizing
14193         // that base class's move assignment operator.)
14194         CXXBaseSpecifier *&Existing =
14195             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14196                 .first->second;
14197         if (Existing && Existing != &BI) {
14198           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14199             << Class << Base;
14200           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14201               << (Base->getCanonicalDecl() ==
14202                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14203               << Base << Existing->getType() << Existing->getSourceRange();
14204           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14205               << (Base->getCanonicalDecl() ==
14206                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14207               << Base << BI.getType() << BaseSpec->getSourceRange();
14208 
14209           // Only diagnose each vbase once.
14210           Existing = nullptr;
14211         }
14212       } else {
14213         // Only walk over bases that have defaulted move assignment operators.
14214         // We assume that any user-provided move assignment operator handles
14215         // the multiple-moves-of-vbase case itself somehow.
14216         if (!SMOR.getMethod()->isDefaulted())
14217           continue;
14218 
14219         // We're going to move the base classes of Base. Add them to the list.
14220         for (auto &BI : Base->bases())
14221           Worklist.push_back(&BI);
14222       }
14223     }
14224   }
14225 }
14226 
14227 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14228                                         CXXMethodDecl *MoveAssignOperator) {
14229   assert((MoveAssignOperator->isDefaulted() &&
14230           MoveAssignOperator->isOverloadedOperator() &&
14231           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14232           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14233           !MoveAssignOperator->isDeleted()) &&
14234          "DefineImplicitMoveAssignment called for wrong function");
14235   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14236     return;
14237 
14238   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14239   if (ClassDecl->isInvalidDecl()) {
14240     MoveAssignOperator->setInvalidDecl();
14241     return;
14242   }
14243 
14244   // C++0x [class.copy]p28:
14245   //   The implicitly-defined or move assignment operator for a non-union class
14246   //   X performs memberwise move assignment of its subobjects. The direct base
14247   //   classes of X are assigned first, in the order of their declaration in the
14248   //   base-specifier-list, and then the immediate non-static data members of X
14249   //   are assigned, in the order in which they were declared in the class
14250   //   definition.
14251 
14252   // Issue a warning if our implicit move assignment operator will move
14253   // from a virtual base more than once.
14254   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14255 
14256   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14257 
14258   // The exception specification is needed because we are defining the
14259   // function.
14260   ResolveExceptionSpec(CurrentLocation,
14261                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14262 
14263   // Add a context note for diagnostics produced after this point.
14264   Scope.addContextNote(CurrentLocation);
14265 
14266   // The statements that form the synthesized function body.
14267   SmallVector<Stmt*, 8> Statements;
14268 
14269   // The parameter for the "other" object, which we are move from.
14270   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14271   QualType OtherRefType =
14272       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14273 
14274   // Our location for everything implicitly-generated.
14275   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14276                            ? MoveAssignOperator->getEndLoc()
14277                            : MoveAssignOperator->getLocation();
14278 
14279   // Builds a reference to the "other" object.
14280   RefBuilder OtherRef(Other, OtherRefType);
14281   // Cast to rvalue.
14282   MoveCastBuilder MoveOther(OtherRef);
14283 
14284   // Builds the "this" pointer.
14285   ThisBuilder This;
14286 
14287   // Assign base classes.
14288   bool Invalid = false;
14289   for (auto &Base : ClassDecl->bases()) {
14290     // C++11 [class.copy]p28:
14291     //   It is unspecified whether subobjects representing virtual base classes
14292     //   are assigned more than once by the implicitly-defined copy assignment
14293     //   operator.
14294     // FIXME: Do not assign to a vbase that will be assigned by some other base
14295     // class. For a move-assignment, this can result in the vbase being moved
14296     // multiple times.
14297 
14298     // Form the assignment:
14299     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14300     QualType BaseType = Base.getType().getUnqualifiedType();
14301     if (!BaseType->isRecordType()) {
14302       Invalid = true;
14303       continue;
14304     }
14305 
14306     CXXCastPath BasePath;
14307     BasePath.push_back(&Base);
14308 
14309     // Construct the "from" expression, which is an implicit cast to the
14310     // appropriately-qualified base type.
14311     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14312 
14313     // Dereference "this".
14314     DerefBuilder DerefThis(This);
14315 
14316     // Implicitly cast "this" to the appropriately-qualified base type.
14317     CastBuilder To(DerefThis,
14318                    Context.getQualifiedType(
14319                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14320                    VK_LValue, BasePath);
14321 
14322     // Build the move.
14323     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14324                                             To, From,
14325                                             /*CopyingBaseSubobject=*/true,
14326                                             /*Copying=*/false);
14327     if (Move.isInvalid()) {
14328       MoveAssignOperator->setInvalidDecl();
14329       return;
14330     }
14331 
14332     // Success! Record the move.
14333     Statements.push_back(Move.getAs<Expr>());
14334   }
14335 
14336   // Assign non-static members.
14337   for (auto *Field : ClassDecl->fields()) {
14338     // FIXME: We should form some kind of AST representation for the implied
14339     // memcpy in a union copy operation.
14340     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14341       continue;
14342 
14343     if (Field->isInvalidDecl()) {
14344       Invalid = true;
14345       continue;
14346     }
14347 
14348     // Check for members of reference type; we can't move those.
14349     if (Field->getType()->isReferenceType()) {
14350       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14351         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14352       Diag(Field->getLocation(), diag::note_declared_at);
14353       Invalid = true;
14354       continue;
14355     }
14356 
14357     // Check for members of const-qualified, non-class type.
14358     QualType BaseType = Context.getBaseElementType(Field->getType());
14359     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14360       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14361         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14362       Diag(Field->getLocation(), diag::note_declared_at);
14363       Invalid = true;
14364       continue;
14365     }
14366 
14367     // Suppress assigning zero-width bitfields.
14368     if (Field->isZeroLengthBitField(Context))
14369       continue;
14370 
14371     QualType FieldType = Field->getType().getNonReferenceType();
14372     if (FieldType->isIncompleteArrayType()) {
14373       assert(ClassDecl->hasFlexibleArrayMember() &&
14374              "Incomplete array type is not valid");
14375       continue;
14376     }
14377 
14378     // Build references to the field in the object we're copying from and to.
14379     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14380                               LookupMemberName);
14381     MemberLookup.addDecl(Field);
14382     MemberLookup.resolveKind();
14383     MemberBuilder From(MoveOther, OtherRefType,
14384                        /*IsArrow=*/false, MemberLookup);
14385     MemberBuilder To(This, getCurrentThisType(),
14386                      /*IsArrow=*/true, MemberLookup);
14387 
14388     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14389         "Member reference with rvalue base must be rvalue except for reference "
14390         "members, which aren't allowed for move assignment.");
14391 
14392     // Build the move of this field.
14393     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14394                                             To, From,
14395                                             /*CopyingBaseSubobject=*/false,
14396                                             /*Copying=*/false);
14397     if (Move.isInvalid()) {
14398       MoveAssignOperator->setInvalidDecl();
14399       return;
14400     }
14401 
14402     // Success! Record the copy.
14403     Statements.push_back(Move.getAs<Stmt>());
14404   }
14405 
14406   if (!Invalid) {
14407     // Add a "return *this;"
14408     ExprResult ThisObj =
14409         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14410 
14411     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14412     if (Return.isInvalid())
14413       Invalid = true;
14414     else
14415       Statements.push_back(Return.getAs<Stmt>());
14416   }
14417 
14418   if (Invalid) {
14419     MoveAssignOperator->setInvalidDecl();
14420     return;
14421   }
14422 
14423   StmtResult Body;
14424   {
14425     CompoundScopeRAII CompoundScope(*this);
14426     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14427                              /*isStmtExpr=*/false);
14428     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14429   }
14430   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14431   MoveAssignOperator->markUsed(Context);
14432 
14433   if (ASTMutationListener *L = getASTMutationListener()) {
14434     L->CompletedImplicitDefinition(MoveAssignOperator);
14435   }
14436 }
14437 
14438 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14439                                                     CXXRecordDecl *ClassDecl) {
14440   // C++ [class.copy]p4:
14441   //   If the class definition does not explicitly declare a copy
14442   //   constructor, one is declared implicitly.
14443   assert(ClassDecl->needsImplicitCopyConstructor());
14444 
14445   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14446   if (DSM.isAlreadyBeingDeclared())
14447     return nullptr;
14448 
14449   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14450   QualType ArgType = ClassType;
14451   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14452   if (Const)
14453     ArgType = ArgType.withConst();
14454 
14455   LangAS AS = getDefaultCXXMethodAddrSpace();
14456   if (AS != LangAS::Default)
14457     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14458 
14459   ArgType = Context.getLValueReferenceType(ArgType);
14460 
14461   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14462                                                      CXXCopyConstructor,
14463                                                      Const);
14464 
14465   DeclarationName Name
14466     = Context.DeclarationNames.getCXXConstructorName(
14467                                            Context.getCanonicalType(ClassType));
14468   SourceLocation ClassLoc = ClassDecl->getLocation();
14469   DeclarationNameInfo NameInfo(Name, ClassLoc);
14470 
14471   //   An implicitly-declared copy constructor is an inline public
14472   //   member of its class.
14473   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14474       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14475       ExplicitSpecifier(),
14476       /*isInline=*/true,
14477       /*isImplicitlyDeclared=*/true,
14478       Constexpr ? CSK_constexpr : CSK_unspecified);
14479   CopyConstructor->setAccess(AS_public);
14480   CopyConstructor->setDefaulted();
14481 
14482   if (getLangOpts().CUDA) {
14483     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14484                                             CopyConstructor,
14485                                             /* ConstRHS */ Const,
14486                                             /* Diagnose */ false);
14487   }
14488 
14489   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14490 
14491   // Add the parameter to the constructor.
14492   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14493                                                ClassLoc, ClassLoc,
14494                                                /*IdentifierInfo=*/nullptr,
14495                                                ArgType, /*TInfo=*/nullptr,
14496                                                SC_None, nullptr);
14497   CopyConstructor->setParams(FromParam);
14498 
14499   CopyConstructor->setTrivial(
14500       ClassDecl->needsOverloadResolutionForCopyConstructor()
14501           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14502           : ClassDecl->hasTrivialCopyConstructor());
14503 
14504   CopyConstructor->setTrivialForCall(
14505       ClassDecl->hasAttr<TrivialABIAttr>() ||
14506       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14507            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14508              TAH_ConsiderTrivialABI)
14509            : ClassDecl->hasTrivialCopyConstructorForCall()));
14510 
14511   // Note that we have declared this constructor.
14512   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14513 
14514   Scope *S = getScopeForContext(ClassDecl);
14515   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14516 
14517   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14518     ClassDecl->setImplicitCopyConstructorIsDeleted();
14519     SetDeclDeleted(CopyConstructor, ClassLoc);
14520   }
14521 
14522   if (S)
14523     PushOnScopeChains(CopyConstructor, S, false);
14524   ClassDecl->addDecl(CopyConstructor);
14525 
14526   return CopyConstructor;
14527 }
14528 
14529 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14530                                          CXXConstructorDecl *CopyConstructor) {
14531   assert((CopyConstructor->isDefaulted() &&
14532           CopyConstructor->isCopyConstructor() &&
14533           !CopyConstructor->doesThisDeclarationHaveABody() &&
14534           !CopyConstructor->isDeleted()) &&
14535          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14536   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14537     return;
14538 
14539   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14540   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14541 
14542   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14543 
14544   // The exception specification is needed because we are defining the
14545   // function.
14546   ResolveExceptionSpec(CurrentLocation,
14547                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14548   MarkVTableUsed(CurrentLocation, ClassDecl);
14549 
14550   // Add a context note for diagnostics produced after this point.
14551   Scope.addContextNote(CurrentLocation);
14552 
14553   // C++11 [class.copy]p7:
14554   //   The [definition of an implicitly declared copy constructor] is
14555   //   deprecated if the class has a user-declared copy assignment operator
14556   //   or a user-declared destructor.
14557   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14558     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14559 
14560   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14561     CopyConstructor->setInvalidDecl();
14562   }  else {
14563     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14564                              ? CopyConstructor->getEndLoc()
14565                              : CopyConstructor->getLocation();
14566     Sema::CompoundScopeRAII CompoundScope(*this);
14567     CopyConstructor->setBody(
14568         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14569     CopyConstructor->markUsed(Context);
14570   }
14571 
14572   if (ASTMutationListener *L = getASTMutationListener()) {
14573     L->CompletedImplicitDefinition(CopyConstructor);
14574   }
14575 }
14576 
14577 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14578                                                     CXXRecordDecl *ClassDecl) {
14579   assert(ClassDecl->needsImplicitMoveConstructor());
14580 
14581   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14582   if (DSM.isAlreadyBeingDeclared())
14583     return nullptr;
14584 
14585   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14586 
14587   QualType ArgType = ClassType;
14588   LangAS AS = getDefaultCXXMethodAddrSpace();
14589   if (AS != LangAS::Default)
14590     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14591   ArgType = Context.getRValueReferenceType(ArgType);
14592 
14593   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14594                                                      CXXMoveConstructor,
14595                                                      false);
14596 
14597   DeclarationName Name
14598     = Context.DeclarationNames.getCXXConstructorName(
14599                                            Context.getCanonicalType(ClassType));
14600   SourceLocation ClassLoc = ClassDecl->getLocation();
14601   DeclarationNameInfo NameInfo(Name, ClassLoc);
14602 
14603   // C++11 [class.copy]p11:
14604   //   An implicitly-declared copy/move constructor is an inline public
14605   //   member of its class.
14606   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14607       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14608       ExplicitSpecifier(),
14609       /*isInline=*/true,
14610       /*isImplicitlyDeclared=*/true,
14611       Constexpr ? CSK_constexpr : CSK_unspecified);
14612   MoveConstructor->setAccess(AS_public);
14613   MoveConstructor->setDefaulted();
14614 
14615   if (getLangOpts().CUDA) {
14616     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14617                                             MoveConstructor,
14618                                             /* ConstRHS */ false,
14619                                             /* Diagnose */ false);
14620   }
14621 
14622   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14623 
14624   // Add the parameter to the constructor.
14625   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14626                                                ClassLoc, ClassLoc,
14627                                                /*IdentifierInfo=*/nullptr,
14628                                                ArgType, /*TInfo=*/nullptr,
14629                                                SC_None, nullptr);
14630   MoveConstructor->setParams(FromParam);
14631 
14632   MoveConstructor->setTrivial(
14633       ClassDecl->needsOverloadResolutionForMoveConstructor()
14634           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14635           : ClassDecl->hasTrivialMoveConstructor());
14636 
14637   MoveConstructor->setTrivialForCall(
14638       ClassDecl->hasAttr<TrivialABIAttr>() ||
14639       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14640            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14641                                     TAH_ConsiderTrivialABI)
14642            : ClassDecl->hasTrivialMoveConstructorForCall()));
14643 
14644   // Note that we have declared this constructor.
14645   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14646 
14647   Scope *S = getScopeForContext(ClassDecl);
14648   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14649 
14650   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14651     ClassDecl->setImplicitMoveConstructorIsDeleted();
14652     SetDeclDeleted(MoveConstructor, ClassLoc);
14653   }
14654 
14655   if (S)
14656     PushOnScopeChains(MoveConstructor, S, false);
14657   ClassDecl->addDecl(MoveConstructor);
14658 
14659   return MoveConstructor;
14660 }
14661 
14662 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14663                                          CXXConstructorDecl *MoveConstructor) {
14664   assert((MoveConstructor->isDefaulted() &&
14665           MoveConstructor->isMoveConstructor() &&
14666           !MoveConstructor->doesThisDeclarationHaveABody() &&
14667           !MoveConstructor->isDeleted()) &&
14668          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14669   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14670     return;
14671 
14672   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14673   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14674 
14675   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14676 
14677   // The exception specification is needed because we are defining the
14678   // function.
14679   ResolveExceptionSpec(CurrentLocation,
14680                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14681   MarkVTableUsed(CurrentLocation, ClassDecl);
14682 
14683   // Add a context note for diagnostics produced after this point.
14684   Scope.addContextNote(CurrentLocation);
14685 
14686   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14687     MoveConstructor->setInvalidDecl();
14688   } else {
14689     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14690                              ? MoveConstructor->getEndLoc()
14691                              : MoveConstructor->getLocation();
14692     Sema::CompoundScopeRAII CompoundScope(*this);
14693     MoveConstructor->setBody(ActOnCompoundStmt(
14694         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14695     MoveConstructor->markUsed(Context);
14696   }
14697 
14698   if (ASTMutationListener *L = getASTMutationListener()) {
14699     L->CompletedImplicitDefinition(MoveConstructor);
14700   }
14701 }
14702 
14703 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14704   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14705 }
14706 
14707 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14708                             SourceLocation CurrentLocation,
14709                             CXXConversionDecl *Conv) {
14710   SynthesizedFunctionScope Scope(*this, Conv);
14711   assert(!Conv->getReturnType()->isUndeducedType());
14712 
14713   CXXRecordDecl *Lambda = Conv->getParent();
14714   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14715   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14716 
14717   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14718     CallOp = InstantiateFunctionDeclaration(
14719         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14720     if (!CallOp)
14721       return;
14722 
14723     Invoker = InstantiateFunctionDeclaration(
14724         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14725     if (!Invoker)
14726       return;
14727   }
14728 
14729   if (CallOp->isInvalidDecl())
14730     return;
14731 
14732   // Mark the call operator referenced (and add to pending instantiations
14733   // if necessary).
14734   // For both the conversion and static-invoker template specializations
14735   // we construct their body's in this function, so no need to add them
14736   // to the PendingInstantiations.
14737   MarkFunctionReferenced(CurrentLocation, CallOp);
14738 
14739   // Fill in the __invoke function with a dummy implementation. IR generation
14740   // will fill in the actual details. Update its type in case it contained
14741   // an 'auto'.
14742   Invoker->markUsed(Context);
14743   Invoker->setReferenced();
14744   Invoker->setType(Conv->getReturnType()->getPointeeType());
14745   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14746 
14747   // Construct the body of the conversion function { return __invoke; }.
14748   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14749                                        VK_LValue, Conv->getLocation());
14750   assert(FunctionRef && "Can't refer to __invoke function?");
14751   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14752   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14753                                      Conv->getLocation()));
14754   Conv->markUsed(Context);
14755   Conv->setReferenced();
14756 
14757   if (ASTMutationListener *L = getASTMutationListener()) {
14758     L->CompletedImplicitDefinition(Conv);
14759     L->CompletedImplicitDefinition(Invoker);
14760   }
14761 }
14762 
14763 
14764 
14765 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14766        SourceLocation CurrentLocation,
14767        CXXConversionDecl *Conv)
14768 {
14769   assert(!Conv->getParent()->isGenericLambda());
14770 
14771   SynthesizedFunctionScope Scope(*this, Conv);
14772 
14773   // Copy-initialize the lambda object as needed to capture it.
14774   Expr *This = ActOnCXXThis(CurrentLocation).get();
14775   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14776 
14777   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14778                                                         Conv->getLocation(),
14779                                                         Conv, DerefThis);
14780 
14781   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14782   // behavior.  Note that only the general conversion function does this
14783   // (since it's unusable otherwise); in the case where we inline the
14784   // block literal, it has block literal lifetime semantics.
14785   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14786     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14787                                           CK_CopyAndAutoreleaseBlockObject,
14788                                           BuildBlock.get(), nullptr, VK_RValue);
14789 
14790   if (BuildBlock.isInvalid()) {
14791     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14792     Conv->setInvalidDecl();
14793     return;
14794   }
14795 
14796   // Create the return statement that returns the block from the conversion
14797   // function.
14798   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14799   if (Return.isInvalid()) {
14800     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14801     Conv->setInvalidDecl();
14802     return;
14803   }
14804 
14805   // Set the body of the conversion function.
14806   Stmt *ReturnS = Return.get();
14807   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14808                                      Conv->getLocation()));
14809   Conv->markUsed(Context);
14810 
14811   // We're done; notify the mutation listener, if any.
14812   if (ASTMutationListener *L = getASTMutationListener()) {
14813     L->CompletedImplicitDefinition(Conv);
14814   }
14815 }
14816 
14817 /// Determine whether the given list arguments contains exactly one
14818 /// "real" (non-default) argument.
14819 static bool hasOneRealArgument(MultiExprArg Args) {
14820   switch (Args.size()) {
14821   case 0:
14822     return false;
14823 
14824   default:
14825     if (!Args[1]->isDefaultArgument())
14826       return false;
14827 
14828     LLVM_FALLTHROUGH;
14829   case 1:
14830     return !Args[0]->isDefaultArgument();
14831   }
14832 
14833   return false;
14834 }
14835 
14836 ExprResult
14837 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14838                             NamedDecl *FoundDecl,
14839                             CXXConstructorDecl *Constructor,
14840                             MultiExprArg ExprArgs,
14841                             bool HadMultipleCandidates,
14842                             bool IsListInitialization,
14843                             bool IsStdInitListInitialization,
14844                             bool RequiresZeroInit,
14845                             unsigned ConstructKind,
14846                             SourceRange ParenRange) {
14847   bool Elidable = false;
14848 
14849   // C++0x [class.copy]p34:
14850   //   When certain criteria are met, an implementation is allowed to
14851   //   omit the copy/move construction of a class object, even if the
14852   //   copy/move constructor and/or destructor for the object have
14853   //   side effects. [...]
14854   //     - when a temporary class object that has not been bound to a
14855   //       reference (12.2) would be copied/moved to a class object
14856   //       with the same cv-unqualified type, the copy/move operation
14857   //       can be omitted by constructing the temporary object
14858   //       directly into the target of the omitted copy/move
14859   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14860       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14861     Expr *SubExpr = ExprArgs[0];
14862     Elidable = SubExpr->isTemporaryObject(
14863         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14864   }
14865 
14866   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14867                                FoundDecl, Constructor,
14868                                Elidable, ExprArgs, HadMultipleCandidates,
14869                                IsListInitialization,
14870                                IsStdInitListInitialization, RequiresZeroInit,
14871                                ConstructKind, ParenRange);
14872 }
14873 
14874 ExprResult
14875 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14876                             NamedDecl *FoundDecl,
14877                             CXXConstructorDecl *Constructor,
14878                             bool Elidable,
14879                             MultiExprArg ExprArgs,
14880                             bool HadMultipleCandidates,
14881                             bool IsListInitialization,
14882                             bool IsStdInitListInitialization,
14883                             bool RequiresZeroInit,
14884                             unsigned ConstructKind,
14885                             SourceRange ParenRange) {
14886   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14887     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14888     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14889       return ExprError();
14890   }
14891 
14892   return BuildCXXConstructExpr(
14893       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14894       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14895       RequiresZeroInit, ConstructKind, ParenRange);
14896 }
14897 
14898 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14899 /// including handling of its default argument expressions.
14900 ExprResult
14901 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14902                             CXXConstructorDecl *Constructor,
14903                             bool Elidable,
14904                             MultiExprArg ExprArgs,
14905                             bool HadMultipleCandidates,
14906                             bool IsListInitialization,
14907                             bool IsStdInitListInitialization,
14908                             bool RequiresZeroInit,
14909                             unsigned ConstructKind,
14910                             SourceRange ParenRange) {
14911   assert(declaresSameEntity(
14912              Constructor->getParent(),
14913              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14914          "given constructor for wrong type");
14915   MarkFunctionReferenced(ConstructLoc, Constructor);
14916   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
14917     return ExprError();
14918 
14919   return CheckForImmediateInvocation(
14920       CXXConstructExpr::Create(
14921           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
14922           HadMultipleCandidates, IsListInitialization,
14923           IsStdInitListInitialization, RequiresZeroInit,
14924           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
14925           ParenRange),
14926       Constructor);
14927 }
14928 
14929 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
14930   assert(Field->hasInClassInitializer());
14931 
14932   // If we already have the in-class initializer nothing needs to be done.
14933   if (Field->getInClassInitializer())
14934     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
14935 
14936   // If we might have already tried and failed to instantiate, don't try again.
14937   if (Field->isInvalidDecl())
14938     return ExprError();
14939 
14940   // Maybe we haven't instantiated the in-class initializer. Go check the
14941   // pattern FieldDecl to see if it has one.
14942   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
14943 
14944   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
14945     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
14946     DeclContext::lookup_result Lookup =
14947         ClassPattern->lookup(Field->getDeclName());
14948 
14949     // Lookup can return at most two results: the pattern for the field, or the
14950     // injected class name of the parent record. No other member can have the
14951     // same name as the field.
14952     // In modules mode, lookup can return multiple results (coming from
14953     // different modules).
14954     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
14955            "more than two lookup results for field name");
14956     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
14957     if (!Pattern) {
14958       assert(isa<CXXRecordDecl>(Lookup[0]) &&
14959              "cannot have other non-field member with same name");
14960       for (auto L : Lookup)
14961         if (isa<FieldDecl>(L)) {
14962           Pattern = cast<FieldDecl>(L);
14963           break;
14964         }
14965       assert(Pattern && "We must have set the Pattern!");
14966     }
14967 
14968     if (!Pattern->hasInClassInitializer() ||
14969         InstantiateInClassInitializer(Loc, Field, Pattern,
14970                                       getTemplateInstantiationArgs(Field))) {
14971       // Don't diagnose this again.
14972       Field->setInvalidDecl();
14973       return ExprError();
14974     }
14975     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
14976   }
14977 
14978   // DR1351:
14979   //   If the brace-or-equal-initializer of a non-static data member
14980   //   invokes a defaulted default constructor of its class or of an
14981   //   enclosing class in a potentially evaluated subexpression, the
14982   //   program is ill-formed.
14983   //
14984   // This resolution is unworkable: the exception specification of the
14985   // default constructor can be needed in an unevaluated context, in
14986   // particular, in the operand of a noexcept-expression, and we can be
14987   // unable to compute an exception specification for an enclosed class.
14988   //
14989   // Any attempt to resolve the exception specification of a defaulted default
14990   // constructor before the initializer is lexically complete will ultimately
14991   // come here at which point we can diagnose it.
14992   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
14993   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
14994       << OutermostClass << Field;
14995   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
14996   // Recover by marking the field invalid, unless we're in a SFINAE context.
14997   if (!isSFINAEContext())
14998     Field->setInvalidDecl();
14999   return ExprError();
15000 }
15001 
15002 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15003   if (VD->isInvalidDecl()) return;
15004   // If initializing the variable failed, don't also diagnose problems with
15005   // the desctructor, they're likely related.
15006   if (VD->getInit() && VD->getInit()->containsErrors())
15007     return;
15008 
15009   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15010   if (ClassDecl->isInvalidDecl()) return;
15011   if (ClassDecl->hasIrrelevantDestructor()) return;
15012   if (ClassDecl->isDependentContext()) return;
15013 
15014   if (VD->isNoDestroy(getASTContext()))
15015     return;
15016 
15017   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15018 
15019   // If this is an array, we'll require the destructor during initialization, so
15020   // we can skip over this. We still want to emit exit-time destructor warnings
15021   // though.
15022   if (!VD->getType()->isArrayType()) {
15023     MarkFunctionReferenced(VD->getLocation(), Destructor);
15024     CheckDestructorAccess(VD->getLocation(), Destructor,
15025                           PDiag(diag::err_access_dtor_var)
15026                               << VD->getDeclName() << VD->getType());
15027     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15028   }
15029 
15030   if (Destructor->isTrivial()) return;
15031 
15032   // If the destructor is constexpr, check whether the variable has constant
15033   // destruction now.
15034   if (Destructor->isConstexpr()) {
15035     bool HasConstantInit = false;
15036     if (VD->getInit() && !VD->getInit()->isValueDependent())
15037       HasConstantInit = VD->evaluateValue();
15038     SmallVector<PartialDiagnosticAt, 8> Notes;
15039     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15040         HasConstantInit) {
15041       Diag(VD->getLocation(),
15042            diag::err_constexpr_var_requires_const_destruction) << VD;
15043       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15044         Diag(Notes[I].first, Notes[I].second);
15045     }
15046   }
15047 
15048   if (!VD->hasGlobalStorage()) return;
15049 
15050   // Emit warning for non-trivial dtor in global scope (a real global,
15051   // class-static, function-static).
15052   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15053 
15054   // TODO: this should be re-enabled for static locals by !CXAAtExit
15055   if (!VD->isStaticLocal())
15056     Diag(VD->getLocation(), diag::warn_global_destructor);
15057 }
15058 
15059 /// Given a constructor and the set of arguments provided for the
15060 /// constructor, convert the arguments and add any required default arguments
15061 /// to form a proper call to this constructor.
15062 ///
15063 /// \returns true if an error occurred, false otherwise.
15064 bool
15065 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15066                               MultiExprArg ArgsPtr,
15067                               SourceLocation Loc,
15068                               SmallVectorImpl<Expr*> &ConvertedArgs,
15069                               bool AllowExplicit,
15070                               bool IsListInitialization) {
15071   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15072   unsigned NumArgs = ArgsPtr.size();
15073   Expr **Args = ArgsPtr.data();
15074 
15075   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15076   unsigned NumParams = Proto->getNumParams();
15077 
15078   // If too few arguments are available, we'll fill in the rest with defaults.
15079   if (NumArgs < NumParams)
15080     ConvertedArgs.reserve(NumParams);
15081   else
15082     ConvertedArgs.reserve(NumArgs);
15083 
15084   VariadicCallType CallType =
15085     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15086   SmallVector<Expr *, 8> AllArgs;
15087   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15088                                         Proto, 0,
15089                                         llvm::makeArrayRef(Args, NumArgs),
15090                                         AllArgs,
15091                                         CallType, AllowExplicit,
15092                                         IsListInitialization);
15093   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15094 
15095   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15096 
15097   CheckConstructorCall(Constructor,
15098                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15099                        Proto, Loc);
15100 
15101   return Invalid;
15102 }
15103 
15104 static inline bool
15105 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15106                                        const FunctionDecl *FnDecl) {
15107   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15108   if (isa<NamespaceDecl>(DC)) {
15109     return SemaRef.Diag(FnDecl->getLocation(),
15110                         diag::err_operator_new_delete_declared_in_namespace)
15111       << FnDecl->getDeclName();
15112   }
15113 
15114   if (isa<TranslationUnitDecl>(DC) &&
15115       FnDecl->getStorageClass() == SC_Static) {
15116     return SemaRef.Diag(FnDecl->getLocation(),
15117                         diag::err_operator_new_delete_declared_static)
15118       << FnDecl->getDeclName();
15119   }
15120 
15121   return false;
15122 }
15123 
15124 static QualType
15125 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15126   QualType QTy = PtrTy->getPointeeType();
15127   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15128   return SemaRef.Context.getPointerType(QTy);
15129 }
15130 
15131 static inline bool
15132 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15133                             CanQualType ExpectedResultType,
15134                             CanQualType ExpectedFirstParamType,
15135                             unsigned DependentParamTypeDiag,
15136                             unsigned InvalidParamTypeDiag) {
15137   QualType ResultType =
15138       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15139 
15140   // Check that the result type is not dependent.
15141   if (ResultType->isDependentType())
15142     return SemaRef.Diag(FnDecl->getLocation(),
15143                         diag::err_operator_new_delete_dependent_result_type)
15144     << FnDecl->getDeclName() << ExpectedResultType;
15145 
15146   // The operator is valid on any address space for OpenCL.
15147   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15148     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15149       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15150     }
15151   }
15152 
15153   // Check that the result type is what we expect.
15154   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
15155     return SemaRef.Diag(FnDecl->getLocation(),
15156                         diag::err_operator_new_delete_invalid_result_type)
15157     << FnDecl->getDeclName() << ExpectedResultType;
15158 
15159   // A function template must have at least 2 parameters.
15160   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15161     return SemaRef.Diag(FnDecl->getLocation(),
15162                       diag::err_operator_new_delete_template_too_few_parameters)
15163         << FnDecl->getDeclName();
15164 
15165   // The function decl must have at least 1 parameter.
15166   if (FnDecl->getNumParams() == 0)
15167     return SemaRef.Diag(FnDecl->getLocation(),
15168                         diag::err_operator_new_delete_too_few_parameters)
15169       << FnDecl->getDeclName();
15170 
15171   // Check the first parameter type is not dependent.
15172   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15173   if (FirstParamType->isDependentType())
15174     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
15175       << FnDecl->getDeclName() << ExpectedFirstParamType;
15176 
15177   // Check that the first parameter type is what we expect.
15178   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15179     // The operator is valid on any address space for OpenCL.
15180     if (auto *PtrTy =
15181             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15182       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15183     }
15184   }
15185   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15186       ExpectedFirstParamType)
15187     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
15188     << FnDecl->getDeclName() << ExpectedFirstParamType;
15189 
15190   return false;
15191 }
15192 
15193 static bool
15194 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15195   // C++ [basic.stc.dynamic.allocation]p1:
15196   //   A program is ill-formed if an allocation function is declared in a
15197   //   namespace scope other than global scope or declared static in global
15198   //   scope.
15199   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15200     return true;
15201 
15202   CanQualType SizeTy =
15203     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15204 
15205   // C++ [basic.stc.dynamic.allocation]p1:
15206   //  The return type shall be void*. The first parameter shall have type
15207   //  std::size_t.
15208   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15209                                   SizeTy,
15210                                   diag::err_operator_new_dependent_param_type,
15211                                   diag::err_operator_new_param_type))
15212     return true;
15213 
15214   // C++ [basic.stc.dynamic.allocation]p1:
15215   //  The first parameter shall not have an associated default argument.
15216   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15217     return SemaRef.Diag(FnDecl->getLocation(),
15218                         diag::err_operator_new_default_arg)
15219       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15220 
15221   return false;
15222 }
15223 
15224 static bool
15225 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15226   // C++ [basic.stc.dynamic.deallocation]p1:
15227   //   A program is ill-formed if deallocation functions are declared in a
15228   //   namespace scope other than global scope or declared static in global
15229   //   scope.
15230   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15231     return true;
15232 
15233   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15234 
15235   // C++ P0722:
15236   //   Within a class C, the first parameter of a destroying operator delete
15237   //   shall be of type C *. The first parameter of any other deallocation
15238   //   function shall be of type void *.
15239   CanQualType ExpectedFirstParamType =
15240       MD && MD->isDestroyingOperatorDelete()
15241           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15242                 SemaRef.Context.getRecordType(MD->getParent())))
15243           : SemaRef.Context.VoidPtrTy;
15244 
15245   // C++ [basic.stc.dynamic.deallocation]p2:
15246   //   Each deallocation function shall return void
15247   if (CheckOperatorNewDeleteTypes(
15248           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15249           diag::err_operator_delete_dependent_param_type,
15250           diag::err_operator_delete_param_type))
15251     return true;
15252 
15253   // C++ P0722:
15254   //   A destroying operator delete shall be a usual deallocation function.
15255   if (MD && !MD->getParent()->isDependentContext() &&
15256       MD->isDestroyingOperatorDelete() &&
15257       !SemaRef.isUsualDeallocationFunction(MD)) {
15258     SemaRef.Diag(MD->getLocation(),
15259                  diag::err_destroying_operator_delete_not_usual);
15260     return true;
15261   }
15262 
15263   return false;
15264 }
15265 
15266 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15267 /// of this overloaded operator is well-formed. If so, returns false;
15268 /// otherwise, emits appropriate diagnostics and returns true.
15269 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15270   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15271          "Expected an overloaded operator declaration");
15272 
15273   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15274 
15275   // C++ [over.oper]p5:
15276   //   The allocation and deallocation functions, operator new,
15277   //   operator new[], operator delete and operator delete[], are
15278   //   described completely in 3.7.3. The attributes and restrictions
15279   //   found in the rest of this subclause do not apply to them unless
15280   //   explicitly stated in 3.7.3.
15281   if (Op == OO_Delete || Op == OO_Array_Delete)
15282     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15283 
15284   if (Op == OO_New || Op == OO_Array_New)
15285     return CheckOperatorNewDeclaration(*this, FnDecl);
15286 
15287   // C++ [over.oper]p6:
15288   //   An operator function shall either be a non-static member
15289   //   function or be a non-member function and have at least one
15290   //   parameter whose type is a class, a reference to a class, an
15291   //   enumeration, or a reference to an enumeration.
15292   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15293     if (MethodDecl->isStatic())
15294       return Diag(FnDecl->getLocation(),
15295                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15296   } else {
15297     bool ClassOrEnumParam = false;
15298     for (auto Param : FnDecl->parameters()) {
15299       QualType ParamType = Param->getType().getNonReferenceType();
15300       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15301           ParamType->isEnumeralType()) {
15302         ClassOrEnumParam = true;
15303         break;
15304       }
15305     }
15306 
15307     if (!ClassOrEnumParam)
15308       return Diag(FnDecl->getLocation(),
15309                   diag::err_operator_overload_needs_class_or_enum)
15310         << FnDecl->getDeclName();
15311   }
15312 
15313   // C++ [over.oper]p8:
15314   //   An operator function cannot have default arguments (8.3.6),
15315   //   except where explicitly stated below.
15316   //
15317   // Only the function-call operator allows default arguments
15318   // (C++ [over.call]p1).
15319   if (Op != OO_Call) {
15320     for (auto Param : FnDecl->parameters()) {
15321       if (Param->hasDefaultArg())
15322         return Diag(Param->getLocation(),
15323                     diag::err_operator_overload_default_arg)
15324           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15325     }
15326   }
15327 
15328   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15329     { false, false, false }
15330 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15331     , { Unary, Binary, MemberOnly }
15332 #include "clang/Basic/OperatorKinds.def"
15333   };
15334 
15335   bool CanBeUnaryOperator = OperatorUses[Op][0];
15336   bool CanBeBinaryOperator = OperatorUses[Op][1];
15337   bool MustBeMemberOperator = OperatorUses[Op][2];
15338 
15339   // C++ [over.oper]p8:
15340   //   [...] Operator functions cannot have more or fewer parameters
15341   //   than the number required for the corresponding operator, as
15342   //   described in the rest of this subclause.
15343   unsigned NumParams = FnDecl->getNumParams()
15344                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15345   if (Op != OO_Call &&
15346       ((NumParams == 1 && !CanBeUnaryOperator) ||
15347        (NumParams == 2 && !CanBeBinaryOperator) ||
15348        (NumParams < 1) || (NumParams > 2))) {
15349     // We have the wrong number of parameters.
15350     unsigned ErrorKind;
15351     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15352       ErrorKind = 2;  // 2 -> unary or binary.
15353     } else if (CanBeUnaryOperator) {
15354       ErrorKind = 0;  // 0 -> unary
15355     } else {
15356       assert(CanBeBinaryOperator &&
15357              "All non-call overloaded operators are unary or binary!");
15358       ErrorKind = 1;  // 1 -> binary
15359     }
15360 
15361     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15362       << FnDecl->getDeclName() << NumParams << ErrorKind;
15363   }
15364 
15365   // Overloaded operators other than operator() cannot be variadic.
15366   if (Op != OO_Call &&
15367       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15368     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15369       << FnDecl->getDeclName();
15370   }
15371 
15372   // Some operators must be non-static member functions.
15373   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15374     return Diag(FnDecl->getLocation(),
15375                 diag::err_operator_overload_must_be_member)
15376       << FnDecl->getDeclName();
15377   }
15378 
15379   // C++ [over.inc]p1:
15380   //   The user-defined function called operator++ implements the
15381   //   prefix and postfix ++ operator. If this function is a member
15382   //   function with no parameters, or a non-member function with one
15383   //   parameter of class or enumeration type, it defines the prefix
15384   //   increment operator ++ for objects of that type. If the function
15385   //   is a member function with one parameter (which shall be of type
15386   //   int) or a non-member function with two parameters (the second
15387   //   of which shall be of type int), it defines the postfix
15388   //   increment operator ++ for objects of that type.
15389   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15390     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15391     QualType ParamType = LastParam->getType();
15392 
15393     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15394         !ParamType->isDependentType())
15395       return Diag(LastParam->getLocation(),
15396                   diag::err_operator_overload_post_incdec_must_be_int)
15397         << LastParam->getType() << (Op == OO_MinusMinus);
15398   }
15399 
15400   return false;
15401 }
15402 
15403 static bool
15404 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15405                                           FunctionTemplateDecl *TpDecl) {
15406   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15407 
15408   // Must have one or two template parameters.
15409   if (TemplateParams->size() == 1) {
15410     NonTypeTemplateParmDecl *PmDecl =
15411         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15412 
15413     // The template parameter must be a char parameter pack.
15414     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15415         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15416       return false;
15417 
15418   } else if (TemplateParams->size() == 2) {
15419     TemplateTypeParmDecl *PmType =
15420         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15421     NonTypeTemplateParmDecl *PmArgs =
15422         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15423 
15424     // The second template parameter must be a parameter pack with the
15425     // first template parameter as its type.
15426     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15427         PmArgs->isTemplateParameterPack()) {
15428       const TemplateTypeParmType *TArgs =
15429           PmArgs->getType()->getAs<TemplateTypeParmType>();
15430       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15431           TArgs->getIndex() == PmType->getIndex()) {
15432         if (!SemaRef.inTemplateInstantiation())
15433           SemaRef.Diag(TpDecl->getLocation(),
15434                        diag::ext_string_literal_operator_template);
15435         return false;
15436       }
15437     }
15438   }
15439 
15440   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15441                diag::err_literal_operator_template)
15442       << TpDecl->getTemplateParameters()->getSourceRange();
15443   return true;
15444 }
15445 
15446 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15447 /// of this literal operator function is well-formed. If so, returns
15448 /// false; otherwise, emits appropriate diagnostics and returns true.
15449 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15450   if (isa<CXXMethodDecl>(FnDecl)) {
15451     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15452       << FnDecl->getDeclName();
15453     return true;
15454   }
15455 
15456   if (FnDecl->isExternC()) {
15457     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15458     if (const LinkageSpecDecl *LSD =
15459             FnDecl->getDeclContext()->getExternCContext())
15460       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15461     return true;
15462   }
15463 
15464   // This might be the definition of a literal operator template.
15465   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15466 
15467   // This might be a specialization of a literal operator template.
15468   if (!TpDecl)
15469     TpDecl = FnDecl->getPrimaryTemplate();
15470 
15471   // template <char...> type operator "" name() and
15472   // template <class T, T...> type operator "" name() are the only valid
15473   // template signatures, and the only valid signatures with no parameters.
15474   if (TpDecl) {
15475     if (FnDecl->param_size() != 0) {
15476       Diag(FnDecl->getLocation(),
15477            diag::err_literal_operator_template_with_params);
15478       return true;
15479     }
15480 
15481     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15482       return true;
15483 
15484   } else if (FnDecl->param_size() == 1) {
15485     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15486 
15487     QualType ParamType = Param->getType().getUnqualifiedType();
15488 
15489     // Only unsigned long long int, long double, any character type, and const
15490     // char * are allowed as the only parameters.
15491     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15492         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15493         Context.hasSameType(ParamType, Context.CharTy) ||
15494         Context.hasSameType(ParamType, Context.WideCharTy) ||
15495         Context.hasSameType(ParamType, Context.Char8Ty) ||
15496         Context.hasSameType(ParamType, Context.Char16Ty) ||
15497         Context.hasSameType(ParamType, Context.Char32Ty)) {
15498     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15499       QualType InnerType = Ptr->getPointeeType();
15500 
15501       // Pointer parameter must be a const char *.
15502       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15503                                 Context.CharTy) &&
15504             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15505         Diag(Param->getSourceRange().getBegin(),
15506              diag::err_literal_operator_param)
15507             << ParamType << "'const char *'" << Param->getSourceRange();
15508         return true;
15509       }
15510 
15511     } else if (ParamType->isRealFloatingType()) {
15512       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15513           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15514       return true;
15515 
15516     } else if (ParamType->isIntegerType()) {
15517       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15518           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15519       return true;
15520 
15521     } else {
15522       Diag(Param->getSourceRange().getBegin(),
15523            diag::err_literal_operator_invalid_param)
15524           << ParamType << Param->getSourceRange();
15525       return true;
15526     }
15527 
15528   } else if (FnDecl->param_size() == 2) {
15529     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15530 
15531     // First, verify that the first parameter is correct.
15532 
15533     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15534 
15535     // Two parameter function must have a pointer to const as a
15536     // first parameter; let's strip those qualifiers.
15537     const PointerType *PT = FirstParamType->getAs<PointerType>();
15538 
15539     if (!PT) {
15540       Diag((*Param)->getSourceRange().getBegin(),
15541            diag::err_literal_operator_param)
15542           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15543       return true;
15544     }
15545 
15546     QualType PointeeType = PT->getPointeeType();
15547     // First parameter must be const
15548     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15549       Diag((*Param)->getSourceRange().getBegin(),
15550            diag::err_literal_operator_param)
15551           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15552       return true;
15553     }
15554 
15555     QualType InnerType = PointeeType.getUnqualifiedType();
15556     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15557     // const char32_t* are allowed as the first parameter to a two-parameter
15558     // function
15559     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15560           Context.hasSameType(InnerType, Context.WideCharTy) ||
15561           Context.hasSameType(InnerType, Context.Char8Ty) ||
15562           Context.hasSameType(InnerType, Context.Char16Ty) ||
15563           Context.hasSameType(InnerType, Context.Char32Ty))) {
15564       Diag((*Param)->getSourceRange().getBegin(),
15565            diag::err_literal_operator_param)
15566           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15567       return true;
15568     }
15569 
15570     // Move on to the second and final parameter.
15571     ++Param;
15572 
15573     // The second parameter must be a std::size_t.
15574     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15575     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15576       Diag((*Param)->getSourceRange().getBegin(),
15577            diag::err_literal_operator_param)
15578           << SecondParamType << Context.getSizeType()
15579           << (*Param)->getSourceRange();
15580       return true;
15581     }
15582   } else {
15583     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15584     return true;
15585   }
15586 
15587   // Parameters are good.
15588 
15589   // A parameter-declaration-clause containing a default argument is not
15590   // equivalent to any of the permitted forms.
15591   for (auto Param : FnDecl->parameters()) {
15592     if (Param->hasDefaultArg()) {
15593       Diag(Param->getDefaultArgRange().getBegin(),
15594            diag::err_literal_operator_default_argument)
15595         << Param->getDefaultArgRange();
15596       break;
15597     }
15598   }
15599 
15600   StringRef LiteralName
15601     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15602   if (LiteralName[0] != '_' &&
15603       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15604     // C++11 [usrlit.suffix]p1:
15605     //   Literal suffix identifiers that do not start with an underscore
15606     //   are reserved for future standardization.
15607     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15608       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15609   }
15610 
15611   return false;
15612 }
15613 
15614 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15615 /// linkage specification, including the language and (if present)
15616 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15617 /// language string literal. LBraceLoc, if valid, provides the location of
15618 /// the '{' brace. Otherwise, this linkage specification does not
15619 /// have any braces.
15620 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15621                                            Expr *LangStr,
15622                                            SourceLocation LBraceLoc) {
15623   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15624   if (!Lit->isAscii()) {
15625     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15626       << LangStr->getSourceRange();
15627     return nullptr;
15628   }
15629 
15630   StringRef Lang = Lit->getString();
15631   LinkageSpecDecl::LanguageIDs Language;
15632   if (Lang == "C")
15633     Language = LinkageSpecDecl::lang_c;
15634   else if (Lang == "C++")
15635     Language = LinkageSpecDecl::lang_cxx;
15636   else {
15637     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15638       << LangStr->getSourceRange();
15639     return nullptr;
15640   }
15641 
15642   // FIXME: Add all the various semantics of linkage specifications
15643 
15644   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15645                                                LangStr->getExprLoc(), Language,
15646                                                LBraceLoc.isValid());
15647   CurContext->addDecl(D);
15648   PushDeclContext(S, D);
15649   return D;
15650 }
15651 
15652 /// ActOnFinishLinkageSpecification - Complete the definition of
15653 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15654 /// valid, it's the position of the closing '}' brace in a linkage
15655 /// specification that uses braces.
15656 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15657                                             Decl *LinkageSpec,
15658                                             SourceLocation RBraceLoc) {
15659   if (RBraceLoc.isValid()) {
15660     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15661     LSDecl->setRBraceLoc(RBraceLoc);
15662   }
15663   PopDeclContext();
15664   return LinkageSpec;
15665 }
15666 
15667 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15668                                   const ParsedAttributesView &AttrList,
15669                                   SourceLocation SemiLoc) {
15670   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15671   // Attribute declarations appertain to empty declaration so we handle
15672   // them here.
15673   ProcessDeclAttributeList(S, ED, AttrList);
15674 
15675   CurContext->addDecl(ED);
15676   return ED;
15677 }
15678 
15679 /// Perform semantic analysis for the variable declaration that
15680 /// occurs within a C++ catch clause, returning the newly-created
15681 /// variable.
15682 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15683                                          TypeSourceInfo *TInfo,
15684                                          SourceLocation StartLoc,
15685                                          SourceLocation Loc,
15686                                          IdentifierInfo *Name) {
15687   bool Invalid = false;
15688   QualType ExDeclType = TInfo->getType();
15689 
15690   // Arrays and functions decay.
15691   if (ExDeclType->isArrayType())
15692     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15693   else if (ExDeclType->isFunctionType())
15694     ExDeclType = Context.getPointerType(ExDeclType);
15695 
15696   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15697   // The exception-declaration shall not denote a pointer or reference to an
15698   // incomplete type, other than [cv] void*.
15699   // N2844 forbids rvalue references.
15700   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15701     Diag(Loc, diag::err_catch_rvalue_ref);
15702     Invalid = true;
15703   }
15704 
15705   if (ExDeclType->isVariablyModifiedType()) {
15706     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15707     Invalid = true;
15708   }
15709 
15710   QualType BaseType = ExDeclType;
15711   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15712   unsigned DK = diag::err_catch_incomplete;
15713   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15714     BaseType = Ptr->getPointeeType();
15715     Mode = 1;
15716     DK = diag::err_catch_incomplete_ptr;
15717   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15718     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15719     BaseType = Ref->getPointeeType();
15720     Mode = 2;
15721     DK = diag::err_catch_incomplete_ref;
15722   }
15723   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15724       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15725     Invalid = true;
15726 
15727   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15728     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15729     Invalid = true;
15730   }
15731 
15732   if (!Invalid && !ExDeclType->isDependentType() &&
15733       RequireNonAbstractType(Loc, ExDeclType,
15734                              diag::err_abstract_type_in_decl,
15735                              AbstractVariableType))
15736     Invalid = true;
15737 
15738   // Only the non-fragile NeXT runtime currently supports C++ catches
15739   // of ObjC types, and no runtime supports catching ObjC types by value.
15740   if (!Invalid && getLangOpts().ObjC) {
15741     QualType T = ExDeclType;
15742     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15743       T = RT->getPointeeType();
15744 
15745     if (T->isObjCObjectType()) {
15746       Diag(Loc, diag::err_objc_object_catch);
15747       Invalid = true;
15748     } else if (T->isObjCObjectPointerType()) {
15749       // FIXME: should this be a test for macosx-fragile specifically?
15750       if (getLangOpts().ObjCRuntime.isFragile())
15751         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15752     }
15753   }
15754 
15755   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15756                                     ExDeclType, TInfo, SC_None);
15757   ExDecl->setExceptionVariable(true);
15758 
15759   // In ARC, infer 'retaining' for variables of retainable type.
15760   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15761     Invalid = true;
15762 
15763   if (!Invalid && !ExDeclType->isDependentType()) {
15764     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15765       // Insulate this from anything else we might currently be parsing.
15766       EnterExpressionEvaluationContext scope(
15767           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15768 
15769       // C++ [except.handle]p16:
15770       //   The object declared in an exception-declaration or, if the
15771       //   exception-declaration does not specify a name, a temporary (12.2) is
15772       //   copy-initialized (8.5) from the exception object. [...]
15773       //   The object is destroyed when the handler exits, after the destruction
15774       //   of any automatic objects initialized within the handler.
15775       //
15776       // We just pretend to initialize the object with itself, then make sure
15777       // it can be destroyed later.
15778       QualType initType = Context.getExceptionObjectType(ExDeclType);
15779 
15780       InitializedEntity entity =
15781         InitializedEntity::InitializeVariable(ExDecl);
15782       InitializationKind initKind =
15783         InitializationKind::CreateCopy(Loc, SourceLocation());
15784 
15785       Expr *opaqueValue =
15786         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15787       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15788       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15789       if (result.isInvalid())
15790         Invalid = true;
15791       else {
15792         // If the constructor used was non-trivial, set this as the
15793         // "initializer".
15794         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15795         if (!construct->getConstructor()->isTrivial()) {
15796           Expr *init = MaybeCreateExprWithCleanups(construct);
15797           ExDecl->setInit(init);
15798         }
15799 
15800         // And make sure it's destructable.
15801         FinalizeVarWithDestructor(ExDecl, recordType);
15802       }
15803     }
15804   }
15805 
15806   if (Invalid)
15807     ExDecl->setInvalidDecl();
15808 
15809   return ExDecl;
15810 }
15811 
15812 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15813 /// handler.
15814 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15815   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15816   bool Invalid = D.isInvalidType();
15817 
15818   // Check for unexpanded parameter packs.
15819   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15820                                       UPPC_ExceptionType)) {
15821     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15822                                              D.getIdentifierLoc());
15823     Invalid = true;
15824   }
15825 
15826   IdentifierInfo *II = D.getIdentifier();
15827   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15828                                              LookupOrdinaryName,
15829                                              ForVisibleRedeclaration)) {
15830     // The scope should be freshly made just for us. There is just no way
15831     // it contains any previous declaration, except for function parameters in
15832     // a function-try-block's catch statement.
15833     assert(!S->isDeclScope(PrevDecl));
15834     if (isDeclInScope(PrevDecl, CurContext, S)) {
15835       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15836         << D.getIdentifier();
15837       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15838       Invalid = true;
15839     } else if (PrevDecl->isTemplateParameter())
15840       // Maybe we will complain about the shadowed template parameter.
15841       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15842   }
15843 
15844   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15845     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15846       << D.getCXXScopeSpec().getRange();
15847     Invalid = true;
15848   }
15849 
15850   VarDecl *ExDecl = BuildExceptionDeclaration(
15851       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15852   if (Invalid)
15853     ExDecl->setInvalidDecl();
15854 
15855   // Add the exception declaration into this scope.
15856   if (II)
15857     PushOnScopeChains(ExDecl, S);
15858   else
15859     CurContext->addDecl(ExDecl);
15860 
15861   ProcessDeclAttributes(S, ExDecl, D);
15862   return ExDecl;
15863 }
15864 
15865 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15866                                          Expr *AssertExpr,
15867                                          Expr *AssertMessageExpr,
15868                                          SourceLocation RParenLoc) {
15869   StringLiteral *AssertMessage =
15870       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15871 
15872   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15873     return nullptr;
15874 
15875   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15876                                       AssertMessage, RParenLoc, false);
15877 }
15878 
15879 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15880                                          Expr *AssertExpr,
15881                                          StringLiteral *AssertMessage,
15882                                          SourceLocation RParenLoc,
15883                                          bool Failed) {
15884   assert(AssertExpr != nullptr && "Expected non-null condition");
15885   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15886       !Failed) {
15887     // In a static_assert-declaration, the constant-expression shall be a
15888     // constant expression that can be contextually converted to bool.
15889     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15890     if (Converted.isInvalid())
15891       Failed = true;
15892 
15893     ExprResult FullAssertExpr =
15894         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15895                             /*DiscardedValue*/ false,
15896                             /*IsConstexpr*/ true);
15897     if (FullAssertExpr.isInvalid())
15898       Failed = true;
15899     else
15900       AssertExpr = FullAssertExpr.get();
15901 
15902     llvm::APSInt Cond;
15903     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15904           diag::err_static_assert_expression_is_not_constant,
15905           /*AllowFold=*/false).isInvalid())
15906       Failed = true;
15907 
15908     if (!Failed && !Cond) {
15909       SmallString<256> MsgBuffer;
15910       llvm::raw_svector_ostream Msg(MsgBuffer);
15911       if (AssertMessage)
15912         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
15913 
15914       Expr *InnerCond = nullptr;
15915       std::string InnerCondDescription;
15916       std::tie(InnerCond, InnerCondDescription) =
15917         findFailedBooleanCondition(Converted.get());
15918       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
15919         // Drill down into concept specialization expressions to see why they
15920         // weren't satisfied.
15921         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15922           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15923         ConstraintSatisfaction Satisfaction;
15924         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
15925           DiagnoseUnsatisfiedConstraint(Satisfaction);
15926       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
15927                            && !isa<IntegerLiteral>(InnerCond)) {
15928         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
15929           << InnerCondDescription << !AssertMessage
15930           << Msg.str() << InnerCond->getSourceRange();
15931       } else {
15932         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15933           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15934       }
15935       Failed = true;
15936     }
15937   } else {
15938     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
15939                                                     /*DiscardedValue*/false,
15940                                                     /*IsConstexpr*/true);
15941     if (FullAssertExpr.isInvalid())
15942       Failed = true;
15943     else
15944       AssertExpr = FullAssertExpr.get();
15945   }
15946 
15947   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
15948                                         AssertExpr, AssertMessage, RParenLoc,
15949                                         Failed);
15950 
15951   CurContext->addDecl(Decl);
15952   return Decl;
15953 }
15954 
15955 /// Perform semantic analysis of the given friend type declaration.
15956 ///
15957 /// \returns A friend declaration that.
15958 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
15959                                       SourceLocation FriendLoc,
15960                                       TypeSourceInfo *TSInfo) {
15961   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
15962 
15963   QualType T = TSInfo->getType();
15964   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
15965 
15966   // C++03 [class.friend]p2:
15967   //   An elaborated-type-specifier shall be used in a friend declaration
15968   //   for a class.*
15969   //
15970   //   * The class-key of the elaborated-type-specifier is required.
15971   if (!CodeSynthesisContexts.empty()) {
15972     // Do not complain about the form of friend template types during any kind
15973     // of code synthesis. For template instantiation, we will have complained
15974     // when the template was defined.
15975   } else {
15976     if (!T->isElaboratedTypeSpecifier()) {
15977       // If we evaluated the type to a record type, suggest putting
15978       // a tag in front.
15979       if (const RecordType *RT = T->getAs<RecordType>()) {
15980         RecordDecl *RD = RT->getDecl();
15981 
15982         SmallString<16> InsertionText(" ");
15983         InsertionText += RD->getKindName();
15984 
15985         Diag(TypeRange.getBegin(),
15986              getLangOpts().CPlusPlus11 ?
15987                diag::warn_cxx98_compat_unelaborated_friend_type :
15988                diag::ext_unelaborated_friend_type)
15989           << (unsigned) RD->getTagKind()
15990           << T
15991           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
15992                                         InsertionText);
15993       } else {
15994         Diag(FriendLoc,
15995              getLangOpts().CPlusPlus11 ?
15996                diag::warn_cxx98_compat_nonclass_type_friend :
15997                diag::ext_nonclass_type_friend)
15998           << T
15999           << TypeRange;
16000       }
16001     } else if (T->getAs<EnumType>()) {
16002       Diag(FriendLoc,
16003            getLangOpts().CPlusPlus11 ?
16004              diag::warn_cxx98_compat_enum_friend :
16005              diag::ext_enum_friend)
16006         << T
16007         << TypeRange;
16008     }
16009 
16010     // C++11 [class.friend]p3:
16011     //   A friend declaration that does not declare a function shall have one
16012     //   of the following forms:
16013     //     friend elaborated-type-specifier ;
16014     //     friend simple-type-specifier ;
16015     //     friend typename-specifier ;
16016     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16017       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16018   }
16019 
16020   //   If the type specifier in a friend declaration designates a (possibly
16021   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16022   //   the friend declaration is ignored.
16023   return FriendDecl::Create(Context, CurContext,
16024                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16025                             FriendLoc);
16026 }
16027 
16028 /// Handle a friend tag declaration where the scope specifier was
16029 /// templated.
16030 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16031                                     unsigned TagSpec, SourceLocation TagLoc,
16032                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16033                                     SourceLocation NameLoc,
16034                                     const ParsedAttributesView &Attr,
16035                                     MultiTemplateParamsArg TempParamLists) {
16036   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16037 
16038   bool IsMemberSpecialization = false;
16039   bool Invalid = false;
16040 
16041   if (TemplateParameterList *TemplateParams =
16042           MatchTemplateParametersToScopeSpecifier(
16043               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16044               IsMemberSpecialization, Invalid)) {
16045     if (TemplateParams->size() > 0) {
16046       // This is a declaration of a class template.
16047       if (Invalid)
16048         return nullptr;
16049 
16050       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16051                                 NameLoc, Attr, TemplateParams, AS_public,
16052                                 /*ModulePrivateLoc=*/SourceLocation(),
16053                                 FriendLoc, TempParamLists.size() - 1,
16054                                 TempParamLists.data()).get();
16055     } else {
16056       // The "template<>" header is extraneous.
16057       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16058         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16059       IsMemberSpecialization = true;
16060     }
16061   }
16062 
16063   if (Invalid) return nullptr;
16064 
16065   bool isAllExplicitSpecializations = true;
16066   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16067     if (TempParamLists[I]->size()) {
16068       isAllExplicitSpecializations = false;
16069       break;
16070     }
16071   }
16072 
16073   // FIXME: don't ignore attributes.
16074 
16075   // If it's explicit specializations all the way down, just forget
16076   // about the template header and build an appropriate non-templated
16077   // friend.  TODO: for source fidelity, remember the headers.
16078   if (isAllExplicitSpecializations) {
16079     if (SS.isEmpty()) {
16080       bool Owned = false;
16081       bool IsDependent = false;
16082       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16083                       Attr, AS_public,
16084                       /*ModulePrivateLoc=*/SourceLocation(),
16085                       MultiTemplateParamsArg(), Owned, IsDependent,
16086                       /*ScopedEnumKWLoc=*/SourceLocation(),
16087                       /*ScopedEnumUsesClassTag=*/false,
16088                       /*UnderlyingType=*/TypeResult(),
16089                       /*IsTypeSpecifier=*/false,
16090                       /*IsTemplateParamOrArg=*/false);
16091     }
16092 
16093     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16094     ElaboratedTypeKeyword Keyword
16095       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16096     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16097                                    *Name, NameLoc);
16098     if (T.isNull())
16099       return nullptr;
16100 
16101     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16102     if (isa<DependentNameType>(T)) {
16103       DependentNameTypeLoc TL =
16104           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16105       TL.setElaboratedKeywordLoc(TagLoc);
16106       TL.setQualifierLoc(QualifierLoc);
16107       TL.setNameLoc(NameLoc);
16108     } else {
16109       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16110       TL.setElaboratedKeywordLoc(TagLoc);
16111       TL.setQualifierLoc(QualifierLoc);
16112       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16113     }
16114 
16115     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16116                                             TSI, FriendLoc, TempParamLists);
16117     Friend->setAccess(AS_public);
16118     CurContext->addDecl(Friend);
16119     return Friend;
16120   }
16121 
16122   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16123 
16124 
16125 
16126   // Handle the case of a templated-scope friend class.  e.g.
16127   //   template <class T> class A<T>::B;
16128   // FIXME: we don't support these right now.
16129   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16130     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16131   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16132   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16133   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16134   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16135   TL.setElaboratedKeywordLoc(TagLoc);
16136   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16137   TL.setNameLoc(NameLoc);
16138 
16139   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16140                                           TSI, FriendLoc, TempParamLists);
16141   Friend->setAccess(AS_public);
16142   Friend->setUnsupportedFriend(true);
16143   CurContext->addDecl(Friend);
16144   return Friend;
16145 }
16146 
16147 /// Handle a friend type declaration.  This works in tandem with
16148 /// ActOnTag.
16149 ///
16150 /// Notes on friend class templates:
16151 ///
16152 /// We generally treat friend class declarations as if they were
16153 /// declaring a class.  So, for example, the elaborated type specifier
16154 /// in a friend declaration is required to obey the restrictions of a
16155 /// class-head (i.e. no typedefs in the scope chain), template
16156 /// parameters are required to match up with simple template-ids, &c.
16157 /// However, unlike when declaring a template specialization, it's
16158 /// okay to refer to a template specialization without an empty
16159 /// template parameter declaration, e.g.
16160 ///   friend class A<T>::B<unsigned>;
16161 /// We permit this as a special case; if there are any template
16162 /// parameters present at all, require proper matching, i.e.
16163 ///   template <> template \<class T> friend class A<int>::B;
16164 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16165                                 MultiTemplateParamsArg TempParams) {
16166   SourceLocation Loc = DS.getBeginLoc();
16167 
16168   assert(DS.isFriendSpecified());
16169   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16170 
16171   // C++ [class.friend]p3:
16172   // A friend declaration that does not declare a function shall have one of
16173   // the following forms:
16174   //     friend elaborated-type-specifier ;
16175   //     friend simple-type-specifier ;
16176   //     friend typename-specifier ;
16177   //
16178   // Any declaration with a type qualifier does not have that form. (It's
16179   // legal to specify a qualified type as a friend, you just can't write the
16180   // keywords.)
16181   if (DS.getTypeQualifiers()) {
16182     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16183       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16184     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16185       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16186     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16187       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16188     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16189       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16190     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16191       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16192   }
16193 
16194   // Try to convert the decl specifier to a type.  This works for
16195   // friend templates because ActOnTag never produces a ClassTemplateDecl
16196   // for a TUK_Friend.
16197   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16198   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16199   QualType T = TSI->getType();
16200   if (TheDeclarator.isInvalidType())
16201     return nullptr;
16202 
16203   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16204     return nullptr;
16205 
16206   // This is definitely an error in C++98.  It's probably meant to
16207   // be forbidden in C++0x, too, but the specification is just
16208   // poorly written.
16209   //
16210   // The problem is with declarations like the following:
16211   //   template <T> friend A<T>::foo;
16212   // where deciding whether a class C is a friend or not now hinges
16213   // on whether there exists an instantiation of A that causes
16214   // 'foo' to equal C.  There are restrictions on class-heads
16215   // (which we declare (by fiat) elaborated friend declarations to
16216   // be) that makes this tractable.
16217   //
16218   // FIXME: handle "template <> friend class A<T>;", which
16219   // is possibly well-formed?  Who even knows?
16220   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16221     Diag(Loc, diag::err_tagless_friend_type_template)
16222       << DS.getSourceRange();
16223     return nullptr;
16224   }
16225 
16226   // C++98 [class.friend]p1: A friend of a class is a function
16227   //   or class that is not a member of the class . . .
16228   // This is fixed in DR77, which just barely didn't make the C++03
16229   // deadline.  It's also a very silly restriction that seriously
16230   // affects inner classes and which nobody else seems to implement;
16231   // thus we never diagnose it, not even in -pedantic.
16232   //
16233   // But note that we could warn about it: it's always useless to
16234   // friend one of your own members (it's not, however, worthless to
16235   // friend a member of an arbitrary specialization of your template).
16236 
16237   Decl *D;
16238   if (!TempParams.empty())
16239     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16240                                    TempParams,
16241                                    TSI,
16242                                    DS.getFriendSpecLoc());
16243   else
16244     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16245 
16246   if (!D)
16247     return nullptr;
16248 
16249   D->setAccess(AS_public);
16250   CurContext->addDecl(D);
16251 
16252   return D;
16253 }
16254 
16255 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16256                                         MultiTemplateParamsArg TemplateParams) {
16257   const DeclSpec &DS = D.getDeclSpec();
16258 
16259   assert(DS.isFriendSpecified());
16260   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16261 
16262   SourceLocation Loc = D.getIdentifierLoc();
16263   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16264 
16265   // C++ [class.friend]p1
16266   //   A friend of a class is a function or class....
16267   // Note that this sees through typedefs, which is intended.
16268   // It *doesn't* see through dependent types, which is correct
16269   // according to [temp.arg.type]p3:
16270   //   If a declaration acquires a function type through a
16271   //   type dependent on a template-parameter and this causes
16272   //   a declaration that does not use the syntactic form of a
16273   //   function declarator to have a function type, the program
16274   //   is ill-formed.
16275   if (!TInfo->getType()->isFunctionType()) {
16276     Diag(Loc, diag::err_unexpected_friend);
16277 
16278     // It might be worthwhile to try to recover by creating an
16279     // appropriate declaration.
16280     return nullptr;
16281   }
16282 
16283   // C++ [namespace.memdef]p3
16284   //  - If a friend declaration in a non-local class first declares a
16285   //    class or function, the friend class or function is a member
16286   //    of the innermost enclosing namespace.
16287   //  - The name of the friend is not found by simple name lookup
16288   //    until a matching declaration is provided in that namespace
16289   //    scope (either before or after the class declaration granting
16290   //    friendship).
16291   //  - If a friend function is called, its name may be found by the
16292   //    name lookup that considers functions from namespaces and
16293   //    classes associated with the types of the function arguments.
16294   //  - When looking for a prior declaration of a class or a function
16295   //    declared as a friend, scopes outside the innermost enclosing
16296   //    namespace scope are not considered.
16297 
16298   CXXScopeSpec &SS = D.getCXXScopeSpec();
16299   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16300   assert(NameInfo.getName());
16301 
16302   // Check for unexpanded parameter packs.
16303   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16304       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16305       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16306     return nullptr;
16307 
16308   // The context we found the declaration in, or in which we should
16309   // create the declaration.
16310   DeclContext *DC;
16311   Scope *DCScope = S;
16312   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16313                         ForExternalRedeclaration);
16314 
16315   // There are five cases here.
16316   //   - There's no scope specifier and we're in a local class. Only look
16317   //     for functions declared in the immediately-enclosing block scope.
16318   // We recover from invalid scope qualifiers as if they just weren't there.
16319   FunctionDecl *FunctionContainingLocalClass = nullptr;
16320   if ((SS.isInvalid() || !SS.isSet()) &&
16321       (FunctionContainingLocalClass =
16322            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16323     // C++11 [class.friend]p11:
16324     //   If a friend declaration appears in a local class and the name
16325     //   specified is an unqualified name, a prior declaration is
16326     //   looked up without considering scopes that are outside the
16327     //   innermost enclosing non-class scope. For a friend function
16328     //   declaration, if there is no prior declaration, the program is
16329     //   ill-formed.
16330 
16331     // Find the innermost enclosing non-class scope. This is the block
16332     // scope containing the local class definition (or for a nested class,
16333     // the outer local class).
16334     DCScope = S->getFnParent();
16335 
16336     // Look up the function name in the scope.
16337     Previous.clear(LookupLocalFriendName);
16338     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16339 
16340     if (!Previous.empty()) {
16341       // All possible previous declarations must have the same context:
16342       // either they were declared at block scope or they are members of
16343       // one of the enclosing local classes.
16344       DC = Previous.getRepresentativeDecl()->getDeclContext();
16345     } else {
16346       // This is ill-formed, but provide the context that we would have
16347       // declared the function in, if we were permitted to, for error recovery.
16348       DC = FunctionContainingLocalClass;
16349     }
16350     adjustContextForLocalExternDecl(DC);
16351 
16352     // C++ [class.friend]p6:
16353     //   A function can be defined in a friend declaration of a class if and
16354     //   only if the class is a non-local class (9.8), the function name is
16355     //   unqualified, and the function has namespace scope.
16356     if (D.isFunctionDefinition()) {
16357       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16358     }
16359 
16360   //   - There's no scope specifier, in which case we just go to the
16361   //     appropriate scope and look for a function or function template
16362   //     there as appropriate.
16363   } else if (SS.isInvalid() || !SS.isSet()) {
16364     // C++11 [namespace.memdef]p3:
16365     //   If the name in a friend declaration is neither qualified nor
16366     //   a template-id and the declaration is a function or an
16367     //   elaborated-type-specifier, the lookup to determine whether
16368     //   the entity has been previously declared shall not consider
16369     //   any scopes outside the innermost enclosing namespace.
16370     bool isTemplateId =
16371         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16372 
16373     // Find the appropriate context according to the above.
16374     DC = CurContext;
16375 
16376     // Skip class contexts.  If someone can cite chapter and verse
16377     // for this behavior, that would be nice --- it's what GCC and
16378     // EDG do, and it seems like a reasonable intent, but the spec
16379     // really only says that checks for unqualified existing
16380     // declarations should stop at the nearest enclosing namespace,
16381     // not that they should only consider the nearest enclosing
16382     // namespace.
16383     while (DC->isRecord())
16384       DC = DC->getParent();
16385 
16386     DeclContext *LookupDC = DC;
16387     while (LookupDC->isTransparentContext())
16388       LookupDC = LookupDC->getParent();
16389 
16390     while (true) {
16391       LookupQualifiedName(Previous, LookupDC);
16392 
16393       if (!Previous.empty()) {
16394         DC = LookupDC;
16395         break;
16396       }
16397 
16398       if (isTemplateId) {
16399         if (isa<TranslationUnitDecl>(LookupDC)) break;
16400       } else {
16401         if (LookupDC->isFileContext()) break;
16402       }
16403       LookupDC = LookupDC->getParent();
16404     }
16405 
16406     DCScope = getScopeForDeclContext(S, DC);
16407 
16408   //   - There's a non-dependent scope specifier, in which case we
16409   //     compute it and do a previous lookup there for a function
16410   //     or function template.
16411   } else if (!SS.getScopeRep()->isDependent()) {
16412     DC = computeDeclContext(SS);
16413     if (!DC) return nullptr;
16414 
16415     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16416 
16417     LookupQualifiedName(Previous, DC);
16418 
16419     // C++ [class.friend]p1: A friend of a class is a function or
16420     //   class that is not a member of the class . . .
16421     if (DC->Equals(CurContext))
16422       Diag(DS.getFriendSpecLoc(),
16423            getLangOpts().CPlusPlus11 ?
16424              diag::warn_cxx98_compat_friend_is_member :
16425              diag::err_friend_is_member);
16426 
16427     if (D.isFunctionDefinition()) {
16428       // C++ [class.friend]p6:
16429       //   A function can be defined in a friend declaration of a class if and
16430       //   only if the class is a non-local class (9.8), the function name is
16431       //   unqualified, and the function has namespace scope.
16432       //
16433       // FIXME: We should only do this if the scope specifier names the
16434       // innermost enclosing namespace; otherwise the fixit changes the
16435       // meaning of the code.
16436       SemaDiagnosticBuilder DB
16437         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16438 
16439       DB << SS.getScopeRep();
16440       if (DC->isFileContext())
16441         DB << FixItHint::CreateRemoval(SS.getRange());
16442       SS.clear();
16443     }
16444 
16445   //   - There's a scope specifier that does not match any template
16446   //     parameter lists, in which case we use some arbitrary context,
16447   //     create a method or method template, and wait for instantiation.
16448   //   - There's a scope specifier that does match some template
16449   //     parameter lists, which we don't handle right now.
16450   } else {
16451     if (D.isFunctionDefinition()) {
16452       // C++ [class.friend]p6:
16453       //   A function can be defined in a friend declaration of a class if and
16454       //   only if the class is a non-local class (9.8), the function name is
16455       //   unqualified, and the function has namespace scope.
16456       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16457         << SS.getScopeRep();
16458     }
16459 
16460     DC = CurContext;
16461     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16462   }
16463 
16464   if (!DC->isRecord()) {
16465     int DiagArg = -1;
16466     switch (D.getName().getKind()) {
16467     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16468     case UnqualifiedIdKind::IK_ConstructorName:
16469       DiagArg = 0;
16470       break;
16471     case UnqualifiedIdKind::IK_DestructorName:
16472       DiagArg = 1;
16473       break;
16474     case UnqualifiedIdKind::IK_ConversionFunctionId:
16475       DiagArg = 2;
16476       break;
16477     case UnqualifiedIdKind::IK_DeductionGuideName:
16478       DiagArg = 3;
16479       break;
16480     case UnqualifiedIdKind::IK_Identifier:
16481     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16482     case UnqualifiedIdKind::IK_LiteralOperatorId:
16483     case UnqualifiedIdKind::IK_OperatorFunctionId:
16484     case UnqualifiedIdKind::IK_TemplateId:
16485       break;
16486     }
16487     // This implies that it has to be an operator or function.
16488     if (DiagArg >= 0) {
16489       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16490       return nullptr;
16491     }
16492   }
16493 
16494   // FIXME: This is an egregious hack to cope with cases where the scope stack
16495   // does not contain the declaration context, i.e., in an out-of-line
16496   // definition of a class.
16497   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16498   if (!DCScope) {
16499     FakeDCScope.setEntity(DC);
16500     DCScope = &FakeDCScope;
16501   }
16502 
16503   bool AddToScope = true;
16504   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16505                                           TemplateParams, AddToScope);
16506   if (!ND) return nullptr;
16507 
16508   assert(ND->getLexicalDeclContext() == CurContext);
16509 
16510   // If we performed typo correction, we might have added a scope specifier
16511   // and changed the decl context.
16512   DC = ND->getDeclContext();
16513 
16514   // Add the function declaration to the appropriate lookup tables,
16515   // adjusting the redeclarations list as necessary.  We don't
16516   // want to do this yet if the friending class is dependent.
16517   //
16518   // Also update the scope-based lookup if the target context's
16519   // lookup context is in lexical scope.
16520   if (!CurContext->isDependentContext()) {
16521     DC = DC->getRedeclContext();
16522     DC->makeDeclVisibleInContext(ND);
16523     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16524       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16525   }
16526 
16527   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16528                                        D.getIdentifierLoc(), ND,
16529                                        DS.getFriendSpecLoc());
16530   FrD->setAccess(AS_public);
16531   CurContext->addDecl(FrD);
16532 
16533   if (ND->isInvalidDecl()) {
16534     FrD->setInvalidDecl();
16535   } else {
16536     if (DC->isRecord()) CheckFriendAccess(ND);
16537 
16538     FunctionDecl *FD;
16539     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16540       FD = FTD->getTemplatedDecl();
16541     else
16542       FD = cast<FunctionDecl>(ND);
16543 
16544     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16545     // default argument expression, that declaration shall be a definition
16546     // and shall be the only declaration of the function or function
16547     // template in the translation unit.
16548     if (functionDeclHasDefaultArgument(FD)) {
16549       // We can't look at FD->getPreviousDecl() because it may not have been set
16550       // if we're in a dependent context. If the function is known to be a
16551       // redeclaration, we will have narrowed Previous down to the right decl.
16552       if (D.isRedeclaration()) {
16553         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16554         Diag(Previous.getRepresentativeDecl()->getLocation(),
16555              diag::note_previous_declaration);
16556       } else if (!D.isFunctionDefinition())
16557         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16558     }
16559 
16560     // Mark templated-scope function declarations as unsupported.
16561     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16562       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16563         << SS.getScopeRep() << SS.getRange()
16564         << cast<CXXRecordDecl>(CurContext);
16565       FrD->setUnsupportedFriend(true);
16566     }
16567   }
16568 
16569   return ND;
16570 }
16571 
16572 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16573   AdjustDeclIfTemplate(Dcl);
16574 
16575   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16576   if (!Fn) {
16577     Diag(DelLoc, diag::err_deleted_non_function);
16578     return;
16579   }
16580 
16581   // Deleted function does not have a body.
16582   Fn->setWillHaveBody(false);
16583 
16584   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16585     // Don't consider the implicit declaration we generate for explicit
16586     // specializations. FIXME: Do not generate these implicit declarations.
16587     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16588          Prev->getPreviousDecl()) &&
16589         !Prev->isDefined()) {
16590       Diag(DelLoc, diag::err_deleted_decl_not_first);
16591       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16592            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16593                               : diag::note_previous_declaration);
16594       // We can't recover from this; the declaration might have already
16595       // been used.
16596       Fn->setInvalidDecl();
16597       return;
16598     }
16599 
16600     // To maintain the invariant that functions are only deleted on their first
16601     // declaration, mark the implicitly-instantiated declaration of the
16602     // explicitly-specialized function as deleted instead of marking the
16603     // instantiated redeclaration.
16604     Fn = Fn->getCanonicalDecl();
16605   }
16606 
16607   // dllimport/dllexport cannot be deleted.
16608   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16609     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16610     Fn->setInvalidDecl();
16611   }
16612 
16613   // C++11 [basic.start.main]p3:
16614   //   A program that defines main as deleted [...] is ill-formed.
16615   if (Fn->isMain())
16616     Diag(DelLoc, diag::err_deleted_main);
16617 
16618   // C++11 [dcl.fct.def.delete]p4:
16619   //  A deleted function is implicitly inline.
16620   Fn->setImplicitlyInline();
16621   Fn->setDeletedAsWritten();
16622 }
16623 
16624 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16625   if (!Dcl || Dcl->isInvalidDecl())
16626     return;
16627 
16628   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16629   if (!FD) {
16630     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16631       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16632         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16633         return;
16634       }
16635     }
16636 
16637     Diag(DefaultLoc, diag::err_default_special_members)
16638         << getLangOpts().CPlusPlus20;
16639     return;
16640   }
16641 
16642   // Reject if this can't possibly be a defaultable function.
16643   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16644   if (!DefKind &&
16645       // A dependent function that doesn't locally look defaultable can
16646       // still instantiate to a defaultable function if it's a constructor
16647       // or assignment operator.
16648       (!FD->isDependentContext() ||
16649        (!isa<CXXConstructorDecl>(FD) &&
16650         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16651     Diag(DefaultLoc, diag::err_default_special_members)
16652         << getLangOpts().CPlusPlus20;
16653     return;
16654   }
16655 
16656   if (DefKind.isComparison() &&
16657       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16658     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16659         << (int)DefKind.asComparison();
16660     return;
16661   }
16662 
16663   // Issue compatibility warning. We already warned if the operator is
16664   // 'operator<=>' when parsing the '<=>' token.
16665   if (DefKind.isComparison() &&
16666       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16667     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16668                          ? diag::warn_cxx17_compat_defaulted_comparison
16669                          : diag::ext_defaulted_comparison);
16670   }
16671 
16672   FD->setDefaulted();
16673   FD->setExplicitlyDefaulted();
16674 
16675   // Defer checking functions that are defaulted in a dependent context.
16676   if (FD->isDependentContext())
16677     return;
16678 
16679   // Unset that we will have a body for this function. We might not,
16680   // if it turns out to be trivial, and we don't need this marking now
16681   // that we've marked it as defaulted.
16682   FD->setWillHaveBody(false);
16683 
16684   // If this definition appears within the record, do the checking when
16685   // the record is complete. This is always the case for a defaulted
16686   // comparison.
16687   if (DefKind.isComparison())
16688     return;
16689   auto *MD = cast<CXXMethodDecl>(FD);
16690 
16691   const FunctionDecl *Primary = FD;
16692   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16693     // Ask the template instantiation pattern that actually had the
16694     // '= default' on it.
16695     Primary = Pattern;
16696 
16697   // If the method was defaulted on its first declaration, we will have
16698   // already performed the checking in CheckCompletedCXXClass. Such a
16699   // declaration doesn't trigger an implicit definition.
16700   if (Primary->getCanonicalDecl()->isDefaulted())
16701     return;
16702 
16703   // FIXME: Once we support defining comparisons out of class, check for a
16704   // defaulted comparison here.
16705   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16706     MD->setInvalidDecl();
16707   else
16708     DefineDefaultedFunction(*this, MD, DefaultLoc);
16709 }
16710 
16711 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16712   for (Stmt *SubStmt : S->children()) {
16713     if (!SubStmt)
16714       continue;
16715     if (isa<ReturnStmt>(SubStmt))
16716       Self.Diag(SubStmt->getBeginLoc(),
16717                 diag::err_return_in_constructor_handler);
16718     if (!isa<Expr>(SubStmt))
16719       SearchForReturnInStmt(Self, SubStmt);
16720   }
16721 }
16722 
16723 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16724   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16725     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16726     SearchForReturnInStmt(*this, Handler);
16727   }
16728 }
16729 
16730 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16731                                              const CXXMethodDecl *Old) {
16732   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16733   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16734 
16735   if (OldFT->hasExtParameterInfos()) {
16736     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16737       // A parameter of the overriding method should be annotated with noescape
16738       // if the corresponding parameter of the overridden method is annotated.
16739       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16740           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16741         Diag(New->getParamDecl(I)->getLocation(),
16742              diag::warn_overriding_method_missing_noescape);
16743         Diag(Old->getParamDecl(I)->getLocation(),
16744              diag::note_overridden_marked_noescape);
16745       }
16746   }
16747 
16748   // Virtual overrides must have the same code_seg.
16749   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16750   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16751   if ((NewCSA || OldCSA) &&
16752       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16753     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16754     Diag(Old->getLocation(), diag::note_previous_declaration);
16755     return true;
16756   }
16757 
16758   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16759 
16760   // If the calling conventions match, everything is fine
16761   if (NewCC == OldCC)
16762     return false;
16763 
16764   // If the calling conventions mismatch because the new function is static,
16765   // suppress the calling convention mismatch error; the error about static
16766   // function override (err_static_overrides_virtual from
16767   // Sema::CheckFunctionDeclaration) is more clear.
16768   if (New->getStorageClass() == SC_Static)
16769     return false;
16770 
16771   Diag(New->getLocation(),
16772        diag::err_conflicting_overriding_cc_attributes)
16773     << New->getDeclName() << New->getType() << Old->getType();
16774   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16775   return true;
16776 }
16777 
16778 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16779                                              const CXXMethodDecl *Old) {
16780   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16781   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16782 
16783   if (Context.hasSameType(NewTy, OldTy) ||
16784       NewTy->isDependentType() || OldTy->isDependentType())
16785     return false;
16786 
16787   // Check if the return types are covariant
16788   QualType NewClassTy, OldClassTy;
16789 
16790   /// Both types must be pointers or references to classes.
16791   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16792     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16793       NewClassTy = NewPT->getPointeeType();
16794       OldClassTy = OldPT->getPointeeType();
16795     }
16796   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16797     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16798       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16799         NewClassTy = NewRT->getPointeeType();
16800         OldClassTy = OldRT->getPointeeType();
16801       }
16802     }
16803   }
16804 
16805   // The return types aren't either both pointers or references to a class type.
16806   if (NewClassTy.isNull()) {
16807     Diag(New->getLocation(),
16808          diag::err_different_return_type_for_overriding_virtual_function)
16809         << New->getDeclName() << NewTy << OldTy
16810         << New->getReturnTypeSourceRange();
16811     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16812         << Old->getReturnTypeSourceRange();
16813 
16814     return true;
16815   }
16816 
16817   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16818     // C++14 [class.virtual]p8:
16819     //   If the class type in the covariant return type of D::f differs from
16820     //   that of B::f, the class type in the return type of D::f shall be
16821     //   complete at the point of declaration of D::f or shall be the class
16822     //   type D.
16823     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16824       if (!RT->isBeingDefined() &&
16825           RequireCompleteType(New->getLocation(), NewClassTy,
16826                               diag::err_covariant_return_incomplete,
16827                               New->getDeclName()))
16828         return true;
16829     }
16830 
16831     // Check if the new class derives from the old class.
16832     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16833       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16834           << New->getDeclName() << NewTy << OldTy
16835           << New->getReturnTypeSourceRange();
16836       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16837           << Old->getReturnTypeSourceRange();
16838       return true;
16839     }
16840 
16841     // Check if we the conversion from derived to base is valid.
16842     if (CheckDerivedToBaseConversion(
16843             NewClassTy, OldClassTy,
16844             diag::err_covariant_return_inaccessible_base,
16845             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16846             New->getLocation(), New->getReturnTypeSourceRange(),
16847             New->getDeclName(), nullptr)) {
16848       // FIXME: this note won't trigger for delayed access control
16849       // diagnostics, and it's impossible to get an undelayed error
16850       // here from access control during the original parse because
16851       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16852       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16853           << Old->getReturnTypeSourceRange();
16854       return true;
16855     }
16856   }
16857 
16858   // The qualifiers of the return types must be the same.
16859   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16860     Diag(New->getLocation(),
16861          diag::err_covariant_return_type_different_qualifications)
16862         << New->getDeclName() << NewTy << OldTy
16863         << New->getReturnTypeSourceRange();
16864     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16865         << Old->getReturnTypeSourceRange();
16866     return true;
16867   }
16868 
16869 
16870   // The new class type must have the same or less qualifiers as the old type.
16871   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16872     Diag(New->getLocation(),
16873          diag::err_covariant_return_type_class_type_more_qualified)
16874         << New->getDeclName() << NewTy << OldTy
16875         << New->getReturnTypeSourceRange();
16876     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16877         << Old->getReturnTypeSourceRange();
16878     return true;
16879   }
16880 
16881   return false;
16882 }
16883 
16884 /// Mark the given method pure.
16885 ///
16886 /// \param Method the method to be marked pure.
16887 ///
16888 /// \param InitRange the source range that covers the "0" initializer.
16889 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16890   SourceLocation EndLoc = InitRange.getEnd();
16891   if (EndLoc.isValid())
16892     Method->setRangeEnd(EndLoc);
16893 
16894   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16895     Method->setPure();
16896     return false;
16897   }
16898 
16899   if (!Method->isInvalidDecl())
16900     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16901       << Method->getDeclName() << InitRange;
16902   return true;
16903 }
16904 
16905 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16906   if (D->getFriendObjectKind())
16907     Diag(D->getLocation(), diag::err_pure_friend);
16908   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16909     CheckPureMethod(M, ZeroLoc);
16910   else
16911     Diag(D->getLocation(), diag::err_illegal_initializer);
16912 }
16913 
16914 /// Determine whether the given declaration is a global variable or
16915 /// static data member.
16916 static bool isNonlocalVariable(const Decl *D) {
16917   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
16918     return Var->hasGlobalStorage();
16919 
16920   return false;
16921 }
16922 
16923 /// Invoked when we are about to parse an initializer for the declaration
16924 /// 'Dcl'.
16925 ///
16926 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
16927 /// static data member of class X, names should be looked up in the scope of
16928 /// class X. If the declaration had a scope specifier, a scope will have
16929 /// been created and passed in for this purpose. Otherwise, S will be null.
16930 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
16931   // If there is no declaration, there was an error parsing it.
16932   if (!D || D->isInvalidDecl())
16933     return;
16934 
16935   // We will always have a nested name specifier here, but this declaration
16936   // might not be out of line if the specifier names the current namespace:
16937   //   extern int n;
16938   //   int ::n = 0;
16939   if (S && D->isOutOfLine())
16940     EnterDeclaratorContext(S, D->getDeclContext());
16941 
16942   // If we are parsing the initializer for a static data member, push a
16943   // new expression evaluation context that is associated with this static
16944   // data member.
16945   if (isNonlocalVariable(D))
16946     PushExpressionEvaluationContext(
16947         ExpressionEvaluationContext::PotentiallyEvaluated, D);
16948 }
16949 
16950 /// Invoked after we are finished parsing an initializer for the declaration D.
16951 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
16952   // If there is no declaration, there was an error parsing it.
16953   if (!D || D->isInvalidDecl())
16954     return;
16955 
16956   if (isNonlocalVariable(D))
16957     PopExpressionEvaluationContext();
16958 
16959   if (S && D->isOutOfLine())
16960     ExitDeclaratorContext(S);
16961 }
16962 
16963 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
16964 /// C++ if/switch/while/for statement.
16965 /// e.g: "if (int x = f()) {...}"
16966 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
16967   // C++ 6.4p2:
16968   // The declarator shall not specify a function or an array.
16969   // The type-specifier-seq shall not contain typedef and shall not declare a
16970   // new class or enumeration.
16971   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
16972          "Parser allowed 'typedef' as storage class of condition decl.");
16973 
16974   Decl *Dcl = ActOnDeclarator(S, D);
16975   if (!Dcl)
16976     return true;
16977 
16978   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
16979     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
16980       << D.getSourceRange();
16981     return true;
16982   }
16983 
16984   return Dcl;
16985 }
16986 
16987 void Sema::LoadExternalVTableUses() {
16988   if (!ExternalSource)
16989     return;
16990 
16991   SmallVector<ExternalVTableUse, 4> VTables;
16992   ExternalSource->ReadUsedVTables(VTables);
16993   SmallVector<VTableUse, 4> NewUses;
16994   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
16995     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
16996       = VTablesUsed.find(VTables[I].Record);
16997     // Even if a definition wasn't required before, it may be required now.
16998     if (Pos != VTablesUsed.end()) {
16999       if (!Pos->second && VTables[I].DefinitionRequired)
17000         Pos->second = true;
17001       continue;
17002     }
17003 
17004     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17005     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17006   }
17007 
17008   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17009 }
17010 
17011 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17012                           bool DefinitionRequired) {
17013   // Ignore any vtable uses in unevaluated operands or for classes that do
17014   // not have a vtable.
17015   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17016       CurContext->isDependentContext() || isUnevaluatedContext())
17017     return;
17018   // Do not mark as used if compiling for the device outside of the target
17019   // region.
17020   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17021       !isInOpenMPDeclareTargetContext() &&
17022       !isInOpenMPTargetExecutionDirective()) {
17023     if (!DefinitionRequired)
17024       MarkVirtualMembersReferenced(Loc, Class);
17025     return;
17026   }
17027 
17028   // Try to insert this class into the map.
17029   LoadExternalVTableUses();
17030   Class = Class->getCanonicalDecl();
17031   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17032     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17033   if (!Pos.second) {
17034     // If we already had an entry, check to see if we are promoting this vtable
17035     // to require a definition. If so, we need to reappend to the VTableUses
17036     // list, since we may have already processed the first entry.
17037     if (DefinitionRequired && !Pos.first->second) {
17038       Pos.first->second = true;
17039     } else {
17040       // Otherwise, we can early exit.
17041       return;
17042     }
17043   } else {
17044     // The Microsoft ABI requires that we perform the destructor body
17045     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17046     // the deleting destructor is emitted with the vtable, not with the
17047     // destructor definition as in the Itanium ABI.
17048     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17049       CXXDestructorDecl *DD = Class->getDestructor();
17050       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17051         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17052           // If this is an out-of-line declaration, marking it referenced will
17053           // not do anything. Manually call CheckDestructor to look up operator
17054           // delete().
17055           ContextRAII SavedContext(*this, DD);
17056           CheckDestructor(DD);
17057         } else {
17058           MarkFunctionReferenced(Loc, Class->getDestructor());
17059         }
17060       }
17061     }
17062   }
17063 
17064   // Local classes need to have their virtual members marked
17065   // immediately. For all other classes, we mark their virtual members
17066   // at the end of the translation unit.
17067   if (Class->isLocalClass())
17068     MarkVirtualMembersReferenced(Loc, Class);
17069   else
17070     VTableUses.push_back(std::make_pair(Class, Loc));
17071 }
17072 
17073 bool Sema::DefineUsedVTables() {
17074   LoadExternalVTableUses();
17075   if (VTableUses.empty())
17076     return false;
17077 
17078   // Note: The VTableUses vector could grow as a result of marking
17079   // the members of a class as "used", so we check the size each
17080   // time through the loop and prefer indices (which are stable) to
17081   // iterators (which are not).
17082   bool DefinedAnything = false;
17083   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17084     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17085     if (!Class)
17086       continue;
17087     TemplateSpecializationKind ClassTSK =
17088         Class->getTemplateSpecializationKind();
17089 
17090     SourceLocation Loc = VTableUses[I].second;
17091 
17092     bool DefineVTable = true;
17093 
17094     // If this class has a key function, but that key function is
17095     // defined in another translation unit, we don't need to emit the
17096     // vtable even though we're using it.
17097     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17098     if (KeyFunction && !KeyFunction->hasBody()) {
17099       // The key function is in another translation unit.
17100       DefineVTable = false;
17101       TemplateSpecializationKind TSK =
17102           KeyFunction->getTemplateSpecializationKind();
17103       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17104              TSK != TSK_ImplicitInstantiation &&
17105              "Instantiations don't have key functions");
17106       (void)TSK;
17107     } else if (!KeyFunction) {
17108       // If we have a class with no key function that is the subject
17109       // of an explicit instantiation declaration, suppress the
17110       // vtable; it will live with the explicit instantiation
17111       // definition.
17112       bool IsExplicitInstantiationDeclaration =
17113           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17114       for (auto R : Class->redecls()) {
17115         TemplateSpecializationKind TSK
17116           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17117         if (TSK == TSK_ExplicitInstantiationDeclaration)
17118           IsExplicitInstantiationDeclaration = true;
17119         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17120           IsExplicitInstantiationDeclaration = false;
17121           break;
17122         }
17123       }
17124 
17125       if (IsExplicitInstantiationDeclaration)
17126         DefineVTable = false;
17127     }
17128 
17129     // The exception specifications for all virtual members may be needed even
17130     // if we are not providing an authoritative form of the vtable in this TU.
17131     // We may choose to emit it available_externally anyway.
17132     if (!DefineVTable) {
17133       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17134       continue;
17135     }
17136 
17137     // Mark all of the virtual members of this class as referenced, so
17138     // that we can build a vtable. Then, tell the AST consumer that a
17139     // vtable for this class is required.
17140     DefinedAnything = true;
17141     MarkVirtualMembersReferenced(Loc, Class);
17142     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17143     if (VTablesUsed[Canonical])
17144       Consumer.HandleVTable(Class);
17145 
17146     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17147     // no key function or the key function is inlined. Don't warn in C++ ABIs
17148     // that lack key functions, since the user won't be able to make one.
17149     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17150         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17151       const FunctionDecl *KeyFunctionDef = nullptr;
17152       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17153                            KeyFunctionDef->isInlined())) {
17154         Diag(Class->getLocation(),
17155              ClassTSK == TSK_ExplicitInstantiationDefinition
17156                  ? diag::warn_weak_template_vtable
17157                  : diag::warn_weak_vtable)
17158             << Class;
17159       }
17160     }
17161   }
17162   VTableUses.clear();
17163 
17164   return DefinedAnything;
17165 }
17166 
17167 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17168                                                  const CXXRecordDecl *RD) {
17169   for (const auto *I : RD->methods())
17170     if (I->isVirtual() && !I->isPure())
17171       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17172 }
17173 
17174 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17175                                         const CXXRecordDecl *RD,
17176                                         bool ConstexprOnly) {
17177   // Mark all functions which will appear in RD's vtable as used.
17178   CXXFinalOverriderMap FinalOverriders;
17179   RD->getFinalOverriders(FinalOverriders);
17180   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17181                                             E = FinalOverriders.end();
17182        I != E; ++I) {
17183     for (OverridingMethods::const_iterator OI = I->second.begin(),
17184                                            OE = I->second.end();
17185          OI != OE; ++OI) {
17186       assert(OI->second.size() > 0 && "no final overrider");
17187       CXXMethodDecl *Overrider = OI->second.front().Method;
17188 
17189       // C++ [basic.def.odr]p2:
17190       //   [...] A virtual member function is used if it is not pure. [...]
17191       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17192         MarkFunctionReferenced(Loc, Overrider);
17193     }
17194   }
17195 
17196   // Only classes that have virtual bases need a VTT.
17197   if (RD->getNumVBases() == 0)
17198     return;
17199 
17200   for (const auto &I : RD->bases()) {
17201     const auto *Base =
17202         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17203     if (Base->getNumVBases() == 0)
17204       continue;
17205     MarkVirtualMembersReferenced(Loc, Base);
17206   }
17207 }
17208 
17209 /// SetIvarInitializers - This routine builds initialization ASTs for the
17210 /// Objective-C implementation whose ivars need be initialized.
17211 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17212   if (!getLangOpts().CPlusPlus)
17213     return;
17214   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17215     SmallVector<ObjCIvarDecl*, 8> ivars;
17216     CollectIvarsToConstructOrDestruct(OID, ivars);
17217     if (ivars.empty())
17218       return;
17219     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17220     for (unsigned i = 0; i < ivars.size(); i++) {
17221       FieldDecl *Field = ivars[i];
17222       if (Field->isInvalidDecl())
17223         continue;
17224 
17225       CXXCtorInitializer *Member;
17226       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17227       InitializationKind InitKind =
17228         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17229 
17230       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17231       ExprResult MemberInit =
17232         InitSeq.Perform(*this, InitEntity, InitKind, None);
17233       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17234       // Note, MemberInit could actually come back empty if no initialization
17235       // is required (e.g., because it would call a trivial default constructor)
17236       if (!MemberInit.get() || MemberInit.isInvalid())
17237         continue;
17238 
17239       Member =
17240         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17241                                          SourceLocation(),
17242                                          MemberInit.getAs<Expr>(),
17243                                          SourceLocation());
17244       AllToInit.push_back(Member);
17245 
17246       // Be sure that the destructor is accessible and is marked as referenced.
17247       if (const RecordType *RecordTy =
17248               Context.getBaseElementType(Field->getType())
17249                   ->getAs<RecordType>()) {
17250         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17251         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17252           MarkFunctionReferenced(Field->getLocation(), Destructor);
17253           CheckDestructorAccess(Field->getLocation(), Destructor,
17254                             PDiag(diag::err_access_dtor_ivar)
17255                               << Context.getBaseElementType(Field->getType()));
17256         }
17257       }
17258     }
17259     ObjCImplementation->setIvarInitializers(Context,
17260                                             AllToInit.data(), AllToInit.size());
17261   }
17262 }
17263 
17264 static
17265 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17266                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17267                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17268                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17269                            Sema &S) {
17270   if (Ctor->isInvalidDecl())
17271     return;
17272 
17273   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17274 
17275   // Target may not be determinable yet, for instance if this is a dependent
17276   // call in an uninstantiated template.
17277   if (Target) {
17278     const FunctionDecl *FNTarget = nullptr;
17279     (void)Target->hasBody(FNTarget);
17280     Target = const_cast<CXXConstructorDecl*>(
17281       cast_or_null<CXXConstructorDecl>(FNTarget));
17282   }
17283 
17284   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17285                      // Avoid dereferencing a null pointer here.
17286                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17287 
17288   if (!Current.insert(Canonical).second)
17289     return;
17290 
17291   // We know that beyond here, we aren't chaining into a cycle.
17292   if (!Target || !Target->isDelegatingConstructor() ||
17293       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17294     Valid.insert(Current.begin(), Current.end());
17295     Current.clear();
17296   // We've hit a cycle.
17297   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17298              Current.count(TCanonical)) {
17299     // If we haven't diagnosed this cycle yet, do so now.
17300     if (!Invalid.count(TCanonical)) {
17301       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17302              diag::warn_delegating_ctor_cycle)
17303         << Ctor;
17304 
17305       // Don't add a note for a function delegating directly to itself.
17306       if (TCanonical != Canonical)
17307         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17308 
17309       CXXConstructorDecl *C = Target;
17310       while (C->getCanonicalDecl() != Canonical) {
17311         const FunctionDecl *FNTarget = nullptr;
17312         (void)C->getTargetConstructor()->hasBody(FNTarget);
17313         assert(FNTarget && "Ctor cycle through bodiless function");
17314 
17315         C = const_cast<CXXConstructorDecl*>(
17316           cast<CXXConstructorDecl>(FNTarget));
17317         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17318       }
17319     }
17320 
17321     Invalid.insert(Current.begin(), Current.end());
17322     Current.clear();
17323   } else {
17324     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17325   }
17326 }
17327 
17328 
17329 void Sema::CheckDelegatingCtorCycles() {
17330   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17331 
17332   for (DelegatingCtorDeclsType::iterator
17333          I = DelegatingCtorDecls.begin(ExternalSource),
17334          E = DelegatingCtorDecls.end();
17335        I != E; ++I)
17336     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17337 
17338   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17339     (*CI)->setInvalidDecl();
17340 }
17341 
17342 namespace {
17343   /// AST visitor that finds references to the 'this' expression.
17344   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17345     Sema &S;
17346 
17347   public:
17348     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17349 
17350     bool VisitCXXThisExpr(CXXThisExpr *E) {
17351       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17352         << E->isImplicit();
17353       return false;
17354     }
17355   };
17356 }
17357 
17358 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17359   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17360   if (!TSInfo)
17361     return false;
17362 
17363   TypeLoc TL = TSInfo->getTypeLoc();
17364   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17365   if (!ProtoTL)
17366     return false;
17367 
17368   // C++11 [expr.prim.general]p3:
17369   //   [The expression this] shall not appear before the optional
17370   //   cv-qualifier-seq and it shall not appear within the declaration of a
17371   //   static member function (although its type and value category are defined
17372   //   within a static member function as they are within a non-static member
17373   //   function). [ Note: this is because declaration matching does not occur
17374   //  until the complete declarator is known. - end note ]
17375   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17376   FindCXXThisExpr Finder(*this);
17377 
17378   // If the return type came after the cv-qualifier-seq, check it now.
17379   if (Proto->hasTrailingReturn() &&
17380       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17381     return true;
17382 
17383   // Check the exception specification.
17384   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17385     return true;
17386 
17387   // Check the trailing requires clause
17388   if (Expr *E = Method->getTrailingRequiresClause())
17389     if (!Finder.TraverseStmt(E))
17390       return true;
17391 
17392   return checkThisInStaticMemberFunctionAttributes(Method);
17393 }
17394 
17395 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17396   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17397   if (!TSInfo)
17398     return false;
17399 
17400   TypeLoc TL = TSInfo->getTypeLoc();
17401   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17402   if (!ProtoTL)
17403     return false;
17404 
17405   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17406   FindCXXThisExpr Finder(*this);
17407 
17408   switch (Proto->getExceptionSpecType()) {
17409   case EST_Unparsed:
17410   case EST_Uninstantiated:
17411   case EST_Unevaluated:
17412   case EST_BasicNoexcept:
17413   case EST_NoThrow:
17414   case EST_DynamicNone:
17415   case EST_MSAny:
17416   case EST_None:
17417     break;
17418 
17419   case EST_DependentNoexcept:
17420   case EST_NoexceptFalse:
17421   case EST_NoexceptTrue:
17422     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17423       return true;
17424     LLVM_FALLTHROUGH;
17425 
17426   case EST_Dynamic:
17427     for (const auto &E : Proto->exceptions()) {
17428       if (!Finder.TraverseType(E))
17429         return true;
17430     }
17431     break;
17432   }
17433 
17434   return false;
17435 }
17436 
17437 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17438   FindCXXThisExpr Finder(*this);
17439 
17440   // Check attributes.
17441   for (const auto *A : Method->attrs()) {
17442     // FIXME: This should be emitted by tblgen.
17443     Expr *Arg = nullptr;
17444     ArrayRef<Expr *> Args;
17445     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17446       Arg = G->getArg();
17447     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17448       Arg = G->getArg();
17449     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17450       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17451     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17452       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17453     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17454       Arg = ETLF->getSuccessValue();
17455       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17456     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17457       Arg = STLF->getSuccessValue();
17458       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17459     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17460       Arg = LR->getArg();
17461     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17462       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17463     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17464       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17465     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17466       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17467     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17468       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17469     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17470       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17471 
17472     if (Arg && !Finder.TraverseStmt(Arg))
17473       return true;
17474 
17475     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17476       if (!Finder.TraverseStmt(Args[I]))
17477         return true;
17478     }
17479   }
17480 
17481   return false;
17482 }
17483 
17484 void Sema::checkExceptionSpecification(
17485     bool IsTopLevel, ExceptionSpecificationType EST,
17486     ArrayRef<ParsedType> DynamicExceptions,
17487     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17488     SmallVectorImpl<QualType> &Exceptions,
17489     FunctionProtoType::ExceptionSpecInfo &ESI) {
17490   Exceptions.clear();
17491   ESI.Type = EST;
17492   if (EST == EST_Dynamic) {
17493     Exceptions.reserve(DynamicExceptions.size());
17494     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17495       // FIXME: Preserve type source info.
17496       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17497 
17498       if (IsTopLevel) {
17499         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17500         collectUnexpandedParameterPacks(ET, Unexpanded);
17501         if (!Unexpanded.empty()) {
17502           DiagnoseUnexpandedParameterPacks(
17503               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17504               Unexpanded);
17505           continue;
17506         }
17507       }
17508 
17509       // Check that the type is valid for an exception spec, and
17510       // drop it if not.
17511       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17512         Exceptions.push_back(ET);
17513     }
17514     ESI.Exceptions = Exceptions;
17515     return;
17516   }
17517 
17518   if (isComputedNoexcept(EST)) {
17519     assert((NoexceptExpr->isTypeDependent() ||
17520             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17521             Context.BoolTy) &&
17522            "Parser should have made sure that the expression is boolean");
17523     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17524       ESI.Type = EST_BasicNoexcept;
17525       return;
17526     }
17527 
17528     ESI.NoexceptExpr = NoexceptExpr;
17529     return;
17530   }
17531 }
17532 
17533 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17534              ExceptionSpecificationType EST,
17535              SourceRange SpecificationRange,
17536              ArrayRef<ParsedType> DynamicExceptions,
17537              ArrayRef<SourceRange> DynamicExceptionRanges,
17538              Expr *NoexceptExpr) {
17539   if (!MethodD)
17540     return;
17541 
17542   // Dig out the method we're referring to.
17543   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17544     MethodD = FunTmpl->getTemplatedDecl();
17545 
17546   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17547   if (!Method)
17548     return;
17549 
17550   // Check the exception specification.
17551   llvm::SmallVector<QualType, 4> Exceptions;
17552   FunctionProtoType::ExceptionSpecInfo ESI;
17553   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17554                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17555                               ESI);
17556 
17557   // Update the exception specification on the function type.
17558   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17559 
17560   if (Method->isStatic())
17561     checkThisInStaticMemberFunctionExceptionSpec(Method);
17562 
17563   if (Method->isVirtual()) {
17564     // Check overrides, which we previously had to delay.
17565     for (const CXXMethodDecl *O : Method->overridden_methods())
17566       CheckOverridingFunctionExceptionSpec(Method, O);
17567   }
17568 }
17569 
17570 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17571 ///
17572 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17573                                        SourceLocation DeclStart, Declarator &D,
17574                                        Expr *BitWidth,
17575                                        InClassInitStyle InitStyle,
17576                                        AccessSpecifier AS,
17577                                        const ParsedAttr &MSPropertyAttr) {
17578   IdentifierInfo *II = D.getIdentifier();
17579   if (!II) {
17580     Diag(DeclStart, diag::err_anonymous_property);
17581     return nullptr;
17582   }
17583   SourceLocation Loc = D.getIdentifierLoc();
17584 
17585   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17586   QualType T = TInfo->getType();
17587   if (getLangOpts().CPlusPlus) {
17588     CheckExtraCXXDefaultArguments(D);
17589 
17590     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17591                                         UPPC_DataMemberType)) {
17592       D.setInvalidType();
17593       T = Context.IntTy;
17594       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17595     }
17596   }
17597 
17598   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17599 
17600   if (D.getDeclSpec().isInlineSpecified())
17601     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17602         << getLangOpts().CPlusPlus17;
17603   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17604     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17605          diag::err_invalid_thread)
17606       << DeclSpec::getSpecifierName(TSCS);
17607 
17608   // Check to see if this name was declared as a member previously
17609   NamedDecl *PrevDecl = nullptr;
17610   LookupResult Previous(*this, II, Loc, LookupMemberName,
17611                         ForVisibleRedeclaration);
17612   LookupName(Previous, S);
17613   switch (Previous.getResultKind()) {
17614   case LookupResult::Found:
17615   case LookupResult::FoundUnresolvedValue:
17616     PrevDecl = Previous.getAsSingle<NamedDecl>();
17617     break;
17618 
17619   case LookupResult::FoundOverloaded:
17620     PrevDecl = Previous.getRepresentativeDecl();
17621     break;
17622 
17623   case LookupResult::NotFound:
17624   case LookupResult::NotFoundInCurrentInstantiation:
17625   case LookupResult::Ambiguous:
17626     break;
17627   }
17628 
17629   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17630     // Maybe we will complain about the shadowed template parameter.
17631     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17632     // Just pretend that we didn't see the previous declaration.
17633     PrevDecl = nullptr;
17634   }
17635 
17636   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17637     PrevDecl = nullptr;
17638 
17639   SourceLocation TSSL = D.getBeginLoc();
17640   MSPropertyDecl *NewPD =
17641       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17642                              MSPropertyAttr.getPropertyDataGetter(),
17643                              MSPropertyAttr.getPropertyDataSetter());
17644   ProcessDeclAttributes(TUScope, NewPD, D);
17645   NewPD->setAccess(AS);
17646 
17647   if (NewPD->isInvalidDecl())
17648     Record->setInvalidDecl();
17649 
17650   if (D.getDeclSpec().isModulePrivateSpecified())
17651     NewPD->setModulePrivate();
17652 
17653   if (NewPD->isInvalidDecl() && PrevDecl) {
17654     // Don't introduce NewFD into scope; there's already something
17655     // with the same name in the same scope.
17656   } else if (II) {
17657     PushOnScopeChains(NewPD, S);
17658   } else
17659     Record->addDecl(NewPD);
17660 
17661   return NewPD;
17662 }
17663 
17664 void Sema::ActOnStartFunctionDeclarationDeclarator(
17665     Declarator &Declarator, unsigned TemplateParameterDepth) {
17666   auto &Info = InventedParameterInfos.emplace_back();
17667   TemplateParameterList *ExplicitParams = nullptr;
17668   ArrayRef<TemplateParameterList *> ExplicitLists =
17669       Declarator.getTemplateParameterLists();
17670   if (!ExplicitLists.empty()) {
17671     bool IsMemberSpecialization, IsInvalid;
17672     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17673         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17674         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17675         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17676         /*SuppressDiagnostic=*/true);
17677   }
17678   if (ExplicitParams) {
17679     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17680     for (NamedDecl *Param : *ExplicitParams)
17681       Info.TemplateParams.push_back(Param);
17682     Info.NumExplicitTemplateParams = ExplicitParams->size();
17683   } else {
17684     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17685     Info.NumExplicitTemplateParams = 0;
17686   }
17687 }
17688 
17689 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17690   auto &FSI = InventedParameterInfos.back();
17691   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17692     if (FSI.NumExplicitTemplateParams != 0) {
17693       TemplateParameterList *ExplicitParams =
17694           Declarator.getTemplateParameterLists().back();
17695       Declarator.setInventedTemplateParameterList(
17696           TemplateParameterList::Create(
17697               Context, ExplicitParams->getTemplateLoc(),
17698               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17699               ExplicitParams->getRAngleLoc(),
17700               ExplicitParams->getRequiresClause()));
17701     } else {
17702       Declarator.setInventedTemplateParameterList(
17703           TemplateParameterList::Create(
17704               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17705               SourceLocation(), /*RequiresClause=*/nullptr));
17706     }
17707   }
17708   InventedParameterInfos.pop_back();
17709 }
17710