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().CPlusPlus2a
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().CPlusPlus2a)
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().CPlusPlus2a) {
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().CPlusPlus2a
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().CPlusPlus2a) {
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().CPlusPlus2a)
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().CPlusPlus2a
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().CPlusPlus2a) {
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().CPlusPlus2a)
2136         return false;
2137       break;
2138 
2139     case Sema::CheckConstexprKind::Diagnose:
2140       SemaRef.Diag(Body->getBeginLoc(),
2141            !SemaRef.getLangOpts().CPlusPlus2a
2142                ? diag::ext_constexpr_function_try_block_cxx2a
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().CPlusPlus2a) ||
2166         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2167       return false;
2168   } else if (Cxx2aLoc.isValid()) {
2169     SemaRef.Diag(Cxx2aLoc,
2170          SemaRef.getLangOpts().CPlusPlus2a
2171            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2172            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
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().CPlusPlus2a
2198                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2199                   : diag::ext_constexpr_union_ctor_no_init);
2200         } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
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 AmbigiousBaseConvID 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 AmbigiousBaseConvID,
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 (AmbigiousBaseConvID)
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 (AmbigiousBaseConvID) {
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, AmbigiousBaseConvID)
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   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5447 
5448   // Bases.
5449   for (const auto &Base : ClassDecl->bases()) {
5450     // Bases are always records in a well-formed non-dependent class.
5451     const RecordType *RT = Base.getType()->getAs<RecordType>();
5452 
5453     // Remember direct virtual bases.
5454     if (Base.isVirtual()) {
5455       if (!VisitVirtualBases)
5456         continue;
5457       DirectVirtualBases.insert(RT);
5458     }
5459 
5460     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5461     // If our base class is invalid, we probably can't get its dtor anyway.
5462     if (BaseClassDecl->isInvalidDecl())
5463       continue;
5464     if (BaseClassDecl->hasIrrelevantDestructor())
5465       continue;
5466 
5467     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5468     assert(Dtor && "No dtor found for BaseClassDecl!");
5469 
5470     // FIXME: caret should be on the start of the class name
5471     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5472                           PDiag(diag::err_access_dtor_base)
5473                               << Base.getType() << Base.getSourceRange(),
5474                           Context.getTypeDeclType(ClassDecl));
5475 
5476     MarkFunctionReferenced(Location, Dtor);
5477     DiagnoseUseOfDecl(Dtor, Location);
5478   }
5479 
5480   if (!VisitVirtualBases)
5481     return;
5482 
5483   // Virtual bases.
5484   for (const auto &VBase : ClassDecl->vbases()) {
5485     // Bases are always records in a well-formed non-dependent class.
5486     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5487 
5488     // Ignore direct virtual bases.
5489     if (DirectVirtualBases.count(RT))
5490       continue;
5491 
5492     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5493     // If our base class is invalid, we probably can't get its dtor anyway.
5494     if (BaseClassDecl->isInvalidDecl())
5495       continue;
5496     if (BaseClassDecl->hasIrrelevantDestructor())
5497       continue;
5498 
5499     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5500     assert(Dtor && "No dtor found for BaseClassDecl!");
5501     if (CheckDestructorAccess(
5502             ClassDecl->getLocation(), Dtor,
5503             PDiag(diag::err_access_dtor_vbase)
5504                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5505             Context.getTypeDeclType(ClassDecl)) ==
5506         AR_accessible) {
5507       CheckDerivedToBaseConversion(
5508           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5509           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5510           SourceRange(), DeclarationName(), nullptr);
5511     }
5512 
5513     MarkFunctionReferenced(Location, Dtor);
5514     DiagnoseUseOfDecl(Dtor, Location);
5515   }
5516 }
5517 
5518 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5519   if (!CDtorDecl)
5520     return;
5521 
5522   if (CXXConstructorDecl *Constructor
5523       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5524     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5525     DiagnoseUninitializedFields(*this, Constructor);
5526   }
5527 }
5528 
5529 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5530   if (!getLangOpts().CPlusPlus)
5531     return false;
5532 
5533   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5534   if (!RD)
5535     return false;
5536 
5537   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5538   // class template specialization here, but doing so breaks a lot of code.
5539 
5540   // We can't answer whether something is abstract until it has a
5541   // definition. If it's currently being defined, we'll walk back
5542   // over all the declarations when we have a full definition.
5543   const CXXRecordDecl *Def = RD->getDefinition();
5544   if (!Def || Def->isBeingDefined())
5545     return false;
5546 
5547   return RD->isAbstract();
5548 }
5549 
5550 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5551                                   TypeDiagnoser &Diagnoser) {
5552   if (!isAbstractType(Loc, T))
5553     return false;
5554 
5555   T = Context.getBaseElementType(T);
5556   Diagnoser.diagnose(*this, Loc, T);
5557   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5558   return true;
5559 }
5560 
5561 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5562   // Check if we've already emitted the list of pure virtual functions
5563   // for this class.
5564   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5565     return;
5566 
5567   // If the diagnostic is suppressed, don't emit the notes. We're only
5568   // going to emit them once, so try to attach them to a diagnostic we're
5569   // actually going to show.
5570   if (Diags.isLastDiagnosticIgnored())
5571     return;
5572 
5573   CXXFinalOverriderMap FinalOverriders;
5574   RD->getFinalOverriders(FinalOverriders);
5575 
5576   // Keep a set of seen pure methods so we won't diagnose the same method
5577   // more than once.
5578   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5579 
5580   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5581                                    MEnd = FinalOverriders.end();
5582        M != MEnd;
5583        ++M) {
5584     for (OverridingMethods::iterator SO = M->second.begin(),
5585                                   SOEnd = M->second.end();
5586          SO != SOEnd; ++SO) {
5587       // C++ [class.abstract]p4:
5588       //   A class is abstract if it contains or inherits at least one
5589       //   pure virtual function for which the final overrider is pure
5590       //   virtual.
5591 
5592       //
5593       if (SO->second.size() != 1)
5594         continue;
5595 
5596       if (!SO->second.front().Method->isPure())
5597         continue;
5598 
5599       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5600         continue;
5601 
5602       Diag(SO->second.front().Method->getLocation(),
5603            diag::note_pure_virtual_function)
5604         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5605     }
5606   }
5607 
5608   if (!PureVirtualClassDiagSet)
5609     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5610   PureVirtualClassDiagSet->insert(RD);
5611 }
5612 
5613 namespace {
5614 struct AbstractUsageInfo {
5615   Sema &S;
5616   CXXRecordDecl *Record;
5617   CanQualType AbstractType;
5618   bool Invalid;
5619 
5620   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5621     : S(S), Record(Record),
5622       AbstractType(S.Context.getCanonicalType(
5623                    S.Context.getTypeDeclType(Record))),
5624       Invalid(false) {}
5625 
5626   void DiagnoseAbstractType() {
5627     if (Invalid) return;
5628     S.DiagnoseAbstractType(Record);
5629     Invalid = true;
5630   }
5631 
5632   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5633 };
5634 
5635 struct CheckAbstractUsage {
5636   AbstractUsageInfo &Info;
5637   const NamedDecl *Ctx;
5638 
5639   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5640     : Info(Info), Ctx(Ctx) {}
5641 
5642   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5643     switch (TL.getTypeLocClass()) {
5644 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5645 #define TYPELOC(CLASS, PARENT) \
5646     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5647 #include "clang/AST/TypeLocNodes.def"
5648     }
5649   }
5650 
5651   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5652     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5653     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5654       if (!TL.getParam(I))
5655         continue;
5656 
5657       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5658       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5659     }
5660   }
5661 
5662   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5663     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5664   }
5665 
5666   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5667     // Visit the type parameters from a permissive context.
5668     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5669       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5670       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5671         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5672           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5673       // TODO: other template argument types?
5674     }
5675   }
5676 
5677   // Visit pointee types from a permissive context.
5678 #define CheckPolymorphic(Type) \
5679   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5680     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5681   }
5682   CheckPolymorphic(PointerTypeLoc)
5683   CheckPolymorphic(ReferenceTypeLoc)
5684   CheckPolymorphic(MemberPointerTypeLoc)
5685   CheckPolymorphic(BlockPointerTypeLoc)
5686   CheckPolymorphic(AtomicTypeLoc)
5687 
5688   /// Handle all the types we haven't given a more specific
5689   /// implementation for above.
5690   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5691     // Every other kind of type that we haven't called out already
5692     // that has an inner type is either (1) sugar or (2) contains that
5693     // inner type in some way as a subobject.
5694     if (TypeLoc Next = TL.getNextTypeLoc())
5695       return Visit(Next, Sel);
5696 
5697     // If there's no inner type and we're in a permissive context,
5698     // don't diagnose.
5699     if (Sel == Sema::AbstractNone) return;
5700 
5701     // Check whether the type matches the abstract type.
5702     QualType T = TL.getType();
5703     if (T->isArrayType()) {
5704       Sel = Sema::AbstractArrayType;
5705       T = Info.S.Context.getBaseElementType(T);
5706     }
5707     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5708     if (CT != Info.AbstractType) return;
5709 
5710     // It matched; do some magic.
5711     if (Sel == Sema::AbstractArrayType) {
5712       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5713         << T << TL.getSourceRange();
5714     } else {
5715       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5716         << Sel << T << TL.getSourceRange();
5717     }
5718     Info.DiagnoseAbstractType();
5719   }
5720 };
5721 
5722 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5723                                   Sema::AbstractDiagSelID Sel) {
5724   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5725 }
5726 
5727 }
5728 
5729 /// Check for invalid uses of an abstract type in a method declaration.
5730 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5731                                     CXXMethodDecl *MD) {
5732   // No need to do the check on definitions, which require that
5733   // the return/param types be complete.
5734   if (MD->doesThisDeclarationHaveABody())
5735     return;
5736 
5737   // For safety's sake, just ignore it if we don't have type source
5738   // information.  This should never happen for non-implicit methods,
5739   // but...
5740   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5741     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5742 }
5743 
5744 /// Check for invalid uses of an abstract type within a class definition.
5745 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5746                                     CXXRecordDecl *RD) {
5747   for (auto *D : RD->decls()) {
5748     if (D->isImplicit()) continue;
5749 
5750     // Methods and method templates.
5751     if (isa<CXXMethodDecl>(D)) {
5752       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5753     } else if (isa<FunctionTemplateDecl>(D)) {
5754       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5755       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5756 
5757     // Fields and static variables.
5758     } else if (isa<FieldDecl>(D)) {
5759       FieldDecl *FD = cast<FieldDecl>(D);
5760       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5761         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5762     } else if (isa<VarDecl>(D)) {
5763       VarDecl *VD = cast<VarDecl>(D);
5764       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5765         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5766 
5767     // Nested classes and class templates.
5768     } else if (isa<CXXRecordDecl>(D)) {
5769       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5770     } else if (isa<ClassTemplateDecl>(D)) {
5771       CheckAbstractClassUsage(Info,
5772                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5773     }
5774   }
5775 }
5776 
5777 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5778   Attr *ClassAttr = getDLLAttr(Class);
5779   if (!ClassAttr)
5780     return;
5781 
5782   assert(ClassAttr->getKind() == attr::DLLExport);
5783 
5784   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5785 
5786   if (TSK == TSK_ExplicitInstantiationDeclaration)
5787     // Don't go any further if this is just an explicit instantiation
5788     // declaration.
5789     return;
5790 
5791   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5792     S.MarkVTableUsed(Class->getLocation(), Class, true);
5793 
5794   for (Decl *Member : Class->decls()) {
5795     // Defined static variables that are members of an exported base
5796     // class must be marked export too.
5797     auto *VD = dyn_cast<VarDecl>(Member);
5798     if (VD && Member->getAttr<DLLExportAttr>() &&
5799         VD->getStorageClass() == SC_Static &&
5800         TSK == TSK_ImplicitInstantiation)
5801       S.MarkVariableReferenced(VD->getLocation(), VD);
5802 
5803     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5804     if (!MD)
5805       continue;
5806 
5807     if (Member->getAttr<DLLExportAttr>()) {
5808       if (MD->isUserProvided()) {
5809         // Instantiate non-default class member functions ...
5810 
5811         // .. except for certain kinds of template specializations.
5812         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5813           continue;
5814 
5815         S.MarkFunctionReferenced(Class->getLocation(), MD);
5816 
5817         // The function will be passed to the consumer when its definition is
5818         // encountered.
5819       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5820                  MD->isCopyAssignmentOperator() ||
5821                  MD->isMoveAssignmentOperator()) {
5822         // Synthesize and instantiate non-trivial implicit methods, explicitly
5823         // defaulted methods, and the copy and move assignment operators. The
5824         // latter are exported even if they are trivial, because the address of
5825         // an operator can be taken and should compare equal across libraries.
5826         DiagnosticErrorTrap Trap(S.Diags);
5827         S.MarkFunctionReferenced(Class->getLocation(), MD);
5828         if (Trap.hasErrorOccurred()) {
5829           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5830               << Class << !S.getLangOpts().CPlusPlus11;
5831           break;
5832         }
5833 
5834         // There is no later point when we will see the definition of this
5835         // function, so pass it to the consumer now.
5836         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5837       }
5838     }
5839   }
5840 }
5841 
5842 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5843                                                         CXXRecordDecl *Class) {
5844   // Only the MS ABI has default constructor closures, so we don't need to do
5845   // this semantic checking anywhere else.
5846   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5847     return;
5848 
5849   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5850   for (Decl *Member : Class->decls()) {
5851     // Look for exported default constructors.
5852     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5853     if (!CD || !CD->isDefaultConstructor())
5854       continue;
5855     auto *Attr = CD->getAttr<DLLExportAttr>();
5856     if (!Attr)
5857       continue;
5858 
5859     // If the class is non-dependent, mark the default arguments as ODR-used so
5860     // that we can properly codegen the constructor closure.
5861     if (!Class->isDependentContext()) {
5862       for (ParmVarDecl *PD : CD->parameters()) {
5863         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5864         S.DiscardCleanupsInEvaluationContext();
5865       }
5866     }
5867 
5868     if (LastExportedDefaultCtor) {
5869       S.Diag(LastExportedDefaultCtor->getLocation(),
5870              diag::err_attribute_dll_ambiguous_default_ctor)
5871           << Class;
5872       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5873           << CD->getDeclName();
5874       return;
5875     }
5876     LastExportedDefaultCtor = CD;
5877   }
5878 }
5879 
5880 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5881                                                        CXXRecordDecl *Class) {
5882   bool ErrorReported = false;
5883   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5884                                                      ClassTemplateDecl *TD) {
5885     if (ErrorReported)
5886       return;
5887     S.Diag(TD->getLocation(),
5888            diag::err_cuda_device_builtin_surftex_cls_template)
5889         << /*surface*/ 0 << TD;
5890     ErrorReported = true;
5891   };
5892 
5893   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5894   if (!TD) {
5895     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5896     if (!SD) {
5897       S.Diag(Class->getLocation(),
5898              diag::err_cuda_device_builtin_surftex_ref_decl)
5899           << /*surface*/ 0 << Class;
5900       S.Diag(Class->getLocation(),
5901              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5902           << Class;
5903       return;
5904     }
5905     TD = SD->getSpecializedTemplate();
5906   }
5907 
5908   TemplateParameterList *Params = TD->getTemplateParameters();
5909   unsigned N = Params->size();
5910 
5911   if (N != 2) {
5912     reportIllegalClassTemplate(S, TD);
5913     S.Diag(TD->getLocation(),
5914            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5915         << TD << 2;
5916   }
5917   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5918     reportIllegalClassTemplate(S, TD);
5919     S.Diag(TD->getLocation(),
5920            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5921         << TD << /*1st*/ 0 << /*type*/ 0;
5922   }
5923   if (N > 1) {
5924     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5925     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5926       reportIllegalClassTemplate(S, TD);
5927       S.Diag(TD->getLocation(),
5928              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5929           << TD << /*2nd*/ 1 << /*integer*/ 1;
5930     }
5931   }
5932 }
5933 
5934 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5935                                                        CXXRecordDecl *Class) {
5936   bool ErrorReported = false;
5937   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5938                                                      ClassTemplateDecl *TD) {
5939     if (ErrorReported)
5940       return;
5941     S.Diag(TD->getLocation(),
5942            diag::err_cuda_device_builtin_surftex_cls_template)
5943         << /*texture*/ 1 << TD;
5944     ErrorReported = true;
5945   };
5946 
5947   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5948   if (!TD) {
5949     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5950     if (!SD) {
5951       S.Diag(Class->getLocation(),
5952              diag::err_cuda_device_builtin_surftex_ref_decl)
5953           << /*texture*/ 1 << Class;
5954       S.Diag(Class->getLocation(),
5955              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5956           << Class;
5957       return;
5958     }
5959     TD = SD->getSpecializedTemplate();
5960   }
5961 
5962   TemplateParameterList *Params = TD->getTemplateParameters();
5963   unsigned N = Params->size();
5964 
5965   if (N != 3) {
5966     reportIllegalClassTemplate(S, TD);
5967     S.Diag(TD->getLocation(),
5968            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5969         << TD << 3;
5970   }
5971   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5972     reportIllegalClassTemplate(S, TD);
5973     S.Diag(TD->getLocation(),
5974            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5975         << TD << /*1st*/ 0 << /*type*/ 0;
5976   }
5977   if (N > 1) {
5978     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5979     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5980       reportIllegalClassTemplate(S, TD);
5981       S.Diag(TD->getLocation(),
5982              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5983           << TD << /*2nd*/ 1 << /*integer*/ 1;
5984     }
5985   }
5986   if (N > 2) {
5987     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
5988     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5989       reportIllegalClassTemplate(S, TD);
5990       S.Diag(TD->getLocation(),
5991              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5992           << TD << /*3rd*/ 2 << /*integer*/ 1;
5993     }
5994   }
5995 }
5996 
5997 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5998   // Mark any compiler-generated routines with the implicit code_seg attribute.
5999   for (auto *Method : Class->methods()) {
6000     if (Method->isUserProvided())
6001       continue;
6002     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6003       Method->addAttr(A);
6004   }
6005 }
6006 
6007 /// Check class-level dllimport/dllexport attribute.
6008 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6009   Attr *ClassAttr = getDLLAttr(Class);
6010 
6011   // MSVC inherits DLL attributes to partial class template specializations.
6012   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6013     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6014       if (Attr *TemplateAttr =
6015               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6016         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6017         A->setInherited(true);
6018         ClassAttr = A;
6019       }
6020     }
6021   }
6022 
6023   if (!ClassAttr)
6024     return;
6025 
6026   if (!Class->isExternallyVisible()) {
6027     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6028         << Class << ClassAttr;
6029     return;
6030   }
6031 
6032   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6033       !ClassAttr->isInherited()) {
6034     // Diagnose dll attributes on members of class with dll attribute.
6035     for (Decl *Member : Class->decls()) {
6036       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6037         continue;
6038       InheritableAttr *MemberAttr = getDLLAttr(Member);
6039       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6040         continue;
6041 
6042       Diag(MemberAttr->getLocation(),
6043              diag::err_attribute_dll_member_of_dll_class)
6044           << MemberAttr << ClassAttr;
6045       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6046       Member->setInvalidDecl();
6047     }
6048   }
6049 
6050   if (Class->getDescribedClassTemplate())
6051     // Don't inherit dll attribute until the template is instantiated.
6052     return;
6053 
6054   // The class is either imported or exported.
6055   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6056 
6057   // Check if this was a dllimport attribute propagated from a derived class to
6058   // a base class template specialization. We don't apply these attributes to
6059   // static data members.
6060   const bool PropagatedImport =
6061       !ClassExported &&
6062       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6063 
6064   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6065 
6066   // Ignore explicit dllexport on explicit class template instantiation
6067   // declarations, except in MinGW mode.
6068   if (ClassExported && !ClassAttr->isInherited() &&
6069       TSK == TSK_ExplicitInstantiationDeclaration &&
6070       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6071     Class->dropAttr<DLLExportAttr>();
6072     return;
6073   }
6074 
6075   // Force declaration of implicit members so they can inherit the attribute.
6076   ForceDeclarationOfImplicitMembers(Class);
6077 
6078   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6079   // seem to be true in practice?
6080 
6081   for (Decl *Member : Class->decls()) {
6082     VarDecl *VD = dyn_cast<VarDecl>(Member);
6083     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6084 
6085     // Only methods and static fields inherit the attributes.
6086     if (!VD && !MD)
6087       continue;
6088 
6089     if (MD) {
6090       // Don't process deleted methods.
6091       if (MD->isDeleted())
6092         continue;
6093 
6094       if (MD->isInlined()) {
6095         // MinGW does not import or export inline methods. But do it for
6096         // template instantiations.
6097         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6098             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6099             TSK != TSK_ExplicitInstantiationDeclaration &&
6100             TSK != TSK_ExplicitInstantiationDefinition)
6101           continue;
6102 
6103         // MSVC versions before 2015 don't export the move assignment operators
6104         // and move constructor, so don't attempt to import/export them if
6105         // we have a definition.
6106         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6107         if ((MD->isMoveAssignmentOperator() ||
6108              (Ctor && Ctor->isMoveConstructor())) &&
6109             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6110           continue;
6111 
6112         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6113         // operator is exported anyway.
6114         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6115             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6116           continue;
6117       }
6118     }
6119 
6120     // Don't apply dllimport attributes to static data members of class template
6121     // instantiations when the attribute is propagated from a derived class.
6122     if (VD && PropagatedImport)
6123       continue;
6124 
6125     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6126       continue;
6127 
6128     if (!getDLLAttr(Member)) {
6129       InheritableAttr *NewAttr = nullptr;
6130 
6131       // Do not export/import inline function when -fno-dllexport-inlines is
6132       // passed. But add attribute for later local static var check.
6133       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6134           TSK != TSK_ExplicitInstantiationDeclaration &&
6135           TSK != TSK_ExplicitInstantiationDefinition) {
6136         if (ClassExported) {
6137           NewAttr = ::new (getASTContext())
6138               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6139         } else {
6140           NewAttr = ::new (getASTContext())
6141               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6142         }
6143       } else {
6144         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6145       }
6146 
6147       NewAttr->setInherited(true);
6148       Member->addAttr(NewAttr);
6149 
6150       if (MD) {
6151         // Propagate DLLAttr to friend re-declarations of MD that have already
6152         // been constructed.
6153         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6154              FD = FD->getPreviousDecl()) {
6155           if (FD->getFriendObjectKind() == Decl::FOK_None)
6156             continue;
6157           assert(!getDLLAttr(FD) &&
6158                  "friend re-decl should not already have a DLLAttr");
6159           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6160           NewAttr->setInherited(true);
6161           FD->addAttr(NewAttr);
6162         }
6163       }
6164     }
6165   }
6166 
6167   if (ClassExported)
6168     DelayedDllExportClasses.push_back(Class);
6169 }
6170 
6171 /// Perform propagation of DLL attributes from a derived class to a
6172 /// templated base class for MS compatibility.
6173 void Sema::propagateDLLAttrToBaseClassTemplate(
6174     CXXRecordDecl *Class, Attr *ClassAttr,
6175     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6176   if (getDLLAttr(
6177           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6178     // If the base class template has a DLL attribute, don't try to change it.
6179     return;
6180   }
6181 
6182   auto TSK = BaseTemplateSpec->getSpecializationKind();
6183   if (!getDLLAttr(BaseTemplateSpec) &&
6184       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6185        TSK == TSK_ImplicitInstantiation)) {
6186     // The template hasn't been instantiated yet (or it has, but only as an
6187     // explicit instantiation declaration or implicit instantiation, which means
6188     // we haven't codegenned any members yet), so propagate the attribute.
6189     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6190     NewAttr->setInherited(true);
6191     BaseTemplateSpec->addAttr(NewAttr);
6192 
6193     // If this was an import, mark that we propagated it from a derived class to
6194     // a base class template specialization.
6195     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6196       ImportAttr->setPropagatedToBaseTemplate();
6197 
6198     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6199     // needs to be run again to work see the new attribute. Otherwise this will
6200     // get run whenever the template is instantiated.
6201     if (TSK != TSK_Undeclared)
6202       checkClassLevelDLLAttribute(BaseTemplateSpec);
6203 
6204     return;
6205   }
6206 
6207   if (getDLLAttr(BaseTemplateSpec)) {
6208     // The template has already been specialized or instantiated with an
6209     // attribute, explicitly or through propagation. We should not try to change
6210     // it.
6211     return;
6212   }
6213 
6214   // The template was previously instantiated or explicitly specialized without
6215   // a dll attribute, It's too late for us to add an attribute, so warn that
6216   // this is unsupported.
6217   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6218       << BaseTemplateSpec->isExplicitSpecialization();
6219   Diag(ClassAttr->getLocation(), diag::note_attribute);
6220   if (BaseTemplateSpec->isExplicitSpecialization()) {
6221     Diag(BaseTemplateSpec->getLocation(),
6222            diag::note_template_class_explicit_specialization_was_here)
6223         << BaseTemplateSpec;
6224   } else {
6225     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6226            diag::note_template_class_instantiation_was_here)
6227         << BaseTemplateSpec;
6228   }
6229 }
6230 
6231 /// Determine the kind of defaulting that would be done for a given function.
6232 ///
6233 /// If the function is both a default constructor and a copy / move constructor
6234 /// (due to having a default argument for the first parameter), this picks
6235 /// CXXDefaultConstructor.
6236 ///
6237 /// FIXME: Check that case is properly handled by all callers.
6238 Sema::DefaultedFunctionKind
6239 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6240   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6241     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6242       if (Ctor->isDefaultConstructor())
6243         return Sema::CXXDefaultConstructor;
6244 
6245       if (Ctor->isCopyConstructor())
6246         return Sema::CXXCopyConstructor;
6247 
6248       if (Ctor->isMoveConstructor())
6249         return Sema::CXXMoveConstructor;
6250     }
6251 
6252     if (MD->isCopyAssignmentOperator())
6253       return Sema::CXXCopyAssignment;
6254 
6255     if (MD->isMoveAssignmentOperator())
6256       return Sema::CXXMoveAssignment;
6257 
6258     if (isa<CXXDestructorDecl>(FD))
6259       return Sema::CXXDestructor;
6260   }
6261 
6262   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6263   case OO_EqualEqual:
6264     return DefaultedComparisonKind::Equal;
6265 
6266   case OO_ExclaimEqual:
6267     return DefaultedComparisonKind::NotEqual;
6268 
6269   case OO_Spaceship:
6270     // No point allowing this if <=> doesn't exist in the current language mode.
6271     if (!getLangOpts().CPlusPlus2a)
6272       break;
6273     return DefaultedComparisonKind::ThreeWay;
6274 
6275   case OO_Less:
6276   case OO_LessEqual:
6277   case OO_Greater:
6278   case OO_GreaterEqual:
6279     // No point allowing this if <=> doesn't exist in the current language mode.
6280     if (!getLangOpts().CPlusPlus2a)
6281       break;
6282     return DefaultedComparisonKind::Relational;
6283 
6284   default:
6285     break;
6286   }
6287 
6288   // Not defaultable.
6289   return DefaultedFunctionKind();
6290 }
6291 
6292 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6293                                     SourceLocation DefaultLoc) {
6294   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6295   if (DFK.isComparison())
6296     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6297 
6298   switch (DFK.asSpecialMember()) {
6299   case Sema::CXXDefaultConstructor:
6300     S.DefineImplicitDefaultConstructor(DefaultLoc,
6301                                        cast<CXXConstructorDecl>(FD));
6302     break;
6303   case Sema::CXXCopyConstructor:
6304     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6305     break;
6306   case Sema::CXXCopyAssignment:
6307     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6308     break;
6309   case Sema::CXXDestructor:
6310     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6311     break;
6312   case Sema::CXXMoveConstructor:
6313     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6314     break;
6315   case Sema::CXXMoveAssignment:
6316     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6317     break;
6318   case Sema::CXXInvalid:
6319     llvm_unreachable("Invalid special member.");
6320   }
6321 }
6322 
6323 /// Determine whether a type is permitted to be passed or returned in
6324 /// registers, per C++ [class.temporary]p3.
6325 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6326                                TargetInfo::CallingConvKind CCK) {
6327   if (D->isDependentType() || D->isInvalidDecl())
6328     return false;
6329 
6330   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6331   // The PS4 platform ABI follows the behavior of Clang 3.2.
6332   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6333     return !D->hasNonTrivialDestructorForCall() &&
6334            !D->hasNonTrivialCopyConstructorForCall();
6335 
6336   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6337     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6338     bool DtorIsTrivialForCall = false;
6339 
6340     // If a class has at least one non-deleted, trivial copy constructor, it
6341     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6342     //
6343     // Note: This permits classes with non-trivial copy or move ctors to be
6344     // passed in registers, so long as they *also* have a trivial copy ctor,
6345     // which is non-conforming.
6346     if (D->needsImplicitCopyConstructor()) {
6347       if (!D->defaultedCopyConstructorIsDeleted()) {
6348         if (D->hasTrivialCopyConstructor())
6349           CopyCtorIsTrivial = true;
6350         if (D->hasTrivialCopyConstructorForCall())
6351           CopyCtorIsTrivialForCall = true;
6352       }
6353     } else {
6354       for (const CXXConstructorDecl *CD : D->ctors()) {
6355         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6356           if (CD->isTrivial())
6357             CopyCtorIsTrivial = true;
6358           if (CD->isTrivialForCall())
6359             CopyCtorIsTrivialForCall = true;
6360         }
6361       }
6362     }
6363 
6364     if (D->needsImplicitDestructor()) {
6365       if (!D->defaultedDestructorIsDeleted() &&
6366           D->hasTrivialDestructorForCall())
6367         DtorIsTrivialForCall = true;
6368     } else if (const auto *DD = D->getDestructor()) {
6369       if (!DD->isDeleted() && DD->isTrivialForCall())
6370         DtorIsTrivialForCall = true;
6371     }
6372 
6373     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6374     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6375       return true;
6376 
6377     // If a class has a destructor, we'd really like to pass it indirectly
6378     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6379     // impossible for small types, which it will pass in a single register or
6380     // stack slot. Most objects with dtors are large-ish, so handle that early.
6381     // We can't call out all large objects as being indirect because there are
6382     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6383     // how we pass large POD types.
6384 
6385     // Note: This permits small classes with nontrivial destructors to be
6386     // passed in registers, which is non-conforming.
6387     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6388     uint64_t TypeSize = isAArch64 ? 128 : 64;
6389 
6390     if (CopyCtorIsTrivial &&
6391         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6392       return true;
6393     return false;
6394   }
6395 
6396   // Per C++ [class.temporary]p3, the relevant condition is:
6397   //   each copy constructor, move constructor, and destructor of X is
6398   //   either trivial or deleted, and X has at least one non-deleted copy
6399   //   or move constructor
6400   bool HasNonDeletedCopyOrMove = false;
6401 
6402   if (D->needsImplicitCopyConstructor() &&
6403       !D->defaultedCopyConstructorIsDeleted()) {
6404     if (!D->hasTrivialCopyConstructorForCall())
6405       return false;
6406     HasNonDeletedCopyOrMove = true;
6407   }
6408 
6409   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6410       !D->defaultedMoveConstructorIsDeleted()) {
6411     if (!D->hasTrivialMoveConstructorForCall())
6412       return false;
6413     HasNonDeletedCopyOrMove = true;
6414   }
6415 
6416   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6417       !D->hasTrivialDestructorForCall())
6418     return false;
6419 
6420   for (const CXXMethodDecl *MD : D->methods()) {
6421     if (MD->isDeleted())
6422       continue;
6423 
6424     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6425     if (CD && CD->isCopyOrMoveConstructor())
6426       HasNonDeletedCopyOrMove = true;
6427     else if (!isa<CXXDestructorDecl>(MD))
6428       continue;
6429 
6430     if (!MD->isTrivialForCall())
6431       return false;
6432   }
6433 
6434   return HasNonDeletedCopyOrMove;
6435 }
6436 
6437 /// Report an error regarding overriding, along with any relevant
6438 /// overridden methods.
6439 ///
6440 /// \param DiagID the primary error to report.
6441 /// \param MD the overriding method.
6442 static bool
6443 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6444                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6445   bool IssuedDiagnostic = false;
6446   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6447     if (Report(O)) {
6448       if (!IssuedDiagnostic) {
6449         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6450         IssuedDiagnostic = true;
6451       }
6452       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6453     }
6454   }
6455   return IssuedDiagnostic;
6456 }
6457 
6458 /// Perform semantic checks on a class definition that has been
6459 /// completing, introducing implicitly-declared members, checking for
6460 /// abstract types, etc.
6461 ///
6462 /// \param S The scope in which the class was parsed. Null if we didn't just
6463 ///        parse a class definition.
6464 /// \param Record The completed class.
6465 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6466   if (!Record)
6467     return;
6468 
6469   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6470     AbstractUsageInfo Info(*this, Record);
6471     CheckAbstractClassUsage(Info, Record);
6472   }
6473 
6474   // If this is not an aggregate type and has no user-declared constructor,
6475   // complain about any non-static data members of reference or const scalar
6476   // type, since they will never get initializers.
6477   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6478       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6479       !Record->isLambda()) {
6480     bool Complained = false;
6481     for (const auto *F : Record->fields()) {
6482       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6483         continue;
6484 
6485       if (F->getType()->isReferenceType() ||
6486           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6487         if (!Complained) {
6488           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6489             << Record->getTagKind() << Record;
6490           Complained = true;
6491         }
6492 
6493         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6494           << F->getType()->isReferenceType()
6495           << F->getDeclName();
6496       }
6497     }
6498   }
6499 
6500   if (Record->getIdentifier()) {
6501     // C++ [class.mem]p13:
6502     //   If T is the name of a class, then each of the following shall have a
6503     //   name different from T:
6504     //     - every member of every anonymous union that is a member of class T.
6505     //
6506     // C++ [class.mem]p14:
6507     //   In addition, if class T has a user-declared constructor (12.1), every
6508     //   non-static data member of class T shall have a name different from T.
6509     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6510     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6511          ++I) {
6512       NamedDecl *D = (*I)->getUnderlyingDecl();
6513       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6514            Record->hasUserDeclaredConstructor()) ||
6515           isa<IndirectFieldDecl>(D)) {
6516         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6517           << D->getDeclName();
6518         break;
6519       }
6520     }
6521   }
6522 
6523   // Warn if the class has virtual methods but non-virtual public destructor.
6524   if (Record->isPolymorphic() && !Record->isDependentType()) {
6525     CXXDestructorDecl *dtor = Record->getDestructor();
6526     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6527         !Record->hasAttr<FinalAttr>())
6528       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6529            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6530   }
6531 
6532   if (Record->isAbstract()) {
6533     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6534       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6535         << FA->isSpelledAsSealed();
6536       DiagnoseAbstractType(Record);
6537     }
6538   }
6539 
6540   // Warn if the class has a final destructor but is not itself marked final.
6541   if (!Record->hasAttr<FinalAttr>()) {
6542     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6543       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6544         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6545             << FA->isSpelledAsSealed()
6546             << FixItHint::CreateInsertion(
6547                    getLocForEndOfToken(Record->getLocation()),
6548                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6549         Diag(Record->getLocation(),
6550              diag::note_final_dtor_non_final_class_silence)
6551             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6552       }
6553     }
6554   }
6555 
6556   // See if trivial_abi has to be dropped.
6557   if (Record->hasAttr<TrivialABIAttr>())
6558     checkIllFormedTrivialABIStruct(*Record);
6559 
6560   // Set HasTrivialSpecialMemberForCall if the record has attribute
6561   // "trivial_abi".
6562   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6563 
6564   if (HasTrivialABI)
6565     Record->setHasTrivialSpecialMemberForCall();
6566 
6567   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6568   // We check these last because they can depend on the properties of the
6569   // primary comparison functions (==, <=>).
6570   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6571 
6572   // Perform checks that can't be done until we know all the properties of a
6573   // member function (whether it's defaulted, deleted, virtual, overriding,
6574   // ...).
6575   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6576     // A static function cannot override anything.
6577     if (MD->getStorageClass() == SC_Static) {
6578       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6579                           [](const CXXMethodDecl *) { return true; }))
6580         return;
6581     }
6582 
6583     // A deleted function cannot override a non-deleted function and vice
6584     // versa.
6585     if (ReportOverrides(*this,
6586                         MD->isDeleted() ? diag::err_deleted_override
6587                                         : diag::err_non_deleted_override,
6588                         MD, [&](const CXXMethodDecl *V) {
6589                           return MD->isDeleted() != V->isDeleted();
6590                         })) {
6591       if (MD->isDefaulted() && MD->isDeleted())
6592         // Explain why this defaulted function was deleted.
6593         DiagnoseDeletedDefaultedFunction(MD);
6594       return;
6595     }
6596 
6597     // A consteval function cannot override a non-consteval function and vice
6598     // versa.
6599     if (ReportOverrides(*this,
6600                         MD->isConsteval() ? diag::err_consteval_override
6601                                           : diag::err_non_consteval_override,
6602                         MD, [&](const CXXMethodDecl *V) {
6603                           return MD->isConsteval() != V->isConsteval();
6604                         })) {
6605       if (MD->isDefaulted() && MD->isDeleted())
6606         // Explain why this defaulted function was deleted.
6607         DiagnoseDeletedDefaultedFunction(MD);
6608       return;
6609     }
6610   };
6611 
6612   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6613     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6614       return false;
6615 
6616     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6617     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6618         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6619       DefaultedSecondaryComparisons.push_back(FD);
6620       return true;
6621     }
6622 
6623     CheckExplicitlyDefaultedFunction(S, FD);
6624     return false;
6625   };
6626 
6627   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6628     // Check whether the explicitly-defaulted members are valid.
6629     bool Incomplete = CheckForDefaultedFunction(M);
6630 
6631     // Skip the rest of the checks for a member of a dependent class.
6632     if (Record->isDependentType())
6633       return;
6634 
6635     // For an explicitly defaulted or deleted special member, we defer
6636     // determining triviality until the class is complete. That time is now!
6637     CXXSpecialMember CSM = getSpecialMember(M);
6638     if (!M->isImplicit() && !M->isUserProvided()) {
6639       if (CSM != CXXInvalid) {
6640         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6641         // Inform the class that we've finished declaring this member.
6642         Record->finishedDefaultedOrDeletedMember(M);
6643         M->setTrivialForCall(
6644             HasTrivialABI ||
6645             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6646         Record->setTrivialForCallFlags(M);
6647       }
6648     }
6649 
6650     // Set triviality for the purpose of calls if this is a user-provided
6651     // copy/move constructor or destructor.
6652     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6653          CSM == CXXDestructor) && M->isUserProvided()) {
6654       M->setTrivialForCall(HasTrivialABI);
6655       Record->setTrivialForCallFlags(M);
6656     }
6657 
6658     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6659         M->hasAttr<DLLExportAttr>()) {
6660       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6661           M->isTrivial() &&
6662           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6663            CSM == CXXDestructor))
6664         M->dropAttr<DLLExportAttr>();
6665 
6666       if (M->hasAttr<DLLExportAttr>()) {
6667         // Define after any fields with in-class initializers have been parsed.
6668         DelayedDllExportMemberFunctions.push_back(M);
6669       }
6670     }
6671 
6672     // Define defaulted constexpr virtual functions that override a base class
6673     // function right away.
6674     // FIXME: We can defer doing this until the vtable is marked as used.
6675     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6676       DefineDefaultedFunction(*this, M, M->getLocation());
6677 
6678     if (!Incomplete)
6679       CheckCompletedMemberFunction(M);
6680   };
6681 
6682   // Check the destructor before any other member function. We need to
6683   // determine whether it's trivial in order to determine whether the claas
6684   // type is a literal type, which is a prerequisite for determining whether
6685   // other special member functions are valid and whether they're implicitly
6686   // 'constexpr'.
6687   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6688     CompleteMemberFunction(Dtor);
6689 
6690   bool HasMethodWithOverrideControl = false,
6691        HasOverridingMethodWithoutOverrideControl = false;
6692   for (auto *D : Record->decls()) {
6693     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6694       // FIXME: We could do this check for dependent types with non-dependent
6695       // bases.
6696       if (!Record->isDependentType()) {
6697         // See if a method overloads virtual methods in a base
6698         // class without overriding any.
6699         if (!M->isStatic())
6700           DiagnoseHiddenVirtualMethods(M);
6701         if (M->hasAttr<OverrideAttr>())
6702           HasMethodWithOverrideControl = true;
6703         else if (M->size_overridden_methods() > 0)
6704           HasOverridingMethodWithoutOverrideControl = true;
6705       }
6706 
6707       if (!isa<CXXDestructorDecl>(M))
6708         CompleteMemberFunction(M);
6709     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6710       CheckForDefaultedFunction(
6711           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6712     }
6713   }
6714 
6715   if (HasMethodWithOverrideControl &&
6716       HasOverridingMethodWithoutOverrideControl) {
6717     // At least one method has the 'override' control declared.
6718     // Diagnose all other overridden methods which do not have 'override'
6719     // specified on them.
6720     for (auto *M : Record->methods())
6721       DiagnoseAbsenceOfOverrideControl(M);
6722   }
6723 
6724   // Check the defaulted secondary comparisons after any other member functions.
6725   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6726     CheckExplicitlyDefaultedFunction(S, FD);
6727 
6728     // If this is a member function, we deferred checking it until now.
6729     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6730       CheckCompletedMemberFunction(MD);
6731   }
6732 
6733   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6734   // whether this class uses any C++ features that are implemented
6735   // completely differently in MSVC, and if so, emit a diagnostic.
6736   // That diagnostic defaults to an error, but we allow projects to
6737   // map it down to a warning (or ignore it).  It's a fairly common
6738   // practice among users of the ms_struct pragma to mass-annotate
6739   // headers, sweeping up a bunch of types that the project doesn't
6740   // really rely on MSVC-compatible layout for.  We must therefore
6741   // support "ms_struct except for C++ stuff" as a secondary ABI.
6742   if (Record->isMsStruct(Context) &&
6743       (Record->isPolymorphic() || Record->getNumBases())) {
6744     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6745   }
6746 
6747   checkClassLevelDLLAttribute(Record);
6748   checkClassLevelCodeSegAttribute(Record);
6749 
6750   bool ClangABICompat4 =
6751       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6752   TargetInfo::CallingConvKind CCK =
6753       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6754   bool CanPass = canPassInRegisters(*this, Record, CCK);
6755 
6756   // Do not change ArgPassingRestrictions if it has already been set to
6757   // APK_CanNeverPassInRegs.
6758   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6759     Record->setArgPassingRestrictions(CanPass
6760                                           ? RecordDecl::APK_CanPassInRegs
6761                                           : RecordDecl::APK_CannotPassInRegs);
6762 
6763   // If canPassInRegisters returns true despite the record having a non-trivial
6764   // destructor, the record is destructed in the callee. This happens only when
6765   // the record or one of its subobjects has a field annotated with trivial_abi
6766   // or a field qualified with ObjC __strong/__weak.
6767   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6768     Record->setParamDestroyedInCallee(true);
6769   else if (Record->hasNonTrivialDestructor())
6770     Record->setParamDestroyedInCallee(CanPass);
6771 
6772   if (getLangOpts().ForceEmitVTables) {
6773     // If we want to emit all the vtables, we need to mark it as used.  This
6774     // is especially required for cases like vtable assumption loads.
6775     MarkVTableUsed(Record->getInnerLocStart(), Record);
6776   }
6777 
6778   if (getLangOpts().CUDA) {
6779     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6780       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6781     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6782       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6783   }
6784 }
6785 
6786 /// Look up the special member function that would be called by a special
6787 /// member function for a subobject of class type.
6788 ///
6789 /// \param Class The class type of the subobject.
6790 /// \param CSM The kind of special member function.
6791 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6792 /// \param ConstRHS True if this is a copy operation with a const object
6793 ///        on its RHS, that is, if the argument to the outer special member
6794 ///        function is 'const' and this is not a field marked 'mutable'.
6795 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6796     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6797     unsigned FieldQuals, bool ConstRHS) {
6798   unsigned LHSQuals = 0;
6799   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6800     LHSQuals = FieldQuals;
6801 
6802   unsigned RHSQuals = FieldQuals;
6803   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6804     RHSQuals = 0;
6805   else if (ConstRHS)
6806     RHSQuals |= Qualifiers::Const;
6807 
6808   return S.LookupSpecialMember(Class, CSM,
6809                                RHSQuals & Qualifiers::Const,
6810                                RHSQuals & Qualifiers::Volatile,
6811                                false,
6812                                LHSQuals & Qualifiers::Const,
6813                                LHSQuals & Qualifiers::Volatile);
6814 }
6815 
6816 class Sema::InheritedConstructorInfo {
6817   Sema &S;
6818   SourceLocation UseLoc;
6819 
6820   /// A mapping from the base classes through which the constructor was
6821   /// inherited to the using shadow declaration in that base class (or a null
6822   /// pointer if the constructor was declared in that base class).
6823   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6824       InheritedFromBases;
6825 
6826 public:
6827   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6828                            ConstructorUsingShadowDecl *Shadow)
6829       : S(S), UseLoc(UseLoc) {
6830     bool DiagnosedMultipleConstructedBases = false;
6831     CXXRecordDecl *ConstructedBase = nullptr;
6832     UsingDecl *ConstructedBaseUsing = nullptr;
6833 
6834     // Find the set of such base class subobjects and check that there's a
6835     // unique constructed subobject.
6836     for (auto *D : Shadow->redecls()) {
6837       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6838       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6839       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6840 
6841       InheritedFromBases.insert(
6842           std::make_pair(DNominatedBase->getCanonicalDecl(),
6843                          DShadow->getNominatedBaseClassShadowDecl()));
6844       if (DShadow->constructsVirtualBase())
6845         InheritedFromBases.insert(
6846             std::make_pair(DConstructedBase->getCanonicalDecl(),
6847                            DShadow->getConstructedBaseClassShadowDecl()));
6848       else
6849         assert(DNominatedBase == DConstructedBase);
6850 
6851       // [class.inhctor.init]p2:
6852       //   If the constructor was inherited from multiple base class subobjects
6853       //   of type B, the program is ill-formed.
6854       if (!ConstructedBase) {
6855         ConstructedBase = DConstructedBase;
6856         ConstructedBaseUsing = D->getUsingDecl();
6857       } else if (ConstructedBase != DConstructedBase &&
6858                  !Shadow->isInvalidDecl()) {
6859         if (!DiagnosedMultipleConstructedBases) {
6860           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6861               << Shadow->getTargetDecl();
6862           S.Diag(ConstructedBaseUsing->getLocation(),
6863                diag::note_ambiguous_inherited_constructor_using)
6864               << ConstructedBase;
6865           DiagnosedMultipleConstructedBases = true;
6866         }
6867         S.Diag(D->getUsingDecl()->getLocation(),
6868                diag::note_ambiguous_inherited_constructor_using)
6869             << DConstructedBase;
6870       }
6871     }
6872 
6873     if (DiagnosedMultipleConstructedBases)
6874       Shadow->setInvalidDecl();
6875   }
6876 
6877   /// Find the constructor to use for inherited construction of a base class,
6878   /// and whether that base class constructor inherits the constructor from a
6879   /// virtual base class (in which case it won't actually invoke it).
6880   std::pair<CXXConstructorDecl *, bool>
6881   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6882     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6883     if (It == InheritedFromBases.end())
6884       return std::make_pair(nullptr, false);
6885 
6886     // This is an intermediary class.
6887     if (It->second)
6888       return std::make_pair(
6889           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6890           It->second->constructsVirtualBase());
6891 
6892     // This is the base class from which the constructor was inherited.
6893     return std::make_pair(Ctor, false);
6894   }
6895 };
6896 
6897 /// Is the special member function which would be selected to perform the
6898 /// specified operation on the specified class type a constexpr constructor?
6899 static bool
6900 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6901                          Sema::CXXSpecialMember CSM, unsigned Quals,
6902                          bool ConstRHS,
6903                          CXXConstructorDecl *InheritedCtor = nullptr,
6904                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6905   // If we're inheriting a constructor, see if we need to call it for this base
6906   // class.
6907   if (InheritedCtor) {
6908     assert(CSM == Sema::CXXDefaultConstructor);
6909     auto BaseCtor =
6910         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6911     if (BaseCtor)
6912       return BaseCtor->isConstexpr();
6913   }
6914 
6915   if (CSM == Sema::CXXDefaultConstructor)
6916     return ClassDecl->hasConstexprDefaultConstructor();
6917   if (CSM == Sema::CXXDestructor)
6918     return ClassDecl->hasConstexprDestructor();
6919 
6920   Sema::SpecialMemberOverloadResult SMOR =
6921       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6922   if (!SMOR.getMethod())
6923     // A constructor we wouldn't select can't be "involved in initializing"
6924     // anything.
6925     return true;
6926   return SMOR.getMethod()->isConstexpr();
6927 }
6928 
6929 /// Determine whether the specified special member function would be constexpr
6930 /// if it were implicitly defined.
6931 static bool defaultedSpecialMemberIsConstexpr(
6932     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6933     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6934     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6935   if (!S.getLangOpts().CPlusPlus11)
6936     return false;
6937 
6938   // C++11 [dcl.constexpr]p4:
6939   // In the definition of a constexpr constructor [...]
6940   bool Ctor = true;
6941   switch (CSM) {
6942   case Sema::CXXDefaultConstructor:
6943     if (Inherited)
6944       break;
6945     // Since default constructor lookup is essentially trivial (and cannot
6946     // involve, for instance, template instantiation), we compute whether a
6947     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6948     //
6949     // This is important for performance; we need to know whether the default
6950     // constructor is constexpr to determine whether the type is a literal type.
6951     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6952 
6953   case Sema::CXXCopyConstructor:
6954   case Sema::CXXMoveConstructor:
6955     // For copy or move constructors, we need to perform overload resolution.
6956     break;
6957 
6958   case Sema::CXXCopyAssignment:
6959   case Sema::CXXMoveAssignment:
6960     if (!S.getLangOpts().CPlusPlus14)
6961       return false;
6962     // In C++1y, we need to perform overload resolution.
6963     Ctor = false;
6964     break;
6965 
6966   case Sema::CXXDestructor:
6967     return ClassDecl->defaultedDestructorIsConstexpr();
6968 
6969   case Sema::CXXInvalid:
6970     return false;
6971   }
6972 
6973   //   -- if the class is a non-empty union, or for each non-empty anonymous
6974   //      union member of a non-union class, exactly one non-static data member
6975   //      shall be initialized; [DR1359]
6976   //
6977   // If we squint, this is guaranteed, since exactly one non-static data member
6978   // will be initialized (if the constructor isn't deleted), we just don't know
6979   // which one.
6980   if (Ctor && ClassDecl->isUnion())
6981     return CSM == Sema::CXXDefaultConstructor
6982                ? ClassDecl->hasInClassInitializer() ||
6983                      !ClassDecl->hasVariantMembers()
6984                : true;
6985 
6986   //   -- the class shall not have any virtual base classes;
6987   if (Ctor && ClassDecl->getNumVBases())
6988     return false;
6989 
6990   // C++1y [class.copy]p26:
6991   //   -- [the class] is a literal type, and
6992   if (!Ctor && !ClassDecl->isLiteral())
6993     return false;
6994 
6995   //   -- every constructor involved in initializing [...] base class
6996   //      sub-objects shall be a constexpr constructor;
6997   //   -- the assignment operator selected to copy/move each direct base
6998   //      class is a constexpr function, and
6999   for (const auto &B : ClassDecl->bases()) {
7000     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7001     if (!BaseType) continue;
7002 
7003     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7004     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7005                                   InheritedCtor, Inherited))
7006       return false;
7007   }
7008 
7009   //   -- every constructor involved in initializing non-static data members
7010   //      [...] shall be a constexpr constructor;
7011   //   -- every non-static data member and base class sub-object shall be
7012   //      initialized
7013   //   -- for each non-static data member of X that is of class type (or array
7014   //      thereof), the assignment operator selected to copy/move that member is
7015   //      a constexpr function
7016   for (const auto *F : ClassDecl->fields()) {
7017     if (F->isInvalidDecl())
7018       continue;
7019     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7020       continue;
7021     QualType BaseType = S.Context.getBaseElementType(F->getType());
7022     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7023       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7024       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7025                                     BaseType.getCVRQualifiers(),
7026                                     ConstArg && !F->isMutable()))
7027         return false;
7028     } else if (CSM == Sema::CXXDefaultConstructor) {
7029       return false;
7030     }
7031   }
7032 
7033   // All OK, it's constexpr!
7034   return true;
7035 }
7036 
7037 namespace {
7038 /// RAII object to register a defaulted function as having its exception
7039 /// specification computed.
7040 struct ComputingExceptionSpec {
7041   Sema &S;
7042 
7043   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7044       : S(S) {
7045     Sema::CodeSynthesisContext Ctx;
7046     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7047     Ctx.PointOfInstantiation = Loc;
7048     Ctx.Entity = FD;
7049     S.pushCodeSynthesisContext(Ctx);
7050   }
7051   ~ComputingExceptionSpec() {
7052     S.popCodeSynthesisContext();
7053   }
7054 };
7055 }
7056 
7057 static Sema::ImplicitExceptionSpecification
7058 ComputeDefaultedSpecialMemberExceptionSpec(
7059     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7060     Sema::InheritedConstructorInfo *ICI);
7061 
7062 static Sema::ImplicitExceptionSpecification
7063 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7064                                         FunctionDecl *FD,
7065                                         Sema::DefaultedComparisonKind DCK);
7066 
7067 static Sema::ImplicitExceptionSpecification
7068 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7069   auto DFK = S.getDefaultedFunctionKind(FD);
7070   if (DFK.isSpecialMember())
7071     return ComputeDefaultedSpecialMemberExceptionSpec(
7072         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7073   if (DFK.isComparison())
7074     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7075                                                    DFK.asComparison());
7076 
7077   auto *CD = cast<CXXConstructorDecl>(FD);
7078   assert(CD->getInheritedConstructor() &&
7079          "only defaulted functions and inherited constructors have implicit "
7080          "exception specs");
7081   Sema::InheritedConstructorInfo ICI(
7082       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7083   return ComputeDefaultedSpecialMemberExceptionSpec(
7084       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7085 }
7086 
7087 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7088                                                             CXXMethodDecl *MD) {
7089   FunctionProtoType::ExtProtoInfo EPI;
7090 
7091   // Build an exception specification pointing back at this member.
7092   EPI.ExceptionSpec.Type = EST_Unevaluated;
7093   EPI.ExceptionSpec.SourceDecl = MD;
7094 
7095   // Set the calling convention to the default for C++ instance methods.
7096   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7097       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7098                                             /*IsCXXMethod=*/true));
7099   return EPI;
7100 }
7101 
7102 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7103   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7104   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7105     return;
7106 
7107   // Evaluate the exception specification.
7108   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7109   auto ESI = IES.getExceptionSpec();
7110 
7111   // Update the type of the special member to use it.
7112   UpdateExceptionSpec(FD, ESI);
7113 }
7114 
7115 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7116   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7117 
7118   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7119   if (!DefKind) {
7120     assert(FD->getDeclContext()->isDependentContext());
7121     return;
7122   }
7123 
7124   if (DefKind.isSpecialMember()
7125           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7126                                                   DefKind.asSpecialMember())
7127           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7128     FD->setInvalidDecl();
7129 }
7130 
7131 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7132                                                  CXXSpecialMember CSM) {
7133   CXXRecordDecl *RD = MD->getParent();
7134 
7135   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7136          "not an explicitly-defaulted special member");
7137 
7138   // Defer all checking for special members of a dependent type.
7139   if (RD->isDependentType())
7140     return false;
7141 
7142   // Whether this was the first-declared instance of the constructor.
7143   // This affects whether we implicitly add an exception spec and constexpr.
7144   bool First = MD == MD->getCanonicalDecl();
7145 
7146   bool HadError = false;
7147 
7148   // C++11 [dcl.fct.def.default]p1:
7149   //   A function that is explicitly defaulted shall
7150   //     -- be a special member function [...] (checked elsewhere),
7151   //     -- have the same type (except for ref-qualifiers, and except that a
7152   //        copy operation can take a non-const reference) as an implicit
7153   //        declaration, and
7154   //     -- not have default arguments.
7155   // C++2a changes the second bullet to instead delete the function if it's
7156   // defaulted on its first declaration, unless it's "an assignment operator,
7157   // and its return type differs or its parameter type is not a reference".
7158   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
7159   bool ShouldDeleteForTypeMismatch = false;
7160   unsigned ExpectedParams = 1;
7161   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7162     ExpectedParams = 0;
7163   if (MD->getNumParams() != ExpectedParams) {
7164     // This checks for default arguments: a copy or move constructor with a
7165     // default argument is classified as a default constructor, and assignment
7166     // operations and destructors can't have default arguments.
7167     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7168       << CSM << MD->getSourceRange();
7169     HadError = true;
7170   } else if (MD->isVariadic()) {
7171     if (DeleteOnTypeMismatch)
7172       ShouldDeleteForTypeMismatch = true;
7173     else {
7174       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7175         << CSM << MD->getSourceRange();
7176       HadError = true;
7177     }
7178   }
7179 
7180   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7181 
7182   bool CanHaveConstParam = false;
7183   if (CSM == CXXCopyConstructor)
7184     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7185   else if (CSM == CXXCopyAssignment)
7186     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7187 
7188   QualType ReturnType = Context.VoidTy;
7189   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7190     // Check for return type matching.
7191     ReturnType = Type->getReturnType();
7192 
7193     QualType DeclType = Context.getTypeDeclType(RD);
7194     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7195     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7196 
7197     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7198       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7199         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7200       HadError = true;
7201     }
7202 
7203     // A defaulted special member cannot have cv-qualifiers.
7204     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7205       if (DeleteOnTypeMismatch)
7206         ShouldDeleteForTypeMismatch = true;
7207       else {
7208         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7209           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7210         HadError = true;
7211       }
7212     }
7213   }
7214 
7215   // Check for parameter type matching.
7216   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7217   bool HasConstParam = false;
7218   if (ExpectedParams && ArgType->isReferenceType()) {
7219     // Argument must be reference to possibly-const T.
7220     QualType ReferentType = ArgType->getPointeeType();
7221     HasConstParam = ReferentType.isConstQualified();
7222 
7223     if (ReferentType.isVolatileQualified()) {
7224       if (DeleteOnTypeMismatch)
7225         ShouldDeleteForTypeMismatch = true;
7226       else {
7227         Diag(MD->getLocation(),
7228              diag::err_defaulted_special_member_volatile_param) << CSM;
7229         HadError = true;
7230       }
7231     }
7232 
7233     if (HasConstParam && !CanHaveConstParam) {
7234       if (DeleteOnTypeMismatch)
7235         ShouldDeleteForTypeMismatch = true;
7236       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7237         Diag(MD->getLocation(),
7238              diag::err_defaulted_special_member_copy_const_param)
7239           << (CSM == CXXCopyAssignment);
7240         // FIXME: Explain why this special member can't be const.
7241         HadError = true;
7242       } else {
7243         Diag(MD->getLocation(),
7244              diag::err_defaulted_special_member_move_const_param)
7245           << (CSM == CXXMoveAssignment);
7246         HadError = true;
7247       }
7248     }
7249   } else if (ExpectedParams) {
7250     // A copy assignment operator can take its argument by value, but a
7251     // defaulted one cannot.
7252     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7253     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7254     HadError = true;
7255   }
7256 
7257   // C++11 [dcl.fct.def.default]p2:
7258   //   An explicitly-defaulted function may be declared constexpr only if it
7259   //   would have been implicitly declared as constexpr,
7260   // Do not apply this rule to members of class templates, since core issue 1358
7261   // makes such functions always instantiate to constexpr functions. For
7262   // functions which cannot be constexpr (for non-constructors in C++11 and for
7263   // destructors in C++14 and C++17), this is checked elsewhere.
7264   //
7265   // FIXME: This should not apply if the member is deleted.
7266   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7267                                                      HasConstParam);
7268   if ((getLangOpts().CPlusPlus2a ||
7269        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7270                                   : isa<CXXConstructorDecl>(MD))) &&
7271       MD->isConstexpr() && !Constexpr &&
7272       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7273     Diag(MD->getBeginLoc(), MD->isConsteval()
7274                                 ? diag::err_incorrect_defaulted_consteval
7275                                 : diag::err_incorrect_defaulted_constexpr)
7276         << CSM;
7277     // FIXME: Explain why the special member can't be constexpr.
7278     HadError = true;
7279   }
7280 
7281   if (First) {
7282     // C++2a [dcl.fct.def.default]p3:
7283     //   If a function is explicitly defaulted on its first declaration, it is
7284     //   implicitly considered to be constexpr if the implicit declaration
7285     //   would be.
7286     MD->setConstexprKind(
7287         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7288                   : CSK_unspecified);
7289 
7290     if (!Type->hasExceptionSpec()) {
7291       // C++2a [except.spec]p3:
7292       //   If a declaration of a function does not have a noexcept-specifier
7293       //   [and] is defaulted on its first declaration, [...] the exception
7294       //   specification is as specified below
7295       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7296       EPI.ExceptionSpec.Type = EST_Unevaluated;
7297       EPI.ExceptionSpec.SourceDecl = MD;
7298       MD->setType(Context.getFunctionType(ReturnType,
7299                                           llvm::makeArrayRef(&ArgType,
7300                                                              ExpectedParams),
7301                                           EPI));
7302     }
7303   }
7304 
7305   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7306     if (First) {
7307       SetDeclDeleted(MD, MD->getLocation());
7308       if (!inTemplateInstantiation() && !HadError) {
7309         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7310         if (ShouldDeleteForTypeMismatch) {
7311           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7312         } else {
7313           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7314         }
7315       }
7316       if (ShouldDeleteForTypeMismatch && !HadError) {
7317         Diag(MD->getLocation(),
7318              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7319       }
7320     } else {
7321       // C++11 [dcl.fct.def.default]p4:
7322       //   [For a] user-provided explicitly-defaulted function [...] if such a
7323       //   function is implicitly defined as deleted, the program is ill-formed.
7324       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7325       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7326       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7327       HadError = true;
7328     }
7329   }
7330 
7331   return HadError;
7332 }
7333 
7334 namespace {
7335 /// Helper class for building and checking a defaulted comparison.
7336 ///
7337 /// Defaulted functions are built in two phases:
7338 ///
7339 ///  * First, the set of operations that the function will perform are
7340 ///    identified, and some of them are checked. If any of the checked
7341 ///    operations is invalid in certain ways, the comparison function is
7342 ///    defined as deleted and no body is built.
7343 ///  * Then, if the function is not defined as deleted, the body is built.
7344 ///
7345 /// This is accomplished by performing two visitation steps over the eventual
7346 /// body of the function.
7347 template<typename Derived, typename ResultList, typename Result,
7348          typename Subobject>
7349 class DefaultedComparisonVisitor {
7350 public:
7351   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7352 
7353   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7354                              DefaultedComparisonKind DCK)
7355       : S(S), RD(RD), FD(FD), DCK(DCK) {
7356     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7357       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7358       // UnresolvedSet to avoid this copy.
7359       Fns.assign(Info->getUnqualifiedLookups().begin(),
7360                  Info->getUnqualifiedLookups().end());
7361     }
7362   }
7363 
7364   ResultList visit() {
7365     // The type of an lvalue naming a parameter of this function.
7366     QualType ParamLvalType =
7367         FD->getParamDecl(0)->getType().getNonReferenceType();
7368 
7369     ResultList Results;
7370 
7371     switch (DCK) {
7372     case DefaultedComparisonKind::None:
7373       llvm_unreachable("not a defaulted comparison");
7374 
7375     case DefaultedComparisonKind::Equal:
7376     case DefaultedComparisonKind::ThreeWay:
7377       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7378       return Results;
7379 
7380     case DefaultedComparisonKind::NotEqual:
7381     case DefaultedComparisonKind::Relational:
7382       Results.add(getDerived().visitExpandedSubobject(
7383           ParamLvalType, getDerived().getCompleteObject()));
7384       return Results;
7385     }
7386     llvm_unreachable("");
7387   }
7388 
7389 protected:
7390   Derived &getDerived() { return static_cast<Derived&>(*this); }
7391 
7392   /// Visit the expanded list of subobjects of the given type, as specified in
7393   /// C++2a [class.compare.default].
7394   ///
7395   /// \return \c true if the ResultList object said we're done, \c false if not.
7396   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7397                        Qualifiers Quals) {
7398     // C++2a [class.compare.default]p4:
7399     //   The direct base class subobjects of C
7400     for (CXXBaseSpecifier &Base : Record->bases())
7401       if (Results.add(getDerived().visitSubobject(
7402               S.Context.getQualifiedType(Base.getType(), Quals),
7403               getDerived().getBase(&Base))))
7404         return true;
7405 
7406     //   followed by the non-static data members of C
7407     for (FieldDecl *Field : Record->fields()) {
7408       // Recursively expand anonymous structs.
7409       if (Field->isAnonymousStructOrUnion()) {
7410         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7411                             Quals))
7412           return true;
7413         continue;
7414       }
7415 
7416       // Figure out the type of an lvalue denoting this field.
7417       Qualifiers FieldQuals = Quals;
7418       if (Field->isMutable())
7419         FieldQuals.removeConst();
7420       QualType FieldType =
7421           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7422 
7423       if (Results.add(getDerived().visitSubobject(
7424               FieldType, getDerived().getField(Field))))
7425         return true;
7426     }
7427 
7428     //   form a list of subobjects.
7429     return false;
7430   }
7431 
7432   Result visitSubobject(QualType Type, Subobject Subobj) {
7433     //   In that list, any subobject of array type is recursively expanded
7434     const ArrayType *AT = S.Context.getAsArrayType(Type);
7435     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7436       return getDerived().visitSubobjectArray(CAT->getElementType(),
7437                                               CAT->getSize(), Subobj);
7438     return getDerived().visitExpandedSubobject(Type, Subobj);
7439   }
7440 
7441   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7442                              Subobject Subobj) {
7443     return getDerived().visitSubobject(Type, Subobj);
7444   }
7445 
7446 protected:
7447   Sema &S;
7448   CXXRecordDecl *RD;
7449   FunctionDecl *FD;
7450   DefaultedComparisonKind DCK;
7451   UnresolvedSet<16> Fns;
7452 };
7453 
7454 /// Information about a defaulted comparison, as determined by
7455 /// DefaultedComparisonAnalyzer.
7456 struct DefaultedComparisonInfo {
7457   bool Deleted = false;
7458   bool Constexpr = true;
7459   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7460 
7461   static DefaultedComparisonInfo deleted() {
7462     DefaultedComparisonInfo Deleted;
7463     Deleted.Deleted = true;
7464     return Deleted;
7465   }
7466 
7467   bool add(const DefaultedComparisonInfo &R) {
7468     Deleted |= R.Deleted;
7469     Constexpr &= R.Constexpr;
7470     Category = commonComparisonType(Category, R.Category);
7471     return Deleted;
7472   }
7473 };
7474 
7475 /// An element in the expanded list of subobjects of a defaulted comparison, as
7476 /// specified in C++2a [class.compare.default]p4.
7477 struct DefaultedComparisonSubobject {
7478   enum { CompleteObject, Member, Base } Kind;
7479   NamedDecl *Decl;
7480   SourceLocation Loc;
7481 };
7482 
7483 /// A visitor over the notional body of a defaulted comparison that determines
7484 /// whether that body would be deleted or constexpr.
7485 class DefaultedComparisonAnalyzer
7486     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7487                                         DefaultedComparisonInfo,
7488                                         DefaultedComparisonInfo,
7489                                         DefaultedComparisonSubobject> {
7490 public:
7491   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7492 
7493 private:
7494   DiagnosticKind Diagnose;
7495 
7496 public:
7497   using Base = DefaultedComparisonVisitor;
7498   using Result = DefaultedComparisonInfo;
7499   using Subobject = DefaultedComparisonSubobject;
7500 
7501   friend Base;
7502 
7503   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7504                               DefaultedComparisonKind DCK,
7505                               DiagnosticKind Diagnose = NoDiagnostics)
7506       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7507 
7508   Result visit() {
7509     if ((DCK == DefaultedComparisonKind::Equal ||
7510          DCK == DefaultedComparisonKind::ThreeWay) &&
7511         RD->hasVariantMembers()) {
7512       // C++2a [class.compare.default]p2 [P2002R0]:
7513       //   A defaulted comparison operator function for class C is defined as
7514       //   deleted if [...] C has variant members.
7515       if (Diagnose == ExplainDeleted) {
7516         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7517           << FD << RD->isUnion() << RD;
7518       }
7519       return Result::deleted();
7520     }
7521 
7522     return Base::visit();
7523   }
7524 
7525 private:
7526   Subobject getCompleteObject() {
7527     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7528   }
7529 
7530   Subobject getBase(CXXBaseSpecifier *Base) {
7531     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7532                      Base->getBaseTypeLoc()};
7533   }
7534 
7535   Subobject getField(FieldDecl *Field) {
7536     return Subobject{Subobject::Member, Field, Field->getLocation()};
7537   }
7538 
7539   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7540     // C++2a [class.compare.default]p2 [P2002R0]:
7541     //   A defaulted <=> or == operator function for class C is defined as
7542     //   deleted if any non-static data member of C is of reference type
7543     if (Type->isReferenceType()) {
7544       if (Diagnose == ExplainDeleted) {
7545         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7546             << FD << RD;
7547       }
7548       return Result::deleted();
7549     }
7550 
7551     // [...] Let xi be an lvalue denoting the ith element [...]
7552     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7553     Expr *Args[] = {&Xi, &Xi};
7554 
7555     // All operators start by trying to apply that same operator recursively.
7556     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7557     assert(OO != OO_None && "not an overloaded operator!");
7558     return visitBinaryOperator(OO, Args, Subobj);
7559   }
7560 
7561   Result
7562   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7563                       Subobject Subobj,
7564                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7565     // Note that there is no need to consider rewritten candidates here if
7566     // we've already found there is no viable 'operator<=>' candidate (and are
7567     // considering synthesizing a '<=>' from '==' and '<').
7568     OverloadCandidateSet CandidateSet(
7569         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7570         OverloadCandidateSet::OperatorRewriteInfo(
7571             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7572 
7573     /// C++2a [class.compare.default]p1 [P2002R0]:
7574     ///   [...] the defaulted function itself is never a candidate for overload
7575     ///   resolution [...]
7576     CandidateSet.exclude(FD);
7577 
7578     if (Args[0]->getType()->isOverloadableType())
7579       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7580     else {
7581       // FIXME: We determine whether this is a valid expression by checking to
7582       // see if there's a viable builtin operator candidate for it. That isn't
7583       // really what the rules ask us to do, but should give the right results.
7584       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7585     }
7586 
7587     Result R;
7588 
7589     OverloadCandidateSet::iterator Best;
7590     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7591     case OR_Success: {
7592       // C++2a [class.compare.secondary]p2 [P2002R0]:
7593       //   The operator function [...] is defined as deleted if [...] the
7594       //   candidate selected by overload resolution is not a rewritten
7595       //   candidate.
7596       if ((DCK == DefaultedComparisonKind::NotEqual ||
7597            DCK == DefaultedComparisonKind::Relational) &&
7598           !Best->RewriteKind) {
7599         if (Diagnose == ExplainDeleted) {
7600           S.Diag(Best->Function->getLocation(),
7601                  diag::note_defaulted_comparison_not_rewritten_callee)
7602               << FD;
7603         }
7604         return Result::deleted();
7605       }
7606 
7607       // Throughout C++2a [class.compare]: if overload resolution does not
7608       // result in a usable function, the candidate function is defined as
7609       // deleted. This requires that we selected an accessible function.
7610       //
7611       // Note that this only considers the access of the function when named
7612       // within the type of the subobject, and not the access path for any
7613       // derived-to-base conversion.
7614       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7615       if (ArgClass && Best->FoundDecl.getDecl() &&
7616           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7617         QualType ObjectType = Subobj.Kind == Subobject::Member
7618                                   ? Args[0]->getType()
7619                                   : S.Context.getRecordType(RD);
7620         if (!S.isMemberAccessibleForDeletion(
7621                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7622                 Diagnose == ExplainDeleted
7623                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7624                           << FD << Subobj.Kind << Subobj.Decl
7625                     : S.PDiag()))
7626           return Result::deleted();
7627       }
7628 
7629       // C++2a [class.compare.default]p3 [P2002R0]:
7630       //   A defaulted comparison function is constexpr-compatible if [...]
7631       //   no overlod resolution performed [...] results in a non-constexpr
7632       //   function.
7633       if (FunctionDecl *BestFD = Best->Function) {
7634         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7635         // If it's not constexpr, explain why not.
7636         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7637           if (Subobj.Kind != Subobject::CompleteObject)
7638             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7639               << Subobj.Kind << Subobj.Decl;
7640           S.Diag(BestFD->getLocation(),
7641                  diag::note_defaulted_comparison_not_constexpr_here);
7642           // Bail out after explaining; we don't want any more notes.
7643           return Result::deleted();
7644         }
7645         R.Constexpr &= BestFD->isConstexpr();
7646       }
7647 
7648       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7649         if (auto *BestFD = Best->Function) {
7650           // If any callee has an undeduced return type, deduce it now.
7651           // FIXME: It's not clear how a failure here should be handled. For
7652           // now, we produce an eager diagnostic, because that is forward
7653           // compatible with most (all?) other reasonable options.
7654           if (BestFD->getReturnType()->isUndeducedType() &&
7655               S.DeduceReturnType(BestFD, FD->getLocation(),
7656                                  /*Diagnose=*/false)) {
7657             // Don't produce a duplicate error when asked to explain why the
7658             // comparison is deleted: we diagnosed that when initially checking
7659             // the defaulted operator.
7660             if (Diagnose == NoDiagnostics) {
7661               S.Diag(
7662                   FD->getLocation(),
7663                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7664                   << Subobj.Kind << Subobj.Decl;
7665               S.Diag(
7666                   Subobj.Loc,
7667                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7668                   << Subobj.Kind << Subobj.Decl;
7669               S.Diag(BestFD->getLocation(),
7670                      diag::note_defaulted_comparison_cannot_deduce_callee)
7671                   << Subobj.Kind << Subobj.Decl;
7672             }
7673             return Result::deleted();
7674           }
7675           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7676               BestFD->getCallResultType())) {
7677             R.Category = Info->Kind;
7678           } else {
7679             if (Diagnose == ExplainDeleted) {
7680               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7681                   << Subobj.Kind << Subobj.Decl
7682                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
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         } else {
7690           Optional<ComparisonCategoryType> Cat =
7691               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7692           assert(Cat && "no category for builtin comparison?");
7693           R.Category = *Cat;
7694         }
7695       }
7696 
7697       // Note that we might be rewriting to a different operator. That call is
7698       // not considered until we come to actually build the comparison function.
7699       break;
7700     }
7701 
7702     case OR_Ambiguous:
7703       if (Diagnose == ExplainDeleted) {
7704         unsigned Kind = 0;
7705         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7706           Kind = OO == OO_EqualEqual ? 1 : 2;
7707         CandidateSet.NoteCandidates(
7708             PartialDiagnosticAt(
7709                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7710                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7711             S, OCD_AmbiguousCandidates, Args);
7712       }
7713       R = Result::deleted();
7714       break;
7715 
7716     case OR_Deleted:
7717       if (Diagnose == ExplainDeleted) {
7718         if ((DCK == DefaultedComparisonKind::NotEqual ||
7719              DCK == DefaultedComparisonKind::Relational) &&
7720             !Best->RewriteKind) {
7721           S.Diag(Best->Function->getLocation(),
7722                  diag::note_defaulted_comparison_not_rewritten_callee)
7723               << FD;
7724         } else {
7725           S.Diag(Subobj.Loc,
7726                  diag::note_defaulted_comparison_calls_deleted)
7727               << FD << Subobj.Kind << Subobj.Decl;
7728           S.NoteDeletedFunction(Best->Function);
7729         }
7730       }
7731       R = Result::deleted();
7732       break;
7733 
7734     case OR_No_Viable_Function:
7735       // If there's no usable candidate, we're done unless we can rewrite a
7736       // '<=>' in terms of '==' and '<'.
7737       if (OO == OO_Spaceship &&
7738           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7739         // For any kind of comparison category return type, we need a usable
7740         // '==' and a usable '<'.
7741         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7742                                        &CandidateSet)))
7743           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7744         break;
7745       }
7746 
7747       if (Diagnose == ExplainDeleted) {
7748         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7749             << FD << Subobj.Kind << Subobj.Decl;
7750 
7751         // For a three-way comparison, list both the candidates for the
7752         // original operator and the candidates for the synthesized operator.
7753         if (SpaceshipCandidates) {
7754           SpaceshipCandidates->NoteCandidates(
7755               S, Args,
7756               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7757                                                       Args, FD->getLocation()));
7758           S.Diag(Subobj.Loc,
7759                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7760               << (OO == OO_EqualEqual ? 0 : 1);
7761         }
7762 
7763         CandidateSet.NoteCandidates(
7764             S, Args,
7765             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7766                                             FD->getLocation()));
7767       }
7768       R = Result::deleted();
7769       break;
7770     }
7771 
7772     return R;
7773   }
7774 };
7775 
7776 /// A list of statements.
7777 struct StmtListResult {
7778   bool IsInvalid = false;
7779   llvm::SmallVector<Stmt*, 16> Stmts;
7780 
7781   bool add(const StmtResult &S) {
7782     IsInvalid |= S.isInvalid();
7783     if (IsInvalid)
7784       return true;
7785     Stmts.push_back(S.get());
7786     return false;
7787   }
7788 };
7789 
7790 /// A visitor over the notional body of a defaulted comparison that synthesizes
7791 /// the actual body.
7792 class DefaultedComparisonSynthesizer
7793     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7794                                         StmtListResult, StmtResult,
7795                                         std::pair<ExprResult, ExprResult>> {
7796   SourceLocation Loc;
7797   unsigned ArrayDepth = 0;
7798 
7799 public:
7800   using Base = DefaultedComparisonVisitor;
7801   using ExprPair = std::pair<ExprResult, ExprResult>;
7802 
7803   friend Base;
7804 
7805   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7806                                  DefaultedComparisonKind DCK,
7807                                  SourceLocation BodyLoc)
7808       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7809 
7810   /// Build a suitable function body for this defaulted comparison operator.
7811   StmtResult build() {
7812     Sema::CompoundScopeRAII CompoundScope(S);
7813 
7814     StmtListResult Stmts = visit();
7815     if (Stmts.IsInvalid)
7816       return StmtError();
7817 
7818     ExprResult RetVal;
7819     switch (DCK) {
7820     case DefaultedComparisonKind::None:
7821       llvm_unreachable("not a defaulted comparison");
7822 
7823     case DefaultedComparisonKind::Equal: {
7824       // C++2a [class.eq]p3:
7825       //   [...] compar[e] the corresponding elements [...] until the first
7826       //   index i where xi == yi yields [...] false. If no such index exists,
7827       //   V is true. Otherwise, V is false.
7828       //
7829       // Join the comparisons with '&&'s and return the result. Use a right
7830       // fold (traversing the conditions right-to-left), because that
7831       // short-circuits more naturally.
7832       auto OldStmts = std::move(Stmts.Stmts);
7833       Stmts.Stmts.clear();
7834       ExprResult CmpSoFar;
7835       // Finish a particular comparison chain.
7836       auto FinishCmp = [&] {
7837         if (Expr *Prior = CmpSoFar.get()) {
7838           // Convert the last expression to 'return ...;'
7839           if (RetVal.isUnset() && Stmts.Stmts.empty())
7840             RetVal = CmpSoFar;
7841           // Convert any prior comparison to 'if (!(...)) return false;'
7842           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7843             return true;
7844           CmpSoFar = ExprResult();
7845         }
7846         return false;
7847       };
7848       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7849         Expr *E = dyn_cast<Expr>(EAsStmt);
7850         if (!E) {
7851           // Found an array comparison.
7852           if (FinishCmp() || Stmts.add(EAsStmt))
7853             return StmtError();
7854           continue;
7855         }
7856 
7857         if (CmpSoFar.isUnset()) {
7858           CmpSoFar = E;
7859           continue;
7860         }
7861         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7862         if (CmpSoFar.isInvalid())
7863           return StmtError();
7864       }
7865       if (FinishCmp())
7866         return StmtError();
7867       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7868       //   If no such index exists, V is true.
7869       if (RetVal.isUnset())
7870         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7871       break;
7872     }
7873 
7874     case DefaultedComparisonKind::ThreeWay: {
7875       // Per C++2a [class.spaceship]p3, as a fallback add:
7876       // return static_cast<R>(std::strong_ordering::equal);
7877       QualType StrongOrdering = S.CheckComparisonCategoryType(
7878           ComparisonCategoryType::StrongOrdering, Loc,
7879           Sema::ComparisonCategoryUsage::DefaultedOperator);
7880       if (StrongOrdering.isNull())
7881         return StmtError();
7882       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7883                              .getValueInfo(ComparisonCategoryResult::Equal)
7884                              ->VD;
7885       RetVal = getDecl(EqualVD);
7886       if (RetVal.isInvalid())
7887         return StmtError();
7888       RetVal = buildStaticCastToR(RetVal.get());
7889       break;
7890     }
7891 
7892     case DefaultedComparisonKind::NotEqual:
7893     case DefaultedComparisonKind::Relational:
7894       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7895       break;
7896     }
7897 
7898     // Build the final return statement.
7899     if (RetVal.isInvalid())
7900       return StmtError();
7901     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7902     if (ReturnStmt.isInvalid())
7903       return StmtError();
7904     Stmts.Stmts.push_back(ReturnStmt.get());
7905 
7906     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7907   }
7908 
7909 private:
7910   ExprResult getDecl(ValueDecl *VD) {
7911     return S.BuildDeclarationNameExpr(
7912         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7913   }
7914 
7915   ExprResult getParam(unsigned I) {
7916     ParmVarDecl *PD = FD->getParamDecl(I);
7917     return getDecl(PD);
7918   }
7919 
7920   ExprPair getCompleteObject() {
7921     unsigned Param = 0;
7922     ExprResult LHS;
7923     if (isa<CXXMethodDecl>(FD)) {
7924       // LHS is '*this'.
7925       LHS = S.ActOnCXXThis(Loc);
7926       if (!LHS.isInvalid())
7927         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7928     } else {
7929       LHS = getParam(Param++);
7930     }
7931     ExprResult RHS = getParam(Param++);
7932     assert(Param == FD->getNumParams());
7933     return {LHS, RHS};
7934   }
7935 
7936   ExprPair getBase(CXXBaseSpecifier *Base) {
7937     ExprPair Obj = getCompleteObject();
7938     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7939       return {ExprError(), ExprError()};
7940     CXXCastPath Path = {Base};
7941     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7942                                 CK_DerivedToBase, VK_LValue, &Path),
7943             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7944                                 CK_DerivedToBase, VK_LValue, &Path)};
7945   }
7946 
7947   ExprPair getField(FieldDecl *Field) {
7948     ExprPair Obj = getCompleteObject();
7949     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7950       return {ExprError(), ExprError()};
7951 
7952     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
7953     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
7954     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
7955                                       CXXScopeSpec(), Field, Found, NameInfo),
7956             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
7957                                       CXXScopeSpec(), Field, Found, NameInfo)};
7958   }
7959 
7960   // FIXME: When expanding a subobject, register a note in the code synthesis
7961   // stack to say which subobject we're comparing.
7962 
7963   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
7964     if (Cond.isInvalid())
7965       return StmtError();
7966 
7967     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
7968     if (NotCond.isInvalid())
7969       return StmtError();
7970 
7971     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
7972     assert(!False.isInvalid() && "should never fail");
7973     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
7974     if (ReturnFalse.isInvalid())
7975       return StmtError();
7976 
7977     return S.ActOnIfStmt(Loc, false, nullptr,
7978                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
7979                                           Sema::ConditionKind::Boolean),
7980                          ReturnFalse.get(), SourceLocation(), nullptr);
7981   }
7982 
7983   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
7984                                  ExprPair Subobj) {
7985     QualType SizeType = S.Context.getSizeType();
7986     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
7987 
7988     // Build 'size_t i$n = 0'.
7989     IdentifierInfo *IterationVarName = nullptr;
7990     {
7991       SmallString<8> Str;
7992       llvm::raw_svector_ostream OS(Str);
7993       OS << "i" << ArrayDepth;
7994       IterationVarName = &S.Context.Idents.get(OS.str());
7995     }
7996     VarDecl *IterationVar = VarDecl::Create(
7997         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
7998         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
7999     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8000     IterationVar->setInit(
8001         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8002     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8003 
8004     auto IterRef = [&] {
8005       ExprResult Ref = S.BuildDeclarationNameExpr(
8006           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8007           IterationVar);
8008       assert(!Ref.isInvalid() && "can't reference our own variable?");
8009       return Ref.get();
8010     };
8011 
8012     // Build 'i$n != Size'.
8013     ExprResult Cond = S.CreateBuiltinBinOp(
8014         Loc, BO_NE, IterRef(),
8015         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8016     assert(!Cond.isInvalid() && "should never fail");
8017 
8018     // Build '++i$n'.
8019     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8020     assert(!Inc.isInvalid() && "should never fail");
8021 
8022     // Build 'a[i$n]' and 'b[i$n]'.
8023     auto Index = [&](ExprResult E) {
8024       if (E.isInvalid())
8025         return ExprError();
8026       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8027     };
8028     Subobj.first = Index(Subobj.first);
8029     Subobj.second = Index(Subobj.second);
8030 
8031     // Compare the array elements.
8032     ++ArrayDepth;
8033     StmtResult Substmt = visitSubobject(Type, Subobj);
8034     --ArrayDepth;
8035 
8036     if (Substmt.isInvalid())
8037       return StmtError();
8038 
8039     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8040     // For outer levels or for an 'operator<=>' we already have a suitable
8041     // statement that returns as necessary.
8042     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8043       assert(DCK == DefaultedComparisonKind::Equal &&
8044              "should have non-expression statement");
8045       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8046       if (Substmt.isInvalid())
8047         return StmtError();
8048     }
8049 
8050     // Build 'for (...) ...'
8051     return S.ActOnForStmt(Loc, Loc, Init,
8052                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8053                                            Sema::ConditionKind::Boolean),
8054                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8055                           Substmt.get());
8056   }
8057 
8058   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8059     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8060       return StmtError();
8061 
8062     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8063     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8064     ExprResult Op;
8065     if (Type->isOverloadableType())
8066       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8067                                    Obj.second.get(), /*PerformADL=*/true,
8068                                    /*AllowRewrittenCandidates=*/true, FD);
8069     else
8070       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8071     if (Op.isInvalid())
8072       return StmtError();
8073 
8074     switch (DCK) {
8075     case DefaultedComparisonKind::None:
8076       llvm_unreachable("not a defaulted comparison");
8077 
8078     case DefaultedComparisonKind::Equal:
8079       // Per C++2a [class.eq]p2, each comparison is individually contextually
8080       // converted to bool.
8081       Op = S.PerformContextuallyConvertToBool(Op.get());
8082       if (Op.isInvalid())
8083         return StmtError();
8084       return Op.get();
8085 
8086     case DefaultedComparisonKind::ThreeWay: {
8087       // Per C++2a [class.spaceship]p3, form:
8088       //   if (R cmp = static_cast<R>(op); cmp != 0)
8089       //     return cmp;
8090       QualType R = FD->getReturnType();
8091       Op = buildStaticCastToR(Op.get());
8092       if (Op.isInvalid())
8093         return StmtError();
8094 
8095       // R cmp = ...;
8096       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8097       VarDecl *VD =
8098           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8099                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8100       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8101       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8102 
8103       // cmp != 0
8104       ExprResult VDRef = getDecl(VD);
8105       if (VDRef.isInvalid())
8106         return StmtError();
8107       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8108       Expr *Zero =
8109           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8110       ExprResult Comp;
8111       if (VDRef.get()->getType()->isOverloadableType())
8112         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8113                                        true, FD);
8114       else
8115         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8116       if (Comp.isInvalid())
8117         return StmtError();
8118       Sema::ConditionResult Cond = S.ActOnCondition(
8119           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8120       if (Cond.isInvalid())
8121         return StmtError();
8122 
8123       // return cmp;
8124       VDRef = getDecl(VD);
8125       if (VDRef.isInvalid())
8126         return StmtError();
8127       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8128       if (ReturnStmt.isInvalid())
8129         return StmtError();
8130 
8131       // if (...)
8132       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond,
8133                            ReturnStmt.get(), /*ElseLoc=*/SourceLocation(),
8134                            /*Else=*/nullptr);
8135     }
8136 
8137     case DefaultedComparisonKind::NotEqual:
8138     case DefaultedComparisonKind::Relational:
8139       // C++2a [class.compare.secondary]p2:
8140       //   Otherwise, the operator function yields x @ y.
8141       return Op.get();
8142     }
8143     llvm_unreachable("");
8144   }
8145 
8146   /// Build "static_cast<R>(E)".
8147   ExprResult buildStaticCastToR(Expr *E) {
8148     QualType R = FD->getReturnType();
8149     assert(!R->isUndeducedType() && "type should have been deduced already");
8150 
8151     // Don't bother forming a no-op cast in the common case.
8152     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8153       return E;
8154     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8155                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8156                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8157   }
8158 };
8159 }
8160 
8161 /// Perform the unqualified lookups that might be needed to form a defaulted
8162 /// comparison function for the given operator.
8163 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8164                                                   UnresolvedSetImpl &Operators,
8165                                                   OverloadedOperatorKind Op) {
8166   auto Lookup = [&](OverloadedOperatorKind OO) {
8167     Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators);
8168   };
8169 
8170   // Every defaulted operator looks up itself.
8171   Lookup(Op);
8172   // ... and the rewritten form of itself, if any.
8173   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8174     Lookup(ExtraOp);
8175 
8176   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8177   // synthesize a three-way comparison from '<' and '=='. In a dependent
8178   // context, we also need to look up '==' in case we implicitly declare a
8179   // defaulted 'operator=='.
8180   if (Op == OO_Spaceship) {
8181     Lookup(OO_ExclaimEqual);
8182     Lookup(OO_Less);
8183     Lookup(OO_EqualEqual);
8184   }
8185 }
8186 
8187 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8188                                               DefaultedComparisonKind DCK) {
8189   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8190 
8191   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8192   assert(RD && "defaulted comparison is not defaulted in a class");
8193 
8194   // Perform any unqualified lookups we're going to need to default this
8195   // function.
8196   if (S) {
8197     UnresolvedSet<32> Operators;
8198     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8199                                           FD->getOverloadedOperator());
8200     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8201         Context, Operators.pairs()));
8202   }
8203 
8204   // C++2a [class.compare.default]p1:
8205   //   A defaulted comparison operator function for some class C shall be a
8206   //   non-template function declared in the member-specification of C that is
8207   //    -- a non-static const member of C having one parameter of type
8208   //       const C&, or
8209   //    -- a friend of C having two parameters of type const C& or two
8210   //       parameters of type C.
8211   QualType ExpectedParmType1 = Context.getRecordType(RD);
8212   QualType ExpectedParmType2 =
8213       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8214   if (isa<CXXMethodDecl>(FD))
8215     ExpectedParmType1 = ExpectedParmType2;
8216   for (const ParmVarDecl *Param : FD->parameters()) {
8217     if (!Param->getType()->isDependentType() &&
8218         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8219         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8220       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8221       // corresponding defaulted 'operator<=>' already.
8222       if (!FD->isImplicit()) {
8223         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8224             << (int)DCK << Param->getType() << ExpectedParmType1
8225             << !isa<CXXMethodDecl>(FD)
8226             << ExpectedParmType2 << Param->getSourceRange();
8227       }
8228       return true;
8229     }
8230   }
8231   if (FD->getNumParams() == 2 &&
8232       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8233                            FD->getParamDecl(1)->getType())) {
8234     if (!FD->isImplicit()) {
8235       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8236           << (int)DCK
8237           << FD->getParamDecl(0)->getType()
8238           << FD->getParamDecl(0)->getSourceRange()
8239           << FD->getParamDecl(1)->getType()
8240           << FD->getParamDecl(1)->getSourceRange();
8241     }
8242     return true;
8243   }
8244 
8245   // ... non-static const member ...
8246   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8247     assert(!MD->isStatic() && "comparison function cannot be a static member");
8248     if (!MD->isConst()) {
8249       SourceLocation InsertLoc;
8250       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8251         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8252       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8253       // corresponding defaulted 'operator<=>' already.
8254       if (!MD->isImplicit()) {
8255         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8256           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8257       }
8258 
8259       // Add the 'const' to the type to recover.
8260       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8261       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8262       EPI.TypeQuals.addConst();
8263       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8264                                           FPT->getParamTypes(), EPI));
8265     }
8266   } else {
8267     // A non-member function declared in a class must be a friend.
8268     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8269   }
8270 
8271   // C++2a [class.eq]p1, [class.rel]p1:
8272   //   A [defaulted comparison other than <=>] shall have a declared return
8273   //   type bool.
8274   if (DCK != DefaultedComparisonKind::ThreeWay &&
8275       !FD->getDeclaredReturnType()->isDependentType() &&
8276       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8277     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8278         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8279         << FD->getReturnTypeSourceRange();
8280     return true;
8281   }
8282   // C++2a [class.spaceship]p2 [P2002R0]:
8283   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8284   //   R shall not contain a placeholder type.
8285   if (DCK == DefaultedComparisonKind::ThreeWay &&
8286       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8287       !Context.hasSameType(FD->getDeclaredReturnType(),
8288                            Context.getAutoDeductType())) {
8289     Diag(FD->getLocation(),
8290          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8291         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8292         << FD->getReturnTypeSourceRange();
8293     return true;
8294   }
8295 
8296   // For a defaulted function in a dependent class, defer all remaining checks
8297   // until instantiation.
8298   if (RD->isDependentType())
8299     return false;
8300 
8301   // Determine whether the function should be defined as deleted.
8302   DefaultedComparisonInfo Info =
8303       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8304 
8305   bool First = FD == FD->getCanonicalDecl();
8306 
8307   // If we want to delete the function, then do so; there's nothing else to
8308   // check in that case.
8309   if (Info.Deleted) {
8310     if (!First) {
8311       // C++11 [dcl.fct.def.default]p4:
8312       //   [For a] user-provided explicitly-defaulted function [...] if such a
8313       //   function is implicitly defined as deleted, the program is ill-formed.
8314       //
8315       // This is really just a consequence of the general rule that you can
8316       // only delete a function on its first declaration.
8317       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8318           << FD->isImplicit() << (int)DCK;
8319       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8320                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8321           .visit();
8322       return true;
8323     }
8324 
8325     SetDeclDeleted(FD, FD->getLocation());
8326     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8327       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8328           << (int)DCK;
8329       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8330                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8331           .visit();
8332     }
8333     return false;
8334   }
8335 
8336   // C++2a [class.spaceship]p2:
8337   //   The return type is deduced as the common comparison type of R0, R1, ...
8338   if (DCK == DefaultedComparisonKind::ThreeWay &&
8339       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8340     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8341     if (RetLoc.isInvalid())
8342       RetLoc = FD->getBeginLoc();
8343     // FIXME: Should we really care whether we have the complete type and the
8344     // 'enumerator' constants here? A forward declaration seems sufficient.
8345     QualType Cat = CheckComparisonCategoryType(
8346         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8347     if (Cat.isNull())
8348       return true;
8349     Context.adjustDeducedFunctionResultType(
8350         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8351   }
8352 
8353   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8354   //   An explicitly-defaulted function that is not defined as deleted may be
8355   //   declared constexpr or consteval only if it is constexpr-compatible.
8356   // C++2a [class.compare.default]p3 [P2002R0]:
8357   //   A defaulted comparison function is constexpr-compatible if it satisfies
8358   //   the requirements for a constexpr function [...]
8359   // The only relevant requirements are that the parameter and return types are
8360   // literal types. The remaining conditions are checked by the analyzer.
8361   if (FD->isConstexpr()) {
8362     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8363         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8364         !Info.Constexpr) {
8365       Diag(FD->getBeginLoc(),
8366            diag::err_incorrect_defaulted_comparison_constexpr)
8367           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8368       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8369                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8370           .visit();
8371     }
8372   }
8373 
8374   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8375   //   If a constexpr-compatible function is explicitly defaulted on its first
8376   //   declaration, it is implicitly considered to be constexpr.
8377   // FIXME: Only applying this to the first declaration seems problematic, as
8378   // simple reorderings can affect the meaning of the program.
8379   if (First && !FD->isConstexpr() && Info.Constexpr)
8380     FD->setConstexprKind(CSK_constexpr);
8381 
8382   // C++2a [except.spec]p3:
8383   //   If a declaration of a function does not have a noexcept-specifier
8384   //   [and] is defaulted on its first declaration, [...] the exception
8385   //   specification is as specified below
8386   if (FD->getExceptionSpecType() == EST_None) {
8387     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8388     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8389     EPI.ExceptionSpec.Type = EST_Unevaluated;
8390     EPI.ExceptionSpec.SourceDecl = FD;
8391     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8392                                         FPT->getParamTypes(), EPI));
8393   }
8394 
8395   return false;
8396 }
8397 
8398 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8399                                              FunctionDecl *Spaceship) {
8400   Sema::CodeSynthesisContext Ctx;
8401   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8402   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8403   Ctx.Entity = Spaceship;
8404   pushCodeSynthesisContext(Ctx);
8405 
8406   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8407     EqualEqual->setImplicit();
8408 
8409   popCodeSynthesisContext();
8410 }
8411 
8412 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8413                                      DefaultedComparisonKind DCK) {
8414   assert(FD->isDefaulted() && !FD->isDeleted() &&
8415          !FD->doesThisDeclarationHaveABody());
8416   if (FD->willHaveBody() || FD->isInvalidDecl())
8417     return;
8418 
8419   SynthesizedFunctionScope Scope(*this, FD);
8420 
8421   // Add a context note for diagnostics produced after this point.
8422   Scope.addContextNote(UseLoc);
8423 
8424   {
8425     // Build and set up the function body.
8426     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8427     SourceLocation BodyLoc =
8428         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8429     StmtResult Body =
8430         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8431     if (Body.isInvalid()) {
8432       FD->setInvalidDecl();
8433       return;
8434     }
8435     FD->setBody(Body.get());
8436     FD->markUsed(Context);
8437   }
8438 
8439   // The exception specification is needed because we are defining the
8440   // function. Note that this will reuse the body we just built.
8441   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8442 
8443   if (ASTMutationListener *L = getASTMutationListener())
8444     L->CompletedImplicitDefinition(FD);
8445 }
8446 
8447 static Sema::ImplicitExceptionSpecification
8448 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8449                                         FunctionDecl *FD,
8450                                         Sema::DefaultedComparisonKind DCK) {
8451   ComputingExceptionSpec CES(S, FD, Loc);
8452   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8453 
8454   if (FD->isInvalidDecl())
8455     return ExceptSpec;
8456 
8457   // The common case is that we just defined the comparison function. In that
8458   // case, just look at whether the body can throw.
8459   if (FD->hasBody()) {
8460     ExceptSpec.CalledStmt(FD->getBody());
8461   } else {
8462     // Otherwise, build a body so we can check it. This should ideally only
8463     // happen when we're not actually marking the function referenced. (This is
8464     // only really important for efficiency: we don't want to build and throw
8465     // away bodies for comparison functions more than we strictly need to.)
8466 
8467     // Pretend to synthesize the function body in an unevaluated context.
8468     // Note that we can't actually just go ahead and define the function here:
8469     // we are not permitted to mark its callees as referenced.
8470     Sema::SynthesizedFunctionScope Scope(S, FD);
8471     EnterExpressionEvaluationContext Context(
8472         S, Sema::ExpressionEvaluationContext::Unevaluated);
8473 
8474     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8475     SourceLocation BodyLoc =
8476         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8477     StmtResult Body =
8478         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8479     if (!Body.isInvalid())
8480       ExceptSpec.CalledStmt(Body.get());
8481 
8482     // FIXME: Can we hold onto this body and just transform it to potentially
8483     // evaluated when we're asked to define the function rather than rebuilding
8484     // it? Either that, or we should only build the bits of the body that we
8485     // need (the expressions, not the statements).
8486   }
8487 
8488   return ExceptSpec;
8489 }
8490 
8491 void Sema::CheckDelayedMemberExceptionSpecs() {
8492   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8493   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8494 
8495   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8496   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8497 
8498   // Perform any deferred checking of exception specifications for virtual
8499   // destructors.
8500   for (auto &Check : Overriding)
8501     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8502 
8503   // Perform any deferred checking of exception specifications for befriended
8504   // special members.
8505   for (auto &Check : Equivalent)
8506     CheckEquivalentExceptionSpec(Check.second, Check.first);
8507 }
8508 
8509 namespace {
8510 /// CRTP base class for visiting operations performed by a special member
8511 /// function (or inherited constructor).
8512 template<typename Derived>
8513 struct SpecialMemberVisitor {
8514   Sema &S;
8515   CXXMethodDecl *MD;
8516   Sema::CXXSpecialMember CSM;
8517   Sema::InheritedConstructorInfo *ICI;
8518 
8519   // Properties of the special member, computed for convenience.
8520   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8521 
8522   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8523                        Sema::InheritedConstructorInfo *ICI)
8524       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8525     switch (CSM) {
8526     case Sema::CXXDefaultConstructor:
8527     case Sema::CXXCopyConstructor:
8528     case Sema::CXXMoveConstructor:
8529       IsConstructor = true;
8530       break;
8531     case Sema::CXXCopyAssignment:
8532     case Sema::CXXMoveAssignment:
8533       IsAssignment = true;
8534       break;
8535     case Sema::CXXDestructor:
8536       break;
8537     case Sema::CXXInvalid:
8538       llvm_unreachable("invalid special member kind");
8539     }
8540 
8541     if (MD->getNumParams()) {
8542       if (const ReferenceType *RT =
8543               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8544         ConstArg = RT->getPointeeType().isConstQualified();
8545     }
8546   }
8547 
8548   Derived &getDerived() { return static_cast<Derived&>(*this); }
8549 
8550   /// Is this a "move" special member?
8551   bool isMove() const {
8552     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8553   }
8554 
8555   /// Look up the corresponding special member in the given class.
8556   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8557                                              unsigned Quals, bool IsMutable) {
8558     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8559                                        ConstArg && !IsMutable);
8560   }
8561 
8562   /// Look up the constructor for the specified base class to see if it's
8563   /// overridden due to this being an inherited constructor.
8564   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8565     if (!ICI)
8566       return {};
8567     assert(CSM == Sema::CXXDefaultConstructor);
8568     auto *BaseCtor =
8569       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8570     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8571       return MD;
8572     return {};
8573   }
8574 
8575   /// A base or member subobject.
8576   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8577 
8578   /// Get the location to use for a subobject in diagnostics.
8579   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8580     // FIXME: For an indirect virtual base, the direct base leading to
8581     // the indirect virtual base would be a more useful choice.
8582     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8583       return B->getBaseTypeLoc();
8584     else
8585       return Subobj.get<FieldDecl*>()->getLocation();
8586   }
8587 
8588   enum BasesToVisit {
8589     /// Visit all non-virtual (direct) bases.
8590     VisitNonVirtualBases,
8591     /// Visit all direct bases, virtual or not.
8592     VisitDirectBases,
8593     /// Visit all non-virtual bases, and all virtual bases if the class
8594     /// is not abstract.
8595     VisitPotentiallyConstructedBases,
8596     /// Visit all direct or virtual bases.
8597     VisitAllBases
8598   };
8599 
8600   // Visit the bases and members of the class.
8601   bool visit(BasesToVisit Bases) {
8602     CXXRecordDecl *RD = MD->getParent();
8603 
8604     if (Bases == VisitPotentiallyConstructedBases)
8605       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8606 
8607     for (auto &B : RD->bases())
8608       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8609           getDerived().visitBase(&B))
8610         return true;
8611 
8612     if (Bases == VisitAllBases)
8613       for (auto &B : RD->vbases())
8614         if (getDerived().visitBase(&B))
8615           return true;
8616 
8617     for (auto *F : RD->fields())
8618       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8619           getDerived().visitField(F))
8620         return true;
8621 
8622     return false;
8623   }
8624 };
8625 }
8626 
8627 namespace {
8628 struct SpecialMemberDeletionInfo
8629     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8630   bool Diagnose;
8631 
8632   SourceLocation Loc;
8633 
8634   bool AllFieldsAreConst;
8635 
8636   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8637                             Sema::CXXSpecialMember CSM,
8638                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8639       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8640         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8641 
8642   bool inUnion() const { return MD->getParent()->isUnion(); }
8643 
8644   Sema::CXXSpecialMember getEffectiveCSM() {
8645     return ICI ? Sema::CXXInvalid : CSM;
8646   }
8647 
8648   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8649 
8650   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8651   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8652 
8653   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8654   bool shouldDeleteForField(FieldDecl *FD);
8655   bool shouldDeleteForAllConstMembers();
8656 
8657   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8658                                      unsigned Quals);
8659   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8660                                     Sema::SpecialMemberOverloadResult SMOR,
8661                                     bool IsDtorCallInCtor);
8662 
8663   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8664 };
8665 }
8666 
8667 /// Is the given special member inaccessible when used on the given
8668 /// sub-object.
8669 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8670                                              CXXMethodDecl *target) {
8671   /// If we're operating on a base class, the object type is the
8672   /// type of this special member.
8673   QualType objectTy;
8674   AccessSpecifier access = target->getAccess();
8675   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8676     objectTy = S.Context.getTypeDeclType(MD->getParent());
8677     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8678 
8679   // If we're operating on a field, the object type is the type of the field.
8680   } else {
8681     objectTy = S.Context.getTypeDeclType(target->getParent());
8682   }
8683 
8684   return S.isMemberAccessibleForDeletion(
8685       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8686 }
8687 
8688 /// Check whether we should delete a special member due to the implicit
8689 /// definition containing a call to a special member of a subobject.
8690 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8691     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8692     bool IsDtorCallInCtor) {
8693   CXXMethodDecl *Decl = SMOR.getMethod();
8694   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8695 
8696   int DiagKind = -1;
8697 
8698   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8699     DiagKind = !Decl ? 0 : 1;
8700   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8701     DiagKind = 2;
8702   else if (!isAccessible(Subobj, Decl))
8703     DiagKind = 3;
8704   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8705            !Decl->isTrivial()) {
8706     // A member of a union must have a trivial corresponding special member.
8707     // As a weird special case, a destructor call from a union's constructor
8708     // must be accessible and non-deleted, but need not be trivial. Such a
8709     // destructor is never actually called, but is semantically checked as
8710     // if it were.
8711     DiagKind = 4;
8712   }
8713 
8714   if (DiagKind == -1)
8715     return false;
8716 
8717   if (Diagnose) {
8718     if (Field) {
8719       S.Diag(Field->getLocation(),
8720              diag::note_deleted_special_member_class_subobject)
8721         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8722         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8723     } else {
8724       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8725       S.Diag(Base->getBeginLoc(),
8726              diag::note_deleted_special_member_class_subobject)
8727           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8728           << Base->getType() << DiagKind << IsDtorCallInCtor
8729           << /*IsObjCPtr*/false;
8730     }
8731 
8732     if (DiagKind == 1)
8733       S.NoteDeletedFunction(Decl);
8734     // FIXME: Explain inaccessibility if DiagKind == 3.
8735   }
8736 
8737   return true;
8738 }
8739 
8740 /// Check whether we should delete a special member function due to having a
8741 /// direct or virtual base class or non-static data member of class type M.
8742 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8743     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8744   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8745   bool IsMutable = Field && Field->isMutable();
8746 
8747   // C++11 [class.ctor]p5:
8748   // -- any direct or virtual base class, or non-static data member with no
8749   //    brace-or-equal-initializer, has class type M (or array thereof) and
8750   //    either M has no default constructor or overload resolution as applied
8751   //    to M's default constructor results in an ambiguity or in a function
8752   //    that is deleted or inaccessible
8753   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8754   // -- a direct or virtual base class B that cannot be copied/moved because
8755   //    overload resolution, as applied to B's corresponding special member,
8756   //    results in an ambiguity or a function that is deleted or inaccessible
8757   //    from the defaulted special member
8758   // C++11 [class.dtor]p5:
8759   // -- any direct or virtual base class [...] has a type with a destructor
8760   //    that is deleted or inaccessible
8761   if (!(CSM == Sema::CXXDefaultConstructor &&
8762         Field && Field->hasInClassInitializer()) &&
8763       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8764                                    false))
8765     return true;
8766 
8767   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8768   // -- any direct or virtual base class or non-static data member has a
8769   //    type with a destructor that is deleted or inaccessible
8770   if (IsConstructor) {
8771     Sema::SpecialMemberOverloadResult SMOR =
8772         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8773                               false, false, false, false, false);
8774     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8775       return true;
8776   }
8777 
8778   return false;
8779 }
8780 
8781 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8782     FieldDecl *FD, QualType FieldType) {
8783   // The defaulted special functions are defined as deleted if this is a variant
8784   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8785   // type under ARC.
8786   if (!FieldType.hasNonTrivialObjCLifetime())
8787     return false;
8788 
8789   // Don't make the defaulted default constructor defined as deleted if the
8790   // member has an in-class initializer.
8791   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8792     return false;
8793 
8794   if (Diagnose) {
8795     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8796     S.Diag(FD->getLocation(),
8797            diag::note_deleted_special_member_class_subobject)
8798         << getEffectiveCSM() << ParentClass << /*IsField*/true
8799         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8800   }
8801 
8802   return true;
8803 }
8804 
8805 /// Check whether we should delete a special member function due to the class
8806 /// having a particular direct or virtual base class.
8807 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8808   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8809   // If program is correct, BaseClass cannot be null, but if it is, the error
8810   // must be reported elsewhere.
8811   if (!BaseClass)
8812     return false;
8813   // If we have an inheriting constructor, check whether we're calling an
8814   // inherited constructor instead of a default constructor.
8815   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8816   if (auto *BaseCtor = SMOR.getMethod()) {
8817     // Note that we do not check access along this path; other than that,
8818     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8819     // FIXME: Check that the base has a usable destructor! Sink this into
8820     // shouldDeleteForClassSubobject.
8821     if (BaseCtor->isDeleted() && Diagnose) {
8822       S.Diag(Base->getBeginLoc(),
8823              diag::note_deleted_special_member_class_subobject)
8824           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8825           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8826           << /*IsObjCPtr*/false;
8827       S.NoteDeletedFunction(BaseCtor);
8828     }
8829     return BaseCtor->isDeleted();
8830   }
8831   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8832 }
8833 
8834 /// Check whether we should delete a special member function due to the class
8835 /// having a particular non-static data member.
8836 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8837   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8838   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8839 
8840   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8841     return true;
8842 
8843   if (CSM == Sema::CXXDefaultConstructor) {
8844     // For a default constructor, all references must be initialized in-class
8845     // and, if a union, it must have a non-const member.
8846     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8847       if (Diagnose)
8848         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8849           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8850       return true;
8851     }
8852     // C++11 [class.ctor]p5: any non-variant non-static data member of
8853     // const-qualified type (or array thereof) with no
8854     // brace-or-equal-initializer does not have a user-provided default
8855     // constructor.
8856     if (!inUnion() && FieldType.isConstQualified() &&
8857         !FD->hasInClassInitializer() &&
8858         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8859       if (Diagnose)
8860         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8861           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8862       return true;
8863     }
8864 
8865     if (inUnion() && !FieldType.isConstQualified())
8866       AllFieldsAreConst = false;
8867   } else if (CSM == Sema::CXXCopyConstructor) {
8868     // For a copy constructor, data members must not be of rvalue reference
8869     // type.
8870     if (FieldType->isRValueReferenceType()) {
8871       if (Diagnose)
8872         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8873           << MD->getParent() << FD << FieldType;
8874       return true;
8875     }
8876   } else if (IsAssignment) {
8877     // For an assignment operator, data members must not be of reference type.
8878     if (FieldType->isReferenceType()) {
8879       if (Diagnose)
8880         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8881           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8882       return true;
8883     }
8884     if (!FieldRecord && FieldType.isConstQualified()) {
8885       // C++11 [class.copy]p23:
8886       // -- a non-static data member of const non-class type (or array thereof)
8887       if (Diagnose)
8888         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8889           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8890       return true;
8891     }
8892   }
8893 
8894   if (FieldRecord) {
8895     // Some additional restrictions exist on the variant members.
8896     if (!inUnion() && FieldRecord->isUnion() &&
8897         FieldRecord->isAnonymousStructOrUnion()) {
8898       bool AllVariantFieldsAreConst = true;
8899 
8900       // FIXME: Handle anonymous unions declared within anonymous unions.
8901       for (auto *UI : FieldRecord->fields()) {
8902         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8903 
8904         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8905           return true;
8906 
8907         if (!UnionFieldType.isConstQualified())
8908           AllVariantFieldsAreConst = false;
8909 
8910         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8911         if (UnionFieldRecord &&
8912             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8913                                           UnionFieldType.getCVRQualifiers()))
8914           return true;
8915       }
8916 
8917       // At least one member in each anonymous union must be non-const
8918       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8919           !FieldRecord->field_empty()) {
8920         if (Diagnose)
8921           S.Diag(FieldRecord->getLocation(),
8922                  diag::note_deleted_default_ctor_all_const)
8923             << !!ICI << MD->getParent() << /*anonymous union*/1;
8924         return true;
8925       }
8926 
8927       // Don't check the implicit member of the anonymous union type.
8928       // This is technically non-conformant, but sanity demands it.
8929       return false;
8930     }
8931 
8932     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8933                                       FieldType.getCVRQualifiers()))
8934       return true;
8935   }
8936 
8937   return false;
8938 }
8939 
8940 /// C++11 [class.ctor] p5:
8941 ///   A defaulted default constructor for a class X is defined as deleted if
8942 /// X is a union and all of its variant members are of const-qualified type.
8943 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8944   // This is a silly definition, because it gives an empty union a deleted
8945   // default constructor. Don't do that.
8946   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8947     bool AnyFields = false;
8948     for (auto *F : MD->getParent()->fields())
8949       if ((AnyFields = !F->isUnnamedBitfield()))
8950         break;
8951     if (!AnyFields)
8952       return false;
8953     if (Diagnose)
8954       S.Diag(MD->getParent()->getLocation(),
8955              diag::note_deleted_default_ctor_all_const)
8956         << !!ICI << MD->getParent() << /*not anonymous union*/0;
8957     return true;
8958   }
8959   return false;
8960 }
8961 
8962 /// Determine whether a defaulted special member function should be defined as
8963 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
8964 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
8965 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
8966                                      InheritedConstructorInfo *ICI,
8967                                      bool Diagnose) {
8968   if (MD->isInvalidDecl())
8969     return false;
8970   CXXRecordDecl *RD = MD->getParent();
8971   assert(!RD->isDependentType() && "do deletion after instantiation");
8972   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
8973     return false;
8974 
8975   // C++11 [expr.lambda.prim]p19:
8976   //   The closure type associated with a lambda-expression has a
8977   //   deleted (8.4.3) default constructor and a deleted copy
8978   //   assignment operator.
8979   // C++2a adds back these operators if the lambda has no lambda-capture.
8980   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
8981       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
8982     if (Diagnose)
8983       Diag(RD->getLocation(), diag::note_lambda_decl);
8984     return true;
8985   }
8986 
8987   // For an anonymous struct or union, the copy and assignment special members
8988   // will never be used, so skip the check. For an anonymous union declared at
8989   // namespace scope, the constructor and destructor are used.
8990   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
8991       RD->isAnonymousStructOrUnion())
8992     return false;
8993 
8994   // C++11 [class.copy]p7, p18:
8995   //   If the class definition declares a move constructor or move assignment
8996   //   operator, an implicitly declared copy constructor or copy assignment
8997   //   operator is defined as deleted.
8998   if (MD->isImplicit() &&
8999       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9000     CXXMethodDecl *UserDeclaredMove = nullptr;
9001 
9002     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9003     // deletion of the corresponding copy operation, not both copy operations.
9004     // MSVC 2015 has adopted the standards conforming behavior.
9005     bool DeletesOnlyMatchingCopy =
9006         getLangOpts().MSVCCompat &&
9007         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9008 
9009     if (RD->hasUserDeclaredMoveConstructor() &&
9010         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9011       if (!Diagnose) return true;
9012 
9013       // Find any user-declared move constructor.
9014       for (auto *I : RD->ctors()) {
9015         if (I->isMoveConstructor()) {
9016           UserDeclaredMove = I;
9017           break;
9018         }
9019       }
9020       assert(UserDeclaredMove);
9021     } else if (RD->hasUserDeclaredMoveAssignment() &&
9022                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9023       if (!Diagnose) return true;
9024 
9025       // Find any user-declared move assignment operator.
9026       for (auto *I : RD->methods()) {
9027         if (I->isMoveAssignmentOperator()) {
9028           UserDeclaredMove = I;
9029           break;
9030         }
9031       }
9032       assert(UserDeclaredMove);
9033     }
9034 
9035     if (UserDeclaredMove) {
9036       Diag(UserDeclaredMove->getLocation(),
9037            diag::note_deleted_copy_user_declared_move)
9038         << (CSM == CXXCopyAssignment) << RD
9039         << UserDeclaredMove->isMoveAssignmentOperator();
9040       return true;
9041     }
9042   }
9043 
9044   // Do access control from the special member function
9045   ContextRAII MethodContext(*this, MD);
9046 
9047   // C++11 [class.dtor]p5:
9048   // -- for a virtual destructor, lookup of the non-array deallocation function
9049   //    results in an ambiguity or in a function that is deleted or inaccessible
9050   if (CSM == CXXDestructor && MD->isVirtual()) {
9051     FunctionDecl *OperatorDelete = nullptr;
9052     DeclarationName Name =
9053       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9054     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9055                                  OperatorDelete, /*Diagnose*/false)) {
9056       if (Diagnose)
9057         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9058       return true;
9059     }
9060   }
9061 
9062   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9063 
9064   // Per DR1611, do not consider virtual bases of constructors of abstract
9065   // classes, since we are not going to construct them.
9066   // Per DR1658, do not consider virtual bases of destructors of abstract
9067   // classes either.
9068   // Per DR2180, for assignment operators we only assign (and thus only
9069   // consider) direct bases.
9070   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9071                                  : SMI.VisitPotentiallyConstructedBases))
9072     return true;
9073 
9074   if (SMI.shouldDeleteForAllConstMembers())
9075     return true;
9076 
9077   if (getLangOpts().CUDA) {
9078     // We should delete the special member in CUDA mode if target inference
9079     // failed.
9080     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9081     // is treated as certain special member, which may not reflect what special
9082     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9083     // expects CSM to match MD, therefore recalculate CSM.
9084     assert(ICI || CSM == getSpecialMember(MD));
9085     auto RealCSM = CSM;
9086     if (ICI)
9087       RealCSM = getSpecialMember(MD);
9088 
9089     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9090                                                    SMI.ConstArg, Diagnose);
9091   }
9092 
9093   return false;
9094 }
9095 
9096 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9097   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9098   assert(DFK && "not a defaultable function");
9099   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9100 
9101   if (DFK.isSpecialMember()) {
9102     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9103                               nullptr, /*Diagnose=*/true);
9104   } else {
9105     DefaultedComparisonAnalyzer(
9106         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9107         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9108         .visit();
9109   }
9110 }
9111 
9112 /// Perform lookup for a special member of the specified kind, and determine
9113 /// whether it is trivial. If the triviality can be determined without the
9114 /// lookup, skip it. This is intended for use when determining whether a
9115 /// special member of a containing object is trivial, and thus does not ever
9116 /// perform overload resolution for default constructors.
9117 ///
9118 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9119 /// member that was most likely to be intended to be trivial, if any.
9120 ///
9121 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9122 /// determine whether the special member is trivial.
9123 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9124                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9125                                      bool ConstRHS,
9126                                      Sema::TrivialABIHandling TAH,
9127                                      CXXMethodDecl **Selected) {
9128   if (Selected)
9129     *Selected = nullptr;
9130 
9131   switch (CSM) {
9132   case Sema::CXXInvalid:
9133     llvm_unreachable("not a special member");
9134 
9135   case Sema::CXXDefaultConstructor:
9136     // C++11 [class.ctor]p5:
9137     //   A default constructor is trivial if:
9138     //    - all the [direct subobjects] have trivial default constructors
9139     //
9140     // Note, no overload resolution is performed in this case.
9141     if (RD->hasTrivialDefaultConstructor())
9142       return true;
9143 
9144     if (Selected) {
9145       // If there's a default constructor which could have been trivial, dig it
9146       // out. Otherwise, if there's any user-provided default constructor, point
9147       // to that as an example of why there's not a trivial one.
9148       CXXConstructorDecl *DefCtor = nullptr;
9149       if (RD->needsImplicitDefaultConstructor())
9150         S.DeclareImplicitDefaultConstructor(RD);
9151       for (auto *CI : RD->ctors()) {
9152         if (!CI->isDefaultConstructor())
9153           continue;
9154         DefCtor = CI;
9155         if (!DefCtor->isUserProvided())
9156           break;
9157       }
9158 
9159       *Selected = DefCtor;
9160     }
9161 
9162     return false;
9163 
9164   case Sema::CXXDestructor:
9165     // C++11 [class.dtor]p5:
9166     //   A destructor is trivial if:
9167     //    - all the direct [subobjects] have trivial destructors
9168     if (RD->hasTrivialDestructor() ||
9169         (TAH == Sema::TAH_ConsiderTrivialABI &&
9170          RD->hasTrivialDestructorForCall()))
9171       return true;
9172 
9173     if (Selected) {
9174       if (RD->needsImplicitDestructor())
9175         S.DeclareImplicitDestructor(RD);
9176       *Selected = RD->getDestructor();
9177     }
9178 
9179     return false;
9180 
9181   case Sema::CXXCopyConstructor:
9182     // C++11 [class.copy]p12:
9183     //   A copy constructor is trivial if:
9184     //    - the constructor selected to copy each direct [subobject] is trivial
9185     if (RD->hasTrivialCopyConstructor() ||
9186         (TAH == Sema::TAH_ConsiderTrivialABI &&
9187          RD->hasTrivialCopyConstructorForCall())) {
9188       if (Quals == Qualifiers::Const)
9189         // We must either select the trivial copy constructor or reach an
9190         // ambiguity; no need to actually perform overload resolution.
9191         return true;
9192     } else if (!Selected) {
9193       return false;
9194     }
9195     // In C++98, we are not supposed to perform overload resolution here, but we
9196     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9197     // cases like B as having a non-trivial copy constructor:
9198     //   struct A { template<typename T> A(T&); };
9199     //   struct B { mutable A a; };
9200     goto NeedOverloadResolution;
9201 
9202   case Sema::CXXCopyAssignment:
9203     // C++11 [class.copy]p25:
9204     //   A copy assignment operator is trivial if:
9205     //    - the assignment operator selected to copy each direct [subobject] is
9206     //      trivial
9207     if (RD->hasTrivialCopyAssignment()) {
9208       if (Quals == Qualifiers::Const)
9209         return true;
9210     } else if (!Selected) {
9211       return false;
9212     }
9213     // In C++98, we are not supposed to perform overload resolution here, but we
9214     // treat that as a language defect.
9215     goto NeedOverloadResolution;
9216 
9217   case Sema::CXXMoveConstructor:
9218   case Sema::CXXMoveAssignment:
9219   NeedOverloadResolution:
9220     Sema::SpecialMemberOverloadResult SMOR =
9221         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9222 
9223     // The standard doesn't describe how to behave if the lookup is ambiguous.
9224     // We treat it as not making the member non-trivial, just like the standard
9225     // mandates for the default constructor. This should rarely matter, because
9226     // the member will also be deleted.
9227     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9228       return true;
9229 
9230     if (!SMOR.getMethod()) {
9231       assert(SMOR.getKind() ==
9232              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9233       return false;
9234     }
9235 
9236     // We deliberately don't check if we found a deleted special member. We're
9237     // not supposed to!
9238     if (Selected)
9239       *Selected = SMOR.getMethod();
9240 
9241     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9242         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9243       return SMOR.getMethod()->isTrivialForCall();
9244     return SMOR.getMethod()->isTrivial();
9245   }
9246 
9247   llvm_unreachable("unknown special method kind");
9248 }
9249 
9250 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9251   for (auto *CI : RD->ctors())
9252     if (!CI->isImplicit())
9253       return CI;
9254 
9255   // Look for constructor templates.
9256   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9257   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9258     if (CXXConstructorDecl *CD =
9259           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9260       return CD;
9261   }
9262 
9263   return nullptr;
9264 }
9265 
9266 /// The kind of subobject we are checking for triviality. The values of this
9267 /// enumeration are used in diagnostics.
9268 enum TrivialSubobjectKind {
9269   /// The subobject is a base class.
9270   TSK_BaseClass,
9271   /// The subobject is a non-static data member.
9272   TSK_Field,
9273   /// The object is actually the complete object.
9274   TSK_CompleteObject
9275 };
9276 
9277 /// Check whether the special member selected for a given type would be trivial.
9278 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9279                                       QualType SubType, bool ConstRHS,
9280                                       Sema::CXXSpecialMember CSM,
9281                                       TrivialSubobjectKind Kind,
9282                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9283   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9284   if (!SubRD)
9285     return true;
9286 
9287   CXXMethodDecl *Selected;
9288   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9289                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9290     return true;
9291 
9292   if (Diagnose) {
9293     if (ConstRHS)
9294       SubType.addConst();
9295 
9296     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9297       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9298         << Kind << SubType.getUnqualifiedType();
9299       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9300         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9301     } else if (!Selected)
9302       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9303         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9304     else if (Selected->isUserProvided()) {
9305       if (Kind == TSK_CompleteObject)
9306         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9307           << Kind << SubType.getUnqualifiedType() << CSM;
9308       else {
9309         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9310           << Kind << SubType.getUnqualifiedType() << CSM;
9311         S.Diag(Selected->getLocation(), diag::note_declared_at);
9312       }
9313     } else {
9314       if (Kind != TSK_CompleteObject)
9315         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9316           << Kind << SubType.getUnqualifiedType() << CSM;
9317 
9318       // Explain why the defaulted or deleted special member isn't trivial.
9319       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9320                                Diagnose);
9321     }
9322   }
9323 
9324   return false;
9325 }
9326 
9327 /// Check whether the members of a class type allow a special member to be
9328 /// trivial.
9329 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9330                                      Sema::CXXSpecialMember CSM,
9331                                      bool ConstArg,
9332                                      Sema::TrivialABIHandling TAH,
9333                                      bool Diagnose) {
9334   for (const auto *FI : RD->fields()) {
9335     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9336       continue;
9337 
9338     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9339 
9340     // Pretend anonymous struct or union members are members of this class.
9341     if (FI->isAnonymousStructOrUnion()) {
9342       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9343                                     CSM, ConstArg, TAH, Diagnose))
9344         return false;
9345       continue;
9346     }
9347 
9348     // C++11 [class.ctor]p5:
9349     //   A default constructor is trivial if [...]
9350     //    -- no non-static data member of its class has a
9351     //       brace-or-equal-initializer
9352     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9353       if (Diagnose)
9354         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9355       return false;
9356     }
9357 
9358     // Objective C ARC 4.3.5:
9359     //   [...] nontrivally ownership-qualified types are [...] not trivially
9360     //   default constructible, copy constructible, move constructible, copy
9361     //   assignable, move assignable, or destructible [...]
9362     if (FieldType.hasNonTrivialObjCLifetime()) {
9363       if (Diagnose)
9364         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9365           << RD << FieldType.getObjCLifetime();
9366       return false;
9367     }
9368 
9369     bool ConstRHS = ConstArg && !FI->isMutable();
9370     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9371                                    CSM, TSK_Field, TAH, Diagnose))
9372       return false;
9373   }
9374 
9375   return true;
9376 }
9377 
9378 /// Diagnose why the specified class does not have a trivial special member of
9379 /// the given kind.
9380 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9381   QualType Ty = Context.getRecordType(RD);
9382 
9383   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9384   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9385                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9386                             /*Diagnose*/true);
9387 }
9388 
9389 /// Determine whether a defaulted or deleted special member function is trivial,
9390 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9391 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9392 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9393                                   TrivialABIHandling TAH, bool Diagnose) {
9394   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9395 
9396   CXXRecordDecl *RD = MD->getParent();
9397 
9398   bool ConstArg = false;
9399 
9400   // C++11 [class.copy]p12, p25: [DR1593]
9401   //   A [special member] is trivial if [...] its parameter-type-list is
9402   //   equivalent to the parameter-type-list of an implicit declaration [...]
9403   switch (CSM) {
9404   case CXXDefaultConstructor:
9405   case CXXDestructor:
9406     // Trivial default constructors and destructors cannot have parameters.
9407     break;
9408 
9409   case CXXCopyConstructor:
9410   case CXXCopyAssignment: {
9411     // Trivial copy operations always have const, non-volatile parameter types.
9412     ConstArg = true;
9413     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9414     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9415     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9416       if (Diagnose)
9417         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9418           << Param0->getSourceRange() << Param0->getType()
9419           << Context.getLValueReferenceType(
9420                Context.getRecordType(RD).withConst());
9421       return false;
9422     }
9423     break;
9424   }
9425 
9426   case CXXMoveConstructor:
9427   case CXXMoveAssignment: {
9428     // Trivial move operations always have non-cv-qualified parameters.
9429     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9430     const RValueReferenceType *RT =
9431       Param0->getType()->getAs<RValueReferenceType>();
9432     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9433       if (Diagnose)
9434         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9435           << Param0->getSourceRange() << Param0->getType()
9436           << Context.getRValueReferenceType(Context.getRecordType(RD));
9437       return false;
9438     }
9439     break;
9440   }
9441 
9442   case CXXInvalid:
9443     llvm_unreachable("not a special member");
9444   }
9445 
9446   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9447     if (Diagnose)
9448       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9449            diag::note_nontrivial_default_arg)
9450         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9451     return false;
9452   }
9453   if (MD->isVariadic()) {
9454     if (Diagnose)
9455       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9456     return false;
9457   }
9458 
9459   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9460   //   A copy/move [constructor or assignment operator] is trivial if
9461   //    -- the [member] selected to copy/move each direct base class subobject
9462   //       is trivial
9463   //
9464   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9465   //   A [default constructor or destructor] is trivial if
9466   //    -- all the direct base classes have trivial [default constructors or
9467   //       destructors]
9468   for (const auto &BI : RD->bases())
9469     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9470                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9471       return false;
9472 
9473   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9474   //   A copy/move [constructor or assignment operator] for a class X is
9475   //   trivial if
9476   //    -- for each non-static data member of X that is of class type (or array
9477   //       thereof), the constructor selected to copy/move that member is
9478   //       trivial
9479   //
9480   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9481   //   A [default constructor or destructor] is trivial if
9482   //    -- for all of the non-static data members of its class that are of class
9483   //       type (or array thereof), each such class has a trivial [default
9484   //       constructor or destructor]
9485   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9486     return false;
9487 
9488   // C++11 [class.dtor]p5:
9489   //   A destructor is trivial if [...]
9490   //    -- the destructor is not virtual
9491   if (CSM == CXXDestructor && MD->isVirtual()) {
9492     if (Diagnose)
9493       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9494     return false;
9495   }
9496 
9497   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9498   //   A [special member] for class X is trivial if [...]
9499   //    -- class X has no virtual functions and no virtual base classes
9500   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9501     if (!Diagnose)
9502       return false;
9503 
9504     if (RD->getNumVBases()) {
9505       // Check for virtual bases. We already know that the corresponding
9506       // member in all bases is trivial, so vbases must all be direct.
9507       CXXBaseSpecifier &BS = *RD->vbases_begin();
9508       assert(BS.isVirtual());
9509       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9510       return false;
9511     }
9512 
9513     // Must have a virtual method.
9514     for (const auto *MI : RD->methods()) {
9515       if (MI->isVirtual()) {
9516         SourceLocation MLoc = MI->getBeginLoc();
9517         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9518         return false;
9519       }
9520     }
9521 
9522     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9523   }
9524 
9525   // Looks like it's trivial!
9526   return true;
9527 }
9528 
9529 namespace {
9530 struct FindHiddenVirtualMethod {
9531   Sema *S;
9532   CXXMethodDecl *Method;
9533   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9534   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9535 
9536 private:
9537   /// Check whether any most overridden method from MD in Methods
9538   static bool CheckMostOverridenMethods(
9539       const CXXMethodDecl *MD,
9540       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9541     if (MD->size_overridden_methods() == 0)
9542       return Methods.count(MD->getCanonicalDecl());
9543     for (const CXXMethodDecl *O : MD->overridden_methods())
9544       if (CheckMostOverridenMethods(O, Methods))
9545         return true;
9546     return false;
9547   }
9548 
9549 public:
9550   /// Member lookup function that determines whether a given C++
9551   /// method overloads virtual methods in a base class without overriding any,
9552   /// to be used with CXXRecordDecl::lookupInBases().
9553   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9554     RecordDecl *BaseRecord =
9555         Specifier->getType()->castAs<RecordType>()->getDecl();
9556 
9557     DeclarationName Name = Method->getDeclName();
9558     assert(Name.getNameKind() == DeclarationName::Identifier);
9559 
9560     bool foundSameNameMethod = false;
9561     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9562     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9563          Path.Decls = Path.Decls.slice(1)) {
9564       NamedDecl *D = Path.Decls.front();
9565       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9566         MD = MD->getCanonicalDecl();
9567         foundSameNameMethod = true;
9568         // Interested only in hidden virtual methods.
9569         if (!MD->isVirtual())
9570           continue;
9571         // If the method we are checking overrides a method from its base
9572         // don't warn about the other overloaded methods. Clang deviates from
9573         // GCC by only diagnosing overloads of inherited virtual functions that
9574         // do not override any other virtual functions in the base. GCC's
9575         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9576         // function from a base class. These cases may be better served by a
9577         // warning (not specific to virtual functions) on call sites when the
9578         // call would select a different function from the base class, were it
9579         // visible.
9580         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9581         if (!S->IsOverload(Method, MD, false))
9582           return true;
9583         // Collect the overload only if its hidden.
9584         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9585           overloadedMethods.push_back(MD);
9586       }
9587     }
9588 
9589     if (foundSameNameMethod)
9590       OverloadedMethods.append(overloadedMethods.begin(),
9591                                overloadedMethods.end());
9592     return foundSameNameMethod;
9593   }
9594 };
9595 } // end anonymous namespace
9596 
9597 /// Add the most overriden methods from MD to Methods
9598 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9599                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9600   if (MD->size_overridden_methods() == 0)
9601     Methods.insert(MD->getCanonicalDecl());
9602   else
9603     for (const CXXMethodDecl *O : MD->overridden_methods())
9604       AddMostOverridenMethods(O, Methods);
9605 }
9606 
9607 /// Check if a method overloads virtual methods in a base class without
9608 /// overriding any.
9609 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9610                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9611   if (!MD->getDeclName().isIdentifier())
9612     return;
9613 
9614   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9615                      /*bool RecordPaths=*/false,
9616                      /*bool DetectVirtual=*/false);
9617   FindHiddenVirtualMethod FHVM;
9618   FHVM.Method = MD;
9619   FHVM.S = this;
9620 
9621   // Keep the base methods that were overridden or introduced in the subclass
9622   // by 'using' in a set. A base method not in this set is hidden.
9623   CXXRecordDecl *DC = MD->getParent();
9624   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9625   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9626     NamedDecl *ND = *I;
9627     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9628       ND = shad->getTargetDecl();
9629     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9630       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9631   }
9632 
9633   if (DC->lookupInBases(FHVM, Paths))
9634     OverloadedMethods = FHVM.OverloadedMethods;
9635 }
9636 
9637 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9638                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9639   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9640     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9641     PartialDiagnostic PD = PDiag(
9642          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9643     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9644     Diag(overloadedMD->getLocation(), PD);
9645   }
9646 }
9647 
9648 /// Diagnose methods which overload virtual methods in a base class
9649 /// without overriding any.
9650 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9651   if (MD->isInvalidDecl())
9652     return;
9653 
9654   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9655     return;
9656 
9657   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9658   FindHiddenVirtualMethods(MD, OverloadedMethods);
9659   if (!OverloadedMethods.empty()) {
9660     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9661       << MD << (OverloadedMethods.size() > 1);
9662 
9663     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9664   }
9665 }
9666 
9667 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9668   auto PrintDiagAndRemoveAttr = [&]() {
9669     // No diagnostics if this is a template instantiation.
9670     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
9671       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9672            diag::ext_cannot_use_trivial_abi) << &RD;
9673     RD.dropAttr<TrivialABIAttr>();
9674   };
9675 
9676   // Ill-formed if the struct has virtual functions.
9677   if (RD.isPolymorphic()) {
9678     PrintDiagAndRemoveAttr();
9679     return;
9680   }
9681 
9682   for (const auto &B : RD.bases()) {
9683     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9684     // virtual base.
9685     if ((!B.getType()->isDependentType() &&
9686          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
9687         B.isVirtual()) {
9688       PrintDiagAndRemoveAttr();
9689       return;
9690     }
9691   }
9692 
9693   for (const auto *FD : RD.fields()) {
9694     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9695     // non-trivial for the purpose of calls.
9696     QualType FT = FD->getType();
9697     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9698       PrintDiagAndRemoveAttr();
9699       return;
9700     }
9701 
9702     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9703       if (!RT->isDependentType() &&
9704           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9705         PrintDiagAndRemoveAttr();
9706         return;
9707       }
9708   }
9709 }
9710 
9711 void Sema::ActOnFinishCXXMemberSpecification(
9712     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9713     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9714   if (!TagDecl)
9715     return;
9716 
9717   AdjustDeclIfTemplate(TagDecl);
9718 
9719   for (const ParsedAttr &AL : AttrList) {
9720     if (AL.getKind() != ParsedAttr::AT_Visibility)
9721       continue;
9722     AL.setInvalid();
9723     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9724   }
9725 
9726   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9727               // strict aliasing violation!
9728               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9729               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9730 
9731   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9732 }
9733 
9734 /// Find the equality comparison functions that should be implicitly declared
9735 /// in a given class definition, per C++2a [class.compare.default]p3.
9736 static void findImplicitlyDeclaredEqualityComparisons(
9737     ASTContext &Ctx, CXXRecordDecl *RD,
9738     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9739   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9740   if (!RD->lookup(EqEq).empty())
9741     // Member operator== explicitly declared: no implicit operator==s.
9742     return;
9743 
9744   // Traverse friends looking for an '==' or a '<=>'.
9745   for (FriendDecl *Friend : RD->friends()) {
9746     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9747     if (!FD) continue;
9748 
9749     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9750       // Friend operator== explicitly declared: no implicit operator==s.
9751       Spaceships.clear();
9752       return;
9753     }
9754 
9755     if (FD->getOverloadedOperator() == OO_Spaceship &&
9756         FD->isExplicitlyDefaulted())
9757       Spaceships.push_back(FD);
9758   }
9759 
9760   // Look for members named 'operator<=>'.
9761   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9762   for (NamedDecl *ND : RD->lookup(Cmp)) {
9763     // Note that we could find a non-function here (either a function template
9764     // or a using-declaration). Neither case results in an implicit
9765     // 'operator=='.
9766     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9767       if (FD->isExplicitlyDefaulted())
9768         Spaceships.push_back(FD);
9769   }
9770 }
9771 
9772 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9773 /// special functions, such as the default constructor, copy
9774 /// constructor, or destructor, to the given C++ class (C++
9775 /// [special]p1).  This routine can only be executed just before the
9776 /// definition of the class is complete.
9777 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9778   if (ClassDecl->needsImplicitDefaultConstructor()) {
9779     ++getASTContext().NumImplicitDefaultConstructors;
9780 
9781     if (ClassDecl->hasInheritedConstructor())
9782       DeclareImplicitDefaultConstructor(ClassDecl);
9783   }
9784 
9785   if (ClassDecl->needsImplicitCopyConstructor()) {
9786     ++getASTContext().NumImplicitCopyConstructors;
9787 
9788     // If the properties or semantics of the copy constructor couldn't be
9789     // determined while the class was being declared, force a declaration
9790     // of it now.
9791     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9792         ClassDecl->hasInheritedConstructor())
9793       DeclareImplicitCopyConstructor(ClassDecl);
9794     // For the MS ABI we need to know whether the copy ctor is deleted. A
9795     // prerequisite for deleting the implicit copy ctor is that the class has a
9796     // move ctor or move assignment that is either user-declared or whose
9797     // semantics are inherited from a subobject. FIXME: We should provide a more
9798     // direct way for CodeGen to ask whether the constructor was deleted.
9799     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9800              (ClassDecl->hasUserDeclaredMoveConstructor() ||
9801               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9802               ClassDecl->hasUserDeclaredMoveAssignment() ||
9803               ClassDecl->needsOverloadResolutionForMoveAssignment()))
9804       DeclareImplicitCopyConstructor(ClassDecl);
9805   }
9806 
9807   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
9808     ++getASTContext().NumImplicitMoveConstructors;
9809 
9810     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9811         ClassDecl->hasInheritedConstructor())
9812       DeclareImplicitMoveConstructor(ClassDecl);
9813   }
9814 
9815   if (ClassDecl->needsImplicitCopyAssignment()) {
9816     ++getASTContext().NumImplicitCopyAssignmentOperators;
9817 
9818     // If we have a dynamic class, then the copy assignment operator may be
9819     // virtual, so we have to declare it immediately. This ensures that, e.g.,
9820     // it shows up in the right place in the vtable and that we diagnose
9821     // problems with the implicit exception specification.
9822     if (ClassDecl->isDynamicClass() ||
9823         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9824         ClassDecl->hasInheritedAssignment())
9825       DeclareImplicitCopyAssignment(ClassDecl);
9826   }
9827 
9828   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9829     ++getASTContext().NumImplicitMoveAssignmentOperators;
9830 
9831     // Likewise for the move assignment operator.
9832     if (ClassDecl->isDynamicClass() ||
9833         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9834         ClassDecl->hasInheritedAssignment())
9835       DeclareImplicitMoveAssignment(ClassDecl);
9836   }
9837 
9838   if (ClassDecl->needsImplicitDestructor()) {
9839     ++getASTContext().NumImplicitDestructors;
9840 
9841     // If we have a dynamic class, then the destructor may be virtual, so we
9842     // have to declare the destructor immediately. This ensures that, e.g., it
9843     // shows up in the right place in the vtable and that we diagnose problems
9844     // with the implicit exception specification.
9845     if (ClassDecl->isDynamicClass() ||
9846         ClassDecl->needsOverloadResolutionForDestructor())
9847       DeclareImplicitDestructor(ClassDecl);
9848   }
9849 
9850   // C++2a [class.compare.default]p3:
9851   //   If the member-specification does not explicitly declare any member or
9852   //   friend named operator==, an == operator function is declared implicitly
9853   //   for each defaulted three-way comparison operator function defined in the
9854   //   member-specification
9855   // FIXME: Consider doing this lazily.
9856   if (getLangOpts().CPlusPlus2a) {
9857     llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships;
9858     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9859                                               DefaultedSpaceships);
9860     for (auto *FD : DefaultedSpaceships)
9861       DeclareImplicitEqualityComparison(ClassDecl, FD);
9862   }
9863 }
9864 
9865 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
9866   if (!D)
9867     return 0;
9868 
9869   // The order of template parameters is not important here. All names
9870   // get added to the same scope.
9871   SmallVector<TemplateParameterList *, 4> ParameterLists;
9872 
9873   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9874     D = TD->getTemplatedDecl();
9875 
9876   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9877     ParameterLists.push_back(PSD->getTemplateParameters());
9878 
9879   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9880     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9881       ParameterLists.push_back(DD->getTemplateParameterList(i));
9882 
9883     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9884       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9885         ParameterLists.push_back(FTD->getTemplateParameters());
9886     }
9887   }
9888 
9889   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9890     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9891       ParameterLists.push_back(TD->getTemplateParameterList(i));
9892 
9893     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9894       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9895         ParameterLists.push_back(CTD->getTemplateParameters());
9896     }
9897   }
9898 
9899   unsigned Count = 0;
9900   for (TemplateParameterList *Params : ParameterLists) {
9901     if (Params->size() > 0)
9902       // Ignore explicit specializations; they don't contribute to the template
9903       // depth.
9904       ++Count;
9905     for (NamedDecl *Param : *Params) {
9906       if (Param->getDeclName()) {
9907         S->AddDecl(Param);
9908         IdResolver.AddDecl(Param);
9909       }
9910     }
9911   }
9912 
9913   return Count;
9914 }
9915 
9916 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
9917   if (!RecordD) return;
9918   AdjustDeclIfTemplate(RecordD);
9919   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
9920   PushDeclContext(S, Record);
9921 }
9922 
9923 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
9924   if (!RecordD) return;
9925   PopDeclContext();
9926 }
9927 
9928 /// This is used to implement the constant expression evaluation part of the
9929 /// attribute enable_if extension. There is nothing in standard C++ which would
9930 /// require reentering parameters.
9931 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
9932   if (!Param)
9933     return;
9934 
9935   S->AddDecl(Param);
9936   if (Param->getDeclName())
9937     IdResolver.AddDecl(Param);
9938 }
9939 
9940 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
9941 /// parsing a top-level (non-nested) C++ class, and we are now
9942 /// parsing those parts of the given Method declaration that could
9943 /// not be parsed earlier (C++ [class.mem]p2), such as default
9944 /// arguments. This action should enter the scope of the given
9945 /// Method declaration as if we had just parsed the qualified method
9946 /// name. However, it should not bring the parameters into scope;
9947 /// that will be performed by ActOnDelayedCXXMethodParameter.
9948 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
9949 }
9950 
9951 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
9952 /// C++ method declaration. We're (re-)introducing the given
9953 /// function parameter into scope for use in parsing later parts of
9954 /// the method declaration. For example, we could see an
9955 /// ActOnParamDefaultArgument event for this parameter.
9956 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
9957   if (!ParamD)
9958     return;
9959 
9960   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
9961 
9962   // If this parameter has an unparsed default argument, clear it out
9963   // to make way for the parsed default argument.
9964   if (Param->hasUnparsedDefaultArg())
9965     Param->setDefaultArg(nullptr);
9966 
9967   S->AddDecl(Param);
9968   if (Param->getDeclName())
9969     IdResolver.AddDecl(Param);
9970 }
9971 
9972 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
9973 /// processing the delayed method declaration for Method. The method
9974 /// declaration is now considered finished. There may be a separate
9975 /// ActOnStartOfFunctionDef action later (not necessarily
9976 /// immediately!) for this method, if it was also defined inside the
9977 /// class body.
9978 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
9979   if (!MethodD)
9980     return;
9981 
9982   AdjustDeclIfTemplate(MethodD);
9983 
9984   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
9985 
9986   // Now that we have our default arguments, check the constructor
9987   // again. It could produce additional diagnostics or affect whether
9988   // the class has implicitly-declared destructors, among other
9989   // things.
9990   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
9991     CheckConstructor(Constructor);
9992 
9993   // Check the default arguments, which we may have added.
9994   if (!Method->isInvalidDecl())
9995     CheckCXXDefaultArguments(Method);
9996 }
9997 
9998 // Emit the given diagnostic for each non-address-space qualifier.
9999 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10000 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10001   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10002   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10003     bool DiagOccured = false;
10004     FTI.MethodQualifiers->forEachQualifier(
10005         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10006                                    SourceLocation SL) {
10007           // This diagnostic should be emitted on any qualifier except an addr
10008           // space qualifier. However, forEachQualifier currently doesn't visit
10009           // addr space qualifiers, so there's no way to write this condition
10010           // right now; we just diagnose on everything.
10011           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10012           DiagOccured = true;
10013         });
10014     if (DiagOccured)
10015       D.setInvalidType();
10016   }
10017 }
10018 
10019 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10020 /// the well-formedness of the constructor declarator @p D with type @p
10021 /// R. If there are any errors in the declarator, this routine will
10022 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10023 /// will be updated to reflect a well-formed type for the constructor and
10024 /// returned.
10025 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10026                                           StorageClass &SC) {
10027   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10028 
10029   // C++ [class.ctor]p3:
10030   //   A constructor shall not be virtual (10.3) or static (9.4). A
10031   //   constructor can be invoked for a const, volatile or const
10032   //   volatile object. A constructor shall not be declared const,
10033   //   volatile, or const volatile (9.3.2).
10034   if (isVirtual) {
10035     if (!D.isInvalidType())
10036       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10037         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10038         << SourceRange(D.getIdentifierLoc());
10039     D.setInvalidType();
10040   }
10041   if (SC == SC_Static) {
10042     if (!D.isInvalidType())
10043       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10044         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10045         << SourceRange(D.getIdentifierLoc());
10046     D.setInvalidType();
10047     SC = SC_None;
10048   }
10049 
10050   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10051     diagnoseIgnoredQualifiers(
10052         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10053         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10054         D.getDeclSpec().getRestrictSpecLoc(),
10055         D.getDeclSpec().getAtomicSpecLoc());
10056     D.setInvalidType();
10057   }
10058 
10059   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10060 
10061   // C++0x [class.ctor]p4:
10062   //   A constructor shall not be declared with a ref-qualifier.
10063   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10064   if (FTI.hasRefQualifier()) {
10065     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10066       << FTI.RefQualifierIsLValueRef
10067       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10068     D.setInvalidType();
10069   }
10070 
10071   // Rebuild the function type "R" without any type qualifiers (in
10072   // case any of the errors above fired) and with "void" as the
10073   // return type, since constructors don't have return types.
10074   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10075   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10076     return R;
10077 
10078   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10079   EPI.TypeQuals = Qualifiers();
10080   EPI.RefQualifier = RQ_None;
10081 
10082   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10083 }
10084 
10085 /// CheckConstructor - Checks a fully-formed constructor for
10086 /// well-formedness, issuing any diagnostics required. Returns true if
10087 /// the constructor declarator is invalid.
10088 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10089   CXXRecordDecl *ClassDecl
10090     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10091   if (!ClassDecl)
10092     return Constructor->setInvalidDecl();
10093 
10094   // C++ [class.copy]p3:
10095   //   A declaration of a constructor for a class X is ill-formed if
10096   //   its first parameter is of type (optionally cv-qualified) X and
10097   //   either there are no other parameters or else all other
10098   //   parameters have default arguments.
10099   if (!Constructor->isInvalidDecl() &&
10100       ((Constructor->getNumParams() == 1) ||
10101        (Constructor->getNumParams() > 1 &&
10102         Constructor->getParamDecl(1)->hasDefaultArg())) &&
10103       Constructor->getTemplateSpecializationKind()
10104                                               != TSK_ImplicitInstantiation) {
10105     QualType ParamType = Constructor->getParamDecl(0)->getType();
10106     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10107     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10108       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10109       const char *ConstRef
10110         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10111                                                         : " const &";
10112       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10113         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10114 
10115       // FIXME: Rather that making the constructor invalid, we should endeavor
10116       // to fix the type.
10117       Constructor->setInvalidDecl();
10118     }
10119   }
10120 }
10121 
10122 /// CheckDestructor - Checks a fully-formed destructor definition for
10123 /// well-formedness, issuing any diagnostics required.  Returns true
10124 /// on error.
10125 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10126   CXXRecordDecl *RD = Destructor->getParent();
10127 
10128   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10129     SourceLocation Loc;
10130 
10131     if (!Destructor->isImplicit())
10132       Loc = Destructor->getLocation();
10133     else
10134       Loc = RD->getLocation();
10135 
10136     // If we have a virtual destructor, look up the deallocation function
10137     if (FunctionDecl *OperatorDelete =
10138             FindDeallocationFunctionForDestructor(Loc, RD)) {
10139       Expr *ThisArg = nullptr;
10140 
10141       // If the notional 'delete this' expression requires a non-trivial
10142       // conversion from 'this' to the type of a destroying operator delete's
10143       // first parameter, perform that conversion now.
10144       if (OperatorDelete->isDestroyingOperatorDelete()) {
10145         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10146         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10147           // C++ [class.dtor]p13:
10148           //   ... as if for the expression 'delete this' appearing in a
10149           //   non-virtual destructor of the destructor's class.
10150           ContextRAII SwitchContext(*this, Destructor);
10151           ExprResult This =
10152               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10153           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10154           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10155           if (This.isInvalid()) {
10156             // FIXME: Register this as a context note so that it comes out
10157             // in the right order.
10158             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10159             return true;
10160           }
10161           ThisArg = This.get();
10162         }
10163       }
10164 
10165       DiagnoseUseOfDecl(OperatorDelete, Loc);
10166       MarkFunctionReferenced(Loc, OperatorDelete);
10167       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10168     }
10169   }
10170 
10171   return false;
10172 }
10173 
10174 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10175 /// the well-formednes of the destructor declarator @p D with type @p
10176 /// R. If there are any errors in the declarator, this routine will
10177 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10178 /// will be updated to reflect a well-formed type for the destructor and
10179 /// returned.
10180 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10181                                          StorageClass& SC) {
10182   // C++ [class.dtor]p1:
10183   //   [...] A typedef-name that names a class is a class-name
10184   //   (7.1.3); however, a typedef-name that names a class shall not
10185   //   be used as the identifier in the declarator for a destructor
10186   //   declaration.
10187   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10188   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10189     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10190       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10191   else if (const TemplateSpecializationType *TST =
10192              DeclaratorType->getAs<TemplateSpecializationType>())
10193     if (TST->isTypeAlias())
10194       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10195         << DeclaratorType << 1;
10196 
10197   // C++ [class.dtor]p2:
10198   //   A destructor is used to destroy objects of its class type. A
10199   //   destructor takes no parameters, and no return type can be
10200   //   specified for it (not even void). The address of a destructor
10201   //   shall not be taken. A destructor shall not be static. A
10202   //   destructor can be invoked for a const, volatile or const
10203   //   volatile object. A destructor shall not be declared const,
10204   //   volatile or const volatile (9.3.2).
10205   if (SC == SC_Static) {
10206     if (!D.isInvalidType())
10207       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10208         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10209         << SourceRange(D.getIdentifierLoc())
10210         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10211 
10212     SC = SC_None;
10213   }
10214   if (!D.isInvalidType()) {
10215     // Destructors don't have return types, but the parser will
10216     // happily parse something like:
10217     //
10218     //   class X {
10219     //     float ~X();
10220     //   };
10221     //
10222     // The return type will be eliminated later.
10223     if (D.getDeclSpec().hasTypeSpecifier())
10224       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10225         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10226         << SourceRange(D.getIdentifierLoc());
10227     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10228       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10229                                 SourceLocation(),
10230                                 D.getDeclSpec().getConstSpecLoc(),
10231                                 D.getDeclSpec().getVolatileSpecLoc(),
10232                                 D.getDeclSpec().getRestrictSpecLoc(),
10233                                 D.getDeclSpec().getAtomicSpecLoc());
10234       D.setInvalidType();
10235     }
10236   }
10237 
10238   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10239 
10240   // C++0x [class.dtor]p2:
10241   //   A destructor shall not be declared with a ref-qualifier.
10242   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10243   if (FTI.hasRefQualifier()) {
10244     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10245       << FTI.RefQualifierIsLValueRef
10246       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10247     D.setInvalidType();
10248   }
10249 
10250   // Make sure we don't have any parameters.
10251   if (FTIHasNonVoidParameters(FTI)) {
10252     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10253 
10254     // Delete the parameters.
10255     FTI.freeParams();
10256     D.setInvalidType();
10257   }
10258 
10259   // Make sure the destructor isn't variadic.
10260   if (FTI.isVariadic) {
10261     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10262     D.setInvalidType();
10263   }
10264 
10265   // Rebuild the function type "R" without any type qualifiers or
10266   // parameters (in case any of the errors above fired) and with
10267   // "void" as the return type, since destructors don't have return
10268   // types.
10269   if (!D.isInvalidType())
10270     return R;
10271 
10272   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10273   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10274   EPI.Variadic = false;
10275   EPI.TypeQuals = Qualifiers();
10276   EPI.RefQualifier = RQ_None;
10277   return Context.getFunctionType(Context.VoidTy, None, EPI);
10278 }
10279 
10280 static void extendLeft(SourceRange &R, SourceRange Before) {
10281   if (Before.isInvalid())
10282     return;
10283   R.setBegin(Before.getBegin());
10284   if (R.getEnd().isInvalid())
10285     R.setEnd(Before.getEnd());
10286 }
10287 
10288 static void extendRight(SourceRange &R, SourceRange After) {
10289   if (After.isInvalid())
10290     return;
10291   if (R.getBegin().isInvalid())
10292     R.setBegin(After.getBegin());
10293   R.setEnd(After.getEnd());
10294 }
10295 
10296 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10297 /// well-formednes of the conversion function declarator @p D with
10298 /// type @p R. If there are any errors in the declarator, this routine
10299 /// will emit diagnostics and return true. Otherwise, it will return
10300 /// false. Either way, the type @p R will be updated to reflect a
10301 /// well-formed type for the conversion operator.
10302 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10303                                      StorageClass& SC) {
10304   // C++ [class.conv.fct]p1:
10305   //   Neither parameter types nor return type can be specified. The
10306   //   type of a conversion function (8.3.5) is "function taking no
10307   //   parameter returning conversion-type-id."
10308   if (SC == SC_Static) {
10309     if (!D.isInvalidType())
10310       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10311         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10312         << D.getName().getSourceRange();
10313     D.setInvalidType();
10314     SC = SC_None;
10315   }
10316 
10317   TypeSourceInfo *ConvTSI = nullptr;
10318   QualType ConvType =
10319       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10320 
10321   const DeclSpec &DS = D.getDeclSpec();
10322   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10323     // Conversion functions don't have return types, but the parser will
10324     // happily parse something like:
10325     //
10326     //   class X {
10327     //     float operator bool();
10328     //   };
10329     //
10330     // The return type will be changed later anyway.
10331     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10332       << SourceRange(DS.getTypeSpecTypeLoc())
10333       << SourceRange(D.getIdentifierLoc());
10334     D.setInvalidType();
10335   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10336     // It's also plausible that the user writes type qualifiers in the wrong
10337     // place, such as:
10338     //   struct S { const operator int(); };
10339     // FIXME: we could provide a fixit to move the qualifiers onto the
10340     // conversion type.
10341     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10342         << SourceRange(D.getIdentifierLoc()) << 0;
10343     D.setInvalidType();
10344   }
10345 
10346   const auto *Proto = R->castAs<FunctionProtoType>();
10347 
10348   // Make sure we don't have any parameters.
10349   if (Proto->getNumParams() > 0) {
10350     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10351 
10352     // Delete the parameters.
10353     D.getFunctionTypeInfo().freeParams();
10354     D.setInvalidType();
10355   } else if (Proto->isVariadic()) {
10356     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10357     D.setInvalidType();
10358   }
10359 
10360   // Diagnose "&operator bool()" and other such nonsense.  This
10361   // is actually a gcc extension which we don't support.
10362   if (Proto->getReturnType() != ConvType) {
10363     bool NeedsTypedef = false;
10364     SourceRange Before, After;
10365 
10366     // Walk the chunks and extract information on them for our diagnostic.
10367     bool PastFunctionChunk = false;
10368     for (auto &Chunk : D.type_objects()) {
10369       switch (Chunk.Kind) {
10370       case DeclaratorChunk::Function:
10371         if (!PastFunctionChunk) {
10372           if (Chunk.Fun.HasTrailingReturnType) {
10373             TypeSourceInfo *TRT = nullptr;
10374             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10375             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10376           }
10377           PastFunctionChunk = true;
10378           break;
10379         }
10380         LLVM_FALLTHROUGH;
10381       case DeclaratorChunk::Array:
10382         NeedsTypedef = true;
10383         extendRight(After, Chunk.getSourceRange());
10384         break;
10385 
10386       case DeclaratorChunk::Pointer:
10387       case DeclaratorChunk::BlockPointer:
10388       case DeclaratorChunk::Reference:
10389       case DeclaratorChunk::MemberPointer:
10390       case DeclaratorChunk::Pipe:
10391         extendLeft(Before, Chunk.getSourceRange());
10392         break;
10393 
10394       case DeclaratorChunk::Paren:
10395         extendLeft(Before, Chunk.Loc);
10396         extendRight(After, Chunk.EndLoc);
10397         break;
10398       }
10399     }
10400 
10401     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10402                          After.isValid()  ? After.getBegin() :
10403                                             D.getIdentifierLoc();
10404     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10405     DB << Before << After;
10406 
10407     if (!NeedsTypedef) {
10408       DB << /*don't need a typedef*/0;
10409 
10410       // If we can provide a correct fix-it hint, do so.
10411       if (After.isInvalid() && ConvTSI) {
10412         SourceLocation InsertLoc =
10413             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10414         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10415            << FixItHint::CreateInsertionFromRange(
10416                   InsertLoc, CharSourceRange::getTokenRange(Before))
10417            << FixItHint::CreateRemoval(Before);
10418       }
10419     } else if (!Proto->getReturnType()->isDependentType()) {
10420       DB << /*typedef*/1 << Proto->getReturnType();
10421     } else if (getLangOpts().CPlusPlus11) {
10422       DB << /*alias template*/2 << Proto->getReturnType();
10423     } else {
10424       DB << /*might not be fixable*/3;
10425     }
10426 
10427     // Recover by incorporating the other type chunks into the result type.
10428     // Note, this does *not* change the name of the function. This is compatible
10429     // with the GCC extension:
10430     //   struct S { &operator int(); } s;
10431     //   int &r = s.operator int(); // ok in GCC
10432     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10433     ConvType = Proto->getReturnType();
10434   }
10435 
10436   // C++ [class.conv.fct]p4:
10437   //   The conversion-type-id shall not represent a function type nor
10438   //   an array type.
10439   if (ConvType->isArrayType()) {
10440     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10441     ConvType = Context.getPointerType(ConvType);
10442     D.setInvalidType();
10443   } else if (ConvType->isFunctionType()) {
10444     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10445     ConvType = Context.getPointerType(ConvType);
10446     D.setInvalidType();
10447   }
10448 
10449   // Rebuild the function type "R" without any parameters (in case any
10450   // of the errors above fired) and with the conversion type as the
10451   // return type.
10452   if (D.isInvalidType())
10453     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10454 
10455   // C++0x explicit conversion operators.
10456   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
10457     Diag(DS.getExplicitSpecLoc(),
10458          getLangOpts().CPlusPlus11
10459              ? diag::warn_cxx98_compat_explicit_conversion_functions
10460              : diag::ext_explicit_conversion_functions)
10461         << SourceRange(DS.getExplicitSpecRange());
10462 }
10463 
10464 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10465 /// the declaration of the given C++ conversion function. This routine
10466 /// is responsible for recording the conversion function in the C++
10467 /// class, if possible.
10468 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10469   assert(Conversion && "Expected to receive a conversion function declaration");
10470 
10471   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10472 
10473   // Make sure we aren't redeclaring the conversion function.
10474   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10475 
10476   // C++ [class.conv.fct]p1:
10477   //   [...] A conversion function is never used to convert a
10478   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10479   //   same object type (or a reference to it), to a (possibly
10480   //   cv-qualified) base class of that type (or a reference to it),
10481   //   or to (possibly cv-qualified) void.
10482   // FIXME: Suppress this warning if the conversion function ends up being a
10483   // virtual function that overrides a virtual function in a base class.
10484   QualType ClassType
10485     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10486   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10487     ConvType = ConvTypeRef->getPointeeType();
10488   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10489       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10490     /* Suppress diagnostics for instantiations. */;
10491   else if (ConvType->isRecordType()) {
10492     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10493     if (ConvType == ClassType)
10494       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10495         << ClassType;
10496     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10497       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10498         <<  ClassType << ConvType;
10499   } else if (ConvType->isVoidType()) {
10500     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10501       << ClassType << ConvType;
10502   }
10503 
10504   if (FunctionTemplateDecl *ConversionTemplate
10505                                 = Conversion->getDescribedFunctionTemplate())
10506     return ConversionTemplate;
10507 
10508   return Conversion;
10509 }
10510 
10511 namespace {
10512 /// Utility class to accumulate and print a diagnostic listing the invalid
10513 /// specifier(s) on a declaration.
10514 struct BadSpecifierDiagnoser {
10515   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10516       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10517   ~BadSpecifierDiagnoser() {
10518     Diagnostic << Specifiers;
10519   }
10520 
10521   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10522     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10523   }
10524   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10525     return check(SpecLoc,
10526                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10527   }
10528   void check(SourceLocation SpecLoc, const char *Spec) {
10529     if (SpecLoc.isInvalid()) return;
10530     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10531     if (!Specifiers.empty()) Specifiers += " ";
10532     Specifiers += Spec;
10533   }
10534 
10535   Sema &S;
10536   Sema::SemaDiagnosticBuilder Diagnostic;
10537   std::string Specifiers;
10538 };
10539 }
10540 
10541 /// Check the validity of a declarator that we parsed for a deduction-guide.
10542 /// These aren't actually declarators in the grammar, so we need to check that
10543 /// the user didn't specify any pieces that are not part of the deduction-guide
10544 /// grammar.
10545 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10546                                          StorageClass &SC) {
10547   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10548   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10549   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10550 
10551   // C++ [temp.deduct.guide]p3:
10552   //   A deduction-gide shall be declared in the same scope as the
10553   //   corresponding class template.
10554   if (!CurContext->getRedeclContext()->Equals(
10555           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10556     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10557       << GuidedTemplateDecl;
10558     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10559   }
10560 
10561   auto &DS = D.getMutableDeclSpec();
10562   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10563   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10564       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10565       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10566     BadSpecifierDiagnoser Diagnoser(
10567         *this, D.getIdentifierLoc(),
10568         diag::err_deduction_guide_invalid_specifier);
10569 
10570     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10571     DS.ClearStorageClassSpecs();
10572     SC = SC_None;
10573 
10574     // 'explicit' is permitted.
10575     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10576     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10577     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10578     DS.ClearConstexprSpec();
10579 
10580     Diagnoser.check(DS.getConstSpecLoc(), "const");
10581     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10582     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10583     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10584     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10585     DS.ClearTypeQualifiers();
10586 
10587     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10588     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10589     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10590     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10591     DS.ClearTypeSpecType();
10592   }
10593 
10594   if (D.isInvalidType())
10595     return;
10596 
10597   // Check the declarator is simple enough.
10598   bool FoundFunction = false;
10599   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10600     if (Chunk.Kind == DeclaratorChunk::Paren)
10601       continue;
10602     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10603       Diag(D.getDeclSpec().getBeginLoc(),
10604            diag::err_deduction_guide_with_complex_decl)
10605           << D.getSourceRange();
10606       break;
10607     }
10608     if (!Chunk.Fun.hasTrailingReturnType()) {
10609       Diag(D.getName().getBeginLoc(),
10610            diag::err_deduction_guide_no_trailing_return_type);
10611       break;
10612     }
10613 
10614     // Check that the return type is written as a specialization of
10615     // the template specified as the deduction-guide's name.
10616     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10617     TypeSourceInfo *TSI = nullptr;
10618     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10619     assert(TSI && "deduction guide has valid type but invalid return type?");
10620     bool AcceptableReturnType = false;
10621     bool MightInstantiateToSpecialization = false;
10622     if (auto RetTST =
10623             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10624       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10625       bool TemplateMatches =
10626           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10627       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10628         AcceptableReturnType = true;
10629       else {
10630         // This could still instantiate to the right type, unless we know it
10631         // names the wrong class template.
10632         auto *TD = SpecifiedName.getAsTemplateDecl();
10633         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10634                                              !TemplateMatches);
10635       }
10636     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10637       MightInstantiateToSpecialization = true;
10638     }
10639 
10640     if (!AcceptableReturnType) {
10641       Diag(TSI->getTypeLoc().getBeginLoc(),
10642            diag::err_deduction_guide_bad_trailing_return_type)
10643           << GuidedTemplate << TSI->getType()
10644           << MightInstantiateToSpecialization
10645           << TSI->getTypeLoc().getSourceRange();
10646     }
10647 
10648     // Keep going to check that we don't have any inner declarator pieces (we
10649     // could still have a function returning a pointer to a function).
10650     FoundFunction = true;
10651   }
10652 
10653   if (D.isFunctionDefinition())
10654     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10655 }
10656 
10657 //===----------------------------------------------------------------------===//
10658 // Namespace Handling
10659 //===----------------------------------------------------------------------===//
10660 
10661 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10662 /// reopened.
10663 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10664                                             SourceLocation Loc,
10665                                             IdentifierInfo *II, bool *IsInline,
10666                                             NamespaceDecl *PrevNS) {
10667   assert(*IsInline != PrevNS->isInline());
10668 
10669   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10670   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10671   // inline namespaces, with the intention of bringing names into namespace std.
10672   //
10673   // We support this just well enough to get that case working; this is not
10674   // sufficient to support reopening namespaces as inline in general.
10675   if (*IsInline && II && II->getName().startswith("__atomic") &&
10676       S.getSourceManager().isInSystemHeader(Loc)) {
10677     // Mark all prior declarations of the namespace as inline.
10678     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10679          NS = NS->getPreviousDecl())
10680       NS->setInline(*IsInline);
10681     // Patch up the lookup table for the containing namespace. This isn't really
10682     // correct, but it's good enough for this particular case.
10683     for (auto *I : PrevNS->decls())
10684       if (auto *ND = dyn_cast<NamedDecl>(I))
10685         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10686     return;
10687   }
10688 
10689   if (PrevNS->isInline())
10690     // The user probably just forgot the 'inline', so suggest that it
10691     // be added back.
10692     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10693       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10694   else
10695     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10696 
10697   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10698   *IsInline = PrevNS->isInline();
10699 }
10700 
10701 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10702 /// definition.
10703 Decl *Sema::ActOnStartNamespaceDef(
10704     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10705     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10706     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10707   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10708   // For anonymous namespace, take the location of the left brace.
10709   SourceLocation Loc = II ? IdentLoc : LBrace;
10710   bool IsInline = InlineLoc.isValid();
10711   bool IsInvalid = false;
10712   bool IsStd = false;
10713   bool AddToKnown = false;
10714   Scope *DeclRegionScope = NamespcScope->getParent();
10715 
10716   NamespaceDecl *PrevNS = nullptr;
10717   if (II) {
10718     // C++ [namespace.def]p2:
10719     //   The identifier in an original-namespace-definition shall not
10720     //   have been previously defined in the declarative region in
10721     //   which the original-namespace-definition appears. The
10722     //   identifier in an original-namespace-definition is the name of
10723     //   the namespace. Subsequently in that declarative region, it is
10724     //   treated as an original-namespace-name.
10725     //
10726     // Since namespace names are unique in their scope, and we don't
10727     // look through using directives, just look for any ordinary names
10728     // as if by qualified name lookup.
10729     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10730                    ForExternalRedeclaration);
10731     LookupQualifiedName(R, CurContext->getRedeclContext());
10732     NamedDecl *PrevDecl =
10733         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10734     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10735 
10736     if (PrevNS) {
10737       // This is an extended namespace definition.
10738       if (IsInline != PrevNS->isInline())
10739         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10740                                         &IsInline, PrevNS);
10741     } else if (PrevDecl) {
10742       // This is an invalid name redefinition.
10743       Diag(Loc, diag::err_redefinition_different_kind)
10744         << II;
10745       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10746       IsInvalid = true;
10747       // Continue on to push Namespc as current DeclContext and return it.
10748     } else if (II->isStr("std") &&
10749                CurContext->getRedeclContext()->isTranslationUnit()) {
10750       // This is the first "real" definition of the namespace "std", so update
10751       // our cache of the "std" namespace to point at this definition.
10752       PrevNS = getStdNamespace();
10753       IsStd = true;
10754       AddToKnown = !IsInline;
10755     } else {
10756       // We've seen this namespace for the first time.
10757       AddToKnown = !IsInline;
10758     }
10759   } else {
10760     // Anonymous namespaces.
10761 
10762     // Determine whether the parent already has an anonymous namespace.
10763     DeclContext *Parent = CurContext->getRedeclContext();
10764     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10765       PrevNS = TU->getAnonymousNamespace();
10766     } else {
10767       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10768       PrevNS = ND->getAnonymousNamespace();
10769     }
10770 
10771     if (PrevNS && IsInline != PrevNS->isInline())
10772       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10773                                       &IsInline, PrevNS);
10774   }
10775 
10776   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10777                                                  StartLoc, Loc, II, PrevNS);
10778   if (IsInvalid)
10779     Namespc->setInvalidDecl();
10780 
10781   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10782   AddPragmaAttributes(DeclRegionScope, Namespc);
10783 
10784   // FIXME: Should we be merging attributes?
10785   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10786     PushNamespaceVisibilityAttr(Attr, Loc);
10787 
10788   if (IsStd)
10789     StdNamespace = Namespc;
10790   if (AddToKnown)
10791     KnownNamespaces[Namespc] = false;
10792 
10793   if (II) {
10794     PushOnScopeChains(Namespc, DeclRegionScope);
10795   } else {
10796     // Link the anonymous namespace into its parent.
10797     DeclContext *Parent = CurContext->getRedeclContext();
10798     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10799       TU->setAnonymousNamespace(Namespc);
10800     } else {
10801       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10802     }
10803 
10804     CurContext->addDecl(Namespc);
10805 
10806     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10807     //   behaves as if it were replaced by
10808     //     namespace unique { /* empty body */ }
10809     //     using namespace unique;
10810     //     namespace unique { namespace-body }
10811     //   where all occurrences of 'unique' in a translation unit are
10812     //   replaced by the same identifier and this identifier differs
10813     //   from all other identifiers in the entire program.
10814 
10815     // We just create the namespace with an empty name and then add an
10816     // implicit using declaration, just like the standard suggests.
10817     //
10818     // CodeGen enforces the "universally unique" aspect by giving all
10819     // declarations semantically contained within an anonymous
10820     // namespace internal linkage.
10821 
10822     if (!PrevNS) {
10823       UD = UsingDirectiveDecl::Create(Context, Parent,
10824                                       /* 'using' */ LBrace,
10825                                       /* 'namespace' */ SourceLocation(),
10826                                       /* qualifier */ NestedNameSpecifierLoc(),
10827                                       /* identifier */ SourceLocation(),
10828                                       Namespc,
10829                                       /* Ancestor */ Parent);
10830       UD->setImplicit();
10831       Parent->addDecl(UD);
10832     }
10833   }
10834 
10835   ActOnDocumentableDecl(Namespc);
10836 
10837   // Although we could have an invalid decl (i.e. the namespace name is a
10838   // redefinition), push it as current DeclContext and try to continue parsing.
10839   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10840   // for the namespace has the declarations that showed up in that particular
10841   // namespace definition.
10842   PushDeclContext(NamespcScope, Namespc);
10843   return Namespc;
10844 }
10845 
10846 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10847 /// is a namespace alias, returns the namespace it points to.
10848 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10849   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10850     return AD->getNamespace();
10851   return dyn_cast_or_null<NamespaceDecl>(D);
10852 }
10853 
10854 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10855 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10856 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10857   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10858   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10859   Namespc->setRBraceLoc(RBrace);
10860   PopDeclContext();
10861   if (Namespc->hasAttr<VisibilityAttr>())
10862     PopPragmaVisibility(true, RBrace);
10863   // If this namespace contains an export-declaration, export it now.
10864   if (DeferredExportedNamespaces.erase(Namespc))
10865     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10866 }
10867 
10868 CXXRecordDecl *Sema::getStdBadAlloc() const {
10869   return cast_or_null<CXXRecordDecl>(
10870                                   StdBadAlloc.get(Context.getExternalSource()));
10871 }
10872 
10873 EnumDecl *Sema::getStdAlignValT() const {
10874   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10875 }
10876 
10877 NamespaceDecl *Sema::getStdNamespace() const {
10878   return cast_or_null<NamespaceDecl>(
10879                                  StdNamespace.get(Context.getExternalSource()));
10880 }
10881 
10882 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10883   if (!StdExperimentalNamespaceCache) {
10884     if (auto Std = getStdNamespace()) {
10885       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10886                           SourceLocation(), LookupNamespaceName);
10887       if (!LookupQualifiedName(Result, Std) ||
10888           !(StdExperimentalNamespaceCache =
10889                 Result.getAsSingle<NamespaceDecl>()))
10890         Result.suppressDiagnostics();
10891     }
10892   }
10893   return StdExperimentalNamespaceCache;
10894 }
10895 
10896 namespace {
10897 
10898 enum UnsupportedSTLSelect {
10899   USS_InvalidMember,
10900   USS_MissingMember,
10901   USS_NonTrivial,
10902   USS_Other
10903 };
10904 
10905 struct InvalidSTLDiagnoser {
10906   Sema &S;
10907   SourceLocation Loc;
10908   QualType TyForDiags;
10909 
10910   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
10911                       const VarDecl *VD = nullptr) {
10912     {
10913       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
10914                << TyForDiags << ((int)Sel);
10915       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
10916         assert(!Name.empty());
10917         D << Name;
10918       }
10919     }
10920     if (Sel == USS_InvalidMember) {
10921       S.Diag(VD->getLocation(), diag::note_var_declared_here)
10922           << VD << VD->getSourceRange();
10923     }
10924     return QualType();
10925   }
10926 };
10927 } // namespace
10928 
10929 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
10930                                            SourceLocation Loc,
10931                                            ComparisonCategoryUsage Usage) {
10932   assert(getLangOpts().CPlusPlus &&
10933          "Looking for comparison category type outside of C++.");
10934 
10935   // Use an elaborated type for diagnostics which has a name containing the
10936   // prepended 'std' namespace but not any inline namespace names.
10937   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
10938     auto *NNS =
10939         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
10940     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
10941   };
10942 
10943   // Check if we've already successfully checked the comparison category type
10944   // before. If so, skip checking it again.
10945   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
10946   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
10947     // The only thing we need to check is that the type has a reachable
10948     // definition in the current context.
10949     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
10950       return QualType();
10951 
10952     return Info->getType();
10953   }
10954 
10955   // If lookup failed
10956   if (!Info) {
10957     std::string NameForDiags = "std::";
10958     NameForDiags += ComparisonCategories::getCategoryString(Kind);
10959     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
10960         << NameForDiags << (int)Usage;
10961     return QualType();
10962   }
10963 
10964   assert(Info->Kind == Kind);
10965   assert(Info->Record);
10966 
10967   // Update the Record decl in case we encountered a forward declaration on our
10968   // first pass. FIXME: This is a bit of a hack.
10969   if (Info->Record->hasDefinition())
10970     Info->Record = Info->Record->getDefinition();
10971 
10972   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
10973     return QualType();
10974 
10975   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
10976 
10977   if (!Info->Record->isTriviallyCopyable())
10978     return UnsupportedSTLError(USS_NonTrivial);
10979 
10980   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
10981     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
10982     // Tolerate empty base classes.
10983     if (Base->isEmpty())
10984       continue;
10985     // Reject STL implementations which have at least one non-empty base.
10986     return UnsupportedSTLError();
10987   }
10988 
10989   // Check that the STL has implemented the types using a single integer field.
10990   // This expectation allows better codegen for builtin operators. We require:
10991   //   (1) The class has exactly one field.
10992   //   (2) The field is an integral or enumeration type.
10993   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
10994   if (std::distance(FIt, FEnd) != 1 ||
10995       !FIt->getType()->isIntegralOrEnumerationType()) {
10996     return UnsupportedSTLError();
10997   }
10998 
10999   // Build each of the require values and store them in Info.
11000   for (ComparisonCategoryResult CCR :
11001        ComparisonCategories::getPossibleResultsForType(Kind)) {
11002     StringRef MemName = ComparisonCategories::getResultString(CCR);
11003     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11004 
11005     if (!ValInfo)
11006       return UnsupportedSTLError(USS_MissingMember, MemName);
11007 
11008     VarDecl *VD = ValInfo->VD;
11009     assert(VD && "should not be null!");
11010 
11011     // Attempt to diagnose reasons why the STL definition of this type
11012     // might be foobar, including it failing to be a constant expression.
11013     // TODO Handle more ways the lookup or result can be invalid.
11014     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11015         !VD->checkInitIsICE())
11016       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11017 
11018     // Attempt to evaluate the var decl as a constant expression and extract
11019     // the value of its first field as a ICE. If this fails, the STL
11020     // implementation is not supported.
11021     if (!ValInfo->hasValidIntValue())
11022       return UnsupportedSTLError();
11023 
11024     MarkVariableReferenced(Loc, VD);
11025   }
11026 
11027   // We've successfully built the required types and expressions. Update
11028   // the cache and return the newly cached value.
11029   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11030   return Info->getType();
11031 }
11032 
11033 /// Retrieve the special "std" namespace, which may require us to
11034 /// implicitly define the namespace.
11035 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11036   if (!StdNamespace) {
11037     // The "std" namespace has not yet been defined, so build one implicitly.
11038     StdNamespace = NamespaceDecl::Create(Context,
11039                                          Context.getTranslationUnitDecl(),
11040                                          /*Inline=*/false,
11041                                          SourceLocation(), SourceLocation(),
11042                                          &PP.getIdentifierTable().get("std"),
11043                                          /*PrevDecl=*/nullptr);
11044     getStdNamespace()->setImplicit(true);
11045   }
11046 
11047   return getStdNamespace();
11048 }
11049 
11050 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11051   assert(getLangOpts().CPlusPlus &&
11052          "Looking for std::initializer_list outside of C++.");
11053 
11054   // We're looking for implicit instantiations of
11055   // template <typename E> class std::initializer_list.
11056 
11057   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11058     return false;
11059 
11060   ClassTemplateDecl *Template = nullptr;
11061   const TemplateArgument *Arguments = nullptr;
11062 
11063   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11064 
11065     ClassTemplateSpecializationDecl *Specialization =
11066         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11067     if (!Specialization)
11068       return false;
11069 
11070     Template = Specialization->getSpecializedTemplate();
11071     Arguments = Specialization->getTemplateArgs().data();
11072   } else if (const TemplateSpecializationType *TST =
11073                  Ty->getAs<TemplateSpecializationType>()) {
11074     Template = dyn_cast_or_null<ClassTemplateDecl>(
11075         TST->getTemplateName().getAsTemplateDecl());
11076     Arguments = TST->getArgs();
11077   }
11078   if (!Template)
11079     return false;
11080 
11081   if (!StdInitializerList) {
11082     // Haven't recognized std::initializer_list yet, maybe this is it.
11083     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11084     if (TemplateClass->getIdentifier() !=
11085             &PP.getIdentifierTable().get("initializer_list") ||
11086         !getStdNamespace()->InEnclosingNamespaceSetOf(
11087             TemplateClass->getDeclContext()))
11088       return false;
11089     // This is a template called std::initializer_list, but is it the right
11090     // template?
11091     TemplateParameterList *Params = Template->getTemplateParameters();
11092     if (Params->getMinRequiredArguments() != 1)
11093       return false;
11094     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11095       return false;
11096 
11097     // It's the right template.
11098     StdInitializerList = Template;
11099   }
11100 
11101   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11102     return false;
11103 
11104   // This is an instance of std::initializer_list. Find the argument type.
11105   if (Element)
11106     *Element = Arguments[0].getAsType();
11107   return true;
11108 }
11109 
11110 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11111   NamespaceDecl *Std = S.getStdNamespace();
11112   if (!Std) {
11113     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11114     return nullptr;
11115   }
11116 
11117   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11118                       Loc, Sema::LookupOrdinaryName);
11119   if (!S.LookupQualifiedName(Result, Std)) {
11120     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11121     return nullptr;
11122   }
11123   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11124   if (!Template) {
11125     Result.suppressDiagnostics();
11126     // We found something weird. Complain about the first thing we found.
11127     NamedDecl *Found = *Result.begin();
11128     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11129     return nullptr;
11130   }
11131 
11132   // We found some template called std::initializer_list. Now verify that it's
11133   // correct.
11134   TemplateParameterList *Params = Template->getTemplateParameters();
11135   if (Params->getMinRequiredArguments() != 1 ||
11136       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11137     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11138     return nullptr;
11139   }
11140 
11141   return Template;
11142 }
11143 
11144 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11145   if (!StdInitializerList) {
11146     StdInitializerList = LookupStdInitializerList(*this, Loc);
11147     if (!StdInitializerList)
11148       return QualType();
11149   }
11150 
11151   TemplateArgumentListInfo Args(Loc, Loc);
11152   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11153                                        Context.getTrivialTypeSourceInfo(Element,
11154                                                                         Loc)));
11155   return Context.getCanonicalType(
11156       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11157 }
11158 
11159 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11160   // C++ [dcl.init.list]p2:
11161   //   A constructor is an initializer-list constructor if its first parameter
11162   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11163   //   std::initializer_list<E> for some type E, and either there are no other
11164   //   parameters or else all other parameters have default arguments.
11165   if (Ctor->getNumParams() < 1 ||
11166       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
11167     return false;
11168 
11169   QualType ArgType = Ctor->getParamDecl(0)->getType();
11170   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11171     ArgType = RT->getPointeeType().getUnqualifiedType();
11172 
11173   return isStdInitializerList(ArgType, nullptr);
11174 }
11175 
11176 /// Determine whether a using statement is in a context where it will be
11177 /// apply in all contexts.
11178 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11179   switch (CurContext->getDeclKind()) {
11180     case Decl::TranslationUnit:
11181       return true;
11182     case Decl::LinkageSpec:
11183       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11184     default:
11185       return false;
11186   }
11187 }
11188 
11189 namespace {
11190 
11191 // Callback to only accept typo corrections that are namespaces.
11192 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11193 public:
11194   bool ValidateCandidate(const TypoCorrection &candidate) override {
11195     if (NamedDecl *ND = candidate.getCorrectionDecl())
11196       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11197     return false;
11198   }
11199 
11200   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11201     return std::make_unique<NamespaceValidatorCCC>(*this);
11202   }
11203 };
11204 
11205 }
11206 
11207 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11208                                        CXXScopeSpec &SS,
11209                                        SourceLocation IdentLoc,
11210                                        IdentifierInfo *Ident) {
11211   R.clear();
11212   NamespaceValidatorCCC CCC{};
11213   if (TypoCorrection Corrected =
11214           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11215                         Sema::CTK_ErrorRecovery)) {
11216     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11217       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11218       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11219                               Ident->getName().equals(CorrectedStr);
11220       S.diagnoseTypo(Corrected,
11221                      S.PDiag(diag::err_using_directive_member_suggest)
11222                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11223                      S.PDiag(diag::note_namespace_defined_here));
11224     } else {
11225       S.diagnoseTypo(Corrected,
11226                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11227                      S.PDiag(diag::note_namespace_defined_here));
11228     }
11229     R.addDecl(Corrected.getFoundDecl());
11230     return true;
11231   }
11232   return false;
11233 }
11234 
11235 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11236                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11237                                 SourceLocation IdentLoc,
11238                                 IdentifierInfo *NamespcName,
11239                                 const ParsedAttributesView &AttrList) {
11240   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11241   assert(NamespcName && "Invalid NamespcName.");
11242   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11243 
11244   // This can only happen along a recovery path.
11245   while (S->isTemplateParamScope())
11246     S = S->getParent();
11247   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11248 
11249   UsingDirectiveDecl *UDir = nullptr;
11250   NestedNameSpecifier *Qualifier = nullptr;
11251   if (SS.isSet())
11252     Qualifier = SS.getScopeRep();
11253 
11254   // Lookup namespace name.
11255   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11256   LookupParsedName(R, S, &SS);
11257   if (R.isAmbiguous())
11258     return nullptr;
11259 
11260   if (R.empty()) {
11261     R.clear();
11262     // Allow "using namespace std;" or "using namespace ::std;" even if
11263     // "std" hasn't been defined yet, for GCC compatibility.
11264     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11265         NamespcName->isStr("std")) {
11266       Diag(IdentLoc, diag::ext_using_undefined_std);
11267       R.addDecl(getOrCreateStdNamespace());
11268       R.resolveKind();
11269     }
11270     // Otherwise, attempt typo correction.
11271     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11272   }
11273 
11274   if (!R.empty()) {
11275     NamedDecl *Named = R.getRepresentativeDecl();
11276     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11277     assert(NS && "expected namespace decl");
11278 
11279     // The use of a nested name specifier may trigger deprecation warnings.
11280     DiagnoseUseOfDecl(Named, IdentLoc);
11281 
11282     // C++ [namespace.udir]p1:
11283     //   A using-directive specifies that the names in the nominated
11284     //   namespace can be used in the scope in which the
11285     //   using-directive appears after the using-directive. During
11286     //   unqualified name lookup (3.4.1), the names appear as if they
11287     //   were declared in the nearest enclosing namespace which
11288     //   contains both the using-directive and the nominated
11289     //   namespace. [Note: in this context, "contains" means "contains
11290     //   directly or indirectly". ]
11291 
11292     // Find enclosing context containing both using-directive and
11293     // nominated namespace.
11294     DeclContext *CommonAncestor = NS;
11295     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11296       CommonAncestor = CommonAncestor->getParent();
11297 
11298     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11299                                       SS.getWithLocInContext(Context),
11300                                       IdentLoc, Named, CommonAncestor);
11301 
11302     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11303         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11304       Diag(IdentLoc, diag::warn_using_directive_in_header);
11305     }
11306 
11307     PushUsingDirective(S, UDir);
11308   } else {
11309     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11310   }
11311 
11312   if (UDir)
11313     ProcessDeclAttributeList(S, UDir, AttrList);
11314 
11315   return UDir;
11316 }
11317 
11318 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11319   // If the scope has an associated entity and the using directive is at
11320   // namespace or translation unit scope, add the UsingDirectiveDecl into
11321   // its lookup structure so qualified name lookup can find it.
11322   DeclContext *Ctx = S->getEntity();
11323   if (Ctx && !Ctx->isFunctionOrMethod())
11324     Ctx->addDecl(UDir);
11325   else
11326     // Otherwise, it is at block scope. The using-directives will affect lookup
11327     // only to the end of the scope.
11328     S->PushUsingDirective(UDir);
11329 }
11330 
11331 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11332                                   SourceLocation UsingLoc,
11333                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11334                                   UnqualifiedId &Name,
11335                                   SourceLocation EllipsisLoc,
11336                                   const ParsedAttributesView &AttrList) {
11337   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11338 
11339   if (SS.isEmpty()) {
11340     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11341     return nullptr;
11342   }
11343 
11344   switch (Name.getKind()) {
11345   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11346   case UnqualifiedIdKind::IK_Identifier:
11347   case UnqualifiedIdKind::IK_OperatorFunctionId:
11348   case UnqualifiedIdKind::IK_LiteralOperatorId:
11349   case UnqualifiedIdKind::IK_ConversionFunctionId:
11350     break;
11351 
11352   case UnqualifiedIdKind::IK_ConstructorName:
11353   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11354     // C++11 inheriting constructors.
11355     Diag(Name.getBeginLoc(),
11356          getLangOpts().CPlusPlus11
11357              ? diag::warn_cxx98_compat_using_decl_constructor
11358              : diag::err_using_decl_constructor)
11359         << SS.getRange();
11360 
11361     if (getLangOpts().CPlusPlus11) break;
11362 
11363     return nullptr;
11364 
11365   case UnqualifiedIdKind::IK_DestructorName:
11366     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11367     return nullptr;
11368 
11369   case UnqualifiedIdKind::IK_TemplateId:
11370     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11371         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11372     return nullptr;
11373 
11374   case UnqualifiedIdKind::IK_DeductionGuideName:
11375     llvm_unreachable("cannot parse qualified deduction guide name");
11376   }
11377 
11378   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11379   DeclarationName TargetName = TargetNameInfo.getName();
11380   if (!TargetName)
11381     return nullptr;
11382 
11383   // Warn about access declarations.
11384   if (UsingLoc.isInvalid()) {
11385     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11386                                  ? diag::err_access_decl
11387                                  : diag::warn_access_decl_deprecated)
11388         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11389   }
11390 
11391   if (EllipsisLoc.isInvalid()) {
11392     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11393         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11394       return nullptr;
11395   } else {
11396     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11397         !TargetNameInfo.containsUnexpandedParameterPack()) {
11398       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11399         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11400       EllipsisLoc = SourceLocation();
11401     }
11402   }
11403 
11404   NamedDecl *UD =
11405       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11406                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11407                             /*IsInstantiation*/false);
11408   if (UD)
11409     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11410 
11411   return UD;
11412 }
11413 
11414 /// Determine whether a using declaration considers the given
11415 /// declarations as "equivalent", e.g., if they are redeclarations of
11416 /// the same entity or are both typedefs of the same type.
11417 static bool
11418 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11419   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11420     return true;
11421 
11422   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11423     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11424       return Context.hasSameType(TD1->getUnderlyingType(),
11425                                  TD2->getUnderlyingType());
11426 
11427   return false;
11428 }
11429 
11430 
11431 /// Determines whether to create a using shadow decl for a particular
11432 /// decl, given the set of decls existing prior to this using lookup.
11433 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11434                                 const LookupResult &Previous,
11435                                 UsingShadowDecl *&PrevShadow) {
11436   // Diagnose finding a decl which is not from a base class of the
11437   // current class.  We do this now because there are cases where this
11438   // function will silently decide not to build a shadow decl, which
11439   // will pre-empt further diagnostics.
11440   //
11441   // We don't need to do this in C++11 because we do the check once on
11442   // the qualifier.
11443   //
11444   // FIXME: diagnose the following if we care enough:
11445   //   struct A { int foo; };
11446   //   struct B : A { using A::foo; };
11447   //   template <class T> struct C : A {};
11448   //   template <class T> struct D : C<T> { using B::foo; } // <---
11449   // This is invalid (during instantiation) in C++03 because B::foo
11450   // resolves to the using decl in B, which is not a base class of D<T>.
11451   // We can't diagnose it immediately because C<T> is an unknown
11452   // specialization.  The UsingShadowDecl in D<T> then points directly
11453   // to A::foo, which will look well-formed when we instantiate.
11454   // The right solution is to not collapse the shadow-decl chain.
11455   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11456     DeclContext *OrigDC = Orig->getDeclContext();
11457 
11458     // Handle enums and anonymous structs.
11459     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11460     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11461     while (OrigRec->isAnonymousStructOrUnion())
11462       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11463 
11464     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11465       if (OrigDC == CurContext) {
11466         Diag(Using->getLocation(),
11467              diag::err_using_decl_nested_name_specifier_is_current_class)
11468           << Using->getQualifierLoc().getSourceRange();
11469         Diag(Orig->getLocation(), diag::note_using_decl_target);
11470         Using->setInvalidDecl();
11471         return true;
11472       }
11473 
11474       Diag(Using->getQualifierLoc().getBeginLoc(),
11475            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11476         << Using->getQualifier()
11477         << cast<CXXRecordDecl>(CurContext)
11478         << Using->getQualifierLoc().getSourceRange();
11479       Diag(Orig->getLocation(), diag::note_using_decl_target);
11480       Using->setInvalidDecl();
11481       return true;
11482     }
11483   }
11484 
11485   if (Previous.empty()) return false;
11486 
11487   NamedDecl *Target = Orig;
11488   if (isa<UsingShadowDecl>(Target))
11489     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11490 
11491   // If the target happens to be one of the previous declarations, we
11492   // don't have a conflict.
11493   //
11494   // FIXME: but we might be increasing its access, in which case we
11495   // should redeclare it.
11496   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11497   bool FoundEquivalentDecl = false;
11498   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11499          I != E; ++I) {
11500     NamedDecl *D = (*I)->getUnderlyingDecl();
11501     // We can have UsingDecls in our Previous results because we use the same
11502     // LookupResult for checking whether the UsingDecl itself is a valid
11503     // redeclaration.
11504     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11505       continue;
11506 
11507     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11508       // C++ [class.mem]p19:
11509       //   If T is the name of a class, then [every named member other than
11510       //   a non-static data member] shall have a name different from T
11511       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11512           !isa<IndirectFieldDecl>(Target) &&
11513           !isa<UnresolvedUsingValueDecl>(Target) &&
11514           DiagnoseClassNameShadow(
11515               CurContext,
11516               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11517         return true;
11518     }
11519 
11520     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11521       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11522         PrevShadow = Shadow;
11523       FoundEquivalentDecl = true;
11524     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11525       // We don't conflict with an existing using shadow decl of an equivalent
11526       // declaration, but we're not a redeclaration of it.
11527       FoundEquivalentDecl = true;
11528     }
11529 
11530     if (isVisible(D))
11531       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11532   }
11533 
11534   if (FoundEquivalentDecl)
11535     return false;
11536 
11537   if (FunctionDecl *FD = Target->getAsFunction()) {
11538     NamedDecl *OldDecl = nullptr;
11539     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11540                           /*IsForUsingDecl*/ true)) {
11541     case Ovl_Overload:
11542       return false;
11543 
11544     case Ovl_NonFunction:
11545       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11546       break;
11547 
11548     // We found a decl with the exact signature.
11549     case Ovl_Match:
11550       // If we're in a record, we want to hide the target, so we
11551       // return true (without a diagnostic) to tell the caller not to
11552       // build a shadow decl.
11553       if (CurContext->isRecord())
11554         return true;
11555 
11556       // If we're not in a record, this is an error.
11557       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11558       break;
11559     }
11560 
11561     Diag(Target->getLocation(), diag::note_using_decl_target);
11562     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11563     Using->setInvalidDecl();
11564     return true;
11565   }
11566 
11567   // Target is not a function.
11568 
11569   if (isa<TagDecl>(Target)) {
11570     // No conflict between a tag and a non-tag.
11571     if (!Tag) return false;
11572 
11573     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11574     Diag(Target->getLocation(), diag::note_using_decl_target);
11575     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11576     Using->setInvalidDecl();
11577     return true;
11578   }
11579 
11580   // No conflict between a tag and a non-tag.
11581   if (!NonTag) return false;
11582 
11583   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11584   Diag(Target->getLocation(), diag::note_using_decl_target);
11585   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11586   Using->setInvalidDecl();
11587   return true;
11588 }
11589 
11590 /// Determine whether a direct base class is a virtual base class.
11591 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11592   if (!Derived->getNumVBases())
11593     return false;
11594   for (auto &B : Derived->bases())
11595     if (B.getType()->getAsCXXRecordDecl() == Base)
11596       return B.isVirtual();
11597   llvm_unreachable("not a direct base class");
11598 }
11599 
11600 /// Builds a shadow declaration corresponding to a 'using' declaration.
11601 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11602                                             UsingDecl *UD,
11603                                             NamedDecl *Orig,
11604                                             UsingShadowDecl *PrevDecl) {
11605   // If we resolved to another shadow declaration, just coalesce them.
11606   NamedDecl *Target = Orig;
11607   if (isa<UsingShadowDecl>(Target)) {
11608     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11609     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11610   }
11611 
11612   NamedDecl *NonTemplateTarget = Target;
11613   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11614     NonTemplateTarget = TargetTD->getTemplatedDecl();
11615 
11616   UsingShadowDecl *Shadow;
11617   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11618     bool IsVirtualBase =
11619         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11620                             UD->getQualifier()->getAsRecordDecl());
11621     Shadow = ConstructorUsingShadowDecl::Create(
11622         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11623   } else {
11624     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11625                                      Target);
11626   }
11627   UD->addShadowDecl(Shadow);
11628 
11629   Shadow->setAccess(UD->getAccess());
11630   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11631     Shadow->setInvalidDecl();
11632 
11633   Shadow->setPreviousDecl(PrevDecl);
11634 
11635   if (S)
11636     PushOnScopeChains(Shadow, S);
11637   else
11638     CurContext->addDecl(Shadow);
11639 
11640 
11641   return Shadow;
11642 }
11643 
11644 /// Hides a using shadow declaration.  This is required by the current
11645 /// using-decl implementation when a resolvable using declaration in a
11646 /// class is followed by a declaration which would hide or override
11647 /// one or more of the using decl's targets; for example:
11648 ///
11649 ///   struct Base { void foo(int); };
11650 ///   struct Derived : Base {
11651 ///     using Base::foo;
11652 ///     void foo(int);
11653 ///   };
11654 ///
11655 /// The governing language is C++03 [namespace.udecl]p12:
11656 ///
11657 ///   When a using-declaration brings names from a base class into a
11658 ///   derived class scope, member functions in the derived class
11659 ///   override and/or hide member functions with the same name and
11660 ///   parameter types in a base class (rather than conflicting).
11661 ///
11662 /// There are two ways to implement this:
11663 ///   (1) optimistically create shadow decls when they're not hidden
11664 ///       by existing declarations, or
11665 ///   (2) don't create any shadow decls (or at least don't make them
11666 ///       visible) until we've fully parsed/instantiated the class.
11667 /// The problem with (1) is that we might have to retroactively remove
11668 /// a shadow decl, which requires several O(n) operations because the
11669 /// decl structures are (very reasonably) not designed for removal.
11670 /// (2) avoids this but is very fiddly and phase-dependent.
11671 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11672   if (Shadow->getDeclName().getNameKind() ==
11673         DeclarationName::CXXConversionFunctionName)
11674     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11675 
11676   // Remove it from the DeclContext...
11677   Shadow->getDeclContext()->removeDecl(Shadow);
11678 
11679   // ...and the scope, if applicable...
11680   if (S) {
11681     S->RemoveDecl(Shadow);
11682     IdResolver.RemoveDecl(Shadow);
11683   }
11684 
11685   // ...and the using decl.
11686   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11687 
11688   // TODO: complain somehow if Shadow was used.  It shouldn't
11689   // be possible for this to happen, because...?
11690 }
11691 
11692 /// Find the base specifier for a base class with the given type.
11693 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11694                                                 QualType DesiredBase,
11695                                                 bool &AnyDependentBases) {
11696   // Check whether the named type is a direct base class.
11697   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11698     .getUnqualifiedType();
11699   for (auto &Base : Derived->bases()) {
11700     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11701     if (CanonicalDesiredBase == BaseType)
11702       return &Base;
11703     if (BaseType->isDependentType())
11704       AnyDependentBases = true;
11705   }
11706   return nullptr;
11707 }
11708 
11709 namespace {
11710 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11711 public:
11712   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11713                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11714       : HasTypenameKeyword(HasTypenameKeyword),
11715         IsInstantiation(IsInstantiation), OldNNS(NNS),
11716         RequireMemberOf(RequireMemberOf) {}
11717 
11718   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11719     NamedDecl *ND = Candidate.getCorrectionDecl();
11720 
11721     // Keywords are not valid here.
11722     if (!ND || isa<NamespaceDecl>(ND))
11723       return false;
11724 
11725     // Completely unqualified names are invalid for a 'using' declaration.
11726     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11727       return false;
11728 
11729     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11730     // reject.
11731 
11732     if (RequireMemberOf) {
11733       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11734       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11735         // No-one ever wants a using-declaration to name an injected-class-name
11736         // of a base class, unless they're declaring an inheriting constructor.
11737         ASTContext &Ctx = ND->getASTContext();
11738         if (!Ctx.getLangOpts().CPlusPlus11)
11739           return false;
11740         QualType FoundType = Ctx.getRecordType(FoundRecord);
11741 
11742         // Check that the injected-class-name is named as a member of its own
11743         // type; we don't want to suggest 'using Derived::Base;', since that
11744         // means something else.
11745         NestedNameSpecifier *Specifier =
11746             Candidate.WillReplaceSpecifier()
11747                 ? Candidate.getCorrectionSpecifier()
11748                 : OldNNS;
11749         if (!Specifier->getAsType() ||
11750             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11751           return false;
11752 
11753         // Check that this inheriting constructor declaration actually names a
11754         // direct base class of the current class.
11755         bool AnyDependentBases = false;
11756         if (!findDirectBaseWithType(RequireMemberOf,
11757                                     Ctx.getRecordType(FoundRecord),
11758                                     AnyDependentBases) &&
11759             !AnyDependentBases)
11760           return false;
11761       } else {
11762         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11763         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11764           return false;
11765 
11766         // FIXME: Check that the base class member is accessible?
11767       }
11768     } else {
11769       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11770       if (FoundRecord && FoundRecord->isInjectedClassName())
11771         return false;
11772     }
11773 
11774     if (isa<TypeDecl>(ND))
11775       return HasTypenameKeyword || !IsInstantiation;
11776 
11777     return !HasTypenameKeyword;
11778   }
11779 
11780   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11781     return std::make_unique<UsingValidatorCCC>(*this);
11782   }
11783 
11784 private:
11785   bool HasTypenameKeyword;
11786   bool IsInstantiation;
11787   NestedNameSpecifier *OldNNS;
11788   CXXRecordDecl *RequireMemberOf;
11789 };
11790 } // end anonymous namespace
11791 
11792 /// Builds a using declaration.
11793 ///
11794 /// \param IsInstantiation - Whether this call arises from an
11795 ///   instantiation of an unresolved using declaration.  We treat
11796 ///   the lookup differently for these declarations.
11797 NamedDecl *Sema::BuildUsingDeclaration(
11798     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11799     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11800     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11801     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11802   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11803   SourceLocation IdentLoc = NameInfo.getLoc();
11804   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11805 
11806   // FIXME: We ignore attributes for now.
11807 
11808   // For an inheriting constructor declaration, the name of the using
11809   // declaration is the name of a constructor in this class, not in the
11810   // base class.
11811   DeclarationNameInfo UsingName = NameInfo;
11812   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11813     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11814       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11815           Context.getCanonicalType(Context.getRecordType(RD))));
11816 
11817   // Do the redeclaration lookup in the current scope.
11818   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11819                         ForVisibleRedeclaration);
11820   Previous.setHideTags(false);
11821   if (S) {
11822     LookupName(Previous, S);
11823 
11824     // It is really dumb that we have to do this.
11825     LookupResult::Filter F = Previous.makeFilter();
11826     while (F.hasNext()) {
11827       NamedDecl *D = F.next();
11828       if (!isDeclInScope(D, CurContext, S))
11829         F.erase();
11830       // If we found a local extern declaration that's not ordinarily visible,
11831       // and this declaration is being added to a non-block scope, ignore it.
11832       // We're only checking for scope conflicts here, not also for violations
11833       // of the linkage rules.
11834       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11835                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11836         F.erase();
11837     }
11838     F.done();
11839   } else {
11840     assert(IsInstantiation && "no scope in non-instantiation");
11841     if (CurContext->isRecord())
11842       LookupQualifiedName(Previous, CurContext);
11843     else {
11844       // No redeclaration check is needed here; in non-member contexts we
11845       // diagnosed all possible conflicts with other using-declarations when
11846       // building the template:
11847       //
11848       // For a dependent non-type using declaration, the only valid case is
11849       // if we instantiate to a single enumerator. We check for conflicts
11850       // between shadow declarations we introduce, and we check in the template
11851       // definition for conflicts between a non-type using declaration and any
11852       // other declaration, which together covers all cases.
11853       //
11854       // A dependent typename using declaration will never successfully
11855       // instantiate, since it will always name a class member, so we reject
11856       // that in the template definition.
11857     }
11858   }
11859 
11860   // Check for invalid redeclarations.
11861   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11862                                   SS, IdentLoc, Previous))
11863     return nullptr;
11864 
11865   // Check for bad qualifiers.
11866   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11867                               IdentLoc))
11868     return nullptr;
11869 
11870   DeclContext *LookupContext = computeDeclContext(SS);
11871   NamedDecl *D;
11872   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11873   if (!LookupContext || EllipsisLoc.isValid()) {
11874     if (HasTypenameKeyword) {
11875       // FIXME: not all declaration name kinds are legal here
11876       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11877                                               UsingLoc, TypenameLoc,
11878                                               QualifierLoc,
11879                                               IdentLoc, NameInfo.getName(),
11880                                               EllipsisLoc);
11881     } else {
11882       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11883                                            QualifierLoc, NameInfo, EllipsisLoc);
11884     }
11885     D->setAccess(AS);
11886     CurContext->addDecl(D);
11887     return D;
11888   }
11889 
11890   auto Build = [&](bool Invalid) {
11891     UsingDecl *UD =
11892         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11893                           UsingName, HasTypenameKeyword);
11894     UD->setAccess(AS);
11895     CurContext->addDecl(UD);
11896     UD->setInvalidDecl(Invalid);
11897     return UD;
11898   };
11899   auto BuildInvalid = [&]{ return Build(true); };
11900   auto BuildValid = [&]{ return Build(false); };
11901 
11902   if (RequireCompleteDeclContext(SS, LookupContext))
11903     return BuildInvalid();
11904 
11905   // Look up the target name.
11906   LookupResult R(*this, NameInfo, LookupOrdinaryName);
11907 
11908   // Unlike most lookups, we don't always want to hide tag
11909   // declarations: tag names are visible through the using declaration
11910   // even if hidden by ordinary names, *except* in a dependent context
11911   // where it's important for the sanity of two-phase lookup.
11912   if (!IsInstantiation)
11913     R.setHideTags(false);
11914 
11915   // For the purposes of this lookup, we have a base object type
11916   // equal to that of the current context.
11917   if (CurContext->isRecord()) {
11918     R.setBaseObjectType(
11919                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
11920   }
11921 
11922   LookupQualifiedName(R, LookupContext);
11923 
11924   // Try to correct typos if possible. If constructor name lookup finds no
11925   // results, that means the named class has no explicit constructors, and we
11926   // suppressed declaring implicit ones (probably because it's dependent or
11927   // invalid).
11928   if (R.empty() &&
11929       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
11930     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
11931     // it will believe that glibc provides a ::gets in cases where it does not,
11932     // and will try to pull it into namespace std with a using-declaration.
11933     // Just ignore the using-declaration in that case.
11934     auto *II = NameInfo.getName().getAsIdentifierInfo();
11935     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
11936         CurContext->isStdNamespace() &&
11937         isa<TranslationUnitDecl>(LookupContext) &&
11938         getSourceManager().isInSystemHeader(UsingLoc))
11939       return nullptr;
11940     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
11941                           dyn_cast<CXXRecordDecl>(CurContext));
11942     if (TypoCorrection Corrected =
11943             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
11944                         CTK_ErrorRecovery)) {
11945       // We reject candidates where DroppedSpecifier == true, hence the
11946       // literal '0' below.
11947       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
11948                                 << NameInfo.getName() << LookupContext << 0
11949                                 << SS.getRange());
11950 
11951       // If we picked a correction with no attached Decl we can't do anything
11952       // useful with it, bail out.
11953       NamedDecl *ND = Corrected.getCorrectionDecl();
11954       if (!ND)
11955         return BuildInvalid();
11956 
11957       // If we corrected to an inheriting constructor, handle it as one.
11958       auto *RD = dyn_cast<CXXRecordDecl>(ND);
11959       if (RD && RD->isInjectedClassName()) {
11960         // The parent of the injected class name is the class itself.
11961         RD = cast<CXXRecordDecl>(RD->getParent());
11962 
11963         // Fix up the information we'll use to build the using declaration.
11964         if (Corrected.WillReplaceSpecifier()) {
11965           NestedNameSpecifierLocBuilder Builder;
11966           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
11967                               QualifierLoc.getSourceRange());
11968           QualifierLoc = Builder.getWithLocInContext(Context);
11969         }
11970 
11971         // In this case, the name we introduce is the name of a derived class
11972         // constructor.
11973         auto *CurClass = cast<CXXRecordDecl>(CurContext);
11974         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11975             Context.getCanonicalType(Context.getRecordType(CurClass))));
11976         UsingName.setNamedTypeInfo(nullptr);
11977         for (auto *Ctor : LookupConstructors(RD))
11978           R.addDecl(Ctor);
11979         R.resolveKind();
11980       } else {
11981         // FIXME: Pick up all the declarations if we found an overloaded
11982         // function.
11983         UsingName.setName(ND->getDeclName());
11984         R.addDecl(ND);
11985       }
11986     } else {
11987       Diag(IdentLoc, diag::err_no_member)
11988         << NameInfo.getName() << LookupContext << SS.getRange();
11989       return BuildInvalid();
11990     }
11991   }
11992 
11993   if (R.isAmbiguous())
11994     return BuildInvalid();
11995 
11996   if (HasTypenameKeyword) {
11997     // If we asked for a typename and got a non-type decl, error out.
11998     if (!R.getAsSingle<TypeDecl>()) {
11999       Diag(IdentLoc, diag::err_using_typename_non_type);
12000       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12001         Diag((*I)->getUnderlyingDecl()->getLocation(),
12002              diag::note_using_decl_target);
12003       return BuildInvalid();
12004     }
12005   } else {
12006     // If we asked for a non-typename and we got a type, error out,
12007     // but only if this is an instantiation of an unresolved using
12008     // decl.  Otherwise just silently find the type name.
12009     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12010       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12011       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12012       return BuildInvalid();
12013     }
12014   }
12015 
12016   // C++14 [namespace.udecl]p6:
12017   // A using-declaration shall not name a namespace.
12018   if (R.getAsSingle<NamespaceDecl>()) {
12019     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12020       << SS.getRange();
12021     return BuildInvalid();
12022   }
12023 
12024   // C++14 [namespace.udecl]p7:
12025   // A using-declaration shall not name a scoped enumerator.
12026   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12027     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12028       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12029         << SS.getRange();
12030       return BuildInvalid();
12031     }
12032   }
12033 
12034   UsingDecl *UD = BuildValid();
12035 
12036   // Some additional rules apply to inheriting constructors.
12037   if (UsingName.getName().getNameKind() ==
12038         DeclarationName::CXXConstructorName) {
12039     // Suppress access diagnostics; the access check is instead performed at the
12040     // point of use for an inheriting constructor.
12041     R.suppressDiagnostics();
12042     if (CheckInheritingConstructorUsingDecl(UD))
12043       return UD;
12044   }
12045 
12046   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12047     UsingShadowDecl *PrevDecl = nullptr;
12048     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12049       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12050   }
12051 
12052   return UD;
12053 }
12054 
12055 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12056                                     ArrayRef<NamedDecl *> Expansions) {
12057   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12058          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12059          isa<UsingPackDecl>(InstantiatedFrom));
12060 
12061   auto *UPD =
12062       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12063   UPD->setAccess(InstantiatedFrom->getAccess());
12064   CurContext->addDecl(UPD);
12065   return UPD;
12066 }
12067 
12068 /// Additional checks for a using declaration referring to a constructor name.
12069 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12070   assert(!UD->hasTypename() && "expecting a constructor name");
12071 
12072   const Type *SourceType = UD->getQualifier()->getAsType();
12073   assert(SourceType &&
12074          "Using decl naming constructor doesn't have type in scope spec.");
12075   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12076 
12077   // Check whether the named type is a direct base class.
12078   bool AnyDependentBases = false;
12079   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12080                                       AnyDependentBases);
12081   if (!Base && !AnyDependentBases) {
12082     Diag(UD->getUsingLoc(),
12083          diag::err_using_decl_constructor_not_in_direct_base)
12084       << UD->getNameInfo().getSourceRange()
12085       << QualType(SourceType, 0) << TargetClass;
12086     UD->setInvalidDecl();
12087     return true;
12088   }
12089 
12090   if (Base)
12091     Base->setInheritConstructors();
12092 
12093   return false;
12094 }
12095 
12096 /// Checks that the given using declaration is not an invalid
12097 /// redeclaration.  Note that this is checking only for the using decl
12098 /// itself, not for any ill-formedness among the UsingShadowDecls.
12099 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12100                                        bool HasTypenameKeyword,
12101                                        const CXXScopeSpec &SS,
12102                                        SourceLocation NameLoc,
12103                                        const LookupResult &Prev) {
12104   NestedNameSpecifier *Qual = SS.getScopeRep();
12105 
12106   // C++03 [namespace.udecl]p8:
12107   // C++0x [namespace.udecl]p10:
12108   //   A using-declaration is a declaration and can therefore be used
12109   //   repeatedly where (and only where) multiple declarations are
12110   //   allowed.
12111   //
12112   // That's in non-member contexts.
12113   if (!CurContext->getRedeclContext()->isRecord()) {
12114     // A dependent qualifier outside a class can only ever resolve to an
12115     // enumeration type. Therefore it conflicts with any other non-type
12116     // declaration in the same scope.
12117     // FIXME: How should we check for dependent type-type conflicts at block
12118     // scope?
12119     if (Qual->isDependent() && !HasTypenameKeyword) {
12120       for (auto *D : Prev) {
12121         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12122           bool OldCouldBeEnumerator =
12123               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12124           Diag(NameLoc,
12125                OldCouldBeEnumerator ? diag::err_redefinition
12126                                     : diag::err_redefinition_different_kind)
12127               << Prev.getLookupName();
12128           Diag(D->getLocation(), diag::note_previous_definition);
12129           return true;
12130         }
12131       }
12132     }
12133     return false;
12134   }
12135 
12136   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12137     NamedDecl *D = *I;
12138 
12139     bool DTypename;
12140     NestedNameSpecifier *DQual;
12141     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12142       DTypename = UD->hasTypename();
12143       DQual = UD->getQualifier();
12144     } else if (UnresolvedUsingValueDecl *UD
12145                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12146       DTypename = false;
12147       DQual = UD->getQualifier();
12148     } else if (UnresolvedUsingTypenameDecl *UD
12149                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12150       DTypename = true;
12151       DQual = UD->getQualifier();
12152     } else continue;
12153 
12154     // using decls differ if one says 'typename' and the other doesn't.
12155     // FIXME: non-dependent using decls?
12156     if (HasTypenameKeyword != DTypename) continue;
12157 
12158     // using decls differ if they name different scopes (but note that
12159     // template instantiation can cause this check to trigger when it
12160     // didn't before instantiation).
12161     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12162         Context.getCanonicalNestedNameSpecifier(DQual))
12163       continue;
12164 
12165     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12166     Diag(D->getLocation(), diag::note_using_decl) << 1;
12167     return true;
12168   }
12169 
12170   return false;
12171 }
12172 
12173 
12174 /// Checks that the given nested-name qualifier used in a using decl
12175 /// in the current context is appropriately related to the current
12176 /// scope.  If an error is found, diagnoses it and returns true.
12177 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12178                                    bool HasTypename,
12179                                    const CXXScopeSpec &SS,
12180                                    const DeclarationNameInfo &NameInfo,
12181                                    SourceLocation NameLoc) {
12182   DeclContext *NamedContext = computeDeclContext(SS);
12183 
12184   if (!CurContext->isRecord()) {
12185     // C++03 [namespace.udecl]p3:
12186     // C++0x [namespace.udecl]p8:
12187     //   A using-declaration for a class member shall be a member-declaration.
12188 
12189     // If we weren't able to compute a valid scope, it might validly be a
12190     // dependent class scope or a dependent enumeration unscoped scope. If
12191     // we have a 'typename' keyword, the scope must resolve to a class type.
12192     if ((HasTypename && !NamedContext) ||
12193         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12194       auto *RD = NamedContext
12195                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12196                      : nullptr;
12197       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12198         RD = nullptr;
12199 
12200       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12201         << SS.getRange();
12202 
12203       // If we have a complete, non-dependent source type, try to suggest a
12204       // way to get the same effect.
12205       if (!RD)
12206         return true;
12207 
12208       // Find what this using-declaration was referring to.
12209       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12210       R.setHideTags(false);
12211       R.suppressDiagnostics();
12212       LookupQualifiedName(R, RD);
12213 
12214       if (R.getAsSingle<TypeDecl>()) {
12215         if (getLangOpts().CPlusPlus11) {
12216           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12217           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12218             << 0 // alias declaration
12219             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12220                                           NameInfo.getName().getAsString() +
12221                                               " = ");
12222         } else {
12223           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12224           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12225           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12226             << 1 // typedef declaration
12227             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12228             << FixItHint::CreateInsertion(
12229                    InsertLoc, " " + NameInfo.getName().getAsString());
12230         }
12231       } else if (R.getAsSingle<VarDecl>()) {
12232         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12233         // repeating the type of the static data member here.
12234         FixItHint FixIt;
12235         if (getLangOpts().CPlusPlus11) {
12236           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12237           FixIt = FixItHint::CreateReplacement(
12238               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12239         }
12240 
12241         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12242           << 2 // reference declaration
12243           << FixIt;
12244       } else if (R.getAsSingle<EnumConstantDecl>()) {
12245         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12246         // repeating the type of the enumeration here, and we can't do so if
12247         // the type is anonymous.
12248         FixItHint FixIt;
12249         if (getLangOpts().CPlusPlus11) {
12250           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12251           FixIt = FixItHint::CreateReplacement(
12252               UsingLoc,
12253               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12254         }
12255 
12256         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12257           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12258           << FixIt;
12259       }
12260       return true;
12261     }
12262 
12263     // Otherwise, this might be valid.
12264     return false;
12265   }
12266 
12267   // The current scope is a record.
12268 
12269   // If the named context is dependent, we can't decide much.
12270   if (!NamedContext) {
12271     // FIXME: in C++0x, we can diagnose if we can prove that the
12272     // nested-name-specifier does not refer to a base class, which is
12273     // still possible in some cases.
12274 
12275     // Otherwise we have to conservatively report that things might be
12276     // okay.
12277     return false;
12278   }
12279 
12280   if (!NamedContext->isRecord()) {
12281     // Ideally this would point at the last name in the specifier,
12282     // but we don't have that level of source info.
12283     Diag(SS.getRange().getBegin(),
12284          diag::err_using_decl_nested_name_specifier_is_not_class)
12285       << SS.getScopeRep() << SS.getRange();
12286     return true;
12287   }
12288 
12289   if (!NamedContext->isDependentContext() &&
12290       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12291     return true;
12292 
12293   if (getLangOpts().CPlusPlus11) {
12294     // C++11 [namespace.udecl]p3:
12295     //   In a using-declaration used as a member-declaration, the
12296     //   nested-name-specifier shall name a base class of the class
12297     //   being defined.
12298 
12299     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12300                                  cast<CXXRecordDecl>(NamedContext))) {
12301       if (CurContext == NamedContext) {
12302         Diag(NameLoc,
12303              diag::err_using_decl_nested_name_specifier_is_current_class)
12304           << SS.getRange();
12305         return true;
12306       }
12307 
12308       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12309         Diag(SS.getRange().getBegin(),
12310              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12311           << SS.getScopeRep()
12312           << cast<CXXRecordDecl>(CurContext)
12313           << SS.getRange();
12314       }
12315       return true;
12316     }
12317 
12318     return false;
12319   }
12320 
12321   // C++03 [namespace.udecl]p4:
12322   //   A using-declaration used as a member-declaration shall refer
12323   //   to a member of a base class of the class being defined [etc.].
12324 
12325   // Salient point: SS doesn't have to name a base class as long as
12326   // lookup only finds members from base classes.  Therefore we can
12327   // diagnose here only if we can prove that that can't happen,
12328   // i.e. if the class hierarchies provably don't intersect.
12329 
12330   // TODO: it would be nice if "definitely valid" results were cached
12331   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12332   // need to be repeated.
12333 
12334   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12335   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12336     Bases.insert(Base);
12337     return true;
12338   };
12339 
12340   // Collect all bases. Return false if we find a dependent base.
12341   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12342     return false;
12343 
12344   // Returns true if the base is dependent or is one of the accumulated base
12345   // classes.
12346   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12347     return !Bases.count(Base);
12348   };
12349 
12350   // Return false if the class has a dependent base or if it or one
12351   // of its bases is present in the base set of the current context.
12352   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12353       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12354     return false;
12355 
12356   Diag(SS.getRange().getBegin(),
12357        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12358     << SS.getScopeRep()
12359     << cast<CXXRecordDecl>(CurContext)
12360     << SS.getRange();
12361 
12362   return true;
12363 }
12364 
12365 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12366                                   MultiTemplateParamsArg TemplateParamLists,
12367                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12368                                   const ParsedAttributesView &AttrList,
12369                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12370   // Skip up to the relevant declaration scope.
12371   while (S->isTemplateParamScope())
12372     S = S->getParent();
12373   assert((S->getFlags() & Scope::DeclScope) &&
12374          "got alias-declaration outside of declaration scope");
12375 
12376   if (Type.isInvalid())
12377     return nullptr;
12378 
12379   bool Invalid = false;
12380   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12381   TypeSourceInfo *TInfo = nullptr;
12382   GetTypeFromParser(Type.get(), &TInfo);
12383 
12384   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12385     return nullptr;
12386 
12387   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12388                                       UPPC_DeclarationType)) {
12389     Invalid = true;
12390     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12391                                              TInfo->getTypeLoc().getBeginLoc());
12392   }
12393 
12394   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12395                         TemplateParamLists.size()
12396                             ? forRedeclarationInCurContext()
12397                             : ForVisibleRedeclaration);
12398   LookupName(Previous, S);
12399 
12400   // Warn about shadowing the name of a template parameter.
12401   if (Previous.isSingleResult() &&
12402       Previous.getFoundDecl()->isTemplateParameter()) {
12403     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12404     Previous.clear();
12405   }
12406 
12407   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12408          "name in alias declaration must be an identifier");
12409   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12410                                                Name.StartLocation,
12411                                                Name.Identifier, TInfo);
12412 
12413   NewTD->setAccess(AS);
12414 
12415   if (Invalid)
12416     NewTD->setInvalidDecl();
12417 
12418   ProcessDeclAttributeList(S, NewTD, AttrList);
12419   AddPragmaAttributes(S, NewTD);
12420 
12421   CheckTypedefForVariablyModifiedType(S, NewTD);
12422   Invalid |= NewTD->isInvalidDecl();
12423 
12424   bool Redeclaration = false;
12425 
12426   NamedDecl *NewND;
12427   if (TemplateParamLists.size()) {
12428     TypeAliasTemplateDecl *OldDecl = nullptr;
12429     TemplateParameterList *OldTemplateParams = nullptr;
12430 
12431     if (TemplateParamLists.size() != 1) {
12432       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12433         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12434          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12435     }
12436     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12437 
12438     // Check that we can declare a template here.
12439     if (CheckTemplateDeclScope(S, TemplateParams))
12440       return nullptr;
12441 
12442     // Only consider previous declarations in the same scope.
12443     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12444                          /*ExplicitInstantiationOrSpecialization*/false);
12445     if (!Previous.empty()) {
12446       Redeclaration = true;
12447 
12448       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12449       if (!OldDecl && !Invalid) {
12450         Diag(UsingLoc, diag::err_redefinition_different_kind)
12451           << Name.Identifier;
12452 
12453         NamedDecl *OldD = Previous.getRepresentativeDecl();
12454         if (OldD->getLocation().isValid())
12455           Diag(OldD->getLocation(), diag::note_previous_definition);
12456 
12457         Invalid = true;
12458       }
12459 
12460       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12461         if (TemplateParameterListsAreEqual(TemplateParams,
12462                                            OldDecl->getTemplateParameters(),
12463                                            /*Complain=*/true,
12464                                            TPL_TemplateMatch))
12465           OldTemplateParams =
12466               OldDecl->getMostRecentDecl()->getTemplateParameters();
12467         else
12468           Invalid = true;
12469 
12470         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12471         if (!Invalid &&
12472             !Context.hasSameType(OldTD->getUnderlyingType(),
12473                                  NewTD->getUnderlyingType())) {
12474           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12475           // but we can't reasonably accept it.
12476           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12477             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12478           if (OldTD->getLocation().isValid())
12479             Diag(OldTD->getLocation(), diag::note_previous_definition);
12480           Invalid = true;
12481         }
12482       }
12483     }
12484 
12485     // Merge any previous default template arguments into our parameters,
12486     // and check the parameter list.
12487     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12488                                    TPC_TypeAliasTemplate))
12489       return nullptr;
12490 
12491     TypeAliasTemplateDecl *NewDecl =
12492       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12493                                     Name.Identifier, TemplateParams,
12494                                     NewTD);
12495     NewTD->setDescribedAliasTemplate(NewDecl);
12496 
12497     NewDecl->setAccess(AS);
12498 
12499     if (Invalid)
12500       NewDecl->setInvalidDecl();
12501     else if (OldDecl) {
12502       NewDecl->setPreviousDecl(OldDecl);
12503       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12504     }
12505 
12506     NewND = NewDecl;
12507   } else {
12508     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12509       setTagNameForLinkagePurposes(TD, NewTD);
12510       handleTagNumbering(TD, S);
12511     }
12512     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12513     NewND = NewTD;
12514   }
12515 
12516   PushOnScopeChains(NewND, S);
12517   ActOnDocumentableDecl(NewND);
12518   return NewND;
12519 }
12520 
12521 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12522                                    SourceLocation AliasLoc,
12523                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12524                                    SourceLocation IdentLoc,
12525                                    IdentifierInfo *Ident) {
12526 
12527   // Lookup the namespace name.
12528   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12529   LookupParsedName(R, S, &SS);
12530 
12531   if (R.isAmbiguous())
12532     return nullptr;
12533 
12534   if (R.empty()) {
12535     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12536       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12537       return nullptr;
12538     }
12539   }
12540   assert(!R.isAmbiguous() && !R.empty());
12541   NamedDecl *ND = R.getRepresentativeDecl();
12542 
12543   // Check if we have a previous declaration with the same name.
12544   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12545                      ForVisibleRedeclaration);
12546   LookupName(PrevR, S);
12547 
12548   // Check we're not shadowing a template parameter.
12549   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12550     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12551     PrevR.clear();
12552   }
12553 
12554   // Filter out any other lookup result from an enclosing scope.
12555   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12556                        /*AllowInlineNamespace*/false);
12557 
12558   // Find the previous declaration and check that we can redeclare it.
12559   NamespaceAliasDecl *Prev = nullptr;
12560   if (PrevR.isSingleResult()) {
12561     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12562     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12563       // We already have an alias with the same name that points to the same
12564       // namespace; check that it matches.
12565       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12566         Prev = AD;
12567       } else if (isVisible(PrevDecl)) {
12568         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12569           << Alias;
12570         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12571           << AD->getNamespace();
12572         return nullptr;
12573       }
12574     } else if (isVisible(PrevDecl)) {
12575       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12576                             ? diag::err_redefinition
12577                             : diag::err_redefinition_different_kind;
12578       Diag(AliasLoc, DiagID) << Alias;
12579       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12580       return nullptr;
12581     }
12582   }
12583 
12584   // The use of a nested name specifier may trigger deprecation warnings.
12585   DiagnoseUseOfDecl(ND, IdentLoc);
12586 
12587   NamespaceAliasDecl *AliasDecl =
12588     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12589                                Alias, SS.getWithLocInContext(Context),
12590                                IdentLoc, ND);
12591   if (Prev)
12592     AliasDecl->setPreviousDecl(Prev);
12593 
12594   PushOnScopeChains(AliasDecl, S);
12595   return AliasDecl;
12596 }
12597 
12598 namespace {
12599 struct SpecialMemberExceptionSpecInfo
12600     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12601   SourceLocation Loc;
12602   Sema::ImplicitExceptionSpecification ExceptSpec;
12603 
12604   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12605                                  Sema::CXXSpecialMember CSM,
12606                                  Sema::InheritedConstructorInfo *ICI,
12607                                  SourceLocation Loc)
12608       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12609 
12610   bool visitBase(CXXBaseSpecifier *Base);
12611   bool visitField(FieldDecl *FD);
12612 
12613   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12614                            unsigned Quals);
12615 
12616   void visitSubobjectCall(Subobject Subobj,
12617                           Sema::SpecialMemberOverloadResult SMOR);
12618 };
12619 }
12620 
12621 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12622   auto *RT = Base->getType()->getAs<RecordType>();
12623   if (!RT)
12624     return false;
12625 
12626   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12627   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12628   if (auto *BaseCtor = SMOR.getMethod()) {
12629     visitSubobjectCall(Base, BaseCtor);
12630     return false;
12631   }
12632 
12633   visitClassSubobject(BaseClass, Base, 0);
12634   return false;
12635 }
12636 
12637 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12638   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12639     Expr *E = FD->getInClassInitializer();
12640     if (!E)
12641       // FIXME: It's a little wasteful to build and throw away a
12642       // CXXDefaultInitExpr here.
12643       // FIXME: We should have a single context note pointing at Loc, and
12644       // this location should be MD->getLocation() instead, since that's
12645       // the location where we actually use the default init expression.
12646       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12647     if (E)
12648       ExceptSpec.CalledExpr(E);
12649   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12650                             ->getAs<RecordType>()) {
12651     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12652                         FD->getType().getCVRQualifiers());
12653   }
12654   return false;
12655 }
12656 
12657 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12658                                                          Subobject Subobj,
12659                                                          unsigned Quals) {
12660   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12661   bool IsMutable = Field && Field->isMutable();
12662   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12663 }
12664 
12665 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12666     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12667   // Note, if lookup fails, it doesn't matter what exception specification we
12668   // choose because the special member will be deleted.
12669   if (CXXMethodDecl *MD = SMOR.getMethod())
12670     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12671 }
12672 
12673 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12674   llvm::APSInt Result;
12675   ExprResult Converted = CheckConvertedConstantExpression(
12676       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12677   ExplicitSpec.setExpr(Converted.get());
12678   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12679     ExplicitSpec.setKind(Result.getBoolValue()
12680                              ? ExplicitSpecKind::ResolvedTrue
12681                              : ExplicitSpecKind::ResolvedFalse);
12682     return true;
12683   }
12684   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12685   return false;
12686 }
12687 
12688 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12689   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12690   if (!ExplicitExpr->isTypeDependent())
12691     tryResolveExplicitSpecifier(ES);
12692   return ES;
12693 }
12694 
12695 static Sema::ImplicitExceptionSpecification
12696 ComputeDefaultedSpecialMemberExceptionSpec(
12697     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12698     Sema::InheritedConstructorInfo *ICI) {
12699   ComputingExceptionSpec CES(S, MD, Loc);
12700 
12701   CXXRecordDecl *ClassDecl = MD->getParent();
12702 
12703   // C++ [except.spec]p14:
12704   //   An implicitly declared special member function (Clause 12) shall have an
12705   //   exception-specification. [...]
12706   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12707   if (ClassDecl->isInvalidDecl())
12708     return Info.ExceptSpec;
12709 
12710   // FIXME: If this diagnostic fires, we're probably missing a check for
12711   // attempting to resolve an exception specification before it's known
12712   // at a higher level.
12713   if (S.RequireCompleteType(MD->getLocation(),
12714                             S.Context.getRecordType(ClassDecl),
12715                             diag::err_exception_spec_incomplete_type))
12716     return Info.ExceptSpec;
12717 
12718   // C++1z [except.spec]p7:
12719   //   [Look for exceptions thrown by] a constructor selected [...] to
12720   //   initialize a potentially constructed subobject,
12721   // C++1z [except.spec]p8:
12722   //   The exception specification for an implicitly-declared destructor, or a
12723   //   destructor without a noexcept-specifier, is potentially-throwing if and
12724   //   only if any of the destructors for any of its potentially constructed
12725   //   subojects is potentially throwing.
12726   // FIXME: We respect the first rule but ignore the "potentially constructed"
12727   // in the second rule to resolve a core issue (no number yet) that would have
12728   // us reject:
12729   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12730   //   struct B : A {};
12731   //   struct C : B { void f(); };
12732   // ... due to giving B::~B() a non-throwing exception specification.
12733   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12734                                 : Info.VisitAllBases);
12735 
12736   return Info.ExceptSpec;
12737 }
12738 
12739 namespace {
12740 /// RAII object to register a special member as being currently declared.
12741 struct DeclaringSpecialMember {
12742   Sema &S;
12743   Sema::SpecialMemberDecl D;
12744   Sema::ContextRAII SavedContext;
12745   bool WasAlreadyBeingDeclared;
12746 
12747   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12748       : S(S), D(RD, CSM), SavedContext(S, RD) {
12749     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12750     if (WasAlreadyBeingDeclared)
12751       // This almost never happens, but if it does, ensure that our cache
12752       // doesn't contain a stale result.
12753       S.SpecialMemberCache.clear();
12754     else {
12755       // Register a note to be produced if we encounter an error while
12756       // declaring the special member.
12757       Sema::CodeSynthesisContext Ctx;
12758       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12759       // FIXME: We don't have a location to use here. Using the class's
12760       // location maintains the fiction that we declare all special members
12761       // with the class, but (1) it's not clear that lying about that helps our
12762       // users understand what's going on, and (2) there may be outer contexts
12763       // on the stack (some of which are relevant) and printing them exposes
12764       // our lies.
12765       Ctx.PointOfInstantiation = RD->getLocation();
12766       Ctx.Entity = RD;
12767       Ctx.SpecialMember = CSM;
12768       S.pushCodeSynthesisContext(Ctx);
12769     }
12770   }
12771   ~DeclaringSpecialMember() {
12772     if (!WasAlreadyBeingDeclared) {
12773       S.SpecialMembersBeingDeclared.erase(D);
12774       S.popCodeSynthesisContext();
12775     }
12776   }
12777 
12778   /// Are we already trying to declare this special member?
12779   bool isAlreadyBeingDeclared() const {
12780     return WasAlreadyBeingDeclared;
12781   }
12782 };
12783 }
12784 
12785 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12786   // Look up any existing declarations, but don't trigger declaration of all
12787   // implicit special members with this name.
12788   DeclarationName Name = FD->getDeclName();
12789   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12790                  ForExternalRedeclaration);
12791   for (auto *D : FD->getParent()->lookup(Name))
12792     if (auto *Acceptable = R.getAcceptableDecl(D))
12793       R.addDecl(Acceptable);
12794   R.resolveKind();
12795   R.suppressDiagnostics();
12796 
12797   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12798 }
12799 
12800 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12801                                           QualType ResultTy,
12802                                           ArrayRef<QualType> Args) {
12803   // Build an exception specification pointing back at this constructor.
12804   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12805 
12806   LangAS AS = getDefaultCXXMethodAddrSpace();
12807   if (AS != LangAS::Default) {
12808     EPI.TypeQuals.addAddressSpace(AS);
12809   }
12810 
12811   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12812   SpecialMem->setType(QT);
12813 }
12814 
12815 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12816                                                      CXXRecordDecl *ClassDecl) {
12817   // C++ [class.ctor]p5:
12818   //   A default constructor for a class X is a constructor of class X
12819   //   that can be called without an argument. If there is no
12820   //   user-declared constructor for class X, a default constructor is
12821   //   implicitly declared. An implicitly-declared default constructor
12822   //   is an inline public member of its class.
12823   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12824          "Should not build implicit default constructor!");
12825 
12826   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12827   if (DSM.isAlreadyBeingDeclared())
12828     return nullptr;
12829 
12830   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12831                                                      CXXDefaultConstructor,
12832                                                      false);
12833 
12834   // Create the actual constructor declaration.
12835   CanQualType ClassType
12836     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12837   SourceLocation ClassLoc = ClassDecl->getLocation();
12838   DeclarationName Name
12839     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12840   DeclarationNameInfo NameInfo(Name, ClassLoc);
12841   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12842       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12843       /*TInfo=*/nullptr, ExplicitSpecifier(),
12844       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12845       Constexpr ? CSK_constexpr : CSK_unspecified);
12846   DefaultCon->setAccess(AS_public);
12847   DefaultCon->setDefaulted();
12848 
12849   if (getLangOpts().CUDA) {
12850     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12851                                             DefaultCon,
12852                                             /* ConstRHS */ false,
12853                                             /* Diagnose */ false);
12854   }
12855 
12856   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12857 
12858   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12859   // constructors is easy to compute.
12860   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12861 
12862   // Note that we have declared this constructor.
12863   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12864 
12865   Scope *S = getScopeForContext(ClassDecl);
12866   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12867 
12868   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12869     SetDeclDeleted(DefaultCon, ClassLoc);
12870 
12871   if (S)
12872     PushOnScopeChains(DefaultCon, S, false);
12873   ClassDecl->addDecl(DefaultCon);
12874 
12875   return DefaultCon;
12876 }
12877 
12878 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12879                                             CXXConstructorDecl *Constructor) {
12880   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12881           !Constructor->doesThisDeclarationHaveABody() &&
12882           !Constructor->isDeleted()) &&
12883     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12884   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12885     return;
12886 
12887   CXXRecordDecl *ClassDecl = Constructor->getParent();
12888   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12889 
12890   SynthesizedFunctionScope Scope(*this, Constructor);
12891 
12892   // The exception specification is needed because we are defining the
12893   // function.
12894   ResolveExceptionSpec(CurrentLocation,
12895                        Constructor->getType()->castAs<FunctionProtoType>());
12896   MarkVTableUsed(CurrentLocation, ClassDecl);
12897 
12898   // Add a context note for diagnostics produced after this point.
12899   Scope.addContextNote(CurrentLocation);
12900 
12901   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12902     Constructor->setInvalidDecl();
12903     return;
12904   }
12905 
12906   SourceLocation Loc = Constructor->getEndLoc().isValid()
12907                            ? Constructor->getEndLoc()
12908                            : Constructor->getLocation();
12909   Constructor->setBody(new (Context) CompoundStmt(Loc));
12910   Constructor->markUsed(Context);
12911 
12912   if (ASTMutationListener *L = getASTMutationListener()) {
12913     L->CompletedImplicitDefinition(Constructor);
12914   }
12915 
12916   DiagnoseUninitializedFields(*this, Constructor);
12917 }
12918 
12919 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
12920   // Perform any delayed checks on exception specifications.
12921   CheckDelayedMemberExceptionSpecs();
12922 }
12923 
12924 /// Find or create the fake constructor we synthesize to model constructing an
12925 /// object of a derived class via a constructor of a base class.
12926 CXXConstructorDecl *
12927 Sema::findInheritingConstructor(SourceLocation Loc,
12928                                 CXXConstructorDecl *BaseCtor,
12929                                 ConstructorUsingShadowDecl *Shadow) {
12930   CXXRecordDecl *Derived = Shadow->getParent();
12931   SourceLocation UsingLoc = Shadow->getLocation();
12932 
12933   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
12934   // For now we use the name of the base class constructor as a member of the
12935   // derived class to indicate a (fake) inherited constructor name.
12936   DeclarationName Name = BaseCtor->getDeclName();
12937 
12938   // Check to see if we already have a fake constructor for this inherited
12939   // constructor call.
12940   for (NamedDecl *Ctor : Derived->lookup(Name))
12941     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
12942                                ->getInheritedConstructor()
12943                                .getConstructor(),
12944                            BaseCtor))
12945       return cast<CXXConstructorDecl>(Ctor);
12946 
12947   DeclarationNameInfo NameInfo(Name, UsingLoc);
12948   TypeSourceInfo *TInfo =
12949       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
12950   FunctionProtoTypeLoc ProtoLoc =
12951       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
12952 
12953   // Check the inherited constructor is valid and find the list of base classes
12954   // from which it was inherited.
12955   InheritedConstructorInfo ICI(*this, Loc, Shadow);
12956 
12957   bool Constexpr =
12958       BaseCtor->isConstexpr() &&
12959       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
12960                                         false, BaseCtor, &ICI);
12961 
12962   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
12963       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
12964       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
12965       /*isImplicitlyDeclared=*/true,
12966       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
12967       InheritedConstructor(Shadow, BaseCtor),
12968       BaseCtor->getTrailingRequiresClause());
12969   if (Shadow->isInvalidDecl())
12970     DerivedCtor->setInvalidDecl();
12971 
12972   // Build an unevaluated exception specification for this fake constructor.
12973   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
12974   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12975   EPI.ExceptionSpec.Type = EST_Unevaluated;
12976   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
12977   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
12978                                                FPT->getParamTypes(), EPI));
12979 
12980   // Build the parameter declarations.
12981   SmallVector<ParmVarDecl *, 16> ParamDecls;
12982   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
12983     TypeSourceInfo *TInfo =
12984         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
12985     ParmVarDecl *PD = ParmVarDecl::Create(
12986         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
12987         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
12988     PD->setScopeInfo(0, I);
12989     PD->setImplicit();
12990     // Ensure attributes are propagated onto parameters (this matters for
12991     // format, pass_object_size, ...).
12992     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
12993     ParamDecls.push_back(PD);
12994     ProtoLoc.setParam(I, PD);
12995   }
12996 
12997   // Set up the new constructor.
12998   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
12999   DerivedCtor->setAccess(BaseCtor->getAccess());
13000   DerivedCtor->setParams(ParamDecls);
13001   Derived->addDecl(DerivedCtor);
13002 
13003   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13004     SetDeclDeleted(DerivedCtor, UsingLoc);
13005 
13006   return DerivedCtor;
13007 }
13008 
13009 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13010   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13011                                Ctor->getInheritedConstructor().getShadowDecl());
13012   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13013                             /*Diagnose*/true);
13014 }
13015 
13016 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13017                                        CXXConstructorDecl *Constructor) {
13018   CXXRecordDecl *ClassDecl = Constructor->getParent();
13019   assert(Constructor->getInheritedConstructor() &&
13020          !Constructor->doesThisDeclarationHaveABody() &&
13021          !Constructor->isDeleted());
13022   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13023     return;
13024 
13025   // Initializations are performed "as if by a defaulted default constructor",
13026   // so enter the appropriate scope.
13027   SynthesizedFunctionScope Scope(*this, Constructor);
13028 
13029   // The exception specification is needed because we are defining the
13030   // function.
13031   ResolveExceptionSpec(CurrentLocation,
13032                        Constructor->getType()->castAs<FunctionProtoType>());
13033   MarkVTableUsed(CurrentLocation, ClassDecl);
13034 
13035   // Add a context note for diagnostics produced after this point.
13036   Scope.addContextNote(CurrentLocation);
13037 
13038   ConstructorUsingShadowDecl *Shadow =
13039       Constructor->getInheritedConstructor().getShadowDecl();
13040   CXXConstructorDecl *InheritedCtor =
13041       Constructor->getInheritedConstructor().getConstructor();
13042 
13043   // [class.inhctor.init]p1:
13044   //   initialization proceeds as if a defaulted default constructor is used to
13045   //   initialize the D object and each base class subobject from which the
13046   //   constructor was inherited
13047 
13048   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13049   CXXRecordDecl *RD = Shadow->getParent();
13050   SourceLocation InitLoc = Shadow->getLocation();
13051 
13052   // Build explicit initializers for all base classes from which the
13053   // constructor was inherited.
13054   SmallVector<CXXCtorInitializer*, 8> Inits;
13055   for (bool VBase : {false, true}) {
13056     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13057       if (B.isVirtual() != VBase)
13058         continue;
13059 
13060       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13061       if (!BaseRD)
13062         continue;
13063 
13064       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13065       if (!BaseCtor.first)
13066         continue;
13067 
13068       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13069       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13070           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13071 
13072       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13073       Inits.push_back(new (Context) CXXCtorInitializer(
13074           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13075           SourceLocation()));
13076     }
13077   }
13078 
13079   // We now proceed as if for a defaulted default constructor, with the relevant
13080   // initializers replaced.
13081 
13082   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13083     Constructor->setInvalidDecl();
13084     return;
13085   }
13086 
13087   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13088   Constructor->markUsed(Context);
13089 
13090   if (ASTMutationListener *L = getASTMutationListener()) {
13091     L->CompletedImplicitDefinition(Constructor);
13092   }
13093 
13094   DiagnoseUninitializedFields(*this, Constructor);
13095 }
13096 
13097 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13098   // C++ [class.dtor]p2:
13099   //   If a class has no user-declared destructor, a destructor is
13100   //   declared implicitly. An implicitly-declared destructor is an
13101   //   inline public member of its class.
13102   assert(ClassDecl->needsImplicitDestructor());
13103 
13104   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13105   if (DSM.isAlreadyBeingDeclared())
13106     return nullptr;
13107 
13108   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13109                                                      CXXDestructor,
13110                                                      false);
13111 
13112   // Create the actual destructor declaration.
13113   CanQualType ClassType
13114     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13115   SourceLocation ClassLoc = ClassDecl->getLocation();
13116   DeclarationName Name
13117     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13118   DeclarationNameInfo NameInfo(Name, ClassLoc);
13119   CXXDestructorDecl *Destructor =
13120       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13121                                 QualType(), nullptr, /*isInline=*/true,
13122                                 /*isImplicitlyDeclared=*/true,
13123                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13124   Destructor->setAccess(AS_public);
13125   Destructor->setDefaulted();
13126 
13127   if (getLangOpts().CUDA) {
13128     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13129                                             Destructor,
13130                                             /* ConstRHS */ false,
13131                                             /* Diagnose */ false);
13132   }
13133 
13134   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13135 
13136   // We don't need to use SpecialMemberIsTrivial here; triviality for
13137   // destructors is easy to compute.
13138   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13139   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13140                                 ClassDecl->hasTrivialDestructorForCall());
13141 
13142   // Note that we have declared this destructor.
13143   ++getASTContext().NumImplicitDestructorsDeclared;
13144 
13145   Scope *S = getScopeForContext(ClassDecl);
13146   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13147 
13148   // We can't check whether an implicit destructor is deleted before we complete
13149   // the definition of the class, because its validity depends on the alignment
13150   // of the class. We'll check this from ActOnFields once the class is complete.
13151   if (ClassDecl->isCompleteDefinition() &&
13152       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13153     SetDeclDeleted(Destructor, ClassLoc);
13154 
13155   // Introduce this destructor into its scope.
13156   if (S)
13157     PushOnScopeChains(Destructor, S, false);
13158   ClassDecl->addDecl(Destructor);
13159 
13160   return Destructor;
13161 }
13162 
13163 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13164                                     CXXDestructorDecl *Destructor) {
13165   assert((Destructor->isDefaulted() &&
13166           !Destructor->doesThisDeclarationHaveABody() &&
13167           !Destructor->isDeleted()) &&
13168          "DefineImplicitDestructor - call it for implicit default dtor");
13169   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13170     return;
13171 
13172   CXXRecordDecl *ClassDecl = Destructor->getParent();
13173   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13174 
13175   SynthesizedFunctionScope Scope(*this, Destructor);
13176 
13177   // The exception specification is needed because we are defining the
13178   // function.
13179   ResolveExceptionSpec(CurrentLocation,
13180                        Destructor->getType()->castAs<FunctionProtoType>());
13181   MarkVTableUsed(CurrentLocation, ClassDecl);
13182 
13183   // Add a context note for diagnostics produced after this point.
13184   Scope.addContextNote(CurrentLocation);
13185 
13186   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13187                                          Destructor->getParent());
13188 
13189   if (CheckDestructor(Destructor)) {
13190     Destructor->setInvalidDecl();
13191     return;
13192   }
13193 
13194   SourceLocation Loc = Destructor->getEndLoc().isValid()
13195                            ? Destructor->getEndLoc()
13196                            : Destructor->getLocation();
13197   Destructor->setBody(new (Context) CompoundStmt(Loc));
13198   Destructor->markUsed(Context);
13199 
13200   if (ASTMutationListener *L = getASTMutationListener()) {
13201     L->CompletedImplicitDefinition(Destructor);
13202   }
13203 }
13204 
13205 /// Perform any semantic analysis which needs to be delayed until all
13206 /// pending class member declarations have been parsed.
13207 void Sema::ActOnFinishCXXMemberDecls() {
13208   // If the context is an invalid C++ class, just suppress these checks.
13209   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13210     if (Record->isInvalidDecl()) {
13211       DelayedOverridingExceptionSpecChecks.clear();
13212       DelayedEquivalentExceptionSpecChecks.clear();
13213       return;
13214     }
13215     checkForMultipleExportedDefaultConstructors(*this, Record);
13216   }
13217 }
13218 
13219 void Sema::ActOnFinishCXXNonNestedClass() {
13220   referenceDLLExportedClassMethods();
13221 
13222   if (!DelayedDllExportMemberFunctions.empty()) {
13223     SmallVector<CXXMethodDecl*, 4> WorkList;
13224     std::swap(DelayedDllExportMemberFunctions, WorkList);
13225     for (CXXMethodDecl *M : WorkList) {
13226       DefineDefaultedFunction(*this, M, M->getLocation());
13227 
13228       // Pass the method to the consumer to get emitted. This is not necessary
13229       // for explicit instantiation definitions, as they will get emitted
13230       // anyway.
13231       if (M->getParent()->getTemplateSpecializationKind() !=
13232           TSK_ExplicitInstantiationDefinition)
13233         ActOnFinishInlineFunctionDef(M);
13234     }
13235   }
13236 }
13237 
13238 void Sema::referenceDLLExportedClassMethods() {
13239   if (!DelayedDllExportClasses.empty()) {
13240     // Calling ReferenceDllExportedMembers might cause the current function to
13241     // be called again, so use a local copy of DelayedDllExportClasses.
13242     SmallVector<CXXRecordDecl *, 4> WorkList;
13243     std::swap(DelayedDllExportClasses, WorkList);
13244     for (CXXRecordDecl *Class : WorkList)
13245       ReferenceDllExportedMembers(*this, Class);
13246   }
13247 }
13248 
13249 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13250   assert(getLangOpts().CPlusPlus11 &&
13251          "adjusting dtor exception specs was introduced in c++11");
13252 
13253   if (Destructor->isDependentContext())
13254     return;
13255 
13256   // C++11 [class.dtor]p3:
13257   //   A declaration of a destructor that does not have an exception-
13258   //   specification is implicitly considered to have the same exception-
13259   //   specification as an implicit declaration.
13260   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13261   if (DtorType->hasExceptionSpec())
13262     return;
13263 
13264   // Replace the destructor's type, building off the existing one. Fortunately,
13265   // the only thing of interest in the destructor type is its extended info.
13266   // The return and arguments are fixed.
13267   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13268   EPI.ExceptionSpec.Type = EST_Unevaluated;
13269   EPI.ExceptionSpec.SourceDecl = Destructor;
13270   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13271 
13272   // FIXME: If the destructor has a body that could throw, and the newly created
13273   // spec doesn't allow exceptions, we should emit a warning, because this
13274   // change in behavior can break conforming C++03 programs at runtime.
13275   // However, we don't have a body or an exception specification yet, so it
13276   // needs to be done somewhere else.
13277 }
13278 
13279 namespace {
13280 /// An abstract base class for all helper classes used in building the
13281 //  copy/move operators. These classes serve as factory functions and help us
13282 //  avoid using the same Expr* in the AST twice.
13283 class ExprBuilder {
13284   ExprBuilder(const ExprBuilder&) = delete;
13285   ExprBuilder &operator=(const ExprBuilder&) = delete;
13286 
13287 protected:
13288   static Expr *assertNotNull(Expr *E) {
13289     assert(E && "Expression construction must not fail.");
13290     return E;
13291   }
13292 
13293 public:
13294   ExprBuilder() {}
13295   virtual ~ExprBuilder() {}
13296 
13297   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13298 };
13299 
13300 class RefBuilder: public ExprBuilder {
13301   VarDecl *Var;
13302   QualType VarType;
13303 
13304 public:
13305   Expr *build(Sema &S, SourceLocation Loc) const override {
13306     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13307   }
13308 
13309   RefBuilder(VarDecl *Var, QualType VarType)
13310       : Var(Var), VarType(VarType) {}
13311 };
13312 
13313 class ThisBuilder: public ExprBuilder {
13314 public:
13315   Expr *build(Sema &S, SourceLocation Loc) const override {
13316     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13317   }
13318 };
13319 
13320 class CastBuilder: public ExprBuilder {
13321   const ExprBuilder &Builder;
13322   QualType Type;
13323   ExprValueKind Kind;
13324   const CXXCastPath &Path;
13325 
13326 public:
13327   Expr *build(Sema &S, SourceLocation Loc) const override {
13328     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13329                                              CK_UncheckedDerivedToBase, Kind,
13330                                              &Path).get());
13331   }
13332 
13333   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13334               const CXXCastPath &Path)
13335       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13336 };
13337 
13338 class DerefBuilder: public ExprBuilder {
13339   const ExprBuilder &Builder;
13340 
13341 public:
13342   Expr *build(Sema &S, SourceLocation Loc) const override {
13343     return assertNotNull(
13344         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13345   }
13346 
13347   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13348 };
13349 
13350 class MemberBuilder: public ExprBuilder {
13351   const ExprBuilder &Builder;
13352   QualType Type;
13353   CXXScopeSpec SS;
13354   bool IsArrow;
13355   LookupResult &MemberLookup;
13356 
13357 public:
13358   Expr *build(Sema &S, SourceLocation Loc) const override {
13359     return assertNotNull(S.BuildMemberReferenceExpr(
13360         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13361         nullptr, MemberLookup, nullptr, nullptr).get());
13362   }
13363 
13364   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13365                 LookupResult &MemberLookup)
13366       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13367         MemberLookup(MemberLookup) {}
13368 };
13369 
13370 class MoveCastBuilder: public ExprBuilder {
13371   const ExprBuilder &Builder;
13372 
13373 public:
13374   Expr *build(Sema &S, SourceLocation Loc) const override {
13375     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13376   }
13377 
13378   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13379 };
13380 
13381 class LvalueConvBuilder: public ExprBuilder {
13382   const ExprBuilder &Builder;
13383 
13384 public:
13385   Expr *build(Sema &S, SourceLocation Loc) const override {
13386     return assertNotNull(
13387         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13388   }
13389 
13390   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13391 };
13392 
13393 class SubscriptBuilder: public ExprBuilder {
13394   const ExprBuilder &Base;
13395   const ExprBuilder &Index;
13396 
13397 public:
13398   Expr *build(Sema &S, SourceLocation Loc) const override {
13399     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13400         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13401   }
13402 
13403   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13404       : Base(Base), Index(Index) {}
13405 };
13406 
13407 } // end anonymous namespace
13408 
13409 /// When generating a defaulted copy or move assignment operator, if a field
13410 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13411 /// do so. This optimization only applies for arrays of scalars, and for arrays
13412 /// of class type where the selected copy/move-assignment operator is trivial.
13413 static StmtResult
13414 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13415                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13416   // Compute the size of the memory buffer to be copied.
13417   QualType SizeType = S.Context.getSizeType();
13418   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13419                    S.Context.getTypeSizeInChars(T).getQuantity());
13420 
13421   // Take the address of the field references for "from" and "to". We
13422   // directly construct UnaryOperators here because semantic analysis
13423   // does not permit us to take the address of an xvalue.
13424   Expr *From = FromB.build(S, Loc);
13425   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
13426                          S.Context.getPointerType(From->getType()),
13427                          VK_RValue, OK_Ordinary, Loc, false);
13428   Expr *To = ToB.build(S, Loc);
13429   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
13430                        S.Context.getPointerType(To->getType()),
13431                        VK_RValue, OK_Ordinary, Loc, false);
13432 
13433   const Type *E = T->getBaseElementTypeUnsafe();
13434   bool NeedsCollectableMemCpy =
13435       E->isRecordType() &&
13436       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13437 
13438   // Create a reference to the __builtin_objc_memmove_collectable function
13439   StringRef MemCpyName = NeedsCollectableMemCpy ?
13440     "__builtin_objc_memmove_collectable" :
13441     "__builtin_memcpy";
13442   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13443                  Sema::LookupOrdinaryName);
13444   S.LookupName(R, S.TUScope, true);
13445 
13446   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13447   if (!MemCpy)
13448     // Something went horribly wrong earlier, and we will have complained
13449     // about it.
13450     return StmtError();
13451 
13452   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13453                                             VK_RValue, Loc, nullptr);
13454   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13455 
13456   Expr *CallArgs[] = {
13457     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13458   };
13459   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13460                                     Loc, CallArgs, Loc);
13461 
13462   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13463   return Call.getAs<Stmt>();
13464 }
13465 
13466 /// Builds a statement that copies/moves the given entity from \p From to
13467 /// \c To.
13468 ///
13469 /// This routine is used to copy/move the members of a class with an
13470 /// implicitly-declared copy/move assignment operator. When the entities being
13471 /// copied are arrays, this routine builds for loops to copy them.
13472 ///
13473 /// \param S The Sema object used for type-checking.
13474 ///
13475 /// \param Loc The location where the implicit copy/move is being generated.
13476 ///
13477 /// \param T The type of the expressions being copied/moved. Both expressions
13478 /// must have this type.
13479 ///
13480 /// \param To The expression we are copying/moving to.
13481 ///
13482 /// \param From The expression we are copying/moving from.
13483 ///
13484 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13485 /// Otherwise, it's a non-static member subobject.
13486 ///
13487 /// \param Copying Whether we're copying or moving.
13488 ///
13489 /// \param Depth Internal parameter recording the depth of the recursion.
13490 ///
13491 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13492 /// if a memcpy should be used instead.
13493 static StmtResult
13494 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13495                                  const ExprBuilder &To, const ExprBuilder &From,
13496                                  bool CopyingBaseSubobject, bool Copying,
13497                                  unsigned Depth = 0) {
13498   // C++11 [class.copy]p28:
13499   //   Each subobject is assigned in the manner appropriate to its type:
13500   //
13501   //     - if the subobject is of class type, as if by a call to operator= with
13502   //       the subobject as the object expression and the corresponding
13503   //       subobject of x as a single function argument (as if by explicit
13504   //       qualification; that is, ignoring any possible virtual overriding
13505   //       functions in more derived classes);
13506   //
13507   // C++03 [class.copy]p13:
13508   //     - if the subobject is of class type, the copy assignment operator for
13509   //       the class is used (as if by explicit qualification; that is,
13510   //       ignoring any possible virtual overriding functions in more derived
13511   //       classes);
13512   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13513     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13514 
13515     // Look for operator=.
13516     DeclarationName Name
13517       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13518     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13519     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13520 
13521     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13522     // operator.
13523     if (!S.getLangOpts().CPlusPlus11) {
13524       LookupResult::Filter F = OpLookup.makeFilter();
13525       while (F.hasNext()) {
13526         NamedDecl *D = F.next();
13527         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13528           if (Method->isCopyAssignmentOperator() ||
13529               (!Copying && Method->isMoveAssignmentOperator()))
13530             continue;
13531 
13532         F.erase();
13533       }
13534       F.done();
13535     }
13536 
13537     // Suppress the protected check (C++ [class.protected]) for each of the
13538     // assignment operators we found. This strange dance is required when
13539     // we're assigning via a base classes's copy-assignment operator. To
13540     // ensure that we're getting the right base class subobject (without
13541     // ambiguities), we need to cast "this" to that subobject type; to
13542     // ensure that we don't go through the virtual call mechanism, we need
13543     // to qualify the operator= name with the base class (see below). However,
13544     // this means that if the base class has a protected copy assignment
13545     // operator, the protected member access check will fail. So, we
13546     // rewrite "protected" access to "public" access in this case, since we
13547     // know by construction that we're calling from a derived class.
13548     if (CopyingBaseSubobject) {
13549       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13550            L != LEnd; ++L) {
13551         if (L.getAccess() == AS_protected)
13552           L.setAccess(AS_public);
13553       }
13554     }
13555 
13556     // Create the nested-name-specifier that will be used to qualify the
13557     // reference to operator=; this is required to suppress the virtual
13558     // call mechanism.
13559     CXXScopeSpec SS;
13560     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13561     SS.MakeTrivial(S.Context,
13562                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13563                                                CanonicalT),
13564                    Loc);
13565 
13566     // Create the reference to operator=.
13567     ExprResult OpEqualRef
13568       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13569                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13570                                    /*FirstQualifierInScope=*/nullptr,
13571                                    OpLookup,
13572                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13573                                    /*SuppressQualifierCheck=*/true);
13574     if (OpEqualRef.isInvalid())
13575       return StmtError();
13576 
13577     // Build the call to the assignment operator.
13578 
13579     Expr *FromInst = From.build(S, Loc);
13580     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13581                                                   OpEqualRef.getAs<Expr>(),
13582                                                   Loc, FromInst, Loc);
13583     if (Call.isInvalid())
13584       return StmtError();
13585 
13586     // If we built a call to a trivial 'operator=' while copying an array,
13587     // bail out. We'll replace the whole shebang with a memcpy.
13588     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13589     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13590       return StmtResult((Stmt*)nullptr);
13591 
13592     // Convert to an expression-statement, and clean up any produced
13593     // temporaries.
13594     return S.ActOnExprStmt(Call);
13595   }
13596 
13597   //     - if the subobject is of scalar type, the built-in assignment
13598   //       operator is used.
13599   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13600   if (!ArrayTy) {
13601     ExprResult Assignment = S.CreateBuiltinBinOp(
13602         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13603     if (Assignment.isInvalid())
13604       return StmtError();
13605     return S.ActOnExprStmt(Assignment);
13606   }
13607 
13608   //     - if the subobject is an array, each element is assigned, in the
13609   //       manner appropriate to the element type;
13610 
13611   // Construct a loop over the array bounds, e.g.,
13612   //
13613   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13614   //
13615   // that will copy each of the array elements.
13616   QualType SizeType = S.Context.getSizeType();
13617 
13618   // Create the iteration variable.
13619   IdentifierInfo *IterationVarName = nullptr;
13620   {
13621     SmallString<8> Str;
13622     llvm::raw_svector_ostream OS(Str);
13623     OS << "__i" << Depth;
13624     IterationVarName = &S.Context.Idents.get(OS.str());
13625   }
13626   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13627                                           IterationVarName, SizeType,
13628                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13629                                           SC_None);
13630 
13631   // Initialize the iteration variable to zero.
13632   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13633   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13634 
13635   // Creates a reference to the iteration variable.
13636   RefBuilder IterationVarRef(IterationVar, SizeType);
13637   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13638 
13639   // Create the DeclStmt that holds the iteration variable.
13640   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13641 
13642   // Subscript the "from" and "to" expressions with the iteration variable.
13643   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13644   MoveCastBuilder FromIndexMove(FromIndexCopy);
13645   const ExprBuilder *FromIndex;
13646   if (Copying)
13647     FromIndex = &FromIndexCopy;
13648   else
13649     FromIndex = &FromIndexMove;
13650 
13651   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13652 
13653   // Build the copy/move for an individual element of the array.
13654   StmtResult Copy =
13655     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13656                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13657                                      Copying, Depth + 1);
13658   // Bail out if copying fails or if we determined that we should use memcpy.
13659   if (Copy.isInvalid() || !Copy.get())
13660     return Copy;
13661 
13662   // Create the comparison against the array bound.
13663   llvm::APInt Upper
13664     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13665   Expr *Comparison
13666     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
13667                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
13668                                      BO_NE, S.Context.BoolTy,
13669                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
13670 
13671   // Create the pre-increment of the iteration variable. We can determine
13672   // whether the increment will overflow based on the value of the array
13673   // bound.
13674   Expr *Increment = new (S.Context)
13675       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
13676                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
13677 
13678   // Construct the loop that copies all elements of this array.
13679   return S.ActOnForStmt(
13680       Loc, Loc, InitStmt,
13681       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13682       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13683 }
13684 
13685 static StmtResult
13686 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13687                       const ExprBuilder &To, const ExprBuilder &From,
13688                       bool CopyingBaseSubobject, bool Copying) {
13689   // Maybe we should use a memcpy?
13690   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13691       T.isTriviallyCopyableType(S.Context))
13692     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13693 
13694   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13695                                                      CopyingBaseSubobject,
13696                                                      Copying, 0));
13697 
13698   // If we ended up picking a trivial assignment operator for an array of a
13699   // non-trivially-copyable class type, just emit a memcpy.
13700   if (!Result.isInvalid() && !Result.get())
13701     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13702 
13703   return Result;
13704 }
13705 
13706 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13707   // Note: The following rules are largely analoguous to the copy
13708   // constructor rules. Note that virtual bases are not taken into account
13709   // for determining the argument type of the operator. Note also that
13710   // operators taking an object instead of a reference are allowed.
13711   assert(ClassDecl->needsImplicitCopyAssignment());
13712 
13713   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13714   if (DSM.isAlreadyBeingDeclared())
13715     return nullptr;
13716 
13717   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13718   LangAS AS = getDefaultCXXMethodAddrSpace();
13719   if (AS != LangAS::Default)
13720     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13721   QualType RetType = Context.getLValueReferenceType(ArgType);
13722   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13723   if (Const)
13724     ArgType = ArgType.withConst();
13725 
13726   ArgType = Context.getLValueReferenceType(ArgType);
13727 
13728   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13729                                                      CXXCopyAssignment,
13730                                                      Const);
13731 
13732   //   An implicitly-declared copy assignment operator is an inline public
13733   //   member of its class.
13734   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13735   SourceLocation ClassLoc = ClassDecl->getLocation();
13736   DeclarationNameInfo NameInfo(Name, ClassLoc);
13737   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13738       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13739       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13740       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13741       SourceLocation());
13742   CopyAssignment->setAccess(AS_public);
13743   CopyAssignment->setDefaulted();
13744   CopyAssignment->setImplicit();
13745 
13746   if (getLangOpts().CUDA) {
13747     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13748                                             CopyAssignment,
13749                                             /* ConstRHS */ Const,
13750                                             /* Diagnose */ false);
13751   }
13752 
13753   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13754 
13755   // Add the parameter to the operator.
13756   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13757                                                ClassLoc, ClassLoc,
13758                                                /*Id=*/nullptr, ArgType,
13759                                                /*TInfo=*/nullptr, SC_None,
13760                                                nullptr);
13761   CopyAssignment->setParams(FromParam);
13762 
13763   CopyAssignment->setTrivial(
13764     ClassDecl->needsOverloadResolutionForCopyAssignment()
13765       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13766       : ClassDecl->hasTrivialCopyAssignment());
13767 
13768   // Note that we have added this copy-assignment operator.
13769   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13770 
13771   Scope *S = getScopeForContext(ClassDecl);
13772   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13773 
13774   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
13775     SetDeclDeleted(CopyAssignment, ClassLoc);
13776 
13777   if (S)
13778     PushOnScopeChains(CopyAssignment, S, false);
13779   ClassDecl->addDecl(CopyAssignment);
13780 
13781   return CopyAssignment;
13782 }
13783 
13784 /// Diagnose an implicit copy operation for a class which is odr-used, but
13785 /// which is deprecated because the class has a user-declared copy constructor,
13786 /// copy assignment operator, or destructor.
13787 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13788   assert(CopyOp->isImplicit());
13789 
13790   CXXRecordDecl *RD = CopyOp->getParent();
13791   CXXMethodDecl *UserDeclaredOperation = nullptr;
13792 
13793   // In Microsoft mode, assignment operations don't affect constructors and
13794   // vice versa.
13795   if (RD->hasUserDeclaredDestructor()) {
13796     UserDeclaredOperation = RD->getDestructor();
13797   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13798              RD->hasUserDeclaredCopyConstructor() &&
13799              !S.getLangOpts().MSVCCompat) {
13800     // Find any user-declared copy constructor.
13801     for (auto *I : RD->ctors()) {
13802       if (I->isCopyConstructor()) {
13803         UserDeclaredOperation = I;
13804         break;
13805       }
13806     }
13807     assert(UserDeclaredOperation);
13808   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13809              RD->hasUserDeclaredCopyAssignment() &&
13810              !S.getLangOpts().MSVCCompat) {
13811     // Find any user-declared move assignment operator.
13812     for (auto *I : RD->methods()) {
13813       if (I->isCopyAssignmentOperator()) {
13814         UserDeclaredOperation = I;
13815         break;
13816       }
13817     }
13818     assert(UserDeclaredOperation);
13819   }
13820 
13821   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13822     S.Diag(UserDeclaredOperation->getLocation(),
13823            isa<CXXDestructorDecl>(UserDeclaredOperation)
13824                ? diag::warn_deprecated_copy_dtor_operation
13825                : diag::warn_deprecated_copy_operation)
13826         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13827   }
13828 }
13829 
13830 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13831                                         CXXMethodDecl *CopyAssignOperator) {
13832   assert((CopyAssignOperator->isDefaulted() &&
13833           CopyAssignOperator->isOverloadedOperator() &&
13834           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13835           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13836           !CopyAssignOperator->isDeleted()) &&
13837          "DefineImplicitCopyAssignment called for wrong function");
13838   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13839     return;
13840 
13841   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13842   if (ClassDecl->isInvalidDecl()) {
13843     CopyAssignOperator->setInvalidDecl();
13844     return;
13845   }
13846 
13847   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13848 
13849   // The exception specification is needed because we are defining the
13850   // function.
13851   ResolveExceptionSpec(CurrentLocation,
13852                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13853 
13854   // Add a context note for diagnostics produced after this point.
13855   Scope.addContextNote(CurrentLocation);
13856 
13857   // C++11 [class.copy]p18:
13858   //   The [definition of an implicitly declared copy assignment operator] is
13859   //   deprecated if the class has a user-declared copy constructor or a
13860   //   user-declared destructor.
13861   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13862     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13863 
13864   // C++0x [class.copy]p30:
13865   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13866   //   for a non-union class X performs memberwise copy assignment of its
13867   //   subobjects. The direct base classes of X are assigned first, in the
13868   //   order of their declaration in the base-specifier-list, and then the
13869   //   immediate non-static data members of X are assigned, in the order in
13870   //   which they were declared in the class definition.
13871 
13872   // The statements that form the synthesized function body.
13873   SmallVector<Stmt*, 8> Statements;
13874 
13875   // The parameter for the "other" object, which we are copying from.
13876   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13877   Qualifiers OtherQuals = Other->getType().getQualifiers();
13878   QualType OtherRefType = Other->getType();
13879   if (const LValueReferenceType *OtherRef
13880                                 = OtherRefType->getAs<LValueReferenceType>()) {
13881     OtherRefType = OtherRef->getPointeeType();
13882     OtherQuals = OtherRefType.getQualifiers();
13883   }
13884 
13885   // Our location for everything implicitly-generated.
13886   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
13887                            ? CopyAssignOperator->getEndLoc()
13888                            : CopyAssignOperator->getLocation();
13889 
13890   // Builds a DeclRefExpr for the "other" object.
13891   RefBuilder OtherRef(Other, OtherRefType);
13892 
13893   // Builds the "this" pointer.
13894   ThisBuilder This;
13895 
13896   // Assign base classes.
13897   bool Invalid = false;
13898   for (auto &Base : ClassDecl->bases()) {
13899     // Form the assignment:
13900     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
13901     QualType BaseType = Base.getType().getUnqualifiedType();
13902     if (!BaseType->isRecordType()) {
13903       Invalid = true;
13904       continue;
13905     }
13906 
13907     CXXCastPath BasePath;
13908     BasePath.push_back(&Base);
13909 
13910     // Construct the "from" expression, which is an implicit cast to the
13911     // appropriately-qualified base type.
13912     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
13913                      VK_LValue, BasePath);
13914 
13915     // Dereference "this".
13916     DerefBuilder DerefThis(This);
13917     CastBuilder To(DerefThis,
13918                    Context.getQualifiedType(
13919                        BaseType, CopyAssignOperator->getMethodQualifiers()),
13920                    VK_LValue, BasePath);
13921 
13922     // Build the copy.
13923     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
13924                                             To, From,
13925                                             /*CopyingBaseSubobject=*/true,
13926                                             /*Copying=*/true);
13927     if (Copy.isInvalid()) {
13928       CopyAssignOperator->setInvalidDecl();
13929       return;
13930     }
13931 
13932     // Success! Record the copy.
13933     Statements.push_back(Copy.getAs<Expr>());
13934   }
13935 
13936   // Assign non-static members.
13937   for (auto *Field : ClassDecl->fields()) {
13938     // FIXME: We should form some kind of AST representation for the implied
13939     // memcpy in a union copy operation.
13940     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
13941       continue;
13942 
13943     if (Field->isInvalidDecl()) {
13944       Invalid = true;
13945       continue;
13946     }
13947 
13948     // Check for members of reference type; we can't copy those.
13949     if (Field->getType()->isReferenceType()) {
13950       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
13951         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
13952       Diag(Field->getLocation(), diag::note_declared_at);
13953       Invalid = true;
13954       continue;
13955     }
13956 
13957     // Check for members of const-qualified, non-class type.
13958     QualType BaseType = Context.getBaseElementType(Field->getType());
13959     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
13960       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
13961         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
13962       Diag(Field->getLocation(), diag::note_declared_at);
13963       Invalid = true;
13964       continue;
13965     }
13966 
13967     // Suppress assigning zero-width bitfields.
13968     if (Field->isZeroLengthBitField(Context))
13969       continue;
13970 
13971     QualType FieldType = Field->getType().getNonReferenceType();
13972     if (FieldType->isIncompleteArrayType()) {
13973       assert(ClassDecl->hasFlexibleArrayMember() &&
13974              "Incomplete array type is not valid");
13975       continue;
13976     }
13977 
13978     // Build references to the field in the object we're copying from and to.
13979     CXXScopeSpec SS; // Intentionally empty
13980     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
13981                               LookupMemberName);
13982     MemberLookup.addDecl(Field);
13983     MemberLookup.resolveKind();
13984 
13985     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
13986 
13987     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
13988 
13989     // Build the copy of this field.
13990     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
13991                                             To, From,
13992                                             /*CopyingBaseSubobject=*/false,
13993                                             /*Copying=*/true);
13994     if (Copy.isInvalid()) {
13995       CopyAssignOperator->setInvalidDecl();
13996       return;
13997     }
13998 
13999     // Success! Record the copy.
14000     Statements.push_back(Copy.getAs<Stmt>());
14001   }
14002 
14003   if (!Invalid) {
14004     // Add a "return *this;"
14005     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14006 
14007     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14008     if (Return.isInvalid())
14009       Invalid = true;
14010     else
14011       Statements.push_back(Return.getAs<Stmt>());
14012   }
14013 
14014   if (Invalid) {
14015     CopyAssignOperator->setInvalidDecl();
14016     return;
14017   }
14018 
14019   StmtResult Body;
14020   {
14021     CompoundScopeRAII CompoundScope(*this);
14022     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14023                              /*isStmtExpr=*/false);
14024     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14025   }
14026   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14027   CopyAssignOperator->markUsed(Context);
14028 
14029   if (ASTMutationListener *L = getASTMutationListener()) {
14030     L->CompletedImplicitDefinition(CopyAssignOperator);
14031   }
14032 }
14033 
14034 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14035   assert(ClassDecl->needsImplicitMoveAssignment());
14036 
14037   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14038   if (DSM.isAlreadyBeingDeclared())
14039     return nullptr;
14040 
14041   // Note: The following rules are largely analoguous to the move
14042   // constructor rules.
14043 
14044   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14045   LangAS AS = getDefaultCXXMethodAddrSpace();
14046   if (AS != LangAS::Default)
14047     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14048   QualType RetType = Context.getLValueReferenceType(ArgType);
14049   ArgType = Context.getRValueReferenceType(ArgType);
14050 
14051   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14052                                                      CXXMoveAssignment,
14053                                                      false);
14054 
14055   //   An implicitly-declared move assignment operator is an inline public
14056   //   member of its class.
14057   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14058   SourceLocation ClassLoc = ClassDecl->getLocation();
14059   DeclarationNameInfo NameInfo(Name, ClassLoc);
14060   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14061       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14062       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14063       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14064       SourceLocation());
14065   MoveAssignment->setAccess(AS_public);
14066   MoveAssignment->setDefaulted();
14067   MoveAssignment->setImplicit();
14068 
14069   if (getLangOpts().CUDA) {
14070     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14071                                             MoveAssignment,
14072                                             /* ConstRHS */ false,
14073                                             /* Diagnose */ false);
14074   }
14075 
14076   // Build an exception specification pointing back at this member.
14077   FunctionProtoType::ExtProtoInfo EPI =
14078       getImplicitMethodEPI(*this, MoveAssignment);
14079   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14080 
14081   // Add the parameter to the operator.
14082   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14083                                                ClassLoc, ClassLoc,
14084                                                /*Id=*/nullptr, ArgType,
14085                                                /*TInfo=*/nullptr, SC_None,
14086                                                nullptr);
14087   MoveAssignment->setParams(FromParam);
14088 
14089   MoveAssignment->setTrivial(
14090     ClassDecl->needsOverloadResolutionForMoveAssignment()
14091       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14092       : ClassDecl->hasTrivialMoveAssignment());
14093 
14094   // Note that we have added this copy-assignment operator.
14095   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14096 
14097   Scope *S = getScopeForContext(ClassDecl);
14098   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14099 
14100   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14101     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14102     SetDeclDeleted(MoveAssignment, ClassLoc);
14103   }
14104 
14105   if (S)
14106     PushOnScopeChains(MoveAssignment, S, false);
14107   ClassDecl->addDecl(MoveAssignment);
14108 
14109   return MoveAssignment;
14110 }
14111 
14112 /// Check if we're implicitly defining a move assignment operator for a class
14113 /// with virtual bases. Such a move assignment might move-assign the virtual
14114 /// base multiple times.
14115 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14116                                                SourceLocation CurrentLocation) {
14117   assert(!Class->isDependentContext() && "should not define dependent move");
14118 
14119   // Only a virtual base could get implicitly move-assigned multiple times.
14120   // Only a non-trivial move assignment can observe this. We only want to
14121   // diagnose if we implicitly define an assignment operator that assigns
14122   // two base classes, both of which move-assign the same virtual base.
14123   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14124       Class->getNumBases() < 2)
14125     return;
14126 
14127   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14128   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14129   VBaseMap VBases;
14130 
14131   for (auto &BI : Class->bases()) {
14132     Worklist.push_back(&BI);
14133     while (!Worklist.empty()) {
14134       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14135       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14136 
14137       // If the base has no non-trivial move assignment operators,
14138       // we don't care about moves from it.
14139       if (!Base->hasNonTrivialMoveAssignment())
14140         continue;
14141 
14142       // If there's nothing virtual here, skip it.
14143       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14144         continue;
14145 
14146       // If we're not actually going to call a move assignment for this base,
14147       // or the selected move assignment is trivial, skip it.
14148       Sema::SpecialMemberOverloadResult SMOR =
14149         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14150                               /*ConstArg*/false, /*VolatileArg*/false,
14151                               /*RValueThis*/true, /*ConstThis*/false,
14152                               /*VolatileThis*/false);
14153       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14154           !SMOR.getMethod()->isMoveAssignmentOperator())
14155         continue;
14156 
14157       if (BaseSpec->isVirtual()) {
14158         // We're going to move-assign this virtual base, and its move
14159         // assignment operator is not trivial. If this can happen for
14160         // multiple distinct direct bases of Class, diagnose it. (If it
14161         // only happens in one base, we'll diagnose it when synthesizing
14162         // that base class's move assignment operator.)
14163         CXXBaseSpecifier *&Existing =
14164             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14165                 .first->second;
14166         if (Existing && Existing != &BI) {
14167           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14168             << Class << Base;
14169           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14170               << (Base->getCanonicalDecl() ==
14171                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14172               << Base << Existing->getType() << Existing->getSourceRange();
14173           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14174               << (Base->getCanonicalDecl() ==
14175                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14176               << Base << BI.getType() << BaseSpec->getSourceRange();
14177 
14178           // Only diagnose each vbase once.
14179           Existing = nullptr;
14180         }
14181       } else {
14182         // Only walk over bases that have defaulted move assignment operators.
14183         // We assume that any user-provided move assignment operator handles
14184         // the multiple-moves-of-vbase case itself somehow.
14185         if (!SMOR.getMethod()->isDefaulted())
14186           continue;
14187 
14188         // We're going to move the base classes of Base. Add them to the list.
14189         for (auto &BI : Base->bases())
14190           Worklist.push_back(&BI);
14191       }
14192     }
14193   }
14194 }
14195 
14196 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14197                                         CXXMethodDecl *MoveAssignOperator) {
14198   assert((MoveAssignOperator->isDefaulted() &&
14199           MoveAssignOperator->isOverloadedOperator() &&
14200           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14201           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14202           !MoveAssignOperator->isDeleted()) &&
14203          "DefineImplicitMoveAssignment called for wrong function");
14204   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14205     return;
14206 
14207   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14208   if (ClassDecl->isInvalidDecl()) {
14209     MoveAssignOperator->setInvalidDecl();
14210     return;
14211   }
14212 
14213   // C++0x [class.copy]p28:
14214   //   The implicitly-defined or move assignment operator for a non-union class
14215   //   X performs memberwise move assignment of its subobjects. The direct base
14216   //   classes of X are assigned first, in the order of their declaration in the
14217   //   base-specifier-list, and then the immediate non-static data members of X
14218   //   are assigned, in the order in which they were declared in the class
14219   //   definition.
14220 
14221   // Issue a warning if our implicit move assignment operator will move
14222   // from a virtual base more than once.
14223   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14224 
14225   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14226 
14227   // The exception specification is needed because we are defining the
14228   // function.
14229   ResolveExceptionSpec(CurrentLocation,
14230                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14231 
14232   // Add a context note for diagnostics produced after this point.
14233   Scope.addContextNote(CurrentLocation);
14234 
14235   // The statements that form the synthesized function body.
14236   SmallVector<Stmt*, 8> Statements;
14237 
14238   // The parameter for the "other" object, which we are move from.
14239   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14240   QualType OtherRefType =
14241       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14242 
14243   // Our location for everything implicitly-generated.
14244   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14245                            ? MoveAssignOperator->getEndLoc()
14246                            : MoveAssignOperator->getLocation();
14247 
14248   // Builds a reference to the "other" object.
14249   RefBuilder OtherRef(Other, OtherRefType);
14250   // Cast to rvalue.
14251   MoveCastBuilder MoveOther(OtherRef);
14252 
14253   // Builds the "this" pointer.
14254   ThisBuilder This;
14255 
14256   // Assign base classes.
14257   bool Invalid = false;
14258   for (auto &Base : ClassDecl->bases()) {
14259     // C++11 [class.copy]p28:
14260     //   It is unspecified whether subobjects representing virtual base classes
14261     //   are assigned more than once by the implicitly-defined copy assignment
14262     //   operator.
14263     // FIXME: Do not assign to a vbase that will be assigned by some other base
14264     // class. For a move-assignment, this can result in the vbase being moved
14265     // multiple times.
14266 
14267     // Form the assignment:
14268     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14269     QualType BaseType = Base.getType().getUnqualifiedType();
14270     if (!BaseType->isRecordType()) {
14271       Invalid = true;
14272       continue;
14273     }
14274 
14275     CXXCastPath BasePath;
14276     BasePath.push_back(&Base);
14277 
14278     // Construct the "from" expression, which is an implicit cast to the
14279     // appropriately-qualified base type.
14280     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14281 
14282     // Dereference "this".
14283     DerefBuilder DerefThis(This);
14284 
14285     // Implicitly cast "this" to the appropriately-qualified base type.
14286     CastBuilder To(DerefThis,
14287                    Context.getQualifiedType(
14288                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14289                    VK_LValue, BasePath);
14290 
14291     // Build the move.
14292     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14293                                             To, From,
14294                                             /*CopyingBaseSubobject=*/true,
14295                                             /*Copying=*/false);
14296     if (Move.isInvalid()) {
14297       MoveAssignOperator->setInvalidDecl();
14298       return;
14299     }
14300 
14301     // Success! Record the move.
14302     Statements.push_back(Move.getAs<Expr>());
14303   }
14304 
14305   // Assign non-static members.
14306   for (auto *Field : ClassDecl->fields()) {
14307     // FIXME: We should form some kind of AST representation for the implied
14308     // memcpy in a union copy operation.
14309     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14310       continue;
14311 
14312     if (Field->isInvalidDecl()) {
14313       Invalid = true;
14314       continue;
14315     }
14316 
14317     // Check for members of reference type; we can't move those.
14318     if (Field->getType()->isReferenceType()) {
14319       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14320         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14321       Diag(Field->getLocation(), diag::note_declared_at);
14322       Invalid = true;
14323       continue;
14324     }
14325 
14326     // Check for members of const-qualified, non-class type.
14327     QualType BaseType = Context.getBaseElementType(Field->getType());
14328     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14329       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14330         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14331       Diag(Field->getLocation(), diag::note_declared_at);
14332       Invalid = true;
14333       continue;
14334     }
14335 
14336     // Suppress assigning zero-width bitfields.
14337     if (Field->isZeroLengthBitField(Context))
14338       continue;
14339 
14340     QualType FieldType = Field->getType().getNonReferenceType();
14341     if (FieldType->isIncompleteArrayType()) {
14342       assert(ClassDecl->hasFlexibleArrayMember() &&
14343              "Incomplete array type is not valid");
14344       continue;
14345     }
14346 
14347     // Build references to the field in the object we're copying from and to.
14348     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14349                               LookupMemberName);
14350     MemberLookup.addDecl(Field);
14351     MemberLookup.resolveKind();
14352     MemberBuilder From(MoveOther, OtherRefType,
14353                        /*IsArrow=*/false, MemberLookup);
14354     MemberBuilder To(This, getCurrentThisType(),
14355                      /*IsArrow=*/true, MemberLookup);
14356 
14357     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14358         "Member reference with rvalue base must be rvalue except for reference "
14359         "members, which aren't allowed for move assignment.");
14360 
14361     // Build the move of this field.
14362     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14363                                             To, From,
14364                                             /*CopyingBaseSubobject=*/false,
14365                                             /*Copying=*/false);
14366     if (Move.isInvalid()) {
14367       MoveAssignOperator->setInvalidDecl();
14368       return;
14369     }
14370 
14371     // Success! Record the copy.
14372     Statements.push_back(Move.getAs<Stmt>());
14373   }
14374 
14375   if (!Invalid) {
14376     // Add a "return *this;"
14377     ExprResult ThisObj =
14378         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14379 
14380     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14381     if (Return.isInvalid())
14382       Invalid = true;
14383     else
14384       Statements.push_back(Return.getAs<Stmt>());
14385   }
14386 
14387   if (Invalid) {
14388     MoveAssignOperator->setInvalidDecl();
14389     return;
14390   }
14391 
14392   StmtResult Body;
14393   {
14394     CompoundScopeRAII CompoundScope(*this);
14395     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14396                              /*isStmtExpr=*/false);
14397     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14398   }
14399   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14400   MoveAssignOperator->markUsed(Context);
14401 
14402   if (ASTMutationListener *L = getASTMutationListener()) {
14403     L->CompletedImplicitDefinition(MoveAssignOperator);
14404   }
14405 }
14406 
14407 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14408                                                     CXXRecordDecl *ClassDecl) {
14409   // C++ [class.copy]p4:
14410   //   If the class definition does not explicitly declare a copy
14411   //   constructor, one is declared implicitly.
14412   assert(ClassDecl->needsImplicitCopyConstructor());
14413 
14414   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14415   if (DSM.isAlreadyBeingDeclared())
14416     return nullptr;
14417 
14418   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14419   QualType ArgType = ClassType;
14420   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14421   if (Const)
14422     ArgType = ArgType.withConst();
14423 
14424   LangAS AS = getDefaultCXXMethodAddrSpace();
14425   if (AS != LangAS::Default)
14426     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14427 
14428   ArgType = Context.getLValueReferenceType(ArgType);
14429 
14430   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14431                                                      CXXCopyConstructor,
14432                                                      Const);
14433 
14434   DeclarationName Name
14435     = Context.DeclarationNames.getCXXConstructorName(
14436                                            Context.getCanonicalType(ClassType));
14437   SourceLocation ClassLoc = ClassDecl->getLocation();
14438   DeclarationNameInfo NameInfo(Name, ClassLoc);
14439 
14440   //   An implicitly-declared copy constructor is an inline public
14441   //   member of its class.
14442   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14443       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14444       ExplicitSpecifier(),
14445       /*isInline=*/true,
14446       /*isImplicitlyDeclared=*/true,
14447       Constexpr ? CSK_constexpr : CSK_unspecified);
14448   CopyConstructor->setAccess(AS_public);
14449   CopyConstructor->setDefaulted();
14450 
14451   if (getLangOpts().CUDA) {
14452     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14453                                             CopyConstructor,
14454                                             /* ConstRHS */ Const,
14455                                             /* Diagnose */ false);
14456   }
14457 
14458   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14459 
14460   // Add the parameter to the constructor.
14461   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14462                                                ClassLoc, ClassLoc,
14463                                                /*IdentifierInfo=*/nullptr,
14464                                                ArgType, /*TInfo=*/nullptr,
14465                                                SC_None, nullptr);
14466   CopyConstructor->setParams(FromParam);
14467 
14468   CopyConstructor->setTrivial(
14469       ClassDecl->needsOverloadResolutionForCopyConstructor()
14470           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14471           : ClassDecl->hasTrivialCopyConstructor());
14472 
14473   CopyConstructor->setTrivialForCall(
14474       ClassDecl->hasAttr<TrivialABIAttr>() ||
14475       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14476            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14477              TAH_ConsiderTrivialABI)
14478            : ClassDecl->hasTrivialCopyConstructorForCall()));
14479 
14480   // Note that we have declared this constructor.
14481   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14482 
14483   Scope *S = getScopeForContext(ClassDecl);
14484   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14485 
14486   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14487     ClassDecl->setImplicitCopyConstructorIsDeleted();
14488     SetDeclDeleted(CopyConstructor, ClassLoc);
14489   }
14490 
14491   if (S)
14492     PushOnScopeChains(CopyConstructor, S, false);
14493   ClassDecl->addDecl(CopyConstructor);
14494 
14495   return CopyConstructor;
14496 }
14497 
14498 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14499                                          CXXConstructorDecl *CopyConstructor) {
14500   assert((CopyConstructor->isDefaulted() &&
14501           CopyConstructor->isCopyConstructor() &&
14502           !CopyConstructor->doesThisDeclarationHaveABody() &&
14503           !CopyConstructor->isDeleted()) &&
14504          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14505   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14506     return;
14507 
14508   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14509   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14510 
14511   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14512 
14513   // The exception specification is needed because we are defining the
14514   // function.
14515   ResolveExceptionSpec(CurrentLocation,
14516                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14517   MarkVTableUsed(CurrentLocation, ClassDecl);
14518 
14519   // Add a context note for diagnostics produced after this point.
14520   Scope.addContextNote(CurrentLocation);
14521 
14522   // C++11 [class.copy]p7:
14523   //   The [definition of an implicitly declared copy constructor] is
14524   //   deprecated if the class has a user-declared copy assignment operator
14525   //   or a user-declared destructor.
14526   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14527     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14528 
14529   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14530     CopyConstructor->setInvalidDecl();
14531   }  else {
14532     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14533                              ? CopyConstructor->getEndLoc()
14534                              : CopyConstructor->getLocation();
14535     Sema::CompoundScopeRAII CompoundScope(*this);
14536     CopyConstructor->setBody(
14537         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14538     CopyConstructor->markUsed(Context);
14539   }
14540 
14541   if (ASTMutationListener *L = getASTMutationListener()) {
14542     L->CompletedImplicitDefinition(CopyConstructor);
14543   }
14544 }
14545 
14546 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14547                                                     CXXRecordDecl *ClassDecl) {
14548   assert(ClassDecl->needsImplicitMoveConstructor());
14549 
14550   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14551   if (DSM.isAlreadyBeingDeclared())
14552     return nullptr;
14553 
14554   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14555 
14556   QualType ArgType = ClassType;
14557   LangAS AS = getDefaultCXXMethodAddrSpace();
14558   if (AS != LangAS::Default)
14559     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14560   ArgType = Context.getRValueReferenceType(ArgType);
14561 
14562   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14563                                                      CXXMoveConstructor,
14564                                                      false);
14565 
14566   DeclarationName Name
14567     = Context.DeclarationNames.getCXXConstructorName(
14568                                            Context.getCanonicalType(ClassType));
14569   SourceLocation ClassLoc = ClassDecl->getLocation();
14570   DeclarationNameInfo NameInfo(Name, ClassLoc);
14571 
14572   // C++11 [class.copy]p11:
14573   //   An implicitly-declared copy/move constructor is an inline public
14574   //   member of its class.
14575   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14576       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14577       ExplicitSpecifier(),
14578       /*isInline=*/true,
14579       /*isImplicitlyDeclared=*/true,
14580       Constexpr ? CSK_constexpr : CSK_unspecified);
14581   MoveConstructor->setAccess(AS_public);
14582   MoveConstructor->setDefaulted();
14583 
14584   if (getLangOpts().CUDA) {
14585     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14586                                             MoveConstructor,
14587                                             /* ConstRHS */ false,
14588                                             /* Diagnose */ false);
14589   }
14590 
14591   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14592 
14593   // Add the parameter to the constructor.
14594   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14595                                                ClassLoc, ClassLoc,
14596                                                /*IdentifierInfo=*/nullptr,
14597                                                ArgType, /*TInfo=*/nullptr,
14598                                                SC_None, nullptr);
14599   MoveConstructor->setParams(FromParam);
14600 
14601   MoveConstructor->setTrivial(
14602       ClassDecl->needsOverloadResolutionForMoveConstructor()
14603           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14604           : ClassDecl->hasTrivialMoveConstructor());
14605 
14606   MoveConstructor->setTrivialForCall(
14607       ClassDecl->hasAttr<TrivialABIAttr>() ||
14608       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14609            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14610                                     TAH_ConsiderTrivialABI)
14611            : ClassDecl->hasTrivialMoveConstructorForCall()));
14612 
14613   // Note that we have declared this constructor.
14614   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14615 
14616   Scope *S = getScopeForContext(ClassDecl);
14617   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14618 
14619   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14620     ClassDecl->setImplicitMoveConstructorIsDeleted();
14621     SetDeclDeleted(MoveConstructor, ClassLoc);
14622   }
14623 
14624   if (S)
14625     PushOnScopeChains(MoveConstructor, S, false);
14626   ClassDecl->addDecl(MoveConstructor);
14627 
14628   return MoveConstructor;
14629 }
14630 
14631 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14632                                          CXXConstructorDecl *MoveConstructor) {
14633   assert((MoveConstructor->isDefaulted() &&
14634           MoveConstructor->isMoveConstructor() &&
14635           !MoveConstructor->doesThisDeclarationHaveABody() &&
14636           !MoveConstructor->isDeleted()) &&
14637          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14638   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14639     return;
14640 
14641   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14642   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14643 
14644   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14645 
14646   // The exception specification is needed because we are defining the
14647   // function.
14648   ResolveExceptionSpec(CurrentLocation,
14649                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14650   MarkVTableUsed(CurrentLocation, ClassDecl);
14651 
14652   // Add a context note for diagnostics produced after this point.
14653   Scope.addContextNote(CurrentLocation);
14654 
14655   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14656     MoveConstructor->setInvalidDecl();
14657   } else {
14658     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14659                              ? MoveConstructor->getEndLoc()
14660                              : MoveConstructor->getLocation();
14661     Sema::CompoundScopeRAII CompoundScope(*this);
14662     MoveConstructor->setBody(ActOnCompoundStmt(
14663         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14664     MoveConstructor->markUsed(Context);
14665   }
14666 
14667   if (ASTMutationListener *L = getASTMutationListener()) {
14668     L->CompletedImplicitDefinition(MoveConstructor);
14669   }
14670 }
14671 
14672 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14673   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14674 }
14675 
14676 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14677                             SourceLocation CurrentLocation,
14678                             CXXConversionDecl *Conv) {
14679   SynthesizedFunctionScope Scope(*this, Conv);
14680   assert(!Conv->getReturnType()->isUndeducedType());
14681 
14682   CXXRecordDecl *Lambda = Conv->getParent();
14683   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14684   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14685 
14686   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14687     CallOp = InstantiateFunctionDeclaration(
14688         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14689     if (!CallOp)
14690       return;
14691 
14692     Invoker = InstantiateFunctionDeclaration(
14693         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14694     if (!Invoker)
14695       return;
14696   }
14697 
14698   if (CallOp->isInvalidDecl())
14699     return;
14700 
14701   // Mark the call operator referenced (and add to pending instantiations
14702   // if necessary).
14703   // For both the conversion and static-invoker template specializations
14704   // we construct their body's in this function, so no need to add them
14705   // to the PendingInstantiations.
14706   MarkFunctionReferenced(CurrentLocation, CallOp);
14707 
14708   // Fill in the __invoke function with a dummy implementation. IR generation
14709   // will fill in the actual details. Update its type in case it contained
14710   // an 'auto'.
14711   Invoker->markUsed(Context);
14712   Invoker->setReferenced();
14713   Invoker->setType(Conv->getReturnType()->getPointeeType());
14714   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14715 
14716   // Construct the body of the conversion function { return __invoke; }.
14717   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14718                                        VK_LValue, Conv->getLocation());
14719   assert(FunctionRef && "Can't refer to __invoke function?");
14720   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14721   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14722                                      Conv->getLocation()));
14723   Conv->markUsed(Context);
14724   Conv->setReferenced();
14725 
14726   if (ASTMutationListener *L = getASTMutationListener()) {
14727     L->CompletedImplicitDefinition(Conv);
14728     L->CompletedImplicitDefinition(Invoker);
14729   }
14730 }
14731 
14732 
14733 
14734 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14735        SourceLocation CurrentLocation,
14736        CXXConversionDecl *Conv)
14737 {
14738   assert(!Conv->getParent()->isGenericLambda());
14739 
14740   SynthesizedFunctionScope Scope(*this, Conv);
14741 
14742   // Copy-initialize the lambda object as needed to capture it.
14743   Expr *This = ActOnCXXThis(CurrentLocation).get();
14744   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14745 
14746   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14747                                                         Conv->getLocation(),
14748                                                         Conv, DerefThis);
14749 
14750   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14751   // behavior.  Note that only the general conversion function does this
14752   // (since it's unusable otherwise); in the case where we inline the
14753   // block literal, it has block literal lifetime semantics.
14754   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14755     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14756                                           CK_CopyAndAutoreleaseBlockObject,
14757                                           BuildBlock.get(), nullptr, VK_RValue);
14758 
14759   if (BuildBlock.isInvalid()) {
14760     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14761     Conv->setInvalidDecl();
14762     return;
14763   }
14764 
14765   // Create the return statement that returns the block from the conversion
14766   // function.
14767   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14768   if (Return.isInvalid()) {
14769     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14770     Conv->setInvalidDecl();
14771     return;
14772   }
14773 
14774   // Set the body of the conversion function.
14775   Stmt *ReturnS = Return.get();
14776   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14777                                      Conv->getLocation()));
14778   Conv->markUsed(Context);
14779 
14780   // We're done; notify the mutation listener, if any.
14781   if (ASTMutationListener *L = getASTMutationListener()) {
14782     L->CompletedImplicitDefinition(Conv);
14783   }
14784 }
14785 
14786 /// Determine whether the given list arguments contains exactly one
14787 /// "real" (non-default) argument.
14788 static bool hasOneRealArgument(MultiExprArg Args) {
14789   switch (Args.size()) {
14790   case 0:
14791     return false;
14792 
14793   default:
14794     if (!Args[1]->isDefaultArgument())
14795       return false;
14796 
14797     LLVM_FALLTHROUGH;
14798   case 1:
14799     return !Args[0]->isDefaultArgument();
14800   }
14801 
14802   return false;
14803 }
14804 
14805 ExprResult
14806 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14807                             NamedDecl *FoundDecl,
14808                             CXXConstructorDecl *Constructor,
14809                             MultiExprArg ExprArgs,
14810                             bool HadMultipleCandidates,
14811                             bool IsListInitialization,
14812                             bool IsStdInitListInitialization,
14813                             bool RequiresZeroInit,
14814                             unsigned ConstructKind,
14815                             SourceRange ParenRange) {
14816   bool Elidable = false;
14817 
14818   // C++0x [class.copy]p34:
14819   //   When certain criteria are met, an implementation is allowed to
14820   //   omit the copy/move construction of a class object, even if the
14821   //   copy/move constructor and/or destructor for the object have
14822   //   side effects. [...]
14823   //     - when a temporary class object that has not been bound to a
14824   //       reference (12.2) would be copied/moved to a class object
14825   //       with the same cv-unqualified type, the copy/move operation
14826   //       can be omitted by constructing the temporary object
14827   //       directly into the target of the omitted copy/move
14828   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14829       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14830     Expr *SubExpr = ExprArgs[0];
14831     Elidable = SubExpr->isTemporaryObject(
14832         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14833   }
14834 
14835   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14836                                FoundDecl, Constructor,
14837                                Elidable, ExprArgs, HadMultipleCandidates,
14838                                IsListInitialization,
14839                                IsStdInitListInitialization, RequiresZeroInit,
14840                                ConstructKind, ParenRange);
14841 }
14842 
14843 ExprResult
14844 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14845                             NamedDecl *FoundDecl,
14846                             CXXConstructorDecl *Constructor,
14847                             bool Elidable,
14848                             MultiExprArg ExprArgs,
14849                             bool HadMultipleCandidates,
14850                             bool IsListInitialization,
14851                             bool IsStdInitListInitialization,
14852                             bool RequiresZeroInit,
14853                             unsigned ConstructKind,
14854                             SourceRange ParenRange) {
14855   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14856     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14857     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14858       return ExprError();
14859   }
14860 
14861   return BuildCXXConstructExpr(
14862       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14863       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14864       RequiresZeroInit, ConstructKind, ParenRange);
14865 }
14866 
14867 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14868 /// including handling of its default argument expressions.
14869 ExprResult
14870 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14871                             CXXConstructorDecl *Constructor,
14872                             bool Elidable,
14873                             MultiExprArg ExprArgs,
14874                             bool HadMultipleCandidates,
14875                             bool IsListInitialization,
14876                             bool IsStdInitListInitialization,
14877                             bool RequiresZeroInit,
14878                             unsigned ConstructKind,
14879                             SourceRange ParenRange) {
14880   assert(declaresSameEntity(
14881              Constructor->getParent(),
14882              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14883          "given constructor for wrong type");
14884   MarkFunctionReferenced(ConstructLoc, Constructor);
14885   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
14886     return ExprError();
14887 
14888   return CheckForImmediateInvocation(
14889       CXXConstructExpr::Create(
14890           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
14891           HadMultipleCandidates, IsListInitialization,
14892           IsStdInitListInitialization, RequiresZeroInit,
14893           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
14894           ParenRange),
14895       Constructor);
14896 }
14897 
14898 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
14899   assert(Field->hasInClassInitializer());
14900 
14901   // If we already have the in-class initializer nothing needs to be done.
14902   if (Field->getInClassInitializer())
14903     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
14904 
14905   // If we might have already tried and failed to instantiate, don't try again.
14906   if (Field->isInvalidDecl())
14907     return ExprError();
14908 
14909   // Maybe we haven't instantiated the in-class initializer. Go check the
14910   // pattern FieldDecl to see if it has one.
14911   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
14912 
14913   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
14914     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
14915     DeclContext::lookup_result Lookup =
14916         ClassPattern->lookup(Field->getDeclName());
14917 
14918     // Lookup can return at most two results: the pattern for the field, or the
14919     // injected class name of the parent record. No other member can have the
14920     // same name as the field.
14921     // In modules mode, lookup can return multiple results (coming from
14922     // different modules).
14923     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
14924            "more than two lookup results for field name");
14925     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
14926     if (!Pattern) {
14927       assert(isa<CXXRecordDecl>(Lookup[0]) &&
14928              "cannot have other non-field member with same name");
14929       for (auto L : Lookup)
14930         if (isa<FieldDecl>(L)) {
14931           Pattern = cast<FieldDecl>(L);
14932           break;
14933         }
14934       assert(Pattern && "We must have set the Pattern!");
14935     }
14936 
14937     if (!Pattern->hasInClassInitializer() ||
14938         InstantiateInClassInitializer(Loc, Field, Pattern,
14939                                       getTemplateInstantiationArgs(Field))) {
14940       // Don't diagnose this again.
14941       Field->setInvalidDecl();
14942       return ExprError();
14943     }
14944     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
14945   }
14946 
14947   // DR1351:
14948   //   If the brace-or-equal-initializer of a non-static data member
14949   //   invokes a defaulted default constructor of its class or of an
14950   //   enclosing class in a potentially evaluated subexpression, the
14951   //   program is ill-formed.
14952   //
14953   // This resolution is unworkable: the exception specification of the
14954   // default constructor can be needed in an unevaluated context, in
14955   // particular, in the operand of a noexcept-expression, and we can be
14956   // unable to compute an exception specification for an enclosed class.
14957   //
14958   // Any attempt to resolve the exception specification of a defaulted default
14959   // constructor before the initializer is lexically complete will ultimately
14960   // come here at which point we can diagnose it.
14961   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
14962   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
14963       << OutermostClass << Field;
14964   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
14965   // Recover by marking the field invalid, unless we're in a SFINAE context.
14966   if (!isSFINAEContext())
14967     Field->setInvalidDecl();
14968   return ExprError();
14969 }
14970 
14971 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
14972   if (VD->isInvalidDecl()) return;
14973 
14974   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
14975   if (ClassDecl->isInvalidDecl()) return;
14976   if (ClassDecl->hasIrrelevantDestructor()) return;
14977   if (ClassDecl->isDependentContext()) return;
14978 
14979   if (VD->isNoDestroy(getASTContext()))
14980     return;
14981 
14982   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14983 
14984   // If this is an array, we'll require the destructor during initialization, so
14985   // we can skip over this. We still want to emit exit-time destructor warnings
14986   // though.
14987   if (!VD->getType()->isArrayType()) {
14988     MarkFunctionReferenced(VD->getLocation(), Destructor);
14989     CheckDestructorAccess(VD->getLocation(), Destructor,
14990                           PDiag(diag::err_access_dtor_var)
14991                               << VD->getDeclName() << VD->getType());
14992     DiagnoseUseOfDecl(Destructor, VD->getLocation());
14993   }
14994 
14995   if (Destructor->isTrivial()) return;
14996 
14997   // If the destructor is constexpr, check whether the variable has constant
14998   // destruction now.
14999   if (Destructor->isConstexpr()) {
15000     bool HasConstantInit = false;
15001     if (VD->getInit() && !VD->getInit()->isValueDependent())
15002       HasConstantInit = VD->evaluateValue();
15003     SmallVector<PartialDiagnosticAt, 8> Notes;
15004     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15005         HasConstantInit) {
15006       Diag(VD->getLocation(),
15007            diag::err_constexpr_var_requires_const_destruction) << VD;
15008       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15009         Diag(Notes[I].first, Notes[I].second);
15010     }
15011   }
15012 
15013   if (!VD->hasGlobalStorage()) return;
15014 
15015   // Emit warning for non-trivial dtor in global scope (a real global,
15016   // class-static, function-static).
15017   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15018 
15019   // TODO: this should be re-enabled for static locals by !CXAAtExit
15020   if (!VD->isStaticLocal())
15021     Diag(VD->getLocation(), diag::warn_global_destructor);
15022 }
15023 
15024 /// Given a constructor and the set of arguments provided for the
15025 /// constructor, convert the arguments and add any required default arguments
15026 /// to form a proper call to this constructor.
15027 ///
15028 /// \returns true if an error occurred, false otherwise.
15029 bool
15030 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15031                               MultiExprArg ArgsPtr,
15032                               SourceLocation Loc,
15033                               SmallVectorImpl<Expr*> &ConvertedArgs,
15034                               bool AllowExplicit,
15035                               bool IsListInitialization) {
15036   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15037   unsigned NumArgs = ArgsPtr.size();
15038   Expr **Args = ArgsPtr.data();
15039 
15040   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15041   unsigned NumParams = Proto->getNumParams();
15042 
15043   // If too few arguments are available, we'll fill in the rest with defaults.
15044   if (NumArgs < NumParams)
15045     ConvertedArgs.reserve(NumParams);
15046   else
15047     ConvertedArgs.reserve(NumArgs);
15048 
15049   VariadicCallType CallType =
15050     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15051   SmallVector<Expr *, 8> AllArgs;
15052   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15053                                         Proto, 0,
15054                                         llvm::makeArrayRef(Args, NumArgs),
15055                                         AllArgs,
15056                                         CallType, AllowExplicit,
15057                                         IsListInitialization);
15058   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15059 
15060   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15061 
15062   CheckConstructorCall(Constructor,
15063                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15064                        Proto, Loc);
15065 
15066   return Invalid;
15067 }
15068 
15069 static inline bool
15070 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15071                                        const FunctionDecl *FnDecl) {
15072   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15073   if (isa<NamespaceDecl>(DC)) {
15074     return SemaRef.Diag(FnDecl->getLocation(),
15075                         diag::err_operator_new_delete_declared_in_namespace)
15076       << FnDecl->getDeclName();
15077   }
15078 
15079   if (isa<TranslationUnitDecl>(DC) &&
15080       FnDecl->getStorageClass() == SC_Static) {
15081     return SemaRef.Diag(FnDecl->getLocation(),
15082                         diag::err_operator_new_delete_declared_static)
15083       << FnDecl->getDeclName();
15084   }
15085 
15086   return false;
15087 }
15088 
15089 static QualType
15090 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15091   QualType QTy = PtrTy->getPointeeType();
15092   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15093   return SemaRef.Context.getPointerType(QTy);
15094 }
15095 
15096 static inline bool
15097 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15098                             CanQualType ExpectedResultType,
15099                             CanQualType ExpectedFirstParamType,
15100                             unsigned DependentParamTypeDiag,
15101                             unsigned InvalidParamTypeDiag) {
15102   QualType ResultType =
15103       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15104 
15105   // Check that the result type is not dependent.
15106   if (ResultType->isDependentType())
15107     return SemaRef.Diag(FnDecl->getLocation(),
15108                         diag::err_operator_new_delete_dependent_result_type)
15109     << FnDecl->getDeclName() << ExpectedResultType;
15110 
15111   // The operator is valid on any address space for OpenCL.
15112   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15113     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15114       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15115     }
15116   }
15117 
15118   // Check that the result type is what we expect.
15119   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
15120     return SemaRef.Diag(FnDecl->getLocation(),
15121                         diag::err_operator_new_delete_invalid_result_type)
15122     << FnDecl->getDeclName() << ExpectedResultType;
15123 
15124   // A function template must have at least 2 parameters.
15125   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15126     return SemaRef.Diag(FnDecl->getLocation(),
15127                       diag::err_operator_new_delete_template_too_few_parameters)
15128         << FnDecl->getDeclName();
15129 
15130   // The function decl must have at least 1 parameter.
15131   if (FnDecl->getNumParams() == 0)
15132     return SemaRef.Diag(FnDecl->getLocation(),
15133                         diag::err_operator_new_delete_too_few_parameters)
15134       << FnDecl->getDeclName();
15135 
15136   // Check the first parameter type is not dependent.
15137   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15138   if (FirstParamType->isDependentType())
15139     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
15140       << FnDecl->getDeclName() << ExpectedFirstParamType;
15141 
15142   // Check that the first parameter type is what we expect.
15143   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15144     // The operator is valid on any address space for OpenCL.
15145     if (auto *PtrTy =
15146             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15147       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15148     }
15149   }
15150   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15151       ExpectedFirstParamType)
15152     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
15153     << FnDecl->getDeclName() << ExpectedFirstParamType;
15154 
15155   return false;
15156 }
15157 
15158 static bool
15159 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15160   // C++ [basic.stc.dynamic.allocation]p1:
15161   //   A program is ill-formed if an allocation function is declared in a
15162   //   namespace scope other than global scope or declared static in global
15163   //   scope.
15164   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15165     return true;
15166 
15167   CanQualType SizeTy =
15168     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15169 
15170   // C++ [basic.stc.dynamic.allocation]p1:
15171   //  The return type shall be void*. The first parameter shall have type
15172   //  std::size_t.
15173   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15174                                   SizeTy,
15175                                   diag::err_operator_new_dependent_param_type,
15176                                   diag::err_operator_new_param_type))
15177     return true;
15178 
15179   // C++ [basic.stc.dynamic.allocation]p1:
15180   //  The first parameter shall not have an associated default argument.
15181   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15182     return SemaRef.Diag(FnDecl->getLocation(),
15183                         diag::err_operator_new_default_arg)
15184       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15185 
15186   return false;
15187 }
15188 
15189 static bool
15190 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15191   // C++ [basic.stc.dynamic.deallocation]p1:
15192   //   A program is ill-formed if deallocation functions are declared in a
15193   //   namespace scope other than global scope or declared static in global
15194   //   scope.
15195   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15196     return true;
15197 
15198   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15199 
15200   // C++ P0722:
15201   //   Within a class C, the first parameter of a destroying operator delete
15202   //   shall be of type C *. The first parameter of any other deallocation
15203   //   function shall be of type void *.
15204   CanQualType ExpectedFirstParamType =
15205       MD && MD->isDestroyingOperatorDelete()
15206           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15207                 SemaRef.Context.getRecordType(MD->getParent())))
15208           : SemaRef.Context.VoidPtrTy;
15209 
15210   // C++ [basic.stc.dynamic.deallocation]p2:
15211   //   Each deallocation function shall return void
15212   if (CheckOperatorNewDeleteTypes(
15213           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15214           diag::err_operator_delete_dependent_param_type,
15215           diag::err_operator_delete_param_type))
15216     return true;
15217 
15218   // C++ P0722:
15219   //   A destroying operator delete shall be a usual deallocation function.
15220   if (MD && !MD->getParent()->isDependentContext() &&
15221       MD->isDestroyingOperatorDelete() &&
15222       !SemaRef.isUsualDeallocationFunction(MD)) {
15223     SemaRef.Diag(MD->getLocation(),
15224                  diag::err_destroying_operator_delete_not_usual);
15225     return true;
15226   }
15227 
15228   return false;
15229 }
15230 
15231 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15232 /// of this overloaded operator is well-formed. If so, returns false;
15233 /// otherwise, emits appropriate diagnostics and returns true.
15234 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15235   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15236          "Expected an overloaded operator declaration");
15237 
15238   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15239 
15240   // C++ [over.oper]p5:
15241   //   The allocation and deallocation functions, operator new,
15242   //   operator new[], operator delete and operator delete[], are
15243   //   described completely in 3.7.3. The attributes and restrictions
15244   //   found in the rest of this subclause do not apply to them unless
15245   //   explicitly stated in 3.7.3.
15246   if (Op == OO_Delete || Op == OO_Array_Delete)
15247     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15248 
15249   if (Op == OO_New || Op == OO_Array_New)
15250     return CheckOperatorNewDeclaration(*this, FnDecl);
15251 
15252   // C++ [over.oper]p6:
15253   //   An operator function shall either be a non-static member
15254   //   function or be a non-member function and have at least one
15255   //   parameter whose type is a class, a reference to a class, an
15256   //   enumeration, or a reference to an enumeration.
15257   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15258     if (MethodDecl->isStatic())
15259       return Diag(FnDecl->getLocation(),
15260                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15261   } else {
15262     bool ClassOrEnumParam = false;
15263     for (auto Param : FnDecl->parameters()) {
15264       QualType ParamType = Param->getType().getNonReferenceType();
15265       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15266           ParamType->isEnumeralType()) {
15267         ClassOrEnumParam = true;
15268         break;
15269       }
15270     }
15271 
15272     if (!ClassOrEnumParam)
15273       return Diag(FnDecl->getLocation(),
15274                   diag::err_operator_overload_needs_class_or_enum)
15275         << FnDecl->getDeclName();
15276   }
15277 
15278   // C++ [over.oper]p8:
15279   //   An operator function cannot have default arguments (8.3.6),
15280   //   except where explicitly stated below.
15281   //
15282   // Only the function-call operator allows default arguments
15283   // (C++ [over.call]p1).
15284   if (Op != OO_Call) {
15285     for (auto Param : FnDecl->parameters()) {
15286       if (Param->hasDefaultArg())
15287         return Diag(Param->getLocation(),
15288                     diag::err_operator_overload_default_arg)
15289           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15290     }
15291   }
15292 
15293   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15294     { false, false, false }
15295 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15296     , { Unary, Binary, MemberOnly }
15297 #include "clang/Basic/OperatorKinds.def"
15298   };
15299 
15300   bool CanBeUnaryOperator = OperatorUses[Op][0];
15301   bool CanBeBinaryOperator = OperatorUses[Op][1];
15302   bool MustBeMemberOperator = OperatorUses[Op][2];
15303 
15304   // C++ [over.oper]p8:
15305   //   [...] Operator functions cannot have more or fewer parameters
15306   //   than the number required for the corresponding operator, as
15307   //   described in the rest of this subclause.
15308   unsigned NumParams = FnDecl->getNumParams()
15309                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15310   if (Op != OO_Call &&
15311       ((NumParams == 1 && !CanBeUnaryOperator) ||
15312        (NumParams == 2 && !CanBeBinaryOperator) ||
15313        (NumParams < 1) || (NumParams > 2))) {
15314     // We have the wrong number of parameters.
15315     unsigned ErrorKind;
15316     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15317       ErrorKind = 2;  // 2 -> unary or binary.
15318     } else if (CanBeUnaryOperator) {
15319       ErrorKind = 0;  // 0 -> unary
15320     } else {
15321       assert(CanBeBinaryOperator &&
15322              "All non-call overloaded operators are unary or binary!");
15323       ErrorKind = 1;  // 1 -> binary
15324     }
15325 
15326     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15327       << FnDecl->getDeclName() << NumParams << ErrorKind;
15328   }
15329 
15330   // Overloaded operators other than operator() cannot be variadic.
15331   if (Op != OO_Call &&
15332       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15333     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15334       << FnDecl->getDeclName();
15335   }
15336 
15337   // Some operators must be non-static member functions.
15338   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15339     return Diag(FnDecl->getLocation(),
15340                 diag::err_operator_overload_must_be_member)
15341       << FnDecl->getDeclName();
15342   }
15343 
15344   // C++ [over.inc]p1:
15345   //   The user-defined function called operator++ implements the
15346   //   prefix and postfix ++ operator. If this function is a member
15347   //   function with no parameters, or a non-member function with one
15348   //   parameter of class or enumeration type, it defines the prefix
15349   //   increment operator ++ for objects of that type. If the function
15350   //   is a member function with one parameter (which shall be of type
15351   //   int) or a non-member function with two parameters (the second
15352   //   of which shall be of type int), it defines the postfix
15353   //   increment operator ++ for objects of that type.
15354   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15355     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15356     QualType ParamType = LastParam->getType();
15357 
15358     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15359         !ParamType->isDependentType())
15360       return Diag(LastParam->getLocation(),
15361                   diag::err_operator_overload_post_incdec_must_be_int)
15362         << LastParam->getType() << (Op == OO_MinusMinus);
15363   }
15364 
15365   return false;
15366 }
15367 
15368 static bool
15369 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15370                                           FunctionTemplateDecl *TpDecl) {
15371   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15372 
15373   // Must have one or two template parameters.
15374   if (TemplateParams->size() == 1) {
15375     NonTypeTemplateParmDecl *PmDecl =
15376         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15377 
15378     // The template parameter must be a char parameter pack.
15379     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15380         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15381       return false;
15382 
15383   } else if (TemplateParams->size() == 2) {
15384     TemplateTypeParmDecl *PmType =
15385         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15386     NonTypeTemplateParmDecl *PmArgs =
15387         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15388 
15389     // The second template parameter must be a parameter pack with the
15390     // first template parameter as its type.
15391     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15392         PmArgs->isTemplateParameterPack()) {
15393       const TemplateTypeParmType *TArgs =
15394           PmArgs->getType()->getAs<TemplateTypeParmType>();
15395       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15396           TArgs->getIndex() == PmType->getIndex()) {
15397         if (!SemaRef.inTemplateInstantiation())
15398           SemaRef.Diag(TpDecl->getLocation(),
15399                        diag::ext_string_literal_operator_template);
15400         return false;
15401       }
15402     }
15403   }
15404 
15405   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15406                diag::err_literal_operator_template)
15407       << TpDecl->getTemplateParameters()->getSourceRange();
15408   return true;
15409 }
15410 
15411 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15412 /// of this literal operator function is well-formed. If so, returns
15413 /// false; otherwise, emits appropriate diagnostics and returns true.
15414 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15415   if (isa<CXXMethodDecl>(FnDecl)) {
15416     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15417       << FnDecl->getDeclName();
15418     return true;
15419   }
15420 
15421   if (FnDecl->isExternC()) {
15422     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15423     if (const LinkageSpecDecl *LSD =
15424             FnDecl->getDeclContext()->getExternCContext())
15425       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15426     return true;
15427   }
15428 
15429   // This might be the definition of a literal operator template.
15430   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15431 
15432   // This might be a specialization of a literal operator template.
15433   if (!TpDecl)
15434     TpDecl = FnDecl->getPrimaryTemplate();
15435 
15436   // template <char...> type operator "" name() and
15437   // template <class T, T...> type operator "" name() are the only valid
15438   // template signatures, and the only valid signatures with no parameters.
15439   if (TpDecl) {
15440     if (FnDecl->param_size() != 0) {
15441       Diag(FnDecl->getLocation(),
15442            diag::err_literal_operator_template_with_params);
15443       return true;
15444     }
15445 
15446     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15447       return true;
15448 
15449   } else if (FnDecl->param_size() == 1) {
15450     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15451 
15452     QualType ParamType = Param->getType().getUnqualifiedType();
15453 
15454     // Only unsigned long long int, long double, any character type, and const
15455     // char * are allowed as the only parameters.
15456     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15457         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15458         Context.hasSameType(ParamType, Context.CharTy) ||
15459         Context.hasSameType(ParamType, Context.WideCharTy) ||
15460         Context.hasSameType(ParamType, Context.Char8Ty) ||
15461         Context.hasSameType(ParamType, Context.Char16Ty) ||
15462         Context.hasSameType(ParamType, Context.Char32Ty)) {
15463     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15464       QualType InnerType = Ptr->getPointeeType();
15465 
15466       // Pointer parameter must be a const char *.
15467       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15468                                 Context.CharTy) &&
15469             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15470         Diag(Param->getSourceRange().getBegin(),
15471              diag::err_literal_operator_param)
15472             << ParamType << "'const char *'" << Param->getSourceRange();
15473         return true;
15474       }
15475 
15476     } else if (ParamType->isRealFloatingType()) {
15477       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15478           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15479       return true;
15480 
15481     } else if (ParamType->isIntegerType()) {
15482       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15483           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15484       return true;
15485 
15486     } else {
15487       Diag(Param->getSourceRange().getBegin(),
15488            diag::err_literal_operator_invalid_param)
15489           << ParamType << Param->getSourceRange();
15490       return true;
15491     }
15492 
15493   } else if (FnDecl->param_size() == 2) {
15494     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15495 
15496     // First, verify that the first parameter is correct.
15497 
15498     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15499 
15500     // Two parameter function must have a pointer to const as a
15501     // first parameter; let's strip those qualifiers.
15502     const PointerType *PT = FirstParamType->getAs<PointerType>();
15503 
15504     if (!PT) {
15505       Diag((*Param)->getSourceRange().getBegin(),
15506            diag::err_literal_operator_param)
15507           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15508       return true;
15509     }
15510 
15511     QualType PointeeType = PT->getPointeeType();
15512     // First parameter must be const
15513     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15514       Diag((*Param)->getSourceRange().getBegin(),
15515            diag::err_literal_operator_param)
15516           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15517       return true;
15518     }
15519 
15520     QualType InnerType = PointeeType.getUnqualifiedType();
15521     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15522     // const char32_t* are allowed as the first parameter to a two-parameter
15523     // function
15524     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15525           Context.hasSameType(InnerType, Context.WideCharTy) ||
15526           Context.hasSameType(InnerType, Context.Char8Ty) ||
15527           Context.hasSameType(InnerType, Context.Char16Ty) ||
15528           Context.hasSameType(InnerType, Context.Char32Ty))) {
15529       Diag((*Param)->getSourceRange().getBegin(),
15530            diag::err_literal_operator_param)
15531           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15532       return true;
15533     }
15534 
15535     // Move on to the second and final parameter.
15536     ++Param;
15537 
15538     // The second parameter must be a std::size_t.
15539     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15540     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15541       Diag((*Param)->getSourceRange().getBegin(),
15542            diag::err_literal_operator_param)
15543           << SecondParamType << Context.getSizeType()
15544           << (*Param)->getSourceRange();
15545       return true;
15546     }
15547   } else {
15548     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15549     return true;
15550   }
15551 
15552   // Parameters are good.
15553 
15554   // A parameter-declaration-clause containing a default argument is not
15555   // equivalent to any of the permitted forms.
15556   for (auto Param : FnDecl->parameters()) {
15557     if (Param->hasDefaultArg()) {
15558       Diag(Param->getDefaultArgRange().getBegin(),
15559            diag::err_literal_operator_default_argument)
15560         << Param->getDefaultArgRange();
15561       break;
15562     }
15563   }
15564 
15565   StringRef LiteralName
15566     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15567   if (LiteralName[0] != '_' &&
15568       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15569     // C++11 [usrlit.suffix]p1:
15570     //   Literal suffix identifiers that do not start with an underscore
15571     //   are reserved for future standardization.
15572     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15573       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15574   }
15575 
15576   return false;
15577 }
15578 
15579 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15580 /// linkage specification, including the language and (if present)
15581 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15582 /// language string literal. LBraceLoc, if valid, provides the location of
15583 /// the '{' brace. Otherwise, this linkage specification does not
15584 /// have any braces.
15585 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15586                                            Expr *LangStr,
15587                                            SourceLocation LBraceLoc) {
15588   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15589   if (!Lit->isAscii()) {
15590     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15591       << LangStr->getSourceRange();
15592     return nullptr;
15593   }
15594 
15595   StringRef Lang = Lit->getString();
15596   LinkageSpecDecl::LanguageIDs Language;
15597   if (Lang == "C")
15598     Language = LinkageSpecDecl::lang_c;
15599   else if (Lang == "C++")
15600     Language = LinkageSpecDecl::lang_cxx;
15601   else {
15602     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15603       << LangStr->getSourceRange();
15604     return nullptr;
15605   }
15606 
15607   // FIXME: Add all the various semantics of linkage specifications
15608 
15609   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15610                                                LangStr->getExprLoc(), Language,
15611                                                LBraceLoc.isValid());
15612   CurContext->addDecl(D);
15613   PushDeclContext(S, D);
15614   return D;
15615 }
15616 
15617 /// ActOnFinishLinkageSpecification - Complete the definition of
15618 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15619 /// valid, it's the position of the closing '}' brace in a linkage
15620 /// specification that uses braces.
15621 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15622                                             Decl *LinkageSpec,
15623                                             SourceLocation RBraceLoc) {
15624   if (RBraceLoc.isValid()) {
15625     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15626     LSDecl->setRBraceLoc(RBraceLoc);
15627   }
15628   PopDeclContext();
15629   return LinkageSpec;
15630 }
15631 
15632 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15633                                   const ParsedAttributesView &AttrList,
15634                                   SourceLocation SemiLoc) {
15635   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15636   // Attribute declarations appertain to empty declaration so we handle
15637   // them here.
15638   ProcessDeclAttributeList(S, ED, AttrList);
15639 
15640   CurContext->addDecl(ED);
15641   return ED;
15642 }
15643 
15644 /// Perform semantic analysis for the variable declaration that
15645 /// occurs within a C++ catch clause, returning the newly-created
15646 /// variable.
15647 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15648                                          TypeSourceInfo *TInfo,
15649                                          SourceLocation StartLoc,
15650                                          SourceLocation Loc,
15651                                          IdentifierInfo *Name) {
15652   bool Invalid = false;
15653   QualType ExDeclType = TInfo->getType();
15654 
15655   // Arrays and functions decay.
15656   if (ExDeclType->isArrayType())
15657     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15658   else if (ExDeclType->isFunctionType())
15659     ExDeclType = Context.getPointerType(ExDeclType);
15660 
15661   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15662   // The exception-declaration shall not denote a pointer or reference to an
15663   // incomplete type, other than [cv] void*.
15664   // N2844 forbids rvalue references.
15665   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15666     Diag(Loc, diag::err_catch_rvalue_ref);
15667     Invalid = true;
15668   }
15669 
15670   if (ExDeclType->isVariablyModifiedType()) {
15671     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15672     Invalid = true;
15673   }
15674 
15675   QualType BaseType = ExDeclType;
15676   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15677   unsigned DK = diag::err_catch_incomplete;
15678   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15679     BaseType = Ptr->getPointeeType();
15680     Mode = 1;
15681     DK = diag::err_catch_incomplete_ptr;
15682   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15683     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15684     BaseType = Ref->getPointeeType();
15685     Mode = 2;
15686     DK = diag::err_catch_incomplete_ref;
15687   }
15688   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15689       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15690     Invalid = true;
15691 
15692   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15693     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15694     Invalid = true;
15695   }
15696 
15697   if (!Invalid && !ExDeclType->isDependentType() &&
15698       RequireNonAbstractType(Loc, ExDeclType,
15699                              diag::err_abstract_type_in_decl,
15700                              AbstractVariableType))
15701     Invalid = true;
15702 
15703   // Only the non-fragile NeXT runtime currently supports C++ catches
15704   // of ObjC types, and no runtime supports catching ObjC types by value.
15705   if (!Invalid && getLangOpts().ObjC) {
15706     QualType T = ExDeclType;
15707     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15708       T = RT->getPointeeType();
15709 
15710     if (T->isObjCObjectType()) {
15711       Diag(Loc, diag::err_objc_object_catch);
15712       Invalid = true;
15713     } else if (T->isObjCObjectPointerType()) {
15714       // FIXME: should this be a test for macosx-fragile specifically?
15715       if (getLangOpts().ObjCRuntime.isFragile())
15716         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15717     }
15718   }
15719 
15720   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15721                                     ExDeclType, TInfo, SC_None);
15722   ExDecl->setExceptionVariable(true);
15723 
15724   // In ARC, infer 'retaining' for variables of retainable type.
15725   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15726     Invalid = true;
15727 
15728   if (!Invalid && !ExDeclType->isDependentType()) {
15729     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15730       // Insulate this from anything else we might currently be parsing.
15731       EnterExpressionEvaluationContext scope(
15732           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15733 
15734       // C++ [except.handle]p16:
15735       //   The object declared in an exception-declaration or, if the
15736       //   exception-declaration does not specify a name, a temporary (12.2) is
15737       //   copy-initialized (8.5) from the exception object. [...]
15738       //   The object is destroyed when the handler exits, after the destruction
15739       //   of any automatic objects initialized within the handler.
15740       //
15741       // We just pretend to initialize the object with itself, then make sure
15742       // it can be destroyed later.
15743       QualType initType = Context.getExceptionObjectType(ExDeclType);
15744 
15745       InitializedEntity entity =
15746         InitializedEntity::InitializeVariable(ExDecl);
15747       InitializationKind initKind =
15748         InitializationKind::CreateCopy(Loc, SourceLocation());
15749 
15750       Expr *opaqueValue =
15751         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15752       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15753       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15754       if (result.isInvalid())
15755         Invalid = true;
15756       else {
15757         // If the constructor used was non-trivial, set this as the
15758         // "initializer".
15759         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15760         if (!construct->getConstructor()->isTrivial()) {
15761           Expr *init = MaybeCreateExprWithCleanups(construct);
15762           ExDecl->setInit(init);
15763         }
15764 
15765         // And make sure it's destructable.
15766         FinalizeVarWithDestructor(ExDecl, recordType);
15767       }
15768     }
15769   }
15770 
15771   if (Invalid)
15772     ExDecl->setInvalidDecl();
15773 
15774   return ExDecl;
15775 }
15776 
15777 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15778 /// handler.
15779 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15780   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15781   bool Invalid = D.isInvalidType();
15782 
15783   // Check for unexpanded parameter packs.
15784   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15785                                       UPPC_ExceptionType)) {
15786     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15787                                              D.getIdentifierLoc());
15788     Invalid = true;
15789   }
15790 
15791   IdentifierInfo *II = D.getIdentifier();
15792   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15793                                              LookupOrdinaryName,
15794                                              ForVisibleRedeclaration)) {
15795     // The scope should be freshly made just for us. There is just no way
15796     // it contains any previous declaration, except for function parameters in
15797     // a function-try-block's catch statement.
15798     assert(!S->isDeclScope(PrevDecl));
15799     if (isDeclInScope(PrevDecl, CurContext, S)) {
15800       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15801         << D.getIdentifier();
15802       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15803       Invalid = true;
15804     } else if (PrevDecl->isTemplateParameter())
15805       // Maybe we will complain about the shadowed template parameter.
15806       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15807   }
15808 
15809   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15810     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15811       << D.getCXXScopeSpec().getRange();
15812     Invalid = true;
15813   }
15814 
15815   VarDecl *ExDecl = BuildExceptionDeclaration(
15816       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15817   if (Invalid)
15818     ExDecl->setInvalidDecl();
15819 
15820   // Add the exception declaration into this scope.
15821   if (II)
15822     PushOnScopeChains(ExDecl, S);
15823   else
15824     CurContext->addDecl(ExDecl);
15825 
15826   ProcessDeclAttributes(S, ExDecl, D);
15827   return ExDecl;
15828 }
15829 
15830 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15831                                          Expr *AssertExpr,
15832                                          Expr *AssertMessageExpr,
15833                                          SourceLocation RParenLoc) {
15834   StringLiteral *AssertMessage =
15835       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15836 
15837   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15838     return nullptr;
15839 
15840   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15841                                       AssertMessage, RParenLoc, false);
15842 }
15843 
15844 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15845                                          Expr *AssertExpr,
15846                                          StringLiteral *AssertMessage,
15847                                          SourceLocation RParenLoc,
15848                                          bool Failed) {
15849   assert(AssertExpr != nullptr && "Expected non-null condition");
15850   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15851       !Failed) {
15852     // In a static_assert-declaration, the constant-expression shall be a
15853     // constant expression that can be contextually converted to bool.
15854     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15855     if (Converted.isInvalid())
15856       Failed = true;
15857 
15858     ExprResult FullAssertExpr =
15859         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15860                             /*DiscardedValue*/ false,
15861                             /*IsConstexpr*/ true);
15862     if (FullAssertExpr.isInvalid())
15863       Failed = true;
15864     else
15865       AssertExpr = FullAssertExpr.get();
15866 
15867     llvm::APSInt Cond;
15868     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15869           diag::err_static_assert_expression_is_not_constant,
15870           /*AllowFold=*/false).isInvalid())
15871       Failed = true;
15872 
15873     if (!Failed && !Cond) {
15874       SmallString<256> MsgBuffer;
15875       llvm::raw_svector_ostream Msg(MsgBuffer);
15876       if (AssertMessage)
15877         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
15878 
15879       Expr *InnerCond = nullptr;
15880       std::string InnerCondDescription;
15881       std::tie(InnerCond, InnerCondDescription) =
15882         findFailedBooleanCondition(Converted.get());
15883       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
15884         // Drill down into concept specialization expressions to see why they
15885         // weren't satisfied.
15886         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15887           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15888         ConstraintSatisfaction Satisfaction;
15889         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
15890           DiagnoseUnsatisfiedConstraint(Satisfaction);
15891       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
15892                            && !isa<IntegerLiteral>(InnerCond)) {
15893         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
15894           << InnerCondDescription << !AssertMessage
15895           << Msg.str() << InnerCond->getSourceRange();
15896       } else {
15897         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15898           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15899       }
15900       Failed = true;
15901     }
15902   } else {
15903     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
15904                                                     /*DiscardedValue*/false,
15905                                                     /*IsConstexpr*/true);
15906     if (FullAssertExpr.isInvalid())
15907       Failed = true;
15908     else
15909       AssertExpr = FullAssertExpr.get();
15910   }
15911 
15912   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
15913                                         AssertExpr, AssertMessage, RParenLoc,
15914                                         Failed);
15915 
15916   CurContext->addDecl(Decl);
15917   return Decl;
15918 }
15919 
15920 /// Perform semantic analysis of the given friend type declaration.
15921 ///
15922 /// \returns A friend declaration that.
15923 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
15924                                       SourceLocation FriendLoc,
15925                                       TypeSourceInfo *TSInfo) {
15926   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
15927 
15928   QualType T = TSInfo->getType();
15929   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
15930 
15931   // C++03 [class.friend]p2:
15932   //   An elaborated-type-specifier shall be used in a friend declaration
15933   //   for a class.*
15934   //
15935   //   * The class-key of the elaborated-type-specifier is required.
15936   if (!CodeSynthesisContexts.empty()) {
15937     // Do not complain about the form of friend template types during any kind
15938     // of code synthesis. For template instantiation, we will have complained
15939     // when the template was defined.
15940   } else {
15941     if (!T->isElaboratedTypeSpecifier()) {
15942       // If we evaluated the type to a record type, suggest putting
15943       // a tag in front.
15944       if (const RecordType *RT = T->getAs<RecordType>()) {
15945         RecordDecl *RD = RT->getDecl();
15946 
15947         SmallString<16> InsertionText(" ");
15948         InsertionText += RD->getKindName();
15949 
15950         Diag(TypeRange.getBegin(),
15951              getLangOpts().CPlusPlus11 ?
15952                diag::warn_cxx98_compat_unelaborated_friend_type :
15953                diag::ext_unelaborated_friend_type)
15954           << (unsigned) RD->getTagKind()
15955           << T
15956           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
15957                                         InsertionText);
15958       } else {
15959         Diag(FriendLoc,
15960              getLangOpts().CPlusPlus11 ?
15961                diag::warn_cxx98_compat_nonclass_type_friend :
15962                diag::ext_nonclass_type_friend)
15963           << T
15964           << TypeRange;
15965       }
15966     } else if (T->getAs<EnumType>()) {
15967       Diag(FriendLoc,
15968            getLangOpts().CPlusPlus11 ?
15969              diag::warn_cxx98_compat_enum_friend :
15970              diag::ext_enum_friend)
15971         << T
15972         << TypeRange;
15973     }
15974 
15975     // C++11 [class.friend]p3:
15976     //   A friend declaration that does not declare a function shall have one
15977     //   of the following forms:
15978     //     friend elaborated-type-specifier ;
15979     //     friend simple-type-specifier ;
15980     //     friend typename-specifier ;
15981     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
15982       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
15983   }
15984 
15985   //   If the type specifier in a friend declaration designates a (possibly
15986   //   cv-qualified) class type, that class is declared as a friend; otherwise,
15987   //   the friend declaration is ignored.
15988   return FriendDecl::Create(Context, CurContext,
15989                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
15990                             FriendLoc);
15991 }
15992 
15993 /// Handle a friend tag declaration where the scope specifier was
15994 /// templated.
15995 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
15996                                     unsigned TagSpec, SourceLocation TagLoc,
15997                                     CXXScopeSpec &SS, IdentifierInfo *Name,
15998                                     SourceLocation NameLoc,
15999                                     const ParsedAttributesView &Attr,
16000                                     MultiTemplateParamsArg TempParamLists) {
16001   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16002 
16003   bool IsMemberSpecialization = false;
16004   bool Invalid = false;
16005 
16006   if (TemplateParameterList *TemplateParams =
16007           MatchTemplateParametersToScopeSpecifier(
16008               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16009               IsMemberSpecialization, Invalid)) {
16010     if (TemplateParams->size() > 0) {
16011       // This is a declaration of a class template.
16012       if (Invalid)
16013         return nullptr;
16014 
16015       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16016                                 NameLoc, Attr, TemplateParams, AS_public,
16017                                 /*ModulePrivateLoc=*/SourceLocation(),
16018                                 FriendLoc, TempParamLists.size() - 1,
16019                                 TempParamLists.data()).get();
16020     } else {
16021       // The "template<>" header is extraneous.
16022       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16023         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16024       IsMemberSpecialization = true;
16025     }
16026   }
16027 
16028   if (Invalid) return nullptr;
16029 
16030   bool isAllExplicitSpecializations = true;
16031   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16032     if (TempParamLists[I]->size()) {
16033       isAllExplicitSpecializations = false;
16034       break;
16035     }
16036   }
16037 
16038   // FIXME: don't ignore attributes.
16039 
16040   // If it's explicit specializations all the way down, just forget
16041   // about the template header and build an appropriate non-templated
16042   // friend.  TODO: for source fidelity, remember the headers.
16043   if (isAllExplicitSpecializations) {
16044     if (SS.isEmpty()) {
16045       bool Owned = false;
16046       bool IsDependent = false;
16047       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16048                       Attr, AS_public,
16049                       /*ModulePrivateLoc=*/SourceLocation(),
16050                       MultiTemplateParamsArg(), Owned, IsDependent,
16051                       /*ScopedEnumKWLoc=*/SourceLocation(),
16052                       /*ScopedEnumUsesClassTag=*/false,
16053                       /*UnderlyingType=*/TypeResult(),
16054                       /*IsTypeSpecifier=*/false,
16055                       /*IsTemplateParamOrArg=*/false);
16056     }
16057 
16058     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16059     ElaboratedTypeKeyword Keyword
16060       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16061     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16062                                    *Name, NameLoc);
16063     if (T.isNull())
16064       return nullptr;
16065 
16066     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16067     if (isa<DependentNameType>(T)) {
16068       DependentNameTypeLoc TL =
16069           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16070       TL.setElaboratedKeywordLoc(TagLoc);
16071       TL.setQualifierLoc(QualifierLoc);
16072       TL.setNameLoc(NameLoc);
16073     } else {
16074       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16075       TL.setElaboratedKeywordLoc(TagLoc);
16076       TL.setQualifierLoc(QualifierLoc);
16077       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16078     }
16079 
16080     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16081                                             TSI, FriendLoc, TempParamLists);
16082     Friend->setAccess(AS_public);
16083     CurContext->addDecl(Friend);
16084     return Friend;
16085   }
16086 
16087   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16088 
16089 
16090 
16091   // Handle the case of a templated-scope friend class.  e.g.
16092   //   template <class T> class A<T>::B;
16093   // FIXME: we don't support these right now.
16094   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16095     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16096   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16097   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16098   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16099   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16100   TL.setElaboratedKeywordLoc(TagLoc);
16101   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16102   TL.setNameLoc(NameLoc);
16103 
16104   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16105                                           TSI, FriendLoc, TempParamLists);
16106   Friend->setAccess(AS_public);
16107   Friend->setUnsupportedFriend(true);
16108   CurContext->addDecl(Friend);
16109   return Friend;
16110 }
16111 
16112 /// Handle a friend type declaration.  This works in tandem with
16113 /// ActOnTag.
16114 ///
16115 /// Notes on friend class templates:
16116 ///
16117 /// We generally treat friend class declarations as if they were
16118 /// declaring a class.  So, for example, the elaborated type specifier
16119 /// in a friend declaration is required to obey the restrictions of a
16120 /// class-head (i.e. no typedefs in the scope chain), template
16121 /// parameters are required to match up with simple template-ids, &c.
16122 /// However, unlike when declaring a template specialization, it's
16123 /// okay to refer to a template specialization without an empty
16124 /// template parameter declaration, e.g.
16125 ///   friend class A<T>::B<unsigned>;
16126 /// We permit this as a special case; if there are any template
16127 /// parameters present at all, require proper matching, i.e.
16128 ///   template <> template \<class T> friend class A<int>::B;
16129 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16130                                 MultiTemplateParamsArg TempParams) {
16131   SourceLocation Loc = DS.getBeginLoc();
16132 
16133   assert(DS.isFriendSpecified());
16134   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16135 
16136   // C++ [class.friend]p3:
16137   // A friend declaration that does not declare a function shall have one of
16138   // the following forms:
16139   //     friend elaborated-type-specifier ;
16140   //     friend simple-type-specifier ;
16141   //     friend typename-specifier ;
16142   //
16143   // Any declaration with a type qualifier does not have that form. (It's
16144   // legal to specify a qualified type as a friend, you just can't write the
16145   // keywords.)
16146   if (DS.getTypeQualifiers()) {
16147     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16148       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16149     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16150       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16151     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16152       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16153     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16154       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16155     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16156       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16157   }
16158 
16159   // Try to convert the decl specifier to a type.  This works for
16160   // friend templates because ActOnTag never produces a ClassTemplateDecl
16161   // for a TUK_Friend.
16162   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16163   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16164   QualType T = TSI->getType();
16165   if (TheDeclarator.isInvalidType())
16166     return nullptr;
16167 
16168   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16169     return nullptr;
16170 
16171   // This is definitely an error in C++98.  It's probably meant to
16172   // be forbidden in C++0x, too, but the specification is just
16173   // poorly written.
16174   //
16175   // The problem is with declarations like the following:
16176   //   template <T> friend A<T>::foo;
16177   // where deciding whether a class C is a friend or not now hinges
16178   // on whether there exists an instantiation of A that causes
16179   // 'foo' to equal C.  There are restrictions on class-heads
16180   // (which we declare (by fiat) elaborated friend declarations to
16181   // be) that makes this tractable.
16182   //
16183   // FIXME: handle "template <> friend class A<T>;", which
16184   // is possibly well-formed?  Who even knows?
16185   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16186     Diag(Loc, diag::err_tagless_friend_type_template)
16187       << DS.getSourceRange();
16188     return nullptr;
16189   }
16190 
16191   // C++98 [class.friend]p1: A friend of a class is a function
16192   //   or class that is not a member of the class . . .
16193   // This is fixed in DR77, which just barely didn't make the C++03
16194   // deadline.  It's also a very silly restriction that seriously
16195   // affects inner classes and which nobody else seems to implement;
16196   // thus we never diagnose it, not even in -pedantic.
16197   //
16198   // But note that we could warn about it: it's always useless to
16199   // friend one of your own members (it's not, however, worthless to
16200   // friend a member of an arbitrary specialization of your template).
16201 
16202   Decl *D;
16203   if (!TempParams.empty())
16204     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16205                                    TempParams,
16206                                    TSI,
16207                                    DS.getFriendSpecLoc());
16208   else
16209     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16210 
16211   if (!D)
16212     return nullptr;
16213 
16214   D->setAccess(AS_public);
16215   CurContext->addDecl(D);
16216 
16217   return D;
16218 }
16219 
16220 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16221                                         MultiTemplateParamsArg TemplateParams) {
16222   const DeclSpec &DS = D.getDeclSpec();
16223 
16224   assert(DS.isFriendSpecified());
16225   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16226 
16227   SourceLocation Loc = D.getIdentifierLoc();
16228   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16229 
16230   // C++ [class.friend]p1
16231   //   A friend of a class is a function or class....
16232   // Note that this sees through typedefs, which is intended.
16233   // It *doesn't* see through dependent types, which is correct
16234   // according to [temp.arg.type]p3:
16235   //   If a declaration acquires a function type through a
16236   //   type dependent on a template-parameter and this causes
16237   //   a declaration that does not use the syntactic form of a
16238   //   function declarator to have a function type, the program
16239   //   is ill-formed.
16240   if (!TInfo->getType()->isFunctionType()) {
16241     Diag(Loc, diag::err_unexpected_friend);
16242 
16243     // It might be worthwhile to try to recover by creating an
16244     // appropriate declaration.
16245     return nullptr;
16246   }
16247 
16248   // C++ [namespace.memdef]p3
16249   //  - If a friend declaration in a non-local class first declares a
16250   //    class or function, the friend class or function is a member
16251   //    of the innermost enclosing namespace.
16252   //  - The name of the friend is not found by simple name lookup
16253   //    until a matching declaration is provided in that namespace
16254   //    scope (either before or after the class declaration granting
16255   //    friendship).
16256   //  - If a friend function is called, its name may be found by the
16257   //    name lookup that considers functions from namespaces and
16258   //    classes associated with the types of the function arguments.
16259   //  - When looking for a prior declaration of a class or a function
16260   //    declared as a friend, scopes outside the innermost enclosing
16261   //    namespace scope are not considered.
16262 
16263   CXXScopeSpec &SS = D.getCXXScopeSpec();
16264   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16265   assert(NameInfo.getName());
16266 
16267   // Check for unexpanded parameter packs.
16268   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16269       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16270       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16271     return nullptr;
16272 
16273   // The context we found the declaration in, or in which we should
16274   // create the declaration.
16275   DeclContext *DC;
16276   Scope *DCScope = S;
16277   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16278                         ForExternalRedeclaration);
16279 
16280   // There are five cases here.
16281   //   - There's no scope specifier and we're in a local class. Only look
16282   //     for functions declared in the immediately-enclosing block scope.
16283   // We recover from invalid scope qualifiers as if they just weren't there.
16284   FunctionDecl *FunctionContainingLocalClass = nullptr;
16285   if ((SS.isInvalid() || !SS.isSet()) &&
16286       (FunctionContainingLocalClass =
16287            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16288     // C++11 [class.friend]p11:
16289     //   If a friend declaration appears in a local class and the name
16290     //   specified is an unqualified name, a prior declaration is
16291     //   looked up without considering scopes that are outside the
16292     //   innermost enclosing non-class scope. For a friend function
16293     //   declaration, if there is no prior declaration, the program is
16294     //   ill-formed.
16295 
16296     // Find the innermost enclosing non-class scope. This is the block
16297     // scope containing the local class definition (or for a nested class,
16298     // the outer local class).
16299     DCScope = S->getFnParent();
16300 
16301     // Look up the function name in the scope.
16302     Previous.clear(LookupLocalFriendName);
16303     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16304 
16305     if (!Previous.empty()) {
16306       // All possible previous declarations must have the same context:
16307       // either they were declared at block scope or they are members of
16308       // one of the enclosing local classes.
16309       DC = Previous.getRepresentativeDecl()->getDeclContext();
16310     } else {
16311       // This is ill-formed, but provide the context that we would have
16312       // declared the function in, if we were permitted to, for error recovery.
16313       DC = FunctionContainingLocalClass;
16314     }
16315     adjustContextForLocalExternDecl(DC);
16316 
16317     // C++ [class.friend]p6:
16318     //   A function can be defined in a friend declaration of a class if and
16319     //   only if the class is a non-local class (9.8), the function name is
16320     //   unqualified, and the function has namespace scope.
16321     if (D.isFunctionDefinition()) {
16322       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16323     }
16324 
16325   //   - There's no scope specifier, in which case we just go to the
16326   //     appropriate scope and look for a function or function template
16327   //     there as appropriate.
16328   } else if (SS.isInvalid() || !SS.isSet()) {
16329     // C++11 [namespace.memdef]p3:
16330     //   If the name in a friend declaration is neither qualified nor
16331     //   a template-id and the declaration is a function or an
16332     //   elaborated-type-specifier, the lookup to determine whether
16333     //   the entity has been previously declared shall not consider
16334     //   any scopes outside the innermost enclosing namespace.
16335     bool isTemplateId =
16336         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16337 
16338     // Find the appropriate context according to the above.
16339     DC = CurContext;
16340 
16341     // Skip class contexts.  If someone can cite chapter and verse
16342     // for this behavior, that would be nice --- it's what GCC and
16343     // EDG do, and it seems like a reasonable intent, but the spec
16344     // really only says that checks for unqualified existing
16345     // declarations should stop at the nearest enclosing namespace,
16346     // not that they should only consider the nearest enclosing
16347     // namespace.
16348     while (DC->isRecord())
16349       DC = DC->getParent();
16350 
16351     DeclContext *LookupDC = DC;
16352     while (LookupDC->isTransparentContext())
16353       LookupDC = LookupDC->getParent();
16354 
16355     while (true) {
16356       LookupQualifiedName(Previous, LookupDC);
16357 
16358       if (!Previous.empty()) {
16359         DC = LookupDC;
16360         break;
16361       }
16362 
16363       if (isTemplateId) {
16364         if (isa<TranslationUnitDecl>(LookupDC)) break;
16365       } else {
16366         if (LookupDC->isFileContext()) break;
16367       }
16368       LookupDC = LookupDC->getParent();
16369     }
16370 
16371     DCScope = getScopeForDeclContext(S, DC);
16372 
16373   //   - There's a non-dependent scope specifier, in which case we
16374   //     compute it and do a previous lookup there for a function
16375   //     or function template.
16376   } else if (!SS.getScopeRep()->isDependent()) {
16377     DC = computeDeclContext(SS);
16378     if (!DC) return nullptr;
16379 
16380     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16381 
16382     LookupQualifiedName(Previous, DC);
16383 
16384     // C++ [class.friend]p1: A friend of a class is a function or
16385     //   class that is not a member of the class . . .
16386     if (DC->Equals(CurContext))
16387       Diag(DS.getFriendSpecLoc(),
16388            getLangOpts().CPlusPlus11 ?
16389              diag::warn_cxx98_compat_friend_is_member :
16390              diag::err_friend_is_member);
16391 
16392     if (D.isFunctionDefinition()) {
16393       // C++ [class.friend]p6:
16394       //   A function can be defined in a friend declaration of a class if and
16395       //   only if the class is a non-local class (9.8), the function name is
16396       //   unqualified, and the function has namespace scope.
16397       //
16398       // FIXME: We should only do this if the scope specifier names the
16399       // innermost enclosing namespace; otherwise the fixit changes the
16400       // meaning of the code.
16401       SemaDiagnosticBuilder DB
16402         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16403 
16404       DB << SS.getScopeRep();
16405       if (DC->isFileContext())
16406         DB << FixItHint::CreateRemoval(SS.getRange());
16407       SS.clear();
16408     }
16409 
16410   //   - There's a scope specifier that does not match any template
16411   //     parameter lists, in which case we use some arbitrary context,
16412   //     create a method or method template, and wait for instantiation.
16413   //   - There's a scope specifier that does match some template
16414   //     parameter lists, which we don't handle right now.
16415   } else {
16416     if (D.isFunctionDefinition()) {
16417       // C++ [class.friend]p6:
16418       //   A function can be defined in a friend declaration of a class if and
16419       //   only if the class is a non-local class (9.8), the function name is
16420       //   unqualified, and the function has namespace scope.
16421       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16422         << SS.getScopeRep();
16423     }
16424 
16425     DC = CurContext;
16426     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16427   }
16428 
16429   if (!DC->isRecord()) {
16430     int DiagArg = -1;
16431     switch (D.getName().getKind()) {
16432     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16433     case UnqualifiedIdKind::IK_ConstructorName:
16434       DiagArg = 0;
16435       break;
16436     case UnqualifiedIdKind::IK_DestructorName:
16437       DiagArg = 1;
16438       break;
16439     case UnqualifiedIdKind::IK_ConversionFunctionId:
16440       DiagArg = 2;
16441       break;
16442     case UnqualifiedIdKind::IK_DeductionGuideName:
16443       DiagArg = 3;
16444       break;
16445     case UnqualifiedIdKind::IK_Identifier:
16446     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16447     case UnqualifiedIdKind::IK_LiteralOperatorId:
16448     case UnqualifiedIdKind::IK_OperatorFunctionId:
16449     case UnqualifiedIdKind::IK_TemplateId:
16450       break;
16451     }
16452     // This implies that it has to be an operator or function.
16453     if (DiagArg >= 0) {
16454       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16455       return nullptr;
16456     }
16457   }
16458 
16459   // FIXME: This is an egregious hack to cope with cases where the scope stack
16460   // does not contain the declaration context, i.e., in an out-of-line
16461   // definition of a class.
16462   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16463   if (!DCScope) {
16464     FakeDCScope.setEntity(DC);
16465     DCScope = &FakeDCScope;
16466   }
16467 
16468   bool AddToScope = true;
16469   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16470                                           TemplateParams, AddToScope);
16471   if (!ND) return nullptr;
16472 
16473   assert(ND->getLexicalDeclContext() == CurContext);
16474 
16475   // If we performed typo correction, we might have added a scope specifier
16476   // and changed the decl context.
16477   DC = ND->getDeclContext();
16478 
16479   // Add the function declaration to the appropriate lookup tables,
16480   // adjusting the redeclarations list as necessary.  We don't
16481   // want to do this yet if the friending class is dependent.
16482   //
16483   // Also update the scope-based lookup if the target context's
16484   // lookup context is in lexical scope.
16485   if (!CurContext->isDependentContext()) {
16486     DC = DC->getRedeclContext();
16487     DC->makeDeclVisibleInContext(ND);
16488     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16489       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16490   }
16491 
16492   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16493                                        D.getIdentifierLoc(), ND,
16494                                        DS.getFriendSpecLoc());
16495   FrD->setAccess(AS_public);
16496   CurContext->addDecl(FrD);
16497 
16498   if (ND->isInvalidDecl()) {
16499     FrD->setInvalidDecl();
16500   } else {
16501     if (DC->isRecord()) CheckFriendAccess(ND);
16502 
16503     FunctionDecl *FD;
16504     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16505       FD = FTD->getTemplatedDecl();
16506     else
16507       FD = cast<FunctionDecl>(ND);
16508 
16509     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16510     // default argument expression, that declaration shall be a definition
16511     // and shall be the only declaration of the function or function
16512     // template in the translation unit.
16513     if (functionDeclHasDefaultArgument(FD)) {
16514       // We can't look at FD->getPreviousDecl() because it may not have been set
16515       // if we're in a dependent context. If the function is known to be a
16516       // redeclaration, we will have narrowed Previous down to the right decl.
16517       if (D.isRedeclaration()) {
16518         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16519         Diag(Previous.getRepresentativeDecl()->getLocation(),
16520              diag::note_previous_declaration);
16521       } else if (!D.isFunctionDefinition())
16522         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16523     }
16524 
16525     // Mark templated-scope function declarations as unsupported.
16526     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16527       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16528         << SS.getScopeRep() << SS.getRange()
16529         << cast<CXXRecordDecl>(CurContext);
16530       FrD->setUnsupportedFriend(true);
16531     }
16532   }
16533 
16534   return ND;
16535 }
16536 
16537 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16538   AdjustDeclIfTemplate(Dcl);
16539 
16540   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16541   if (!Fn) {
16542     Diag(DelLoc, diag::err_deleted_non_function);
16543     return;
16544   }
16545 
16546   // Deleted function does not have a body.
16547   Fn->setWillHaveBody(false);
16548 
16549   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16550     // Don't consider the implicit declaration we generate for explicit
16551     // specializations. FIXME: Do not generate these implicit declarations.
16552     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16553          Prev->getPreviousDecl()) &&
16554         !Prev->isDefined()) {
16555       Diag(DelLoc, diag::err_deleted_decl_not_first);
16556       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16557            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16558                               : diag::note_previous_declaration);
16559       // We can't recover from this; the declaration might have already
16560       // been used.
16561       Fn->setInvalidDecl();
16562       return;
16563     }
16564 
16565     // To maintain the invariant that functions are only deleted on their first
16566     // declaration, mark the implicitly-instantiated declaration of the
16567     // explicitly-specialized function as deleted instead of marking the
16568     // instantiated redeclaration.
16569     Fn = Fn->getCanonicalDecl();
16570   }
16571 
16572   // dllimport/dllexport cannot be deleted.
16573   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16574     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16575     Fn->setInvalidDecl();
16576   }
16577 
16578   // C++11 [basic.start.main]p3:
16579   //   A program that defines main as deleted [...] is ill-formed.
16580   if (Fn->isMain())
16581     Diag(DelLoc, diag::err_deleted_main);
16582 
16583   // C++11 [dcl.fct.def.delete]p4:
16584   //  A deleted function is implicitly inline.
16585   Fn->setImplicitlyInline();
16586   Fn->setDeletedAsWritten();
16587 }
16588 
16589 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16590   if (!Dcl || Dcl->isInvalidDecl())
16591     return;
16592 
16593   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16594   if (!FD) {
16595     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16596       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16597         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16598         return;
16599       }
16600     }
16601 
16602     Diag(DefaultLoc, diag::err_default_special_members)
16603         << getLangOpts().CPlusPlus2a;
16604     return;
16605   }
16606 
16607   // Reject if this can't possibly be a defaultable function.
16608   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16609   if (!DefKind &&
16610       // A dependent function that doesn't locally look defaultable can
16611       // still instantiate to a defaultable function if it's a constructor
16612       // or assignment operator.
16613       (!FD->isDependentContext() ||
16614        (!isa<CXXConstructorDecl>(FD) &&
16615         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16616     Diag(DefaultLoc, diag::err_default_special_members)
16617         << getLangOpts().CPlusPlus2a;
16618     return;
16619   }
16620 
16621   if (DefKind.isComparison() &&
16622       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16623     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16624         << (int)DefKind.asComparison();
16625     return;
16626   }
16627 
16628   // Issue compatibility warning. We already warned if the operator is
16629   // 'operator<=>' when parsing the '<=>' token.
16630   if (DefKind.isComparison() &&
16631       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16632     Diag(DefaultLoc, getLangOpts().CPlusPlus2a
16633                          ? diag::warn_cxx17_compat_defaulted_comparison
16634                          : diag::ext_defaulted_comparison);
16635   }
16636 
16637   FD->setDefaulted();
16638   FD->setExplicitlyDefaulted();
16639 
16640   // Defer checking functions that are defaulted in a dependent context.
16641   if (FD->isDependentContext())
16642     return;
16643 
16644   // Unset that we will have a body for this function. We might not,
16645   // if it turns out to be trivial, and we don't need this marking now
16646   // that we've marked it as defaulted.
16647   FD->setWillHaveBody(false);
16648 
16649   // If this definition appears within the record, do the checking when
16650   // the record is complete. This is always the case for a defaulted
16651   // comparison.
16652   if (DefKind.isComparison())
16653     return;
16654   auto *MD = cast<CXXMethodDecl>(FD);
16655 
16656   const FunctionDecl *Primary = FD;
16657   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16658     // Ask the template instantiation pattern that actually had the
16659     // '= default' on it.
16660     Primary = Pattern;
16661 
16662   // If the method was defaulted on its first declaration, we will have
16663   // already performed the checking in CheckCompletedCXXClass. Such a
16664   // declaration doesn't trigger an implicit definition.
16665   if (Primary->getCanonicalDecl()->isDefaulted())
16666     return;
16667 
16668   // FIXME: Once we support defining comparisons out of class, check for a
16669   // defaulted comparison here.
16670   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16671     MD->setInvalidDecl();
16672   else
16673     DefineDefaultedFunction(*this, MD, DefaultLoc);
16674 }
16675 
16676 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16677   for (Stmt *SubStmt : S->children()) {
16678     if (!SubStmt)
16679       continue;
16680     if (isa<ReturnStmt>(SubStmt))
16681       Self.Diag(SubStmt->getBeginLoc(),
16682                 diag::err_return_in_constructor_handler);
16683     if (!isa<Expr>(SubStmt))
16684       SearchForReturnInStmt(Self, SubStmt);
16685   }
16686 }
16687 
16688 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16689   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16690     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16691     SearchForReturnInStmt(*this, Handler);
16692   }
16693 }
16694 
16695 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16696                                              const CXXMethodDecl *Old) {
16697   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16698   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16699 
16700   if (OldFT->hasExtParameterInfos()) {
16701     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16702       // A parameter of the overriding method should be annotated with noescape
16703       // if the corresponding parameter of the overridden method is annotated.
16704       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16705           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16706         Diag(New->getParamDecl(I)->getLocation(),
16707              diag::warn_overriding_method_missing_noescape);
16708         Diag(Old->getParamDecl(I)->getLocation(),
16709              diag::note_overridden_marked_noescape);
16710       }
16711   }
16712 
16713   // Virtual overrides must have the same code_seg.
16714   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16715   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16716   if ((NewCSA || OldCSA) &&
16717       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16718     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16719     Diag(Old->getLocation(), diag::note_previous_declaration);
16720     return true;
16721   }
16722 
16723   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16724 
16725   // If the calling conventions match, everything is fine
16726   if (NewCC == OldCC)
16727     return false;
16728 
16729   // If the calling conventions mismatch because the new function is static,
16730   // suppress the calling convention mismatch error; the error about static
16731   // function override (err_static_overrides_virtual from
16732   // Sema::CheckFunctionDeclaration) is more clear.
16733   if (New->getStorageClass() == SC_Static)
16734     return false;
16735 
16736   Diag(New->getLocation(),
16737        diag::err_conflicting_overriding_cc_attributes)
16738     << New->getDeclName() << New->getType() << Old->getType();
16739   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16740   return true;
16741 }
16742 
16743 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16744                                              const CXXMethodDecl *Old) {
16745   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16746   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16747 
16748   if (Context.hasSameType(NewTy, OldTy) ||
16749       NewTy->isDependentType() || OldTy->isDependentType())
16750     return false;
16751 
16752   // Check if the return types are covariant
16753   QualType NewClassTy, OldClassTy;
16754 
16755   /// Both types must be pointers or references to classes.
16756   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16757     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16758       NewClassTy = NewPT->getPointeeType();
16759       OldClassTy = OldPT->getPointeeType();
16760     }
16761   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16762     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16763       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16764         NewClassTy = NewRT->getPointeeType();
16765         OldClassTy = OldRT->getPointeeType();
16766       }
16767     }
16768   }
16769 
16770   // The return types aren't either both pointers or references to a class type.
16771   if (NewClassTy.isNull()) {
16772     Diag(New->getLocation(),
16773          diag::err_different_return_type_for_overriding_virtual_function)
16774         << New->getDeclName() << NewTy << OldTy
16775         << New->getReturnTypeSourceRange();
16776     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16777         << Old->getReturnTypeSourceRange();
16778 
16779     return true;
16780   }
16781 
16782   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16783     // C++14 [class.virtual]p8:
16784     //   If the class type in the covariant return type of D::f differs from
16785     //   that of B::f, the class type in the return type of D::f shall be
16786     //   complete at the point of declaration of D::f or shall be the class
16787     //   type D.
16788     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16789       if (!RT->isBeingDefined() &&
16790           RequireCompleteType(New->getLocation(), NewClassTy,
16791                               diag::err_covariant_return_incomplete,
16792                               New->getDeclName()))
16793         return true;
16794     }
16795 
16796     // Check if the new class derives from the old class.
16797     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16798       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16799           << New->getDeclName() << NewTy << OldTy
16800           << New->getReturnTypeSourceRange();
16801       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16802           << Old->getReturnTypeSourceRange();
16803       return true;
16804     }
16805 
16806     // Check if we the conversion from derived to base is valid.
16807     if (CheckDerivedToBaseConversion(
16808             NewClassTy, OldClassTy,
16809             diag::err_covariant_return_inaccessible_base,
16810             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16811             New->getLocation(), New->getReturnTypeSourceRange(),
16812             New->getDeclName(), nullptr)) {
16813       // FIXME: this note won't trigger for delayed access control
16814       // diagnostics, and it's impossible to get an undelayed error
16815       // here from access control during the original parse because
16816       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16817       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16818           << Old->getReturnTypeSourceRange();
16819       return true;
16820     }
16821   }
16822 
16823   // The qualifiers of the return types must be the same.
16824   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16825     Diag(New->getLocation(),
16826          diag::err_covariant_return_type_different_qualifications)
16827         << New->getDeclName() << NewTy << OldTy
16828         << New->getReturnTypeSourceRange();
16829     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16830         << Old->getReturnTypeSourceRange();
16831     return true;
16832   }
16833 
16834 
16835   // The new class type must have the same or less qualifiers as the old type.
16836   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16837     Diag(New->getLocation(),
16838          diag::err_covariant_return_type_class_type_more_qualified)
16839         << New->getDeclName() << NewTy << OldTy
16840         << New->getReturnTypeSourceRange();
16841     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16842         << Old->getReturnTypeSourceRange();
16843     return true;
16844   }
16845 
16846   return false;
16847 }
16848 
16849 /// Mark the given method pure.
16850 ///
16851 /// \param Method the method to be marked pure.
16852 ///
16853 /// \param InitRange the source range that covers the "0" initializer.
16854 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16855   SourceLocation EndLoc = InitRange.getEnd();
16856   if (EndLoc.isValid())
16857     Method->setRangeEnd(EndLoc);
16858 
16859   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16860     Method->setPure();
16861     return false;
16862   }
16863 
16864   if (!Method->isInvalidDecl())
16865     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16866       << Method->getDeclName() << InitRange;
16867   return true;
16868 }
16869 
16870 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16871   if (D->getFriendObjectKind())
16872     Diag(D->getLocation(), diag::err_pure_friend);
16873   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16874     CheckPureMethod(M, ZeroLoc);
16875   else
16876     Diag(D->getLocation(), diag::err_illegal_initializer);
16877 }
16878 
16879 /// Determine whether the given declaration is a global variable or
16880 /// static data member.
16881 static bool isNonlocalVariable(const Decl *D) {
16882   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
16883     return Var->hasGlobalStorage();
16884 
16885   return false;
16886 }
16887 
16888 /// Invoked when we are about to parse an initializer for the declaration
16889 /// 'Dcl'.
16890 ///
16891 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
16892 /// static data member of class X, names should be looked up in the scope of
16893 /// class X. If the declaration had a scope specifier, a scope will have
16894 /// been created and passed in for this purpose. Otherwise, S will be null.
16895 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
16896   // If there is no declaration, there was an error parsing it.
16897   if (!D || D->isInvalidDecl())
16898     return;
16899 
16900   // We will always have a nested name specifier here, but this declaration
16901   // might not be out of line if the specifier names the current namespace:
16902   //   extern int n;
16903   //   int ::n = 0;
16904   if (S && D->isOutOfLine())
16905     EnterDeclaratorContext(S, D->getDeclContext());
16906 
16907   // If we are parsing the initializer for a static data member, push a
16908   // new expression evaluation context that is associated with this static
16909   // data member.
16910   if (isNonlocalVariable(D))
16911     PushExpressionEvaluationContext(
16912         ExpressionEvaluationContext::PotentiallyEvaluated, D);
16913 }
16914 
16915 /// Invoked after we are finished parsing an initializer for the declaration D.
16916 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
16917   // If there is no declaration, there was an error parsing it.
16918   if (!D || D->isInvalidDecl())
16919     return;
16920 
16921   if (isNonlocalVariable(D))
16922     PopExpressionEvaluationContext();
16923 
16924   if (S && D->isOutOfLine())
16925     ExitDeclaratorContext(S);
16926 }
16927 
16928 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
16929 /// C++ if/switch/while/for statement.
16930 /// e.g: "if (int x = f()) {...}"
16931 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
16932   // C++ 6.4p2:
16933   // The declarator shall not specify a function or an array.
16934   // The type-specifier-seq shall not contain typedef and shall not declare a
16935   // new class or enumeration.
16936   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
16937          "Parser allowed 'typedef' as storage class of condition decl.");
16938 
16939   Decl *Dcl = ActOnDeclarator(S, D);
16940   if (!Dcl)
16941     return true;
16942 
16943   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
16944     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
16945       << D.getSourceRange();
16946     return true;
16947   }
16948 
16949   return Dcl;
16950 }
16951 
16952 void Sema::LoadExternalVTableUses() {
16953   if (!ExternalSource)
16954     return;
16955 
16956   SmallVector<ExternalVTableUse, 4> VTables;
16957   ExternalSource->ReadUsedVTables(VTables);
16958   SmallVector<VTableUse, 4> NewUses;
16959   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
16960     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
16961       = VTablesUsed.find(VTables[I].Record);
16962     // Even if a definition wasn't required before, it may be required now.
16963     if (Pos != VTablesUsed.end()) {
16964       if (!Pos->second && VTables[I].DefinitionRequired)
16965         Pos->second = true;
16966       continue;
16967     }
16968 
16969     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
16970     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
16971   }
16972 
16973   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
16974 }
16975 
16976 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
16977                           bool DefinitionRequired) {
16978   // Ignore any vtable uses in unevaluated operands or for classes that do
16979   // not have a vtable.
16980   if (!Class->isDynamicClass() || Class->isDependentContext() ||
16981       CurContext->isDependentContext() || isUnevaluatedContext())
16982     return;
16983   // Do not mark as used if compiling for the device outside of the target
16984   // region.
16985   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
16986       !isInOpenMPDeclareTargetContext() &&
16987       !isInOpenMPTargetExecutionDirective()) {
16988     if (!DefinitionRequired)
16989       MarkVirtualMembersReferenced(Loc, Class);
16990     return;
16991   }
16992 
16993   // Try to insert this class into the map.
16994   LoadExternalVTableUses();
16995   Class = Class->getCanonicalDecl();
16996   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
16997     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
16998   if (!Pos.second) {
16999     // If we already had an entry, check to see if we are promoting this vtable
17000     // to require a definition. If so, we need to reappend to the VTableUses
17001     // list, since we may have already processed the first entry.
17002     if (DefinitionRequired && !Pos.first->second) {
17003       Pos.first->second = true;
17004     } else {
17005       // Otherwise, we can early exit.
17006       return;
17007     }
17008   } else {
17009     // The Microsoft ABI requires that we perform the destructor body
17010     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17011     // the deleting destructor is emitted with the vtable, not with the
17012     // destructor definition as in the Itanium ABI.
17013     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17014       CXXDestructorDecl *DD = Class->getDestructor();
17015       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17016         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17017           // If this is an out-of-line declaration, marking it referenced will
17018           // not do anything. Manually call CheckDestructor to look up operator
17019           // delete().
17020           ContextRAII SavedContext(*this, DD);
17021           CheckDestructor(DD);
17022         } else {
17023           MarkFunctionReferenced(Loc, Class->getDestructor());
17024         }
17025       }
17026     }
17027   }
17028 
17029   // Local classes need to have their virtual members marked
17030   // immediately. For all other classes, we mark their virtual members
17031   // at the end of the translation unit.
17032   if (Class->isLocalClass())
17033     MarkVirtualMembersReferenced(Loc, Class);
17034   else
17035     VTableUses.push_back(std::make_pair(Class, Loc));
17036 }
17037 
17038 bool Sema::DefineUsedVTables() {
17039   LoadExternalVTableUses();
17040   if (VTableUses.empty())
17041     return false;
17042 
17043   // Note: The VTableUses vector could grow as a result of marking
17044   // the members of a class as "used", so we check the size each
17045   // time through the loop and prefer indices (which are stable) to
17046   // iterators (which are not).
17047   bool DefinedAnything = false;
17048   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17049     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17050     if (!Class)
17051       continue;
17052     TemplateSpecializationKind ClassTSK =
17053         Class->getTemplateSpecializationKind();
17054 
17055     SourceLocation Loc = VTableUses[I].second;
17056 
17057     bool DefineVTable = true;
17058 
17059     // If this class has a key function, but that key function is
17060     // defined in another translation unit, we don't need to emit the
17061     // vtable even though we're using it.
17062     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17063     if (KeyFunction && !KeyFunction->hasBody()) {
17064       // The key function is in another translation unit.
17065       DefineVTable = false;
17066       TemplateSpecializationKind TSK =
17067           KeyFunction->getTemplateSpecializationKind();
17068       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17069              TSK != TSK_ImplicitInstantiation &&
17070              "Instantiations don't have key functions");
17071       (void)TSK;
17072     } else if (!KeyFunction) {
17073       // If we have a class with no key function that is the subject
17074       // of an explicit instantiation declaration, suppress the
17075       // vtable; it will live with the explicit instantiation
17076       // definition.
17077       bool IsExplicitInstantiationDeclaration =
17078           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17079       for (auto R : Class->redecls()) {
17080         TemplateSpecializationKind TSK
17081           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17082         if (TSK == TSK_ExplicitInstantiationDeclaration)
17083           IsExplicitInstantiationDeclaration = true;
17084         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17085           IsExplicitInstantiationDeclaration = false;
17086           break;
17087         }
17088       }
17089 
17090       if (IsExplicitInstantiationDeclaration)
17091         DefineVTable = false;
17092     }
17093 
17094     // The exception specifications for all virtual members may be needed even
17095     // if we are not providing an authoritative form of the vtable in this TU.
17096     // We may choose to emit it available_externally anyway.
17097     if (!DefineVTable) {
17098       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17099       continue;
17100     }
17101 
17102     // Mark all of the virtual members of this class as referenced, so
17103     // that we can build a vtable. Then, tell the AST consumer that a
17104     // vtable for this class is required.
17105     DefinedAnything = true;
17106     MarkVirtualMembersReferenced(Loc, Class);
17107     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17108     if (VTablesUsed[Canonical])
17109       Consumer.HandleVTable(Class);
17110 
17111     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17112     // no key function or the key function is inlined. Don't warn in C++ ABIs
17113     // that lack key functions, since the user won't be able to make one.
17114     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17115         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17116       const FunctionDecl *KeyFunctionDef = nullptr;
17117       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17118                            KeyFunctionDef->isInlined())) {
17119         Diag(Class->getLocation(),
17120              ClassTSK == TSK_ExplicitInstantiationDefinition
17121                  ? diag::warn_weak_template_vtable
17122                  : diag::warn_weak_vtable)
17123             << Class;
17124       }
17125     }
17126   }
17127   VTableUses.clear();
17128 
17129   return DefinedAnything;
17130 }
17131 
17132 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17133                                                  const CXXRecordDecl *RD) {
17134   for (const auto *I : RD->methods())
17135     if (I->isVirtual() && !I->isPure())
17136       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17137 }
17138 
17139 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17140                                         const CXXRecordDecl *RD,
17141                                         bool ConstexprOnly) {
17142   // Mark all functions which will appear in RD's vtable as used.
17143   CXXFinalOverriderMap FinalOverriders;
17144   RD->getFinalOverriders(FinalOverriders);
17145   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17146                                             E = FinalOverriders.end();
17147        I != E; ++I) {
17148     for (OverridingMethods::const_iterator OI = I->second.begin(),
17149                                            OE = I->second.end();
17150          OI != OE; ++OI) {
17151       assert(OI->second.size() > 0 && "no final overrider");
17152       CXXMethodDecl *Overrider = OI->second.front().Method;
17153 
17154       // C++ [basic.def.odr]p2:
17155       //   [...] A virtual member function is used if it is not pure. [...]
17156       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17157         MarkFunctionReferenced(Loc, Overrider);
17158     }
17159   }
17160 
17161   // Only classes that have virtual bases need a VTT.
17162   if (RD->getNumVBases() == 0)
17163     return;
17164 
17165   for (const auto &I : RD->bases()) {
17166     const auto *Base =
17167         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17168     if (Base->getNumVBases() == 0)
17169       continue;
17170     MarkVirtualMembersReferenced(Loc, Base);
17171   }
17172 }
17173 
17174 /// SetIvarInitializers - This routine builds initialization ASTs for the
17175 /// Objective-C implementation whose ivars need be initialized.
17176 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17177   if (!getLangOpts().CPlusPlus)
17178     return;
17179   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17180     SmallVector<ObjCIvarDecl*, 8> ivars;
17181     CollectIvarsToConstructOrDestruct(OID, ivars);
17182     if (ivars.empty())
17183       return;
17184     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17185     for (unsigned i = 0; i < ivars.size(); i++) {
17186       FieldDecl *Field = ivars[i];
17187       if (Field->isInvalidDecl())
17188         continue;
17189 
17190       CXXCtorInitializer *Member;
17191       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17192       InitializationKind InitKind =
17193         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17194 
17195       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17196       ExprResult MemberInit =
17197         InitSeq.Perform(*this, InitEntity, InitKind, None);
17198       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17199       // Note, MemberInit could actually come back empty if no initialization
17200       // is required (e.g., because it would call a trivial default constructor)
17201       if (!MemberInit.get() || MemberInit.isInvalid())
17202         continue;
17203 
17204       Member =
17205         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17206                                          SourceLocation(),
17207                                          MemberInit.getAs<Expr>(),
17208                                          SourceLocation());
17209       AllToInit.push_back(Member);
17210 
17211       // Be sure that the destructor is accessible and is marked as referenced.
17212       if (const RecordType *RecordTy =
17213               Context.getBaseElementType(Field->getType())
17214                   ->getAs<RecordType>()) {
17215         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17216         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17217           MarkFunctionReferenced(Field->getLocation(), Destructor);
17218           CheckDestructorAccess(Field->getLocation(), Destructor,
17219                             PDiag(diag::err_access_dtor_ivar)
17220                               << Context.getBaseElementType(Field->getType()));
17221         }
17222       }
17223     }
17224     ObjCImplementation->setIvarInitializers(Context,
17225                                             AllToInit.data(), AllToInit.size());
17226   }
17227 }
17228 
17229 static
17230 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17231                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17232                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17233                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17234                            Sema &S) {
17235   if (Ctor->isInvalidDecl())
17236     return;
17237 
17238   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17239 
17240   // Target may not be determinable yet, for instance if this is a dependent
17241   // call in an uninstantiated template.
17242   if (Target) {
17243     const FunctionDecl *FNTarget = nullptr;
17244     (void)Target->hasBody(FNTarget);
17245     Target = const_cast<CXXConstructorDecl*>(
17246       cast_or_null<CXXConstructorDecl>(FNTarget));
17247   }
17248 
17249   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17250                      // Avoid dereferencing a null pointer here.
17251                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17252 
17253   if (!Current.insert(Canonical).second)
17254     return;
17255 
17256   // We know that beyond here, we aren't chaining into a cycle.
17257   if (!Target || !Target->isDelegatingConstructor() ||
17258       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17259     Valid.insert(Current.begin(), Current.end());
17260     Current.clear();
17261   // We've hit a cycle.
17262   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17263              Current.count(TCanonical)) {
17264     // If we haven't diagnosed this cycle yet, do so now.
17265     if (!Invalid.count(TCanonical)) {
17266       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17267              diag::warn_delegating_ctor_cycle)
17268         << Ctor;
17269 
17270       // Don't add a note for a function delegating directly to itself.
17271       if (TCanonical != Canonical)
17272         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17273 
17274       CXXConstructorDecl *C = Target;
17275       while (C->getCanonicalDecl() != Canonical) {
17276         const FunctionDecl *FNTarget = nullptr;
17277         (void)C->getTargetConstructor()->hasBody(FNTarget);
17278         assert(FNTarget && "Ctor cycle through bodiless function");
17279 
17280         C = const_cast<CXXConstructorDecl*>(
17281           cast<CXXConstructorDecl>(FNTarget));
17282         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17283       }
17284     }
17285 
17286     Invalid.insert(Current.begin(), Current.end());
17287     Current.clear();
17288   } else {
17289     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17290   }
17291 }
17292 
17293 
17294 void Sema::CheckDelegatingCtorCycles() {
17295   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17296 
17297   for (DelegatingCtorDeclsType::iterator
17298          I = DelegatingCtorDecls.begin(ExternalSource),
17299          E = DelegatingCtorDecls.end();
17300        I != E; ++I)
17301     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17302 
17303   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17304     (*CI)->setInvalidDecl();
17305 }
17306 
17307 namespace {
17308   /// AST visitor that finds references to the 'this' expression.
17309   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17310     Sema &S;
17311 
17312   public:
17313     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17314 
17315     bool VisitCXXThisExpr(CXXThisExpr *E) {
17316       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17317         << E->isImplicit();
17318       return false;
17319     }
17320   };
17321 }
17322 
17323 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17324   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17325   if (!TSInfo)
17326     return false;
17327 
17328   TypeLoc TL = TSInfo->getTypeLoc();
17329   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17330   if (!ProtoTL)
17331     return false;
17332 
17333   // C++11 [expr.prim.general]p3:
17334   //   [The expression this] shall not appear before the optional
17335   //   cv-qualifier-seq and it shall not appear within the declaration of a
17336   //   static member function (although its type and value category are defined
17337   //   within a static member function as they are within a non-static member
17338   //   function). [ Note: this is because declaration matching does not occur
17339   //  until the complete declarator is known. - end note ]
17340   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17341   FindCXXThisExpr Finder(*this);
17342 
17343   // If the return type came after the cv-qualifier-seq, check it now.
17344   if (Proto->hasTrailingReturn() &&
17345       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17346     return true;
17347 
17348   // Check the exception specification.
17349   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17350     return true;
17351 
17352   // Check the trailing requires clause
17353   if (Expr *E = Method->getTrailingRequiresClause())
17354     if (!Finder.TraverseStmt(E))
17355       return true;
17356 
17357   return checkThisInStaticMemberFunctionAttributes(Method);
17358 }
17359 
17360 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17361   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17362   if (!TSInfo)
17363     return false;
17364 
17365   TypeLoc TL = TSInfo->getTypeLoc();
17366   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17367   if (!ProtoTL)
17368     return false;
17369 
17370   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17371   FindCXXThisExpr Finder(*this);
17372 
17373   switch (Proto->getExceptionSpecType()) {
17374   case EST_Unparsed:
17375   case EST_Uninstantiated:
17376   case EST_Unevaluated:
17377   case EST_BasicNoexcept:
17378   case EST_NoThrow:
17379   case EST_DynamicNone:
17380   case EST_MSAny:
17381   case EST_None:
17382     break;
17383 
17384   case EST_DependentNoexcept:
17385   case EST_NoexceptFalse:
17386   case EST_NoexceptTrue:
17387     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17388       return true;
17389     LLVM_FALLTHROUGH;
17390 
17391   case EST_Dynamic:
17392     for (const auto &E : Proto->exceptions()) {
17393       if (!Finder.TraverseType(E))
17394         return true;
17395     }
17396     break;
17397   }
17398 
17399   return false;
17400 }
17401 
17402 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17403   FindCXXThisExpr Finder(*this);
17404 
17405   // Check attributes.
17406   for (const auto *A : Method->attrs()) {
17407     // FIXME: This should be emitted by tblgen.
17408     Expr *Arg = nullptr;
17409     ArrayRef<Expr *> Args;
17410     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17411       Arg = G->getArg();
17412     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17413       Arg = G->getArg();
17414     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17415       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17416     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17417       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17418     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17419       Arg = ETLF->getSuccessValue();
17420       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17421     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17422       Arg = STLF->getSuccessValue();
17423       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17424     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17425       Arg = LR->getArg();
17426     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17427       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17428     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17429       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17430     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17431       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17432     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17433       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17434     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17435       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17436 
17437     if (Arg && !Finder.TraverseStmt(Arg))
17438       return true;
17439 
17440     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17441       if (!Finder.TraverseStmt(Args[I]))
17442         return true;
17443     }
17444   }
17445 
17446   return false;
17447 }
17448 
17449 void Sema::checkExceptionSpecification(
17450     bool IsTopLevel, ExceptionSpecificationType EST,
17451     ArrayRef<ParsedType> DynamicExceptions,
17452     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17453     SmallVectorImpl<QualType> &Exceptions,
17454     FunctionProtoType::ExceptionSpecInfo &ESI) {
17455   Exceptions.clear();
17456   ESI.Type = EST;
17457   if (EST == EST_Dynamic) {
17458     Exceptions.reserve(DynamicExceptions.size());
17459     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17460       // FIXME: Preserve type source info.
17461       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17462 
17463       if (IsTopLevel) {
17464         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17465         collectUnexpandedParameterPacks(ET, Unexpanded);
17466         if (!Unexpanded.empty()) {
17467           DiagnoseUnexpandedParameterPacks(
17468               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17469               Unexpanded);
17470           continue;
17471         }
17472       }
17473 
17474       // Check that the type is valid for an exception spec, and
17475       // drop it if not.
17476       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17477         Exceptions.push_back(ET);
17478     }
17479     ESI.Exceptions = Exceptions;
17480     return;
17481   }
17482 
17483   if (isComputedNoexcept(EST)) {
17484     assert((NoexceptExpr->isTypeDependent() ||
17485             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17486             Context.BoolTy) &&
17487            "Parser should have made sure that the expression is boolean");
17488     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17489       ESI.Type = EST_BasicNoexcept;
17490       return;
17491     }
17492 
17493     ESI.NoexceptExpr = NoexceptExpr;
17494     return;
17495   }
17496 }
17497 
17498 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17499              ExceptionSpecificationType EST,
17500              SourceRange SpecificationRange,
17501              ArrayRef<ParsedType> DynamicExceptions,
17502              ArrayRef<SourceRange> DynamicExceptionRanges,
17503              Expr *NoexceptExpr) {
17504   if (!MethodD)
17505     return;
17506 
17507   // Dig out the method we're referring to.
17508   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17509     MethodD = FunTmpl->getTemplatedDecl();
17510 
17511   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17512   if (!Method)
17513     return;
17514 
17515   // Check the exception specification.
17516   llvm::SmallVector<QualType, 4> Exceptions;
17517   FunctionProtoType::ExceptionSpecInfo ESI;
17518   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17519                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17520                               ESI);
17521 
17522   // Update the exception specification on the function type.
17523   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17524 
17525   if (Method->isStatic())
17526     checkThisInStaticMemberFunctionExceptionSpec(Method);
17527 
17528   if (Method->isVirtual()) {
17529     // Check overrides, which we previously had to delay.
17530     for (const CXXMethodDecl *O : Method->overridden_methods())
17531       CheckOverridingFunctionExceptionSpec(Method, O);
17532   }
17533 }
17534 
17535 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17536 ///
17537 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17538                                        SourceLocation DeclStart, Declarator &D,
17539                                        Expr *BitWidth,
17540                                        InClassInitStyle InitStyle,
17541                                        AccessSpecifier AS,
17542                                        const ParsedAttr &MSPropertyAttr) {
17543   IdentifierInfo *II = D.getIdentifier();
17544   if (!II) {
17545     Diag(DeclStart, diag::err_anonymous_property);
17546     return nullptr;
17547   }
17548   SourceLocation Loc = D.getIdentifierLoc();
17549 
17550   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17551   QualType T = TInfo->getType();
17552   if (getLangOpts().CPlusPlus) {
17553     CheckExtraCXXDefaultArguments(D);
17554 
17555     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17556                                         UPPC_DataMemberType)) {
17557       D.setInvalidType();
17558       T = Context.IntTy;
17559       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17560     }
17561   }
17562 
17563   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17564 
17565   if (D.getDeclSpec().isInlineSpecified())
17566     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17567         << getLangOpts().CPlusPlus17;
17568   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17569     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17570          diag::err_invalid_thread)
17571       << DeclSpec::getSpecifierName(TSCS);
17572 
17573   // Check to see if this name was declared as a member previously
17574   NamedDecl *PrevDecl = nullptr;
17575   LookupResult Previous(*this, II, Loc, LookupMemberName,
17576                         ForVisibleRedeclaration);
17577   LookupName(Previous, S);
17578   switch (Previous.getResultKind()) {
17579   case LookupResult::Found:
17580   case LookupResult::FoundUnresolvedValue:
17581     PrevDecl = Previous.getAsSingle<NamedDecl>();
17582     break;
17583 
17584   case LookupResult::FoundOverloaded:
17585     PrevDecl = Previous.getRepresentativeDecl();
17586     break;
17587 
17588   case LookupResult::NotFound:
17589   case LookupResult::NotFoundInCurrentInstantiation:
17590   case LookupResult::Ambiguous:
17591     break;
17592   }
17593 
17594   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17595     // Maybe we will complain about the shadowed template parameter.
17596     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17597     // Just pretend that we didn't see the previous declaration.
17598     PrevDecl = nullptr;
17599   }
17600 
17601   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17602     PrevDecl = nullptr;
17603 
17604   SourceLocation TSSL = D.getBeginLoc();
17605   MSPropertyDecl *NewPD =
17606       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17607                              MSPropertyAttr.getPropertyDataGetter(),
17608                              MSPropertyAttr.getPropertyDataSetter());
17609   ProcessDeclAttributes(TUScope, NewPD, D);
17610   NewPD->setAccess(AS);
17611 
17612   if (NewPD->isInvalidDecl())
17613     Record->setInvalidDecl();
17614 
17615   if (D.getDeclSpec().isModulePrivateSpecified())
17616     NewPD->setModulePrivate();
17617 
17618   if (NewPD->isInvalidDecl() && PrevDecl) {
17619     // Don't introduce NewFD into scope; there's already something
17620     // with the same name in the same scope.
17621   } else if (II) {
17622     PushOnScopeChains(NewPD, S);
17623   } else
17624     Record->addDecl(NewPD);
17625 
17626   return NewPD;
17627 }
17628 
17629 void Sema::ActOnStartFunctionDeclarationDeclarator(
17630     Declarator &Declarator, unsigned TemplateParameterDepth) {
17631   auto &Info = InventedParameterInfos.emplace_back();
17632   TemplateParameterList *ExplicitParams = nullptr;
17633   ArrayRef<TemplateParameterList *> ExplicitLists =
17634       Declarator.getTemplateParameterLists();
17635   if (!ExplicitLists.empty()) {
17636     bool IsMemberSpecialization, IsInvalid;
17637     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17638         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17639         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17640         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17641         /*SuppressDiagnostic=*/true);
17642   }
17643   if (ExplicitParams) {
17644     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17645     for (NamedDecl *Param : *ExplicitParams)
17646       Info.TemplateParams.push_back(Param);
17647     Info.NumExplicitTemplateParams = ExplicitParams->size();
17648   } else {
17649     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17650     Info.NumExplicitTemplateParams = 0;
17651   }
17652 }
17653 
17654 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17655   auto &FSI = InventedParameterInfos.back();
17656   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17657     if (FSI.NumExplicitTemplateParams != 0) {
17658       TemplateParameterList *ExplicitParams =
17659           Declarator.getTemplateParameterLists().back();
17660       Declarator.setInventedTemplateParameterList(
17661           TemplateParameterList::Create(
17662               Context, ExplicitParams->getTemplateLoc(),
17663               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17664               ExplicitParams->getRAngleLoc(),
17665               ExplicitParams->getRequiresClause()));
17666     } else {
17667       Declarator.setInventedTemplateParameterList(
17668           TemplateParameterList::Create(
17669               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17670               SourceLocation(), /*RequiresClause=*/nullptr));
17671     }
17672   }
17673   InventedParameterInfos.pop_back();
17674 }
17675