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::CalledExpr(Expr *E) {
221   if (!E || 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(E))
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   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
779   QualType R = TInfo->getType();
780 
781   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
782                                       UPPC_DeclarationType))
783     D.setInvalidType();
784 
785   // The syntax only allows a single ref-qualifier prior to the decomposition
786   // declarator. No other declarator chunks are permitted. Also check the type
787   // specifier here.
788   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
789       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
790       (D.getNumTypeObjects() == 1 &&
791        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
792     Diag(Decomp.getLSquareLoc(),
793          (D.hasGroupingParens() ||
794           (D.getNumTypeObjects() &&
795            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
796              ? diag::err_decomp_decl_parens
797              : diag::err_decomp_decl_type)
798         << R;
799 
800     // In most cases, there's no actual problem with an explicitly-specified
801     // type, but a function type won't work here, and ActOnVariableDeclarator
802     // shouldn't be called for such a type.
803     if (R->isFunctionType())
804       D.setInvalidType();
805   }
806 
807   // Build the BindingDecls.
808   SmallVector<BindingDecl*, 8> Bindings;
809 
810   // Build the BindingDecls.
811   for (auto &B : D.getDecompositionDeclarator().bindings()) {
812     // Check for name conflicts.
813     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
814     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
815                           ForVisibleRedeclaration);
816     LookupName(Previous, S,
817                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
818 
819     // It's not permitted to shadow a template parameter name.
820     if (Previous.isSingleResult() &&
821         Previous.getFoundDecl()->isTemplateParameter()) {
822       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
823                                       Previous.getFoundDecl());
824       Previous.clear();
825     }
826 
827     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
828                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
829     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
830                          /*AllowInlineNamespace*/false);
831     if (!Previous.empty()) {
832       auto *Old = Previous.getRepresentativeDecl();
833       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
834       Diag(Old->getLocation(), diag::note_previous_definition);
835     }
836 
837     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
838     PushOnScopeChains(BD, S, true);
839     Bindings.push_back(BD);
840     ParsingInitForAutoVars.insert(BD);
841   }
842 
843   // There are no prior lookup results for the variable itself, because it
844   // is unnamed.
845   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
846                                Decomp.getLSquareLoc());
847   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848                         ForVisibleRedeclaration);
849 
850   // Build the variable that holds the non-decomposed object.
851   bool AddToScope = true;
852   NamedDecl *New =
853       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
854                               MultiTemplateParamsArg(), AddToScope, Bindings);
855   if (AddToScope) {
856     S->AddDecl(New);
857     CurContext->addHiddenDecl(New);
858   }
859 
860   if (isInOpenMPDeclareTargetContext())
861     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
862 
863   return New;
864 }
865 
866 static bool checkSimpleDecomposition(
867     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
868     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
869     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
870   if ((int64_t)Bindings.size() != NumElems) {
871     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
872         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
873         << (NumElems < Bindings.size());
874     return true;
875   }
876 
877   unsigned I = 0;
878   for (auto *B : Bindings) {
879     SourceLocation Loc = B->getLocation();
880     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
881     if (E.isInvalid())
882       return true;
883     E = GetInit(Loc, E.get(), I++);
884     if (E.isInvalid())
885       return true;
886     B->setBinding(ElemType, E.get());
887   }
888 
889   return false;
890 }
891 
892 static bool checkArrayLikeDecomposition(Sema &S,
893                                         ArrayRef<BindingDecl *> Bindings,
894                                         ValueDecl *Src, QualType DecompType,
895                                         const llvm::APSInt &NumElems,
896                                         QualType ElemType) {
897   return checkSimpleDecomposition(
898       S, Bindings, Src, DecompType, NumElems, ElemType,
899       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
900         ExprResult E = S.ActOnIntegerConstant(Loc, I);
901         if (E.isInvalid())
902           return ExprError();
903         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
904       });
905 }
906 
907 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
908                                     ValueDecl *Src, QualType DecompType,
909                                     const ConstantArrayType *CAT) {
910   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
911                                      llvm::APSInt(CAT->getSize()),
912                                      CAT->getElementType());
913 }
914 
915 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
916                                      ValueDecl *Src, QualType DecompType,
917                                      const VectorType *VT) {
918   return checkArrayLikeDecomposition(
919       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
920       S.Context.getQualifiedType(VT->getElementType(),
921                                  DecompType.getQualifiers()));
922 }
923 
924 static bool checkComplexDecomposition(Sema &S,
925                                       ArrayRef<BindingDecl *> Bindings,
926                                       ValueDecl *Src, QualType DecompType,
927                                       const ComplexType *CT) {
928   return checkSimpleDecomposition(
929       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
930       S.Context.getQualifiedType(CT->getElementType(),
931                                  DecompType.getQualifiers()),
932       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
933         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
934       });
935 }
936 
937 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
938                                      TemplateArgumentListInfo &Args) {
939   SmallString<128> SS;
940   llvm::raw_svector_ostream OS(SS);
941   bool First = true;
942   for (auto &Arg : Args.arguments()) {
943     if (!First)
944       OS << ", ";
945     Arg.getArgument().print(PrintingPolicy, OS);
946     First = false;
947   }
948   return OS.str();
949 }
950 
951 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
952                                      SourceLocation Loc, StringRef Trait,
953                                      TemplateArgumentListInfo &Args,
954                                      unsigned DiagID) {
955   auto DiagnoseMissing = [&] {
956     if (DiagID)
957       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
958                                                Args);
959     return true;
960   };
961 
962   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
963   NamespaceDecl *Std = S.getStdNamespace();
964   if (!Std)
965     return DiagnoseMissing();
966 
967   // Look up the trait itself, within namespace std. We can diagnose various
968   // problems with this lookup even if we've been asked to not diagnose a
969   // missing specialization, because this can only fail if the user has been
970   // declaring their own names in namespace std or we don't support the
971   // standard library implementation in use.
972   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
973                       Loc, Sema::LookupOrdinaryName);
974   if (!S.LookupQualifiedName(Result, Std))
975     return DiagnoseMissing();
976   if (Result.isAmbiguous())
977     return true;
978 
979   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
980   if (!TraitTD) {
981     Result.suppressDiagnostics();
982     NamedDecl *Found = *Result.begin();
983     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
984     S.Diag(Found->getLocation(), diag::note_declared_at);
985     return true;
986   }
987 
988   // Build the template-id.
989   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
990   if (TraitTy.isNull())
991     return true;
992   if (!S.isCompleteType(Loc, TraitTy)) {
993     if (DiagID)
994       S.RequireCompleteType(
995           Loc, TraitTy, DiagID,
996           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
997     return true;
998   }
999 
1000   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1001   assert(RD && "specialization of class template is not a class?");
1002 
1003   // Look up the member of the trait type.
1004   S.LookupQualifiedName(TraitMemberLookup, RD);
1005   return TraitMemberLookup.isAmbiguous();
1006 }
1007 
1008 static TemplateArgumentLoc
1009 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1010                                    uint64_t I) {
1011   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1012   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1013 }
1014 
1015 static TemplateArgumentLoc
1016 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1017   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1018 }
1019 
1020 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1021 
1022 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1023                                llvm::APSInt &Size) {
1024   EnterExpressionEvaluationContext ContextRAII(
1025       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1026 
1027   DeclarationName Value = S.PP.getIdentifierInfo("value");
1028   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1029 
1030   // Form template argument list for tuple_size<T>.
1031   TemplateArgumentListInfo Args(Loc, Loc);
1032   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1033 
1034   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1035   // it's not tuple-like.
1036   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1037       R.empty())
1038     return IsTupleLike::NotTupleLike;
1039 
1040   // If we get this far, we've committed to the tuple interpretation, but
1041   // we can still fail if there actually isn't a usable ::value.
1042 
1043   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1044     LookupResult &R;
1045     TemplateArgumentListInfo &Args;
1046     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1047         : R(R), Args(Args) {}
1048     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1049       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1050           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1051     }
1052   } Diagnoser(R, Args);
1053 
1054   ExprResult E =
1055       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1056   if (E.isInvalid())
1057     return IsTupleLike::Error;
1058 
1059   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1060   if (E.isInvalid())
1061     return IsTupleLike::Error;
1062 
1063   return IsTupleLike::TupleLike;
1064 }
1065 
1066 /// \return std::tuple_element<I, T>::type.
1067 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1068                                         unsigned I, QualType T) {
1069   // Form template argument list for tuple_element<I, T>.
1070   TemplateArgumentListInfo Args(Loc, Loc);
1071   Args.addArgument(
1072       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1073   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1074 
1075   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1076   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1077   if (lookupStdTypeTraitMember(
1078           S, R, Loc, "tuple_element", Args,
1079           diag::err_decomp_decl_std_tuple_element_not_specialized))
1080     return QualType();
1081 
1082   auto *TD = R.getAsSingle<TypeDecl>();
1083   if (!TD) {
1084     R.suppressDiagnostics();
1085     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1086       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1087     if (!R.empty())
1088       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1089     return QualType();
1090   }
1091 
1092   return S.Context.getTypeDeclType(TD);
1093 }
1094 
1095 namespace {
1096 struct BindingDiagnosticTrap {
1097   Sema &S;
1098   DiagnosticErrorTrap Trap;
1099   BindingDecl *BD;
1100 
1101   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1102       : S(S), Trap(S.Diags), BD(BD) {}
1103   ~BindingDiagnosticTrap() {
1104     if (Trap.hasErrorOccurred())
1105       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1106   }
1107 };
1108 }
1109 
1110 static bool checkTupleLikeDecomposition(Sema &S,
1111                                         ArrayRef<BindingDecl *> Bindings,
1112                                         VarDecl *Src, QualType DecompType,
1113                                         const llvm::APSInt &TupleSize) {
1114   if ((int64_t)Bindings.size() != TupleSize) {
1115     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1116         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1117         << (TupleSize < Bindings.size());
1118     return true;
1119   }
1120 
1121   if (Bindings.empty())
1122     return false;
1123 
1124   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1125 
1126   // [dcl.decomp]p3:
1127   //   The unqualified-id get is looked up in the scope of E by class member
1128   //   access lookup ...
1129   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1130   bool UseMemberGet = false;
1131   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1132     if (auto *RD = DecompType->getAsCXXRecordDecl())
1133       S.LookupQualifiedName(MemberGet, RD);
1134     if (MemberGet.isAmbiguous())
1135       return true;
1136     //   ... and if that finds at least one declaration that is a function
1137     //   template whose first template parameter is a non-type parameter ...
1138     for (NamedDecl *D : MemberGet) {
1139       if (FunctionTemplateDecl *FTD =
1140               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1141         TemplateParameterList *TPL = FTD->getTemplateParameters();
1142         if (TPL->size() != 0 &&
1143             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1144           //   ... the initializer is e.get<i>().
1145           UseMemberGet = true;
1146           break;
1147         }
1148       }
1149     }
1150   }
1151 
1152   unsigned I = 0;
1153   for (auto *B : Bindings) {
1154     BindingDiagnosticTrap Trap(S, B);
1155     SourceLocation Loc = B->getLocation();
1156 
1157     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1158     if (E.isInvalid())
1159       return true;
1160 
1161     //   e is an lvalue if the type of the entity is an lvalue reference and
1162     //   an xvalue otherwise
1163     if (!Src->getType()->isLValueReferenceType())
1164       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1165                                    E.get(), nullptr, VK_XValue);
1166 
1167     TemplateArgumentListInfo Args(Loc, Loc);
1168     Args.addArgument(
1169         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1170 
1171     if (UseMemberGet) {
1172       //   if [lookup of member get] finds at least one declaration, the
1173       //   initializer is e.get<i-1>().
1174       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1175                                      CXXScopeSpec(), SourceLocation(), nullptr,
1176                                      MemberGet, &Args, nullptr);
1177       if (E.isInvalid())
1178         return true;
1179 
1180       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1181     } else {
1182       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1183       //   in the associated namespaces.
1184       Expr *Get = UnresolvedLookupExpr::Create(
1185           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1186           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1187           UnresolvedSetIterator(), UnresolvedSetIterator());
1188 
1189       Expr *Arg = E.get();
1190       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1191     }
1192     if (E.isInvalid())
1193       return true;
1194     Expr *Init = E.get();
1195 
1196     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1197     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1198     if (T.isNull())
1199       return true;
1200 
1201     //   each vi is a variable of type "reference to T" initialized with the
1202     //   initializer, where the reference is an lvalue reference if the
1203     //   initializer is an lvalue and an rvalue reference otherwise
1204     QualType RefType =
1205         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1206     if (RefType.isNull())
1207       return true;
1208     auto *RefVD = VarDecl::Create(
1209         S.Context, Src->getDeclContext(), Loc, Loc,
1210         B->getDeclName().getAsIdentifierInfo(), RefType,
1211         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1212     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1213     RefVD->setTSCSpec(Src->getTSCSpec());
1214     RefVD->setImplicit();
1215     if (Src->isInlineSpecified())
1216       RefVD->setInlineSpecified();
1217     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1218 
1219     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1220     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1221     InitializationSequence Seq(S, Entity, Kind, Init);
1222     E = Seq.Perform(S, Entity, Kind, Init);
1223     if (E.isInvalid())
1224       return true;
1225     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1226     if (E.isInvalid())
1227       return true;
1228     RefVD->setInit(E.get());
1229     if (!E.get()->isValueDependent())
1230       RefVD->checkInitIsICE();
1231 
1232     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1233                                    DeclarationNameInfo(B->getDeclName(), Loc),
1234                                    RefVD);
1235     if (E.isInvalid())
1236       return true;
1237 
1238     B->setBinding(T, E.get());
1239     I++;
1240   }
1241 
1242   return false;
1243 }
1244 
1245 /// Find the base class to decompose in a built-in decomposition of a class type.
1246 /// This base class search is, unfortunately, not quite like any other that we
1247 /// perform anywhere else in C++.
1248 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1249                                                 const CXXRecordDecl *RD,
1250                                                 CXXCastPath &BasePath) {
1251   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1252                           CXXBasePath &Path) {
1253     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1254   };
1255 
1256   const CXXRecordDecl *ClassWithFields = nullptr;
1257   AccessSpecifier AS = AS_public;
1258   if (RD->hasDirectFields())
1259     // [dcl.decomp]p4:
1260     //   Otherwise, all of E's non-static data members shall be public direct
1261     //   members of E ...
1262     ClassWithFields = RD;
1263   else {
1264     //   ... or of ...
1265     CXXBasePaths Paths;
1266     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1267     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1268       // If no classes have fields, just decompose RD itself. (This will work
1269       // if and only if zero bindings were provided.)
1270       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1271     }
1272 
1273     CXXBasePath *BestPath = nullptr;
1274     for (auto &P : Paths) {
1275       if (!BestPath)
1276         BestPath = &P;
1277       else if (!S.Context.hasSameType(P.back().Base->getType(),
1278                                       BestPath->back().Base->getType())) {
1279         //   ... the same ...
1280         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1281           << false << RD << BestPath->back().Base->getType()
1282           << P.back().Base->getType();
1283         return DeclAccessPair();
1284       } else if (P.Access < BestPath->Access) {
1285         BestPath = &P;
1286       }
1287     }
1288 
1289     //   ... unambiguous ...
1290     QualType BaseType = BestPath->back().Base->getType();
1291     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1292       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1293         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1294       return DeclAccessPair();
1295     }
1296 
1297     //   ... [accessible, implied by other rules] base class of E.
1298     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1299                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1300     AS = BestPath->Access;
1301 
1302     ClassWithFields = BaseType->getAsCXXRecordDecl();
1303     S.BuildBasePathArray(Paths, BasePath);
1304   }
1305 
1306   // The above search did not check whether the selected class itself has base
1307   // classes with fields, so check that now.
1308   CXXBasePaths Paths;
1309   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1310     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1311       << (ClassWithFields == RD) << RD << ClassWithFields
1312       << Paths.front().back().Base->getType();
1313     return DeclAccessPair();
1314   }
1315 
1316   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1317 }
1318 
1319 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1320                                      ValueDecl *Src, QualType DecompType,
1321                                      const CXXRecordDecl *OrigRD) {
1322   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1323                             diag::err_incomplete_type))
1324     return true;
1325 
1326   CXXCastPath BasePath;
1327   DeclAccessPair BasePair =
1328       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1329   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1330   if (!RD)
1331     return true;
1332   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1333                                                  DecompType.getQualifiers());
1334 
1335   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1336     unsigned NumFields =
1337         std::count_if(RD->field_begin(), RD->field_end(),
1338                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1339     assert(Bindings.size() != NumFields);
1340     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1341         << DecompType << (unsigned)Bindings.size() << NumFields
1342         << (NumFields < Bindings.size());
1343     return true;
1344   };
1345 
1346   //   all of E's non-static data members shall be [...] well-formed
1347   //   when named as e.name in the context of the structured binding,
1348   //   E shall not have an anonymous union member, ...
1349   unsigned I = 0;
1350   for (auto *FD : RD->fields()) {
1351     if (FD->isUnnamedBitfield())
1352       continue;
1353 
1354     if (FD->isAnonymousStructOrUnion()) {
1355       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1356         << DecompType << FD->getType()->isUnionType();
1357       S.Diag(FD->getLocation(), diag::note_declared_at);
1358       return true;
1359     }
1360 
1361     // We have a real field to bind.
1362     if (I >= Bindings.size())
1363       return DiagnoseBadNumberOfBindings();
1364     auto *B = Bindings[I++];
1365     SourceLocation Loc = B->getLocation();
1366 
1367     // The field must be accessible in the context of the structured binding.
1368     // We already checked that the base class is accessible.
1369     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1370     // const_cast here.
1371     S.CheckStructuredBindingMemberAccess(
1372         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1373         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1374                                      BasePair.getAccess(), FD->getAccess())));
1375 
1376     // Initialize the binding to Src.FD.
1377     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1378     if (E.isInvalid())
1379       return true;
1380     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1381                             VK_LValue, &BasePath);
1382     if (E.isInvalid())
1383       return true;
1384     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1385                                   CXXScopeSpec(), FD,
1386                                   DeclAccessPair::make(FD, FD->getAccess()),
1387                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1388     if (E.isInvalid())
1389       return true;
1390 
1391     // If the type of the member is T, the referenced type is cv T, where cv is
1392     // the cv-qualification of the decomposition expression.
1393     //
1394     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1395     // 'const' to the type of the field.
1396     Qualifiers Q = DecompType.getQualifiers();
1397     if (FD->isMutable())
1398       Q.removeConst();
1399     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1400   }
1401 
1402   if (I != Bindings.size())
1403     return DiagnoseBadNumberOfBindings();
1404 
1405   return false;
1406 }
1407 
1408 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1409   QualType DecompType = DD->getType();
1410 
1411   // If the type of the decomposition is dependent, then so is the type of
1412   // each binding.
1413   if (DecompType->isDependentType()) {
1414     for (auto *B : DD->bindings())
1415       B->setType(Context.DependentTy);
1416     return;
1417   }
1418 
1419   DecompType = DecompType.getNonReferenceType();
1420   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1421 
1422   // C++1z [dcl.decomp]/2:
1423   //   If E is an array type [...]
1424   // As an extension, we also support decomposition of built-in complex and
1425   // vector types.
1426   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1427     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1428       DD->setInvalidDecl();
1429     return;
1430   }
1431   if (auto *VT = DecompType->getAs<VectorType>()) {
1432     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1433       DD->setInvalidDecl();
1434     return;
1435   }
1436   if (auto *CT = DecompType->getAs<ComplexType>()) {
1437     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1438       DD->setInvalidDecl();
1439     return;
1440   }
1441 
1442   // C++1z [dcl.decomp]/3:
1443   //   if the expression std::tuple_size<E>::value is a well-formed integral
1444   //   constant expression, [...]
1445   llvm::APSInt TupleSize(32);
1446   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1447   case IsTupleLike::Error:
1448     DD->setInvalidDecl();
1449     return;
1450 
1451   case IsTupleLike::TupleLike:
1452     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1453       DD->setInvalidDecl();
1454     return;
1455 
1456   case IsTupleLike::NotTupleLike:
1457     break;
1458   }
1459 
1460   // C++1z [dcl.dcl]/8:
1461   //   [E shall be of array or non-union class type]
1462   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1463   if (!RD || RD->isUnion()) {
1464     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1465         << DD << !RD << DecompType;
1466     DD->setInvalidDecl();
1467     return;
1468   }
1469 
1470   // C++1z [dcl.decomp]/4:
1471   //   all of E's non-static data members shall be [...] direct members of
1472   //   E or of the same unambiguous public base class of E, ...
1473   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1474     DD->setInvalidDecl();
1475 }
1476 
1477 /// Merge the exception specifications of two variable declarations.
1478 ///
1479 /// This is called when there's a redeclaration of a VarDecl. The function
1480 /// checks if the redeclaration might have an exception specification and
1481 /// validates compatibility and merges the specs if necessary.
1482 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1483   // Shortcut if exceptions are disabled.
1484   if (!getLangOpts().CXXExceptions)
1485     return;
1486 
1487   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1488          "Should only be called if types are otherwise the same.");
1489 
1490   QualType NewType = New->getType();
1491   QualType OldType = Old->getType();
1492 
1493   // We're only interested in pointers and references to functions, as well
1494   // as pointers to member functions.
1495   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1496     NewType = R->getPointeeType();
1497     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1498   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1499     NewType = P->getPointeeType();
1500     OldType = OldType->getAs<PointerType>()->getPointeeType();
1501   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1502     NewType = M->getPointeeType();
1503     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1504   }
1505 
1506   if (!NewType->isFunctionProtoType())
1507     return;
1508 
1509   // There's lots of special cases for functions. For function pointers, system
1510   // libraries are hopefully not as broken so that we don't need these
1511   // workarounds.
1512   if (CheckEquivalentExceptionSpec(
1513         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1514         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1515     New->setInvalidDecl();
1516   }
1517 }
1518 
1519 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1520 /// function declaration are well-formed according to C++
1521 /// [dcl.fct.default].
1522 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1523   unsigned NumParams = FD->getNumParams();
1524   unsigned p;
1525 
1526   // Find first parameter with a default argument
1527   for (p = 0; p < NumParams; ++p) {
1528     ParmVarDecl *Param = FD->getParamDecl(p);
1529     if (Param->hasDefaultArg())
1530       break;
1531   }
1532 
1533   // C++11 [dcl.fct.default]p4:
1534   //   In a given function declaration, each parameter subsequent to a parameter
1535   //   with a default argument shall have a default argument supplied in this or
1536   //   a previous declaration or shall be a function parameter pack. A default
1537   //   argument shall not be redefined by a later declaration (not even to the
1538   //   same value).
1539   unsigned LastMissingDefaultArg = 0;
1540   for (; p < NumParams; ++p) {
1541     ParmVarDecl *Param = FD->getParamDecl(p);
1542     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1543       if (Param->isInvalidDecl())
1544         /* We already complained about this parameter. */;
1545       else if (Param->getIdentifier())
1546         Diag(Param->getLocation(),
1547              diag::err_param_default_argument_missing_name)
1548           << Param->getIdentifier();
1549       else
1550         Diag(Param->getLocation(),
1551              diag::err_param_default_argument_missing);
1552 
1553       LastMissingDefaultArg = p;
1554     }
1555   }
1556 
1557   if (LastMissingDefaultArg > 0) {
1558     // Some default arguments were missing. Clear out all of the
1559     // default arguments up to (and including) the last missing
1560     // default argument, so that we leave the function parameters
1561     // in a semantically valid state.
1562     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1563       ParmVarDecl *Param = FD->getParamDecl(p);
1564       if (Param->hasDefaultArg()) {
1565         Param->setDefaultArg(nullptr);
1566       }
1567     }
1568   }
1569 }
1570 
1571 /// Check that the given type is a literal type. Issue a diagnostic if not,
1572 /// if Kind is Diagnose.
1573 /// \return \c true if a problem has been found (and optionally diagnosed).
1574 template <typename... Ts>
1575 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1576                              SourceLocation Loc, QualType T, unsigned DiagID,
1577                              Ts &&...DiagArgs) {
1578   if (T->isDependentType())
1579     return false;
1580 
1581   switch (Kind) {
1582   case Sema::CheckConstexprKind::Diagnose:
1583     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1584                                       std::forward<Ts>(DiagArgs)...);
1585 
1586   case Sema::CheckConstexprKind::CheckValid:
1587     return !T->isLiteralType(SemaRef.Context);
1588   }
1589 
1590   llvm_unreachable("unknown CheckConstexprKind");
1591 }
1592 
1593 // CheckConstexprParameterTypes - Check whether a function's parameter types
1594 // are all literal types. If so, return true. If not, produce a suitable
1595 // diagnostic and return false.
1596 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1597                                          const FunctionDecl *FD,
1598                                          Sema::CheckConstexprKind Kind) {
1599   unsigned ArgIndex = 0;
1600   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1601   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1602                                               e = FT->param_type_end();
1603        i != e; ++i, ++ArgIndex) {
1604     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1605     SourceLocation ParamLoc = PD->getLocation();
1606     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1607                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1608                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1609                          FD->isConsteval()))
1610       return false;
1611   }
1612   return true;
1613 }
1614 
1615 /// Get diagnostic %select index for tag kind for
1616 /// record diagnostic message.
1617 /// WARNING: Indexes apply to particular diagnostics only!
1618 ///
1619 /// \returns diagnostic %select index.
1620 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1621   switch (Tag) {
1622   case TTK_Struct: return 0;
1623   case TTK_Interface: return 1;
1624   case TTK_Class:  return 2;
1625   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1626   }
1627 }
1628 
1629 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1630                                        Stmt *Body,
1631                                        Sema::CheckConstexprKind Kind);
1632 
1633 // Check whether a function declaration satisfies the requirements of a
1634 // constexpr function definition or a constexpr constructor definition. If so,
1635 // return true. If not, produce appropriate diagnostics (unless asked not to by
1636 // Kind) and return false.
1637 //
1638 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1639 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1640                                             CheckConstexprKind Kind) {
1641   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1642   if (MD && MD->isInstance()) {
1643     // C++11 [dcl.constexpr]p4:
1644     //  The definition of a constexpr constructor shall satisfy the following
1645     //  constraints:
1646     //  - the class shall not have any virtual base classes;
1647     //
1648     // FIXME: This only applies to constructors, not arbitrary member
1649     // functions.
1650     const CXXRecordDecl *RD = MD->getParent();
1651     if (RD->getNumVBases()) {
1652       if (Kind == CheckConstexprKind::CheckValid)
1653         return false;
1654 
1655       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1656         << isa<CXXConstructorDecl>(NewFD)
1657         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1658       for (const auto &I : RD->vbases())
1659         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1660             << I.getSourceRange();
1661       return false;
1662     }
1663   }
1664 
1665   if (!isa<CXXConstructorDecl>(NewFD)) {
1666     // C++11 [dcl.constexpr]p3:
1667     //  The definition of a constexpr function shall satisfy the following
1668     //  constraints:
1669     // - it shall not be virtual; (removed in C++20)
1670     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1671     if (Method && Method->isVirtual()) {
1672       if (getLangOpts().CPlusPlus2a) {
1673         if (Kind == CheckConstexprKind::Diagnose)
1674           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1675       } else {
1676         if (Kind == CheckConstexprKind::CheckValid)
1677           return false;
1678 
1679         Method = Method->getCanonicalDecl();
1680         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1681 
1682         // If it's not obvious why this function is virtual, find an overridden
1683         // function which uses the 'virtual' keyword.
1684         const CXXMethodDecl *WrittenVirtual = Method;
1685         while (!WrittenVirtual->isVirtualAsWritten())
1686           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1687         if (WrittenVirtual != Method)
1688           Diag(WrittenVirtual->getLocation(),
1689                diag::note_overridden_virtual_function);
1690         return false;
1691       }
1692     }
1693 
1694     // - its return type shall be a literal type;
1695     QualType RT = NewFD->getReturnType();
1696     if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
1697                          diag::err_constexpr_non_literal_return,
1698                          NewFD->isConsteval()))
1699       return false;
1700   }
1701 
1702   // - each of its parameter types shall be a literal type;
1703   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1704     return false;
1705 
1706   Stmt *Body = NewFD->getBody();
1707   assert(Body &&
1708          "CheckConstexprFunctionDefinition called on function with no body");
1709   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1710 }
1711 
1712 /// Check the given declaration statement is legal within a constexpr function
1713 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1714 ///
1715 /// \return true if the body is OK (maybe only as an extension), false if we
1716 ///         have diagnosed a problem.
1717 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1718                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1719                                    Sema::CheckConstexprKind Kind) {
1720   // C++11 [dcl.constexpr]p3 and p4:
1721   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1722   //  contain only
1723   for (const auto *DclIt : DS->decls()) {
1724     switch (DclIt->getKind()) {
1725     case Decl::StaticAssert:
1726     case Decl::Using:
1727     case Decl::UsingShadow:
1728     case Decl::UsingDirective:
1729     case Decl::UnresolvedUsingTypename:
1730     case Decl::UnresolvedUsingValue:
1731       //   - static_assert-declarations
1732       //   - using-declarations,
1733       //   - using-directives,
1734       continue;
1735 
1736     case Decl::Typedef:
1737     case Decl::TypeAlias: {
1738       //   - typedef declarations and alias-declarations that do not define
1739       //     classes or enumerations,
1740       const auto *TN = cast<TypedefNameDecl>(DclIt);
1741       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1742         // Don't allow variably-modified types in constexpr functions.
1743         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1744           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1745           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1746             << TL.getSourceRange() << TL.getType()
1747             << isa<CXXConstructorDecl>(Dcl);
1748         }
1749         return false;
1750       }
1751       continue;
1752     }
1753 
1754     case Decl::Enum:
1755     case Decl::CXXRecord:
1756       // C++1y allows types to be defined, not just declared.
1757       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1758         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1759           SemaRef.Diag(DS->getBeginLoc(),
1760                        SemaRef.getLangOpts().CPlusPlus14
1761                            ? diag::warn_cxx11_compat_constexpr_type_definition
1762                            : diag::ext_constexpr_type_definition)
1763               << isa<CXXConstructorDecl>(Dcl);
1764         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1765           return false;
1766         }
1767       }
1768       continue;
1769 
1770     case Decl::EnumConstant:
1771     case Decl::IndirectField:
1772     case Decl::ParmVar:
1773       // These can only appear with other declarations which are banned in
1774       // C++11 and permitted in C++1y, so ignore them.
1775       continue;
1776 
1777     case Decl::Var:
1778     case Decl::Decomposition: {
1779       // C++1y [dcl.constexpr]p3 allows anything except:
1780       //   a definition of a variable of non-literal type or of static or
1781       //   thread storage duration or [before C++2a] for which no
1782       //   initialization is performed.
1783       const auto *VD = cast<VarDecl>(DclIt);
1784       if (VD->isThisDeclarationADefinition()) {
1785         if (VD->isStaticLocal()) {
1786           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1787             SemaRef.Diag(VD->getLocation(),
1788                          diag::err_constexpr_local_var_static)
1789               << isa<CXXConstructorDecl>(Dcl)
1790               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1791           }
1792           return false;
1793         }
1794         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1795                              diag::err_constexpr_local_var_non_literal_type,
1796                              isa<CXXConstructorDecl>(Dcl)))
1797           return false;
1798         if (!VD->getType()->isDependentType() &&
1799             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1800           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1801             SemaRef.Diag(
1802                 VD->getLocation(),
1803                 SemaRef.getLangOpts().CPlusPlus2a
1804                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1805                     : diag::ext_constexpr_local_var_no_init)
1806                 << isa<CXXConstructorDecl>(Dcl);
1807           } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
1808             return false;
1809           }
1810           continue;
1811         }
1812       }
1813       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1814         SemaRef.Diag(VD->getLocation(),
1815                      SemaRef.getLangOpts().CPlusPlus14
1816                       ? diag::warn_cxx11_compat_constexpr_local_var
1817                       : diag::ext_constexpr_local_var)
1818           << isa<CXXConstructorDecl>(Dcl);
1819       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1820         return false;
1821       }
1822       continue;
1823     }
1824 
1825     case Decl::NamespaceAlias:
1826     case Decl::Function:
1827       // These are disallowed in C++11 and permitted in C++1y. Allow them
1828       // everywhere as an extension.
1829       if (!Cxx1yLoc.isValid())
1830         Cxx1yLoc = DS->getBeginLoc();
1831       continue;
1832 
1833     default:
1834       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1835         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1836             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1837       }
1838       return false;
1839     }
1840   }
1841 
1842   return true;
1843 }
1844 
1845 /// Check that the given field is initialized within a constexpr constructor.
1846 ///
1847 /// \param Dcl The constexpr constructor being checked.
1848 /// \param Field The field being checked. This may be a member of an anonymous
1849 ///        struct or union nested within the class being checked.
1850 /// \param Inits All declarations, including anonymous struct/union members and
1851 ///        indirect members, for which any initialization was provided.
1852 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1853 ///        multiple notes for different members to the same error.
1854 /// \param Kind Whether we're diagnosing a constructor as written or determining
1855 ///        whether the formal requirements are satisfied.
1856 /// \return \c false if we're checking for validity and the constructor does
1857 ///         not satisfy the requirements on a constexpr constructor.
1858 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1859                                           const FunctionDecl *Dcl,
1860                                           FieldDecl *Field,
1861                                           llvm::SmallSet<Decl*, 16> &Inits,
1862                                           bool &Diagnosed,
1863                                           Sema::CheckConstexprKind Kind) {
1864   // In C++20 onwards, there's nothing to check for validity.
1865   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1866       SemaRef.getLangOpts().CPlusPlus2a)
1867     return true;
1868 
1869   if (Field->isInvalidDecl())
1870     return true;
1871 
1872   if (Field->isUnnamedBitfield())
1873     return true;
1874 
1875   // Anonymous unions with no variant members and empty anonymous structs do not
1876   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1877   // indirect fields don't need initializing.
1878   if (Field->isAnonymousStructOrUnion() &&
1879       (Field->getType()->isUnionType()
1880            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1881            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1882     return true;
1883 
1884   if (!Inits.count(Field)) {
1885     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1886       if (!Diagnosed) {
1887         SemaRef.Diag(Dcl->getLocation(),
1888                      SemaRef.getLangOpts().CPlusPlus2a
1889                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1890                          : diag::ext_constexpr_ctor_missing_init);
1891         Diagnosed = true;
1892       }
1893       SemaRef.Diag(Field->getLocation(),
1894                    diag::note_constexpr_ctor_missing_init);
1895     } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
1896       return false;
1897     }
1898   } else if (Field->isAnonymousStructOrUnion()) {
1899     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1900     for (auto *I : RD->fields())
1901       // If an anonymous union contains an anonymous struct of which any member
1902       // is initialized, all members must be initialized.
1903       if (!RD->isUnion() || Inits.count(I))
1904         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1905                                            Kind))
1906           return false;
1907   }
1908   return true;
1909 }
1910 
1911 /// Check the provided statement is allowed in a constexpr function
1912 /// definition.
1913 static bool
1914 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1915                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1916                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1917                            Sema::CheckConstexprKind Kind) {
1918   // - its function-body shall be [...] a compound-statement that contains only
1919   switch (S->getStmtClass()) {
1920   case Stmt::NullStmtClass:
1921     //   - null statements,
1922     return true;
1923 
1924   case Stmt::DeclStmtClass:
1925     //   - static_assert-declarations
1926     //   - using-declarations,
1927     //   - using-directives,
1928     //   - typedef declarations and alias-declarations that do not define
1929     //     classes or enumerations,
1930     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1931       return false;
1932     return true;
1933 
1934   case Stmt::ReturnStmtClass:
1935     //   - and exactly one return statement;
1936     if (isa<CXXConstructorDecl>(Dcl)) {
1937       // C++1y allows return statements in constexpr constructors.
1938       if (!Cxx1yLoc.isValid())
1939         Cxx1yLoc = S->getBeginLoc();
1940       return true;
1941     }
1942 
1943     ReturnStmts.push_back(S->getBeginLoc());
1944     return true;
1945 
1946   case Stmt::CompoundStmtClass: {
1947     // C++1y allows compound-statements.
1948     if (!Cxx1yLoc.isValid())
1949       Cxx1yLoc = S->getBeginLoc();
1950 
1951     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1952     for (auto *BodyIt : CompStmt->body()) {
1953       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1954                                       Cxx1yLoc, Cxx2aLoc, Kind))
1955         return false;
1956     }
1957     return true;
1958   }
1959 
1960   case Stmt::AttributedStmtClass:
1961     if (!Cxx1yLoc.isValid())
1962       Cxx1yLoc = S->getBeginLoc();
1963     return true;
1964 
1965   case Stmt::IfStmtClass: {
1966     // C++1y allows if-statements.
1967     if (!Cxx1yLoc.isValid())
1968       Cxx1yLoc = S->getBeginLoc();
1969 
1970     IfStmt *If = cast<IfStmt>(S);
1971     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1972                                     Cxx1yLoc, Cxx2aLoc, Kind))
1973       return false;
1974     if (If->getElse() &&
1975         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1976                                     Cxx1yLoc, Cxx2aLoc, Kind))
1977       return false;
1978     return true;
1979   }
1980 
1981   case Stmt::WhileStmtClass:
1982   case Stmt::DoStmtClass:
1983   case Stmt::ForStmtClass:
1984   case Stmt::CXXForRangeStmtClass:
1985   case Stmt::ContinueStmtClass:
1986     // C++1y allows all of these. We don't allow them as extensions in C++11,
1987     // because they don't make sense without variable mutation.
1988     if (!SemaRef.getLangOpts().CPlusPlus14)
1989       break;
1990     if (!Cxx1yLoc.isValid())
1991       Cxx1yLoc = S->getBeginLoc();
1992     for (Stmt *SubStmt : S->children())
1993       if (SubStmt &&
1994           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1995                                       Cxx1yLoc, Cxx2aLoc, Kind))
1996         return false;
1997     return true;
1998 
1999   case Stmt::SwitchStmtClass:
2000   case Stmt::CaseStmtClass:
2001   case Stmt::DefaultStmtClass:
2002   case Stmt::BreakStmtClass:
2003     // C++1y allows switch-statements, and since they don't need variable
2004     // mutation, we can reasonably allow them in C++11 as an extension.
2005     if (!Cxx1yLoc.isValid())
2006       Cxx1yLoc = S->getBeginLoc();
2007     for (Stmt *SubStmt : S->children())
2008       if (SubStmt &&
2009           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2010                                       Cxx1yLoc, Cxx2aLoc, Kind))
2011         return false;
2012     return true;
2013 
2014   case Stmt::GCCAsmStmtClass:
2015   case Stmt::MSAsmStmtClass:
2016     // C++2a allows inline assembly statements.
2017   case Stmt::CXXTryStmtClass:
2018     if (Cxx2aLoc.isInvalid())
2019       Cxx2aLoc = S->getBeginLoc();
2020     for (Stmt *SubStmt : S->children()) {
2021       if (SubStmt &&
2022           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2023                                       Cxx1yLoc, Cxx2aLoc, Kind))
2024         return false;
2025     }
2026     return true;
2027 
2028   case Stmt::CXXCatchStmtClass:
2029     // Do not bother checking the language mode (already covered by the
2030     // try block check).
2031     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2032                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2033                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2034       return false;
2035     return true;
2036 
2037   default:
2038     if (!isa<Expr>(S))
2039       break;
2040 
2041     // C++1y allows expression-statements.
2042     if (!Cxx1yLoc.isValid())
2043       Cxx1yLoc = S->getBeginLoc();
2044     return true;
2045   }
2046 
2047   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2048     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2049         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2050   }
2051   return false;
2052 }
2053 
2054 /// Check the body for the given constexpr function declaration only contains
2055 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2056 ///
2057 /// \return true if the body is OK, false if we have found or diagnosed a
2058 /// problem.
2059 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2060                                        Stmt *Body,
2061                                        Sema::CheckConstexprKind Kind) {
2062   SmallVector<SourceLocation, 4> ReturnStmts;
2063 
2064   if (isa<CXXTryStmt>(Body)) {
2065     // C++11 [dcl.constexpr]p3:
2066     //  The definition of a constexpr function shall satisfy the following
2067     //  constraints: [...]
2068     // - its function-body shall be = delete, = default, or a
2069     //   compound-statement
2070     //
2071     // C++11 [dcl.constexpr]p4:
2072     //  In the definition of a constexpr constructor, [...]
2073     // - its function-body shall not be a function-try-block;
2074     //
2075     // This restriction is lifted in C++2a, as long as inner statements also
2076     // apply the general constexpr rules.
2077     switch (Kind) {
2078     case Sema::CheckConstexprKind::CheckValid:
2079       if (!SemaRef.getLangOpts().CPlusPlus2a)
2080         return false;
2081       break;
2082 
2083     case Sema::CheckConstexprKind::Diagnose:
2084       SemaRef.Diag(Body->getBeginLoc(),
2085            !SemaRef.getLangOpts().CPlusPlus2a
2086                ? diag::ext_constexpr_function_try_block_cxx2a
2087                : diag::warn_cxx17_compat_constexpr_function_try_block)
2088           << isa<CXXConstructorDecl>(Dcl);
2089       break;
2090     }
2091   }
2092 
2093   // - its function-body shall be [...] a compound-statement that contains only
2094   //   [... list of cases ...]
2095   //
2096   // Note that walking the children here is enough to properly check for
2097   // CompoundStmt and CXXTryStmt body.
2098   SourceLocation Cxx1yLoc, Cxx2aLoc;
2099   for (Stmt *SubStmt : Body->children()) {
2100     if (SubStmt &&
2101         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2102                                     Cxx1yLoc, Cxx2aLoc, Kind))
2103       return false;
2104   }
2105 
2106   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2107     // If this is only valid as an extension, report that we don't satisfy the
2108     // constraints of the current language.
2109     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
2110         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2111       return false;
2112   } else if (Cxx2aLoc.isValid()) {
2113     SemaRef.Diag(Cxx2aLoc,
2114          SemaRef.getLangOpts().CPlusPlus2a
2115            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2116            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2117       << isa<CXXConstructorDecl>(Dcl);
2118   } else if (Cxx1yLoc.isValid()) {
2119     SemaRef.Diag(Cxx1yLoc,
2120          SemaRef.getLangOpts().CPlusPlus14
2121            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2122            : diag::ext_constexpr_body_invalid_stmt)
2123       << isa<CXXConstructorDecl>(Dcl);
2124   }
2125 
2126   if (const CXXConstructorDecl *Constructor
2127         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2128     const CXXRecordDecl *RD = Constructor->getParent();
2129     // DR1359:
2130     // - every non-variant non-static data member and base class sub-object
2131     //   shall be initialized;
2132     // DR1460:
2133     // - if the class is a union having variant members, exactly one of them
2134     //   shall be initialized;
2135     if (RD->isUnion()) {
2136       if (Constructor->getNumCtorInitializers() == 0 &&
2137           RD->hasVariantMembers()) {
2138         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2139           SemaRef.Diag(
2140               Dcl->getLocation(),
2141               SemaRef.getLangOpts().CPlusPlus2a
2142                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2143                   : diag::ext_constexpr_union_ctor_no_init);
2144         } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
2145           return false;
2146         }
2147       }
2148     } else if (!Constructor->isDependentContext() &&
2149                !Constructor->isDelegatingConstructor()) {
2150       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2151 
2152       // Skip detailed checking if we have enough initializers, and we would
2153       // allow at most one initializer per member.
2154       bool AnyAnonStructUnionMembers = false;
2155       unsigned Fields = 0;
2156       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2157            E = RD->field_end(); I != E; ++I, ++Fields) {
2158         if (I->isAnonymousStructOrUnion()) {
2159           AnyAnonStructUnionMembers = true;
2160           break;
2161         }
2162       }
2163       // DR1460:
2164       // - if the class is a union-like class, but is not a union, for each of
2165       //   its anonymous union members having variant members, exactly one of
2166       //   them shall be initialized;
2167       if (AnyAnonStructUnionMembers ||
2168           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2169         // Check initialization of non-static data members. Base classes are
2170         // always initialized so do not need to be checked. Dependent bases
2171         // might not have initializers in the member initializer list.
2172         llvm::SmallSet<Decl*, 16> Inits;
2173         for (const auto *I: Constructor->inits()) {
2174           if (FieldDecl *FD = I->getMember())
2175             Inits.insert(FD);
2176           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2177             Inits.insert(ID->chain_begin(), ID->chain_end());
2178         }
2179 
2180         bool Diagnosed = false;
2181         for (auto *I : RD->fields())
2182           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2183                                              Kind))
2184             return false;
2185       }
2186     }
2187   } else {
2188     if (ReturnStmts.empty()) {
2189       // C++1y doesn't require constexpr functions to contain a 'return'
2190       // statement. We still do, unless the return type might be void, because
2191       // otherwise if there's no return statement, the function cannot
2192       // be used in a core constant expression.
2193       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2194                 (Dcl->getReturnType()->isVoidType() ||
2195                  Dcl->getReturnType()->isDependentType());
2196       switch (Kind) {
2197       case Sema::CheckConstexprKind::Diagnose:
2198         SemaRef.Diag(Dcl->getLocation(),
2199                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2200                         : diag::err_constexpr_body_no_return)
2201             << Dcl->isConsteval();
2202         if (!OK)
2203           return false;
2204         break;
2205 
2206       case Sema::CheckConstexprKind::CheckValid:
2207         // The formal requirements don't include this rule in C++14, even
2208         // though the "must be able to produce a constant expression" rules
2209         // still imply it in some cases.
2210         if (!SemaRef.getLangOpts().CPlusPlus14)
2211           return false;
2212         break;
2213       }
2214     } else if (ReturnStmts.size() > 1) {
2215       switch (Kind) {
2216       case Sema::CheckConstexprKind::Diagnose:
2217         SemaRef.Diag(
2218             ReturnStmts.back(),
2219             SemaRef.getLangOpts().CPlusPlus14
2220                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2221                 : diag::ext_constexpr_body_multiple_return);
2222         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2223           SemaRef.Diag(ReturnStmts[I],
2224                        diag::note_constexpr_body_previous_return);
2225         break;
2226 
2227       case Sema::CheckConstexprKind::CheckValid:
2228         if (!SemaRef.getLangOpts().CPlusPlus14)
2229           return false;
2230         break;
2231       }
2232     }
2233   }
2234 
2235   // C++11 [dcl.constexpr]p5:
2236   //   if no function argument values exist such that the function invocation
2237   //   substitution would produce a constant expression, the program is
2238   //   ill-formed; no diagnostic required.
2239   // C++11 [dcl.constexpr]p3:
2240   //   - every constructor call and implicit conversion used in initializing the
2241   //     return value shall be one of those allowed in a constant expression.
2242   // C++11 [dcl.constexpr]p4:
2243   //   - every constructor involved in initializing non-static data members and
2244   //     base class sub-objects shall be a constexpr constructor.
2245   //
2246   // Note that this rule is distinct from the "requirements for a constexpr
2247   // function", so is not checked in CheckValid mode.
2248   SmallVector<PartialDiagnosticAt, 8> Diags;
2249   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2250       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2251     SemaRef.Diag(Dcl->getLocation(),
2252                  diag::ext_constexpr_function_never_constant_expr)
2253         << isa<CXXConstructorDecl>(Dcl);
2254     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2255       SemaRef.Diag(Diags[I].first, Diags[I].second);
2256     // Don't return false here: we allow this for compatibility in
2257     // system headers.
2258   }
2259 
2260   return true;
2261 }
2262 
2263 /// Get the class that is directly named by the current context. This is the
2264 /// class for which an unqualified-id in this scope could name a constructor
2265 /// or destructor.
2266 ///
2267 /// If the scope specifier denotes a class, this will be that class.
2268 /// If the scope specifier is empty, this will be the class whose
2269 /// member-specification we are currently within. Otherwise, there
2270 /// is no such class.
2271 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2272   assert(getLangOpts().CPlusPlus && "No class names in C!");
2273 
2274   if (SS && SS->isInvalid())
2275     return nullptr;
2276 
2277   if (SS && SS->isNotEmpty()) {
2278     DeclContext *DC = computeDeclContext(*SS, true);
2279     return dyn_cast_or_null<CXXRecordDecl>(DC);
2280   }
2281 
2282   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2283 }
2284 
2285 /// isCurrentClassName - Determine whether the identifier II is the
2286 /// name of the class type currently being defined. In the case of
2287 /// nested classes, this will only return true if II is the name of
2288 /// the innermost class.
2289 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2290                               const CXXScopeSpec *SS) {
2291   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2292   return CurDecl && &II == CurDecl->getIdentifier();
2293 }
2294 
2295 /// Determine whether the identifier II is a typo for the name of
2296 /// the class type currently being defined. If so, update it to the identifier
2297 /// that should have been used.
2298 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2299   assert(getLangOpts().CPlusPlus && "No class names in C!");
2300 
2301   if (!getLangOpts().SpellChecking)
2302     return false;
2303 
2304   CXXRecordDecl *CurDecl;
2305   if (SS && SS->isSet() && !SS->isInvalid()) {
2306     DeclContext *DC = computeDeclContext(*SS, true);
2307     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2308   } else
2309     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2310 
2311   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2312       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2313           < II->getLength()) {
2314     II = CurDecl->getIdentifier();
2315     return true;
2316   }
2317 
2318   return false;
2319 }
2320 
2321 /// Determine whether the given class is a base class of the given
2322 /// class, including looking at dependent bases.
2323 static bool findCircularInheritance(const CXXRecordDecl *Class,
2324                                     const CXXRecordDecl *Current) {
2325   SmallVector<const CXXRecordDecl*, 8> Queue;
2326 
2327   Class = Class->getCanonicalDecl();
2328   while (true) {
2329     for (const auto &I : Current->bases()) {
2330       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2331       if (!Base)
2332         continue;
2333 
2334       Base = Base->getDefinition();
2335       if (!Base)
2336         continue;
2337 
2338       if (Base->getCanonicalDecl() == Class)
2339         return true;
2340 
2341       Queue.push_back(Base);
2342     }
2343 
2344     if (Queue.empty())
2345       return false;
2346 
2347     Current = Queue.pop_back_val();
2348   }
2349 
2350   return false;
2351 }
2352 
2353 /// Check the validity of a C++ base class specifier.
2354 ///
2355 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2356 /// and returns NULL otherwise.
2357 CXXBaseSpecifier *
2358 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2359                          SourceRange SpecifierRange,
2360                          bool Virtual, AccessSpecifier Access,
2361                          TypeSourceInfo *TInfo,
2362                          SourceLocation EllipsisLoc) {
2363   QualType BaseType = TInfo->getType();
2364 
2365   // C++ [class.union]p1:
2366   //   A union shall not have base classes.
2367   if (Class->isUnion()) {
2368     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2369       << SpecifierRange;
2370     return nullptr;
2371   }
2372 
2373   if (EllipsisLoc.isValid() &&
2374       !TInfo->getType()->containsUnexpandedParameterPack()) {
2375     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2376       << TInfo->getTypeLoc().getSourceRange();
2377     EllipsisLoc = SourceLocation();
2378   }
2379 
2380   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2381 
2382   if (BaseType->isDependentType()) {
2383     // Make sure that we don't have circular inheritance among our dependent
2384     // bases. For non-dependent bases, the check for completeness below handles
2385     // this.
2386     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2387       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2388           ((BaseDecl = BaseDecl->getDefinition()) &&
2389            findCircularInheritance(Class, BaseDecl))) {
2390         Diag(BaseLoc, diag::err_circular_inheritance)
2391           << BaseType << Context.getTypeDeclType(Class);
2392 
2393         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2394           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2395             << BaseType;
2396 
2397         return nullptr;
2398       }
2399     }
2400 
2401     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2402                                           Class->getTagKind() == TTK_Class,
2403                                           Access, TInfo, EllipsisLoc);
2404   }
2405 
2406   // Base specifiers must be record types.
2407   if (!BaseType->isRecordType()) {
2408     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2409     return nullptr;
2410   }
2411 
2412   // C++ [class.union]p1:
2413   //   A union shall not be used as a base class.
2414   if (BaseType->isUnionType()) {
2415     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2416     return nullptr;
2417   }
2418 
2419   // For the MS ABI, propagate DLL attributes to base class templates.
2420   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2421     if (Attr *ClassAttr = getDLLAttr(Class)) {
2422       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2423               BaseType->getAsCXXRecordDecl())) {
2424         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2425                                             BaseLoc);
2426       }
2427     }
2428   }
2429 
2430   // C++ [class.derived]p2:
2431   //   The class-name in a base-specifier shall not be an incompletely
2432   //   defined class.
2433   if (RequireCompleteType(BaseLoc, BaseType,
2434                           diag::err_incomplete_base_class, SpecifierRange)) {
2435     Class->setInvalidDecl();
2436     return nullptr;
2437   }
2438 
2439   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2440   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2441   assert(BaseDecl && "Record type has no declaration");
2442   BaseDecl = BaseDecl->getDefinition();
2443   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2444   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2445   assert(CXXBaseDecl && "Base type is not a C++ type");
2446 
2447   // Microsoft docs say:
2448   // "If a base-class has a code_seg attribute, derived classes must have the
2449   // same attribute."
2450   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2451   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2452   if ((DerivedCSA || BaseCSA) &&
2453       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2454     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2455     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2456       << CXXBaseDecl;
2457     return nullptr;
2458   }
2459 
2460   // A class which contains a flexible array member is not suitable for use as a
2461   // base class:
2462   //   - If the layout determines that a base comes before another base,
2463   //     the flexible array member would index into the subsequent base.
2464   //   - If the layout determines that base comes before the derived class,
2465   //     the flexible array member would index into the derived class.
2466   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2467     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2468       << CXXBaseDecl->getDeclName();
2469     return nullptr;
2470   }
2471 
2472   // C++ [class]p3:
2473   //   If a class is marked final and it appears as a base-type-specifier in
2474   //   base-clause, the program is ill-formed.
2475   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2476     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2477       << CXXBaseDecl->getDeclName()
2478       << FA->isSpelledAsSealed();
2479     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2480         << CXXBaseDecl->getDeclName() << FA->getRange();
2481     return nullptr;
2482   }
2483 
2484   if (BaseDecl->isInvalidDecl())
2485     Class->setInvalidDecl();
2486 
2487   // Create the base specifier.
2488   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2489                                         Class->getTagKind() == TTK_Class,
2490                                         Access, TInfo, EllipsisLoc);
2491 }
2492 
2493 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2494 /// one entry in the base class list of a class specifier, for
2495 /// example:
2496 ///    class foo : public bar, virtual private baz {
2497 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2498 BaseResult
2499 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2500                          ParsedAttributes &Attributes,
2501                          bool Virtual, AccessSpecifier Access,
2502                          ParsedType basetype, SourceLocation BaseLoc,
2503                          SourceLocation EllipsisLoc) {
2504   if (!classdecl)
2505     return true;
2506 
2507   AdjustDeclIfTemplate(classdecl);
2508   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2509   if (!Class)
2510     return true;
2511 
2512   // We haven't yet attached the base specifiers.
2513   Class->setIsParsingBaseSpecifiers();
2514 
2515   // We do not support any C++11 attributes on base-specifiers yet.
2516   // Diagnose any attributes we see.
2517   for (const ParsedAttr &AL : Attributes) {
2518     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2519       continue;
2520     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2521                           ? (unsigned)diag::warn_unknown_attribute_ignored
2522                           : (unsigned)diag::err_base_specifier_attribute)
2523         << AL;
2524   }
2525 
2526   TypeSourceInfo *TInfo = nullptr;
2527   GetTypeFromParser(basetype, &TInfo);
2528 
2529   if (EllipsisLoc.isInvalid() &&
2530       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2531                                       UPPC_BaseType))
2532     return true;
2533 
2534   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2535                                                       Virtual, Access, TInfo,
2536                                                       EllipsisLoc))
2537     return BaseSpec;
2538   else
2539     Class->setInvalidDecl();
2540 
2541   return true;
2542 }
2543 
2544 /// Use small set to collect indirect bases.  As this is only used
2545 /// locally, there's no need to abstract the small size parameter.
2546 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2547 
2548 /// Recursively add the bases of Type.  Don't add Type itself.
2549 static void
2550 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2551                   const QualType &Type)
2552 {
2553   // Even though the incoming type is a base, it might not be
2554   // a class -- it could be a template parm, for instance.
2555   if (auto Rec = Type->getAs<RecordType>()) {
2556     auto Decl = Rec->getAsCXXRecordDecl();
2557 
2558     // Iterate over its bases.
2559     for (const auto &BaseSpec : Decl->bases()) {
2560       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2561         .getUnqualifiedType();
2562       if (Set.insert(Base).second)
2563         // If we've not already seen it, recurse.
2564         NoteIndirectBases(Context, Set, Base);
2565     }
2566   }
2567 }
2568 
2569 /// Performs the actual work of attaching the given base class
2570 /// specifiers to a C++ class.
2571 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2572                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2573  if (Bases.empty())
2574     return false;
2575 
2576   // Used to keep track of which base types we have already seen, so
2577   // that we can properly diagnose redundant direct base types. Note
2578   // that the key is always the unqualified canonical type of the base
2579   // class.
2580   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2581 
2582   // Used to track indirect bases so we can see if a direct base is
2583   // ambiguous.
2584   IndirectBaseSet IndirectBaseTypes;
2585 
2586   // Copy non-redundant base specifiers into permanent storage.
2587   unsigned NumGoodBases = 0;
2588   bool Invalid = false;
2589   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2590     QualType NewBaseType
2591       = Context.getCanonicalType(Bases[idx]->getType());
2592     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2593 
2594     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2595     if (KnownBase) {
2596       // C++ [class.mi]p3:
2597       //   A class shall not be specified as a direct base class of a
2598       //   derived class more than once.
2599       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2600           << KnownBase->getType() << Bases[idx]->getSourceRange();
2601 
2602       // Delete the duplicate base class specifier; we're going to
2603       // overwrite its pointer later.
2604       Context.Deallocate(Bases[idx]);
2605 
2606       Invalid = true;
2607     } else {
2608       // Okay, add this new base class.
2609       KnownBase = Bases[idx];
2610       Bases[NumGoodBases++] = Bases[idx];
2611 
2612       // Note this base's direct & indirect bases, if there could be ambiguity.
2613       if (Bases.size() > 1)
2614         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2615 
2616       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2617         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2618         if (Class->isInterface() &&
2619               (!RD->isInterfaceLike() ||
2620                KnownBase->getAccessSpecifier() != AS_public)) {
2621           // The Microsoft extension __interface does not permit bases that
2622           // are not themselves public interfaces.
2623           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2624               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2625               << RD->getSourceRange();
2626           Invalid = true;
2627         }
2628         if (RD->hasAttr<WeakAttr>())
2629           Class->addAttr(WeakAttr::CreateImplicit(Context));
2630       }
2631     }
2632   }
2633 
2634   // Attach the remaining base class specifiers to the derived class.
2635   Class->setBases(Bases.data(), NumGoodBases);
2636 
2637   // Check that the only base classes that are duplicate are virtual.
2638   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2639     // Check whether this direct base is inaccessible due to ambiguity.
2640     QualType BaseType = Bases[idx]->getType();
2641 
2642     // Skip all dependent types in templates being used as base specifiers.
2643     // Checks below assume that the base specifier is a CXXRecord.
2644     if (BaseType->isDependentType())
2645       continue;
2646 
2647     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2648       .getUnqualifiedType();
2649 
2650     if (IndirectBaseTypes.count(CanonicalBase)) {
2651       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2652                          /*DetectVirtual=*/true);
2653       bool found
2654         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2655       assert(found);
2656       (void)found;
2657 
2658       if (Paths.isAmbiguous(CanonicalBase))
2659         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2660             << BaseType << getAmbiguousPathsDisplayString(Paths)
2661             << Bases[idx]->getSourceRange();
2662       else
2663         assert(Bases[idx]->isVirtual());
2664     }
2665 
2666     // Delete the base class specifier, since its data has been copied
2667     // into the CXXRecordDecl.
2668     Context.Deallocate(Bases[idx]);
2669   }
2670 
2671   return Invalid;
2672 }
2673 
2674 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2675 /// class, after checking whether there are any duplicate base
2676 /// classes.
2677 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2678                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2679   if (!ClassDecl || Bases.empty())
2680     return;
2681 
2682   AdjustDeclIfTemplate(ClassDecl);
2683   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2684 }
2685 
2686 /// Determine whether the type \p Derived is a C++ class that is
2687 /// derived from the type \p Base.
2688 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2689   if (!getLangOpts().CPlusPlus)
2690     return false;
2691 
2692   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2693   if (!DerivedRD)
2694     return false;
2695 
2696   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2697   if (!BaseRD)
2698     return false;
2699 
2700   // If either the base or the derived type is invalid, don't try to
2701   // check whether one is derived from the other.
2702   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2703     return false;
2704 
2705   // FIXME: In a modules build, do we need the entire path to be visible for us
2706   // to be able to use the inheritance relationship?
2707   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2708     return false;
2709 
2710   return DerivedRD->isDerivedFrom(BaseRD);
2711 }
2712 
2713 /// Determine whether the type \p Derived is a C++ class that is
2714 /// derived from the type \p Base.
2715 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2716                          CXXBasePaths &Paths) {
2717   if (!getLangOpts().CPlusPlus)
2718     return false;
2719 
2720   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2721   if (!DerivedRD)
2722     return false;
2723 
2724   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2725   if (!BaseRD)
2726     return false;
2727 
2728   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2729     return false;
2730 
2731   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2732 }
2733 
2734 static void BuildBasePathArray(const CXXBasePath &Path,
2735                                CXXCastPath &BasePathArray) {
2736   // We first go backward and check if we have a virtual base.
2737   // FIXME: It would be better if CXXBasePath had the base specifier for
2738   // the nearest virtual base.
2739   unsigned Start = 0;
2740   for (unsigned I = Path.size(); I != 0; --I) {
2741     if (Path[I - 1].Base->isVirtual()) {
2742       Start = I - 1;
2743       break;
2744     }
2745   }
2746 
2747   // Now add all bases.
2748   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2749     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2750 }
2751 
2752 
2753 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2754                               CXXCastPath &BasePathArray) {
2755   assert(BasePathArray.empty() && "Base path array must be empty!");
2756   assert(Paths.isRecordingPaths() && "Must record paths!");
2757   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2758 }
2759 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2760 /// conversion (where Derived and Base are class types) is
2761 /// well-formed, meaning that the conversion is unambiguous (and
2762 /// that all of the base classes are accessible). Returns true
2763 /// and emits a diagnostic if the code is ill-formed, returns false
2764 /// otherwise. Loc is the location where this routine should point to
2765 /// if there is an error, and Range is the source range to highlight
2766 /// if there is an error.
2767 ///
2768 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2769 /// diagnostic for the respective type of error will be suppressed, but the
2770 /// check for ill-formed code will still be performed.
2771 bool
2772 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2773                                    unsigned InaccessibleBaseID,
2774                                    unsigned AmbigiousBaseConvID,
2775                                    SourceLocation Loc, SourceRange Range,
2776                                    DeclarationName Name,
2777                                    CXXCastPath *BasePath,
2778                                    bool IgnoreAccess) {
2779   // First, determine whether the path from Derived to Base is
2780   // ambiguous. This is slightly more expensive than checking whether
2781   // the Derived to Base conversion exists, because here we need to
2782   // explore multiple paths to determine if there is an ambiguity.
2783   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2784                      /*DetectVirtual=*/false);
2785   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2786   if (!DerivationOkay)
2787     return true;
2788 
2789   const CXXBasePath *Path = nullptr;
2790   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2791     Path = &Paths.front();
2792 
2793   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2794   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2795   // user to access such bases.
2796   if (!Path && getLangOpts().MSVCCompat) {
2797     for (const CXXBasePath &PossiblePath : Paths) {
2798       if (PossiblePath.size() == 1) {
2799         Path = &PossiblePath;
2800         if (AmbigiousBaseConvID)
2801           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2802               << Base << Derived << Range;
2803         break;
2804       }
2805     }
2806   }
2807 
2808   if (Path) {
2809     if (!IgnoreAccess) {
2810       // Check that the base class can be accessed.
2811       switch (
2812           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2813       case AR_inaccessible:
2814         return true;
2815       case AR_accessible:
2816       case AR_dependent:
2817       case AR_delayed:
2818         break;
2819       }
2820     }
2821 
2822     // Build a base path if necessary.
2823     if (BasePath)
2824       ::BuildBasePathArray(*Path, *BasePath);
2825     return false;
2826   }
2827 
2828   if (AmbigiousBaseConvID) {
2829     // We know that the derived-to-base conversion is ambiguous, and
2830     // we're going to produce a diagnostic. Perform the derived-to-base
2831     // search just one more time to compute all of the possible paths so
2832     // that we can print them out. This is more expensive than any of
2833     // the previous derived-to-base checks we've done, but at this point
2834     // performance isn't as much of an issue.
2835     Paths.clear();
2836     Paths.setRecordingPaths(true);
2837     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2838     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2839     (void)StillOkay;
2840 
2841     // Build up a textual representation of the ambiguous paths, e.g.,
2842     // D -> B -> A, that will be used to illustrate the ambiguous
2843     // conversions in the diagnostic. We only print one of the paths
2844     // to each base class subobject.
2845     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2846 
2847     Diag(Loc, AmbigiousBaseConvID)
2848     << Derived << Base << PathDisplayStr << Range << Name;
2849   }
2850   return true;
2851 }
2852 
2853 bool
2854 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2855                                    SourceLocation Loc, SourceRange Range,
2856                                    CXXCastPath *BasePath,
2857                                    bool IgnoreAccess) {
2858   return CheckDerivedToBaseConversion(
2859       Derived, Base, diag::err_upcast_to_inaccessible_base,
2860       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2861       BasePath, IgnoreAccess);
2862 }
2863 
2864 
2865 /// Builds a string representing ambiguous paths from a
2866 /// specific derived class to different subobjects of the same base
2867 /// class.
2868 ///
2869 /// This function builds a string that can be used in error messages
2870 /// to show the different paths that one can take through the
2871 /// inheritance hierarchy to go from the derived class to different
2872 /// subobjects of a base class. The result looks something like this:
2873 /// @code
2874 /// struct D -> struct B -> struct A
2875 /// struct D -> struct C -> struct A
2876 /// @endcode
2877 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2878   std::string PathDisplayStr;
2879   std::set<unsigned> DisplayedPaths;
2880   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2881        Path != Paths.end(); ++Path) {
2882     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2883       // We haven't displayed a path to this particular base
2884       // class subobject yet.
2885       PathDisplayStr += "\n    ";
2886       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2887       for (CXXBasePath::const_iterator Element = Path->begin();
2888            Element != Path->end(); ++Element)
2889         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2890     }
2891   }
2892 
2893   return PathDisplayStr;
2894 }
2895 
2896 //===----------------------------------------------------------------------===//
2897 // C++ class member Handling
2898 //===----------------------------------------------------------------------===//
2899 
2900 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2901 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2902                                 SourceLocation ColonLoc,
2903                                 const ParsedAttributesView &Attrs) {
2904   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2905   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2906                                                   ASLoc, ColonLoc);
2907   CurContext->addHiddenDecl(ASDecl);
2908   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2909 }
2910 
2911 /// CheckOverrideControl - Check C++11 override control semantics.
2912 void Sema::CheckOverrideControl(NamedDecl *D) {
2913   if (D->isInvalidDecl())
2914     return;
2915 
2916   // We only care about "override" and "final" declarations.
2917   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2918     return;
2919 
2920   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2921 
2922   // We can't check dependent instance methods.
2923   if (MD && MD->isInstance() &&
2924       (MD->getParent()->hasAnyDependentBases() ||
2925        MD->getType()->isDependentType()))
2926     return;
2927 
2928   if (MD && !MD->isVirtual()) {
2929     // If we have a non-virtual method, check if if hides a virtual method.
2930     // (In that case, it's most likely the method has the wrong type.)
2931     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2932     FindHiddenVirtualMethods(MD, OverloadedMethods);
2933 
2934     if (!OverloadedMethods.empty()) {
2935       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2936         Diag(OA->getLocation(),
2937              diag::override_keyword_hides_virtual_member_function)
2938           << "override" << (OverloadedMethods.size() > 1);
2939       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2940         Diag(FA->getLocation(),
2941              diag::override_keyword_hides_virtual_member_function)
2942           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2943           << (OverloadedMethods.size() > 1);
2944       }
2945       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2946       MD->setInvalidDecl();
2947       return;
2948     }
2949     // Fall through into the general case diagnostic.
2950     // FIXME: We might want to attempt typo correction here.
2951   }
2952 
2953   if (!MD || !MD->isVirtual()) {
2954     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2955       Diag(OA->getLocation(),
2956            diag::override_keyword_only_allowed_on_virtual_member_functions)
2957         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2958       D->dropAttr<OverrideAttr>();
2959     }
2960     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2961       Diag(FA->getLocation(),
2962            diag::override_keyword_only_allowed_on_virtual_member_functions)
2963         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2964         << FixItHint::CreateRemoval(FA->getLocation());
2965       D->dropAttr<FinalAttr>();
2966     }
2967     return;
2968   }
2969 
2970   // C++11 [class.virtual]p5:
2971   //   If a function is marked with the virt-specifier override and
2972   //   does not override a member function of a base class, the program is
2973   //   ill-formed.
2974   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2975   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2976     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2977       << MD->getDeclName();
2978 }
2979 
2980 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2981   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2982     return;
2983   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2984   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2985     return;
2986 
2987   SourceLocation Loc = MD->getLocation();
2988   SourceLocation SpellingLoc = Loc;
2989   if (getSourceManager().isMacroArgExpansion(Loc))
2990     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2991   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2992   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2993       return;
2994 
2995   if (MD->size_overridden_methods() > 0) {
2996     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2997                           ? diag::warn_destructor_marked_not_override_overriding
2998                           : diag::warn_function_marked_not_override_overriding;
2999     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3000     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3001     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3002   }
3003 }
3004 
3005 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3006 /// function overrides a virtual member function marked 'final', according to
3007 /// C++11 [class.virtual]p4.
3008 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3009                                                   const CXXMethodDecl *Old) {
3010   FinalAttr *FA = Old->getAttr<FinalAttr>();
3011   if (!FA)
3012     return false;
3013 
3014   Diag(New->getLocation(), diag::err_final_function_overridden)
3015     << New->getDeclName()
3016     << FA->isSpelledAsSealed();
3017   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3018   return true;
3019 }
3020 
3021 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3022   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3023   // FIXME: Destruction of ObjC lifetime types has side-effects.
3024   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3025     return !RD->isCompleteDefinition() ||
3026            !RD->hasTrivialDefaultConstructor() ||
3027            !RD->hasTrivialDestructor();
3028   return false;
3029 }
3030 
3031 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3032   ParsedAttributesView::const_iterator Itr =
3033       llvm::find_if(list, [](const ParsedAttr &AL) {
3034         return AL.isDeclspecPropertyAttribute();
3035       });
3036   if (Itr != list.end())
3037     return &*Itr;
3038   return nullptr;
3039 }
3040 
3041 // Check if there is a field shadowing.
3042 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3043                                       DeclarationName FieldName,
3044                                       const CXXRecordDecl *RD,
3045                                       bool DeclIsField) {
3046   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3047     return;
3048 
3049   // To record a shadowed field in a base
3050   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3051   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3052                            CXXBasePath &Path) {
3053     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3054     // Record an ambiguous path directly
3055     if (Bases.find(Base) != Bases.end())
3056       return true;
3057     for (const auto Field : Base->lookup(FieldName)) {
3058       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3059           Field->getAccess() != AS_private) {
3060         assert(Field->getAccess() != AS_none);
3061         assert(Bases.find(Base) == Bases.end());
3062         Bases[Base] = Field;
3063         return true;
3064       }
3065     }
3066     return false;
3067   };
3068 
3069   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3070                      /*DetectVirtual=*/true);
3071   if (!RD->lookupInBases(FieldShadowed, Paths))
3072     return;
3073 
3074   for (const auto &P : Paths) {
3075     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3076     auto It = Bases.find(Base);
3077     // Skip duplicated bases
3078     if (It == Bases.end())
3079       continue;
3080     auto BaseField = It->second;
3081     assert(BaseField->getAccess() != AS_private);
3082     if (AS_none !=
3083         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3084       Diag(Loc, diag::warn_shadow_field)
3085         << FieldName << RD << Base << DeclIsField;
3086       Diag(BaseField->getLocation(), diag::note_shadow_field);
3087       Bases.erase(It);
3088     }
3089   }
3090 }
3091 
3092 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3093 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3094 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3095 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3096 /// present (but parsing it has been deferred).
3097 NamedDecl *
3098 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3099                                MultiTemplateParamsArg TemplateParameterLists,
3100                                Expr *BW, const VirtSpecifiers &VS,
3101                                InClassInitStyle InitStyle) {
3102   const DeclSpec &DS = D.getDeclSpec();
3103   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3104   DeclarationName Name = NameInfo.getName();
3105   SourceLocation Loc = NameInfo.getLoc();
3106 
3107   // For anonymous bitfields, the location should point to the type.
3108   if (Loc.isInvalid())
3109     Loc = D.getBeginLoc();
3110 
3111   Expr *BitWidth = static_cast<Expr*>(BW);
3112 
3113   assert(isa<CXXRecordDecl>(CurContext));
3114   assert(!DS.isFriendSpecified());
3115 
3116   bool isFunc = D.isDeclarationOfFunction();
3117   const ParsedAttr *MSPropertyAttr =
3118       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3119 
3120   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3121     // The Microsoft extension __interface only permits public member functions
3122     // and prohibits constructors, destructors, operators, non-public member
3123     // functions, static methods and data members.
3124     unsigned InvalidDecl;
3125     bool ShowDeclName = true;
3126     if (!isFunc &&
3127         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3128       InvalidDecl = 0;
3129     else if (!isFunc)
3130       InvalidDecl = 1;
3131     else if (AS != AS_public)
3132       InvalidDecl = 2;
3133     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3134       InvalidDecl = 3;
3135     else switch (Name.getNameKind()) {
3136       case DeclarationName::CXXConstructorName:
3137         InvalidDecl = 4;
3138         ShowDeclName = false;
3139         break;
3140 
3141       case DeclarationName::CXXDestructorName:
3142         InvalidDecl = 5;
3143         ShowDeclName = false;
3144         break;
3145 
3146       case DeclarationName::CXXOperatorName:
3147       case DeclarationName::CXXConversionFunctionName:
3148         InvalidDecl = 6;
3149         break;
3150 
3151       default:
3152         InvalidDecl = 0;
3153         break;
3154     }
3155 
3156     if (InvalidDecl) {
3157       if (ShowDeclName)
3158         Diag(Loc, diag::err_invalid_member_in_interface)
3159           << (InvalidDecl-1) << Name;
3160       else
3161         Diag(Loc, diag::err_invalid_member_in_interface)
3162           << (InvalidDecl-1) << "";
3163       return nullptr;
3164     }
3165   }
3166 
3167   // C++ 9.2p6: A member shall not be declared to have automatic storage
3168   // duration (auto, register) or with the extern storage-class-specifier.
3169   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3170   // data members and cannot be applied to names declared const or static,
3171   // and cannot be applied to reference members.
3172   switch (DS.getStorageClassSpec()) {
3173   case DeclSpec::SCS_unspecified:
3174   case DeclSpec::SCS_typedef:
3175   case DeclSpec::SCS_static:
3176     break;
3177   case DeclSpec::SCS_mutable:
3178     if (isFunc) {
3179       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3180 
3181       // FIXME: It would be nicer if the keyword was ignored only for this
3182       // declarator. Otherwise we could get follow-up errors.
3183       D.getMutableDeclSpec().ClearStorageClassSpecs();
3184     }
3185     break;
3186   default:
3187     Diag(DS.getStorageClassSpecLoc(),
3188          diag::err_storageclass_invalid_for_member);
3189     D.getMutableDeclSpec().ClearStorageClassSpecs();
3190     break;
3191   }
3192 
3193   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3194                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3195                       !isFunc);
3196 
3197   if (DS.hasConstexprSpecifier() && isInstField) {
3198     SemaDiagnosticBuilder B =
3199         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3200     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3201     if (InitStyle == ICIS_NoInit) {
3202       B << 0 << 0;
3203       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3204         B << FixItHint::CreateRemoval(ConstexprLoc);
3205       else {
3206         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3207         D.getMutableDeclSpec().ClearConstexprSpec();
3208         const char *PrevSpec;
3209         unsigned DiagID;
3210         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3211             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3212         (void)Failed;
3213         assert(!Failed && "Making a constexpr member const shouldn't fail");
3214       }
3215     } else {
3216       B << 1;
3217       const char *PrevSpec;
3218       unsigned DiagID;
3219       if (D.getMutableDeclSpec().SetStorageClassSpec(
3220           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3221           Context.getPrintingPolicy())) {
3222         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3223                "This is the only DeclSpec that should fail to be applied");
3224         B << 1;
3225       } else {
3226         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3227         isInstField = false;
3228       }
3229     }
3230   }
3231 
3232   NamedDecl *Member;
3233   if (isInstField) {
3234     CXXScopeSpec &SS = D.getCXXScopeSpec();
3235 
3236     // Data members must have identifiers for names.
3237     if (!Name.isIdentifier()) {
3238       Diag(Loc, diag::err_bad_variable_name)
3239         << Name;
3240       return nullptr;
3241     }
3242 
3243     IdentifierInfo *II = Name.getAsIdentifierInfo();
3244 
3245     // Member field could not be with "template" keyword.
3246     // So TemplateParameterLists should be empty in this case.
3247     if (TemplateParameterLists.size()) {
3248       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3249       if (TemplateParams->size()) {
3250         // There is no such thing as a member field template.
3251         Diag(D.getIdentifierLoc(), diag::err_template_member)
3252             << II
3253             << SourceRange(TemplateParams->getTemplateLoc(),
3254                 TemplateParams->getRAngleLoc());
3255       } else {
3256         // There is an extraneous 'template<>' for this member.
3257         Diag(TemplateParams->getTemplateLoc(),
3258             diag::err_template_member_noparams)
3259             << II
3260             << SourceRange(TemplateParams->getTemplateLoc(),
3261                 TemplateParams->getRAngleLoc());
3262       }
3263       return nullptr;
3264     }
3265 
3266     if (SS.isSet() && !SS.isInvalid()) {
3267       // The user provided a superfluous scope specifier inside a class
3268       // definition:
3269       //
3270       // class X {
3271       //   int X::member;
3272       // };
3273       if (DeclContext *DC = computeDeclContext(SS, false))
3274         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3275                                      D.getName().getKind() ==
3276                                          UnqualifiedIdKind::IK_TemplateId);
3277       else
3278         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3279           << Name << SS.getRange();
3280 
3281       SS.clear();
3282     }
3283 
3284     if (MSPropertyAttr) {
3285       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3286                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3287       if (!Member)
3288         return nullptr;
3289       isInstField = false;
3290     } else {
3291       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3292                                 BitWidth, InitStyle, AS);
3293       if (!Member)
3294         return nullptr;
3295     }
3296 
3297     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3298   } else {
3299     Member = HandleDeclarator(S, D, TemplateParameterLists);
3300     if (!Member)
3301       return nullptr;
3302 
3303     // Non-instance-fields can't have a bitfield.
3304     if (BitWidth) {
3305       if (Member->isInvalidDecl()) {
3306         // don't emit another diagnostic.
3307       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3308         // C++ 9.6p3: A bit-field shall not be a static member.
3309         // "static member 'A' cannot be a bit-field"
3310         Diag(Loc, diag::err_static_not_bitfield)
3311           << Name << BitWidth->getSourceRange();
3312       } else if (isa<TypedefDecl>(Member)) {
3313         // "typedef member 'x' cannot be a bit-field"
3314         Diag(Loc, diag::err_typedef_not_bitfield)
3315           << Name << BitWidth->getSourceRange();
3316       } else {
3317         // A function typedef ("typedef int f(); f a;").
3318         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3319         Diag(Loc, diag::err_not_integral_type_bitfield)
3320           << Name << cast<ValueDecl>(Member)->getType()
3321           << BitWidth->getSourceRange();
3322       }
3323 
3324       BitWidth = nullptr;
3325       Member->setInvalidDecl();
3326     }
3327 
3328     NamedDecl *NonTemplateMember = Member;
3329     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3330       NonTemplateMember = FunTmpl->getTemplatedDecl();
3331     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3332       NonTemplateMember = VarTmpl->getTemplatedDecl();
3333 
3334     Member->setAccess(AS);
3335 
3336     // If we have declared a member function template or static data member
3337     // template, set the access of the templated declaration as well.
3338     if (NonTemplateMember != Member)
3339       NonTemplateMember->setAccess(AS);
3340 
3341     // C++ [temp.deduct.guide]p3:
3342     //   A deduction guide [...] for a member class template [shall be
3343     //   declared] with the same access [as the template].
3344     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3345       auto *TD = DG->getDeducedTemplate();
3346       // Access specifiers are only meaningful if both the template and the
3347       // deduction guide are from the same scope.
3348       if (AS != TD->getAccess() &&
3349           TD->getDeclContext()->getRedeclContext()->Equals(
3350               DG->getDeclContext()->getRedeclContext())) {
3351         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3352         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3353             << TD->getAccess();
3354         const AccessSpecDecl *LastAccessSpec = nullptr;
3355         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3356           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3357             LastAccessSpec = AccessSpec;
3358         }
3359         assert(LastAccessSpec && "differing access with no access specifier");
3360         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3361             << AS;
3362       }
3363     }
3364   }
3365 
3366   if (VS.isOverrideSpecified())
3367     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3368                                          AttributeCommonInfo::AS_Keyword));
3369   if (VS.isFinalSpecified())
3370     Member->addAttr(FinalAttr::Create(
3371         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3372         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3373 
3374   if (VS.getLastLocation().isValid()) {
3375     // Update the end location of a method that has a virt-specifiers.
3376     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3377       MD->setRangeEnd(VS.getLastLocation());
3378   }
3379 
3380   CheckOverrideControl(Member);
3381 
3382   assert((Name || isInstField) && "No identifier for non-field ?");
3383 
3384   if (isInstField) {
3385     FieldDecl *FD = cast<FieldDecl>(Member);
3386     FieldCollector->Add(FD);
3387 
3388     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3389       // Remember all explicit private FieldDecls that have a name, no side
3390       // effects and are not part of a dependent type declaration.
3391       if (!FD->isImplicit() && FD->getDeclName() &&
3392           FD->getAccess() == AS_private &&
3393           !FD->hasAttr<UnusedAttr>() &&
3394           !FD->getParent()->isDependentContext() &&
3395           !InitializationHasSideEffects(*FD))
3396         UnusedPrivateFields.insert(FD);
3397     }
3398   }
3399 
3400   return Member;
3401 }
3402 
3403 namespace {
3404   class UninitializedFieldVisitor
3405       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3406     Sema &S;
3407     // List of Decls to generate a warning on.  Also remove Decls that become
3408     // initialized.
3409     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3410     // List of base classes of the record.  Classes are removed after their
3411     // initializers.
3412     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3413     // Vector of decls to be removed from the Decl set prior to visiting the
3414     // nodes.  These Decls may have been initialized in the prior initializer.
3415     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3416     // If non-null, add a note to the warning pointing back to the constructor.
3417     const CXXConstructorDecl *Constructor;
3418     // Variables to hold state when processing an initializer list.  When
3419     // InitList is true, special case initialization of FieldDecls matching
3420     // InitListFieldDecl.
3421     bool InitList;
3422     FieldDecl *InitListFieldDecl;
3423     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3424 
3425   public:
3426     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3427     UninitializedFieldVisitor(Sema &S,
3428                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3429                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3430       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3431         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3432 
3433     // Returns true if the use of ME is not an uninitialized use.
3434     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3435                                          bool CheckReferenceOnly) {
3436       llvm::SmallVector<FieldDecl*, 4> Fields;
3437       bool ReferenceField = false;
3438       while (ME) {
3439         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3440         if (!FD)
3441           return false;
3442         Fields.push_back(FD);
3443         if (FD->getType()->isReferenceType())
3444           ReferenceField = true;
3445         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3446       }
3447 
3448       // Binding a reference to an uninitialized field is not an
3449       // uninitialized use.
3450       if (CheckReferenceOnly && !ReferenceField)
3451         return true;
3452 
3453       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3454       // Discard the first field since it is the field decl that is being
3455       // initialized.
3456       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3457         UsedFieldIndex.push_back((*I)->getFieldIndex());
3458       }
3459 
3460       for (auto UsedIter = UsedFieldIndex.begin(),
3461                 UsedEnd = UsedFieldIndex.end(),
3462                 OrigIter = InitFieldIndex.begin(),
3463                 OrigEnd = InitFieldIndex.end();
3464            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3465         if (*UsedIter < *OrigIter)
3466           return true;
3467         if (*UsedIter > *OrigIter)
3468           break;
3469       }
3470 
3471       return false;
3472     }
3473 
3474     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3475                           bool AddressOf) {
3476       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3477         return;
3478 
3479       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3480       // or union.
3481       MemberExpr *FieldME = ME;
3482 
3483       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3484 
3485       Expr *Base = ME;
3486       while (MemberExpr *SubME =
3487                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3488 
3489         if (isa<VarDecl>(SubME->getMemberDecl()))
3490           return;
3491 
3492         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3493           if (!FD->isAnonymousStructOrUnion())
3494             FieldME = SubME;
3495 
3496         if (!FieldME->getType().isPODType(S.Context))
3497           AllPODFields = false;
3498 
3499         Base = SubME->getBase();
3500       }
3501 
3502       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3503         return;
3504 
3505       if (AddressOf && AllPODFields)
3506         return;
3507 
3508       ValueDecl* FoundVD = FieldME->getMemberDecl();
3509 
3510       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3511         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3512           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3513         }
3514 
3515         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3516           QualType T = BaseCast->getType();
3517           if (T->isPointerType() &&
3518               BaseClasses.count(T->getPointeeType())) {
3519             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3520                 << T->getPointeeType() << FoundVD;
3521           }
3522         }
3523       }
3524 
3525       if (!Decls.count(FoundVD))
3526         return;
3527 
3528       const bool IsReference = FoundVD->getType()->isReferenceType();
3529 
3530       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3531         // Special checking for initializer lists.
3532         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3533           return;
3534         }
3535       } else {
3536         // Prevent double warnings on use of unbounded references.
3537         if (CheckReferenceOnly && !IsReference)
3538           return;
3539       }
3540 
3541       unsigned diag = IsReference
3542           ? diag::warn_reference_field_is_uninit
3543           : diag::warn_field_is_uninit;
3544       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3545       if (Constructor)
3546         S.Diag(Constructor->getLocation(),
3547                diag::note_uninit_in_this_constructor)
3548           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3549 
3550     }
3551 
3552     void HandleValue(Expr *E, bool AddressOf) {
3553       E = E->IgnoreParens();
3554 
3555       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3556         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3557                          AddressOf /*AddressOf*/);
3558         return;
3559       }
3560 
3561       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3562         Visit(CO->getCond());
3563         HandleValue(CO->getTrueExpr(), AddressOf);
3564         HandleValue(CO->getFalseExpr(), AddressOf);
3565         return;
3566       }
3567 
3568       if (BinaryConditionalOperator *BCO =
3569               dyn_cast<BinaryConditionalOperator>(E)) {
3570         Visit(BCO->getCond());
3571         HandleValue(BCO->getFalseExpr(), AddressOf);
3572         return;
3573       }
3574 
3575       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3576         HandleValue(OVE->getSourceExpr(), AddressOf);
3577         return;
3578       }
3579 
3580       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3581         switch (BO->getOpcode()) {
3582         default:
3583           break;
3584         case(BO_PtrMemD):
3585         case(BO_PtrMemI):
3586           HandleValue(BO->getLHS(), AddressOf);
3587           Visit(BO->getRHS());
3588           return;
3589         case(BO_Comma):
3590           Visit(BO->getLHS());
3591           HandleValue(BO->getRHS(), AddressOf);
3592           return;
3593         }
3594       }
3595 
3596       Visit(E);
3597     }
3598 
3599     void CheckInitListExpr(InitListExpr *ILE) {
3600       InitFieldIndex.push_back(0);
3601       for (auto Child : ILE->children()) {
3602         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3603           CheckInitListExpr(SubList);
3604         } else {
3605           Visit(Child);
3606         }
3607         ++InitFieldIndex.back();
3608       }
3609       InitFieldIndex.pop_back();
3610     }
3611 
3612     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3613                           FieldDecl *Field, const Type *BaseClass) {
3614       // Remove Decls that may have been initialized in the previous
3615       // initializer.
3616       for (ValueDecl* VD : DeclsToRemove)
3617         Decls.erase(VD);
3618       DeclsToRemove.clear();
3619 
3620       Constructor = FieldConstructor;
3621       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3622 
3623       if (ILE && Field) {
3624         InitList = true;
3625         InitListFieldDecl = Field;
3626         InitFieldIndex.clear();
3627         CheckInitListExpr(ILE);
3628       } else {
3629         InitList = false;
3630         Visit(E);
3631       }
3632 
3633       if (Field)
3634         Decls.erase(Field);
3635       if (BaseClass)
3636         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3637     }
3638 
3639     void VisitMemberExpr(MemberExpr *ME) {
3640       // All uses of unbounded reference fields will warn.
3641       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3642     }
3643 
3644     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3645       if (E->getCastKind() == CK_LValueToRValue) {
3646         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3647         return;
3648       }
3649 
3650       Inherited::VisitImplicitCastExpr(E);
3651     }
3652 
3653     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3654       if (E->getConstructor()->isCopyConstructor()) {
3655         Expr *ArgExpr = E->getArg(0);
3656         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3657           if (ILE->getNumInits() == 1)
3658             ArgExpr = ILE->getInit(0);
3659         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3660           if (ICE->getCastKind() == CK_NoOp)
3661             ArgExpr = ICE->getSubExpr();
3662         HandleValue(ArgExpr, false /*AddressOf*/);
3663         return;
3664       }
3665       Inherited::VisitCXXConstructExpr(E);
3666     }
3667 
3668     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3669       Expr *Callee = E->getCallee();
3670       if (isa<MemberExpr>(Callee)) {
3671         HandleValue(Callee, false /*AddressOf*/);
3672         for (auto Arg : E->arguments())
3673           Visit(Arg);
3674         return;
3675       }
3676 
3677       Inherited::VisitCXXMemberCallExpr(E);
3678     }
3679 
3680     void VisitCallExpr(CallExpr *E) {
3681       // Treat std::move as a use.
3682       if (E->isCallToStdMove()) {
3683         HandleValue(E->getArg(0), /*AddressOf=*/false);
3684         return;
3685       }
3686 
3687       Inherited::VisitCallExpr(E);
3688     }
3689 
3690     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3691       Expr *Callee = E->getCallee();
3692 
3693       if (isa<UnresolvedLookupExpr>(Callee))
3694         return Inherited::VisitCXXOperatorCallExpr(E);
3695 
3696       Visit(Callee);
3697       for (auto Arg : E->arguments())
3698         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3699     }
3700 
3701     void VisitBinaryOperator(BinaryOperator *E) {
3702       // If a field assignment is detected, remove the field from the
3703       // uninitiailized field set.
3704       if (E->getOpcode() == BO_Assign)
3705         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3706           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3707             if (!FD->getType()->isReferenceType())
3708               DeclsToRemove.push_back(FD);
3709 
3710       if (E->isCompoundAssignmentOp()) {
3711         HandleValue(E->getLHS(), false /*AddressOf*/);
3712         Visit(E->getRHS());
3713         return;
3714       }
3715 
3716       Inherited::VisitBinaryOperator(E);
3717     }
3718 
3719     void VisitUnaryOperator(UnaryOperator *E) {
3720       if (E->isIncrementDecrementOp()) {
3721         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3722         return;
3723       }
3724       if (E->getOpcode() == UO_AddrOf) {
3725         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3726           HandleValue(ME->getBase(), true /*AddressOf*/);
3727           return;
3728         }
3729       }
3730 
3731       Inherited::VisitUnaryOperator(E);
3732     }
3733   };
3734 
3735   // Diagnose value-uses of fields to initialize themselves, e.g.
3736   //   foo(foo)
3737   // where foo is not also a parameter to the constructor.
3738   // Also diagnose across field uninitialized use such as
3739   //   x(y), y(x)
3740   // TODO: implement -Wuninitialized and fold this into that framework.
3741   static void DiagnoseUninitializedFields(
3742       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3743 
3744     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3745                                            Constructor->getLocation())) {
3746       return;
3747     }
3748 
3749     if (Constructor->isInvalidDecl())
3750       return;
3751 
3752     const CXXRecordDecl *RD = Constructor->getParent();
3753 
3754     if (RD->getDescribedClassTemplate())
3755       return;
3756 
3757     // Holds fields that are uninitialized.
3758     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3759 
3760     // At the beginning, all fields are uninitialized.
3761     for (auto *I : RD->decls()) {
3762       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3763         UninitializedFields.insert(FD);
3764       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3765         UninitializedFields.insert(IFD->getAnonField());
3766       }
3767     }
3768 
3769     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3770     for (auto I : RD->bases())
3771       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3772 
3773     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3774       return;
3775 
3776     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3777                                                    UninitializedFields,
3778                                                    UninitializedBaseClasses);
3779 
3780     for (const auto *FieldInit : Constructor->inits()) {
3781       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3782         break;
3783 
3784       Expr *InitExpr = FieldInit->getInit();
3785       if (!InitExpr)
3786         continue;
3787 
3788       if (CXXDefaultInitExpr *Default =
3789               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3790         InitExpr = Default->getExpr();
3791         if (!InitExpr)
3792           continue;
3793         // In class initializers will point to the constructor.
3794         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3795                                               FieldInit->getAnyMember(),
3796                                               FieldInit->getBaseClass());
3797       } else {
3798         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3799                                               FieldInit->getAnyMember(),
3800                                               FieldInit->getBaseClass());
3801       }
3802     }
3803   }
3804 } // namespace
3805 
3806 /// Enter a new C++ default initializer scope. After calling this, the
3807 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3808 /// parsing or instantiating the initializer failed.
3809 void Sema::ActOnStartCXXInClassMemberInitializer() {
3810   // Create a synthetic function scope to represent the call to the constructor
3811   // that notionally surrounds a use of this initializer.
3812   PushFunctionScope();
3813 }
3814 
3815 /// This is invoked after parsing an in-class initializer for a
3816 /// non-static C++ class member, and after instantiating an in-class initializer
3817 /// in a class template. Such actions are deferred until the class is complete.
3818 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3819                                                   SourceLocation InitLoc,
3820                                                   Expr *InitExpr) {
3821   // Pop the notional constructor scope we created earlier.
3822   PopFunctionScopeInfo(nullptr, D);
3823 
3824   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3825   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3826          "must set init style when field is created");
3827 
3828   if (!InitExpr) {
3829     D->setInvalidDecl();
3830     if (FD)
3831       FD->removeInClassInitializer();
3832     return;
3833   }
3834 
3835   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3836     FD->setInvalidDecl();
3837     FD->removeInClassInitializer();
3838     return;
3839   }
3840 
3841   ExprResult Init = InitExpr;
3842   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3843     InitializedEntity Entity =
3844         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3845     InitializationKind Kind =
3846         FD->getInClassInitStyle() == ICIS_ListInit
3847             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3848                                                    InitExpr->getBeginLoc(),
3849                                                    InitExpr->getEndLoc())
3850             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3851     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3852     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3853     if (Init.isInvalid()) {
3854       FD->setInvalidDecl();
3855       return;
3856     }
3857   }
3858 
3859   // C++11 [class.base.init]p7:
3860   //   The initialization of each base and member constitutes a
3861   //   full-expression.
3862   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3863   if (Init.isInvalid()) {
3864     FD->setInvalidDecl();
3865     return;
3866   }
3867 
3868   InitExpr = Init.get();
3869 
3870   FD->setInClassInitializer(InitExpr);
3871 }
3872 
3873 /// Find the direct and/or virtual base specifiers that
3874 /// correspond to the given base type, for use in base initialization
3875 /// within a constructor.
3876 static bool FindBaseInitializer(Sema &SemaRef,
3877                                 CXXRecordDecl *ClassDecl,
3878                                 QualType BaseType,
3879                                 const CXXBaseSpecifier *&DirectBaseSpec,
3880                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3881   // First, check for a direct base class.
3882   DirectBaseSpec = nullptr;
3883   for (const auto &Base : ClassDecl->bases()) {
3884     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3885       // We found a direct base of this type. That's what we're
3886       // initializing.
3887       DirectBaseSpec = &Base;
3888       break;
3889     }
3890   }
3891 
3892   // Check for a virtual base class.
3893   // FIXME: We might be able to short-circuit this if we know in advance that
3894   // there are no virtual bases.
3895   VirtualBaseSpec = nullptr;
3896   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3897     // We haven't found a base yet; search the class hierarchy for a
3898     // virtual base class.
3899     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3900                        /*DetectVirtual=*/false);
3901     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3902                               SemaRef.Context.getTypeDeclType(ClassDecl),
3903                               BaseType, Paths)) {
3904       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3905            Path != Paths.end(); ++Path) {
3906         if (Path->back().Base->isVirtual()) {
3907           VirtualBaseSpec = Path->back().Base;
3908           break;
3909         }
3910       }
3911     }
3912   }
3913 
3914   return DirectBaseSpec || VirtualBaseSpec;
3915 }
3916 
3917 /// Handle a C++ member initializer using braced-init-list syntax.
3918 MemInitResult
3919 Sema::ActOnMemInitializer(Decl *ConstructorD,
3920                           Scope *S,
3921                           CXXScopeSpec &SS,
3922                           IdentifierInfo *MemberOrBase,
3923                           ParsedType TemplateTypeTy,
3924                           const DeclSpec &DS,
3925                           SourceLocation IdLoc,
3926                           Expr *InitList,
3927                           SourceLocation EllipsisLoc) {
3928   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3929                              DS, IdLoc, InitList,
3930                              EllipsisLoc);
3931 }
3932 
3933 /// Handle a C++ member initializer using parentheses syntax.
3934 MemInitResult
3935 Sema::ActOnMemInitializer(Decl *ConstructorD,
3936                           Scope *S,
3937                           CXXScopeSpec &SS,
3938                           IdentifierInfo *MemberOrBase,
3939                           ParsedType TemplateTypeTy,
3940                           const DeclSpec &DS,
3941                           SourceLocation IdLoc,
3942                           SourceLocation LParenLoc,
3943                           ArrayRef<Expr *> Args,
3944                           SourceLocation RParenLoc,
3945                           SourceLocation EllipsisLoc) {
3946   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3947   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3948                              DS, IdLoc, List, EllipsisLoc);
3949 }
3950 
3951 namespace {
3952 
3953 // Callback to only accept typo corrections that can be a valid C++ member
3954 // intializer: either a non-static field member or a base class.
3955 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3956 public:
3957   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3958       : ClassDecl(ClassDecl) {}
3959 
3960   bool ValidateCandidate(const TypoCorrection &candidate) override {
3961     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3962       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3963         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3964       return isa<TypeDecl>(ND);
3965     }
3966     return false;
3967   }
3968 
3969   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3970     return std::make_unique<MemInitializerValidatorCCC>(*this);
3971   }
3972 
3973 private:
3974   CXXRecordDecl *ClassDecl;
3975 };
3976 
3977 }
3978 
3979 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3980                                              CXXScopeSpec &SS,
3981                                              ParsedType TemplateTypeTy,
3982                                              IdentifierInfo *MemberOrBase) {
3983   if (SS.getScopeRep() || TemplateTypeTy)
3984     return nullptr;
3985   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3986   if (Result.empty())
3987     return nullptr;
3988   ValueDecl *Member;
3989   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3990       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3991     return Member;
3992   return nullptr;
3993 }
3994 
3995 /// Handle a C++ member initializer.
3996 MemInitResult
3997 Sema::BuildMemInitializer(Decl *ConstructorD,
3998                           Scope *S,
3999                           CXXScopeSpec &SS,
4000                           IdentifierInfo *MemberOrBase,
4001                           ParsedType TemplateTypeTy,
4002                           const DeclSpec &DS,
4003                           SourceLocation IdLoc,
4004                           Expr *Init,
4005                           SourceLocation EllipsisLoc) {
4006   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4007   if (!Res.isUsable())
4008     return true;
4009   Init = Res.get();
4010 
4011   if (!ConstructorD)
4012     return true;
4013 
4014   AdjustDeclIfTemplate(ConstructorD);
4015 
4016   CXXConstructorDecl *Constructor
4017     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4018   if (!Constructor) {
4019     // The user wrote a constructor initializer on a function that is
4020     // not a C++ constructor. Ignore the error for now, because we may
4021     // have more member initializers coming; we'll diagnose it just
4022     // once in ActOnMemInitializers.
4023     return true;
4024   }
4025 
4026   CXXRecordDecl *ClassDecl = Constructor->getParent();
4027 
4028   // C++ [class.base.init]p2:
4029   //   Names in a mem-initializer-id are looked up in the scope of the
4030   //   constructor's class and, if not found in that scope, are looked
4031   //   up in the scope containing the constructor's definition.
4032   //   [Note: if the constructor's class contains a member with the
4033   //   same name as a direct or virtual base class of the class, a
4034   //   mem-initializer-id naming the member or base class and composed
4035   //   of a single identifier refers to the class member. A
4036   //   mem-initializer-id for the hidden base class may be specified
4037   //   using a qualified name. ]
4038 
4039   // Look for a member, first.
4040   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4041           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4042     if (EllipsisLoc.isValid())
4043       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4044           << MemberOrBase
4045           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4046 
4047     return BuildMemberInitializer(Member, Init, IdLoc);
4048   }
4049   // It didn't name a member, so see if it names a class.
4050   QualType BaseType;
4051   TypeSourceInfo *TInfo = nullptr;
4052 
4053   if (TemplateTypeTy) {
4054     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4055     if (BaseType.isNull())
4056       return true;
4057   } else if (DS.getTypeSpecType() == TST_decltype) {
4058     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4059   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4060     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4061     return true;
4062   } else {
4063     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4064     LookupParsedName(R, S, &SS);
4065 
4066     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4067     if (!TyD) {
4068       if (R.isAmbiguous()) return true;
4069 
4070       // We don't want access-control diagnostics here.
4071       R.suppressDiagnostics();
4072 
4073       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4074         bool NotUnknownSpecialization = false;
4075         DeclContext *DC = computeDeclContext(SS, false);
4076         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4077           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4078 
4079         if (!NotUnknownSpecialization) {
4080           // When the scope specifier can refer to a member of an unknown
4081           // specialization, we take it as a type name.
4082           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4083                                        SS.getWithLocInContext(Context),
4084                                        *MemberOrBase, IdLoc);
4085           if (BaseType.isNull())
4086             return true;
4087 
4088           TInfo = Context.CreateTypeSourceInfo(BaseType);
4089           DependentNameTypeLoc TL =
4090               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4091           if (!TL.isNull()) {
4092             TL.setNameLoc(IdLoc);
4093             TL.setElaboratedKeywordLoc(SourceLocation());
4094             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4095           }
4096 
4097           R.clear();
4098           R.setLookupName(MemberOrBase);
4099         }
4100       }
4101 
4102       // If no results were found, try to correct typos.
4103       TypoCorrection Corr;
4104       MemInitializerValidatorCCC CCC(ClassDecl);
4105       if (R.empty() && BaseType.isNull() &&
4106           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4107                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4108         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4109           // We have found a non-static data member with a similar
4110           // name to what was typed; complain and initialize that
4111           // member.
4112           diagnoseTypo(Corr,
4113                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4114                          << MemberOrBase << true);
4115           return BuildMemberInitializer(Member, Init, IdLoc);
4116         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4117           const CXXBaseSpecifier *DirectBaseSpec;
4118           const CXXBaseSpecifier *VirtualBaseSpec;
4119           if (FindBaseInitializer(*this, ClassDecl,
4120                                   Context.getTypeDeclType(Type),
4121                                   DirectBaseSpec, VirtualBaseSpec)) {
4122             // We have found a direct or virtual base class with a
4123             // similar name to what was typed; complain and initialize
4124             // that base class.
4125             diagnoseTypo(Corr,
4126                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4127                            << MemberOrBase << false,
4128                          PDiag() /*Suppress note, we provide our own.*/);
4129 
4130             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4131                                                               : VirtualBaseSpec;
4132             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4133                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4134 
4135             TyD = Type;
4136           }
4137         }
4138       }
4139 
4140       if (!TyD && BaseType.isNull()) {
4141         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4142           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4143         return true;
4144       }
4145     }
4146 
4147     if (BaseType.isNull()) {
4148       BaseType = Context.getTypeDeclType(TyD);
4149       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4150       if (SS.isSet()) {
4151         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4152                                              BaseType);
4153         TInfo = Context.CreateTypeSourceInfo(BaseType);
4154         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4155         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4156         TL.setElaboratedKeywordLoc(SourceLocation());
4157         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4158       }
4159     }
4160   }
4161 
4162   if (!TInfo)
4163     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4164 
4165   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4166 }
4167 
4168 MemInitResult
4169 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4170                              SourceLocation IdLoc) {
4171   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4172   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4173   assert((DirectMember || IndirectMember) &&
4174          "Member must be a FieldDecl or IndirectFieldDecl");
4175 
4176   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4177     return true;
4178 
4179   if (Member->isInvalidDecl())
4180     return true;
4181 
4182   MultiExprArg Args;
4183   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4184     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4185   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4186     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4187   } else {
4188     // Template instantiation doesn't reconstruct ParenListExprs for us.
4189     Args = Init;
4190   }
4191 
4192   SourceRange InitRange = Init->getSourceRange();
4193 
4194   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4195     // Can't check initialization for a member of dependent type or when
4196     // any of the arguments are type-dependent expressions.
4197     DiscardCleanupsInEvaluationContext();
4198   } else {
4199     bool InitList = false;
4200     if (isa<InitListExpr>(Init)) {
4201       InitList = true;
4202       Args = Init;
4203     }
4204 
4205     // Initialize the member.
4206     InitializedEntity MemberEntity =
4207       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4208                    : InitializedEntity::InitializeMember(IndirectMember,
4209                                                          nullptr);
4210     InitializationKind Kind =
4211         InitList ? InitializationKind::CreateDirectList(
4212                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4213                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4214                                                     InitRange.getEnd());
4215 
4216     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4217     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4218                                             nullptr);
4219     if (MemberInit.isInvalid())
4220       return true;
4221 
4222     // C++11 [class.base.init]p7:
4223     //   The initialization of each base and member constitutes a
4224     //   full-expression.
4225     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4226                                      /*DiscardedValue*/ false);
4227     if (MemberInit.isInvalid())
4228       return true;
4229 
4230     Init = MemberInit.get();
4231   }
4232 
4233   if (DirectMember) {
4234     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4235                                             InitRange.getBegin(), Init,
4236                                             InitRange.getEnd());
4237   } else {
4238     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4239                                             InitRange.getBegin(), Init,
4240                                             InitRange.getEnd());
4241   }
4242 }
4243 
4244 MemInitResult
4245 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4246                                  CXXRecordDecl *ClassDecl) {
4247   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4248   if (!LangOpts.CPlusPlus11)
4249     return Diag(NameLoc, diag::err_delegating_ctor)
4250       << TInfo->getTypeLoc().getLocalSourceRange();
4251   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4252 
4253   bool InitList = true;
4254   MultiExprArg Args = Init;
4255   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4256     InitList = false;
4257     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4258   }
4259 
4260   SourceRange InitRange = Init->getSourceRange();
4261   // Initialize the object.
4262   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4263                                      QualType(ClassDecl->getTypeForDecl(), 0));
4264   InitializationKind Kind =
4265       InitList ? InitializationKind::CreateDirectList(
4266                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4267                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4268                                                   InitRange.getEnd());
4269   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4270   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4271                                               Args, nullptr);
4272   if (DelegationInit.isInvalid())
4273     return true;
4274 
4275   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4276          "Delegating constructor with no target?");
4277 
4278   // C++11 [class.base.init]p7:
4279   //   The initialization of each base and member constitutes a
4280   //   full-expression.
4281   DelegationInit = ActOnFinishFullExpr(
4282       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4283   if (DelegationInit.isInvalid())
4284     return true;
4285 
4286   // If we are in a dependent context, template instantiation will
4287   // perform this type-checking again. Just save the arguments that we
4288   // received in a ParenListExpr.
4289   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4290   // of the information that we have about the base
4291   // initializer. However, deconstructing the ASTs is a dicey process,
4292   // and this approach is far more likely to get the corner cases right.
4293   if (CurContext->isDependentContext())
4294     DelegationInit = Init;
4295 
4296   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4297                                           DelegationInit.getAs<Expr>(),
4298                                           InitRange.getEnd());
4299 }
4300 
4301 MemInitResult
4302 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4303                            Expr *Init, CXXRecordDecl *ClassDecl,
4304                            SourceLocation EllipsisLoc) {
4305   SourceLocation BaseLoc
4306     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4307 
4308   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4309     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4310              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4311 
4312   // C++ [class.base.init]p2:
4313   //   [...] Unless the mem-initializer-id names a nonstatic data
4314   //   member of the constructor's class or a direct or virtual base
4315   //   of that class, the mem-initializer is ill-formed. A
4316   //   mem-initializer-list can initialize a base class using any
4317   //   name that denotes that base class type.
4318   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4319 
4320   SourceRange InitRange = Init->getSourceRange();
4321   if (EllipsisLoc.isValid()) {
4322     // This is a pack expansion.
4323     if (!BaseType->containsUnexpandedParameterPack())  {
4324       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4325         << SourceRange(BaseLoc, InitRange.getEnd());
4326 
4327       EllipsisLoc = SourceLocation();
4328     }
4329   } else {
4330     // Check for any unexpanded parameter packs.
4331     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4332       return true;
4333 
4334     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4335       return true;
4336   }
4337 
4338   // Check for direct and virtual base classes.
4339   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4340   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4341   if (!Dependent) {
4342     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4343                                        BaseType))
4344       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4345 
4346     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4347                         VirtualBaseSpec);
4348 
4349     // C++ [base.class.init]p2:
4350     // Unless the mem-initializer-id names a nonstatic data member of the
4351     // constructor's class or a direct or virtual base of that class, the
4352     // mem-initializer is ill-formed.
4353     if (!DirectBaseSpec && !VirtualBaseSpec) {
4354       // If the class has any dependent bases, then it's possible that
4355       // one of those types will resolve to the same type as
4356       // BaseType. Therefore, just treat this as a dependent base
4357       // class initialization.  FIXME: Should we try to check the
4358       // initialization anyway? It seems odd.
4359       if (ClassDecl->hasAnyDependentBases())
4360         Dependent = true;
4361       else
4362         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4363           << BaseType << Context.getTypeDeclType(ClassDecl)
4364           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4365     }
4366   }
4367 
4368   if (Dependent) {
4369     DiscardCleanupsInEvaluationContext();
4370 
4371     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4372                                             /*IsVirtual=*/false,
4373                                             InitRange.getBegin(), Init,
4374                                             InitRange.getEnd(), EllipsisLoc);
4375   }
4376 
4377   // C++ [base.class.init]p2:
4378   //   If a mem-initializer-id is ambiguous because it designates both
4379   //   a direct non-virtual base class and an inherited virtual base
4380   //   class, the mem-initializer is ill-formed.
4381   if (DirectBaseSpec && VirtualBaseSpec)
4382     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4383       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4384 
4385   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4386   if (!BaseSpec)
4387     BaseSpec = VirtualBaseSpec;
4388 
4389   // Initialize the base.
4390   bool InitList = true;
4391   MultiExprArg Args = Init;
4392   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4393     InitList = false;
4394     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4395   }
4396 
4397   InitializedEntity BaseEntity =
4398     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4399   InitializationKind Kind =
4400       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4401                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4402                                                   InitRange.getEnd());
4403   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4404   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4405   if (BaseInit.isInvalid())
4406     return true;
4407 
4408   // C++11 [class.base.init]p7:
4409   //   The initialization of each base and member constitutes a
4410   //   full-expression.
4411   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4412                                  /*DiscardedValue*/ false);
4413   if (BaseInit.isInvalid())
4414     return true;
4415 
4416   // If we are in a dependent context, template instantiation will
4417   // perform this type-checking again. Just save the arguments that we
4418   // received in a ParenListExpr.
4419   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4420   // of the information that we have about the base
4421   // initializer. However, deconstructing the ASTs is a dicey process,
4422   // and this approach is far more likely to get the corner cases right.
4423   if (CurContext->isDependentContext())
4424     BaseInit = Init;
4425 
4426   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4427                                           BaseSpec->isVirtual(),
4428                                           InitRange.getBegin(),
4429                                           BaseInit.getAs<Expr>(),
4430                                           InitRange.getEnd(), EllipsisLoc);
4431 }
4432 
4433 // Create a static_cast\<T&&>(expr).
4434 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4435   if (T.isNull()) T = E->getType();
4436   QualType TargetType = SemaRef.BuildReferenceType(
4437       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4438   SourceLocation ExprLoc = E->getBeginLoc();
4439   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4440       TargetType, ExprLoc);
4441 
4442   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4443                                    SourceRange(ExprLoc, ExprLoc),
4444                                    E->getSourceRange()).get();
4445 }
4446 
4447 /// ImplicitInitializerKind - How an implicit base or member initializer should
4448 /// initialize its base or member.
4449 enum ImplicitInitializerKind {
4450   IIK_Default,
4451   IIK_Copy,
4452   IIK_Move,
4453   IIK_Inherit
4454 };
4455 
4456 static bool
4457 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4458                              ImplicitInitializerKind ImplicitInitKind,
4459                              CXXBaseSpecifier *BaseSpec,
4460                              bool IsInheritedVirtualBase,
4461                              CXXCtorInitializer *&CXXBaseInit) {
4462   InitializedEntity InitEntity
4463     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4464                                         IsInheritedVirtualBase);
4465 
4466   ExprResult BaseInit;
4467 
4468   switch (ImplicitInitKind) {
4469   case IIK_Inherit:
4470   case IIK_Default: {
4471     InitializationKind InitKind
4472       = InitializationKind::CreateDefault(Constructor->getLocation());
4473     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4474     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4475     break;
4476   }
4477 
4478   case IIK_Move:
4479   case IIK_Copy: {
4480     bool Moving = ImplicitInitKind == IIK_Move;
4481     ParmVarDecl *Param = Constructor->getParamDecl(0);
4482     QualType ParamType = Param->getType().getNonReferenceType();
4483 
4484     Expr *CopyCtorArg =
4485       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4486                           SourceLocation(), Param, false,
4487                           Constructor->getLocation(), ParamType,
4488                           VK_LValue, nullptr);
4489 
4490     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4491 
4492     // Cast to the base class to avoid ambiguities.
4493     QualType ArgTy =
4494       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4495                                        ParamType.getQualifiers());
4496 
4497     if (Moving) {
4498       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4499     }
4500 
4501     CXXCastPath BasePath;
4502     BasePath.push_back(BaseSpec);
4503     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4504                                             CK_UncheckedDerivedToBase,
4505                                             Moving ? VK_XValue : VK_LValue,
4506                                             &BasePath).get();
4507 
4508     InitializationKind InitKind
4509       = InitializationKind::CreateDirect(Constructor->getLocation(),
4510                                          SourceLocation(), SourceLocation());
4511     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4512     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4513     break;
4514   }
4515   }
4516 
4517   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4518   if (BaseInit.isInvalid())
4519     return true;
4520 
4521   CXXBaseInit =
4522     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4523                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4524                                                         SourceLocation()),
4525                                              BaseSpec->isVirtual(),
4526                                              SourceLocation(),
4527                                              BaseInit.getAs<Expr>(),
4528                                              SourceLocation(),
4529                                              SourceLocation());
4530 
4531   return false;
4532 }
4533 
4534 static bool RefersToRValueRef(Expr *MemRef) {
4535   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4536   return Referenced->getType()->isRValueReferenceType();
4537 }
4538 
4539 static bool
4540 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4541                                ImplicitInitializerKind ImplicitInitKind,
4542                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4543                                CXXCtorInitializer *&CXXMemberInit) {
4544   if (Field->isInvalidDecl())
4545     return true;
4546 
4547   SourceLocation Loc = Constructor->getLocation();
4548 
4549   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4550     bool Moving = ImplicitInitKind == IIK_Move;
4551     ParmVarDecl *Param = Constructor->getParamDecl(0);
4552     QualType ParamType = Param->getType().getNonReferenceType();
4553 
4554     // Suppress copying zero-width bitfields.
4555     if (Field->isZeroLengthBitField(SemaRef.Context))
4556       return false;
4557 
4558     Expr *MemberExprBase =
4559       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4560                           SourceLocation(), Param, false,
4561                           Loc, ParamType, VK_LValue, nullptr);
4562 
4563     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4564 
4565     if (Moving) {
4566       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4567     }
4568 
4569     // Build a reference to this field within the parameter.
4570     CXXScopeSpec SS;
4571     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4572                               Sema::LookupMemberName);
4573     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4574                                   : cast<ValueDecl>(Field), AS_public);
4575     MemberLookup.resolveKind();
4576     ExprResult CtorArg
4577       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4578                                          ParamType, Loc,
4579                                          /*IsArrow=*/false,
4580                                          SS,
4581                                          /*TemplateKWLoc=*/SourceLocation(),
4582                                          /*FirstQualifierInScope=*/nullptr,
4583                                          MemberLookup,
4584                                          /*TemplateArgs=*/nullptr,
4585                                          /*S*/nullptr);
4586     if (CtorArg.isInvalid())
4587       return true;
4588 
4589     // C++11 [class.copy]p15:
4590     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4591     //     with static_cast<T&&>(x.m);
4592     if (RefersToRValueRef(CtorArg.get())) {
4593       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4594     }
4595 
4596     InitializedEntity Entity =
4597         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4598                                                        /*Implicit*/ true)
4599                  : InitializedEntity::InitializeMember(Field, nullptr,
4600                                                        /*Implicit*/ true);
4601 
4602     // Direct-initialize to use the copy constructor.
4603     InitializationKind InitKind =
4604       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4605 
4606     Expr *CtorArgE = CtorArg.getAs<Expr>();
4607     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4608     ExprResult MemberInit =
4609         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4610     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4611     if (MemberInit.isInvalid())
4612       return true;
4613 
4614     if (Indirect)
4615       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4616           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4617     else
4618       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4619           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4620     return false;
4621   }
4622 
4623   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4624          "Unhandled implicit init kind!");
4625 
4626   QualType FieldBaseElementType =
4627     SemaRef.Context.getBaseElementType(Field->getType());
4628 
4629   if (FieldBaseElementType->isRecordType()) {
4630     InitializedEntity InitEntity =
4631         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4632                                                        /*Implicit*/ true)
4633                  : InitializedEntity::InitializeMember(Field, nullptr,
4634                                                        /*Implicit*/ true);
4635     InitializationKind InitKind =
4636       InitializationKind::CreateDefault(Loc);
4637 
4638     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4639     ExprResult MemberInit =
4640       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4641 
4642     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4643     if (MemberInit.isInvalid())
4644       return true;
4645 
4646     if (Indirect)
4647       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4648                                                                Indirect, Loc,
4649                                                                Loc,
4650                                                                MemberInit.get(),
4651                                                                Loc);
4652     else
4653       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4654                                                                Field, Loc, Loc,
4655                                                                MemberInit.get(),
4656                                                                Loc);
4657     return false;
4658   }
4659 
4660   if (!Field->getParent()->isUnion()) {
4661     if (FieldBaseElementType->isReferenceType()) {
4662       SemaRef.Diag(Constructor->getLocation(),
4663                    diag::err_uninitialized_member_in_ctor)
4664       << (int)Constructor->isImplicit()
4665       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4666       << 0 << Field->getDeclName();
4667       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4668       return true;
4669     }
4670 
4671     if (FieldBaseElementType.isConstQualified()) {
4672       SemaRef.Diag(Constructor->getLocation(),
4673                    diag::err_uninitialized_member_in_ctor)
4674       << (int)Constructor->isImplicit()
4675       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4676       << 1 << Field->getDeclName();
4677       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4678       return true;
4679     }
4680   }
4681 
4682   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4683     // ARC and Weak:
4684     //   Default-initialize Objective-C pointers to NULL.
4685     CXXMemberInit
4686       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4687                                                  Loc, Loc,
4688                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4689                                                  Loc);
4690     return false;
4691   }
4692 
4693   // Nothing to initialize.
4694   CXXMemberInit = nullptr;
4695   return false;
4696 }
4697 
4698 namespace {
4699 struct BaseAndFieldInfo {
4700   Sema &S;
4701   CXXConstructorDecl *Ctor;
4702   bool AnyErrorsInInits;
4703   ImplicitInitializerKind IIK;
4704   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4705   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4706   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4707 
4708   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4709     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4710     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4711     if (Ctor->getInheritedConstructor())
4712       IIK = IIK_Inherit;
4713     else if (Generated && Ctor->isCopyConstructor())
4714       IIK = IIK_Copy;
4715     else if (Generated && Ctor->isMoveConstructor())
4716       IIK = IIK_Move;
4717     else
4718       IIK = IIK_Default;
4719   }
4720 
4721   bool isImplicitCopyOrMove() const {
4722     switch (IIK) {
4723     case IIK_Copy:
4724     case IIK_Move:
4725       return true;
4726 
4727     case IIK_Default:
4728     case IIK_Inherit:
4729       return false;
4730     }
4731 
4732     llvm_unreachable("Invalid ImplicitInitializerKind!");
4733   }
4734 
4735   bool addFieldInitializer(CXXCtorInitializer *Init) {
4736     AllToInit.push_back(Init);
4737 
4738     // Check whether this initializer makes the field "used".
4739     if (Init->getInit()->HasSideEffects(S.Context))
4740       S.UnusedPrivateFields.remove(Init->getAnyMember());
4741 
4742     return false;
4743   }
4744 
4745   bool isInactiveUnionMember(FieldDecl *Field) {
4746     RecordDecl *Record = Field->getParent();
4747     if (!Record->isUnion())
4748       return false;
4749 
4750     if (FieldDecl *Active =
4751             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4752       return Active != Field->getCanonicalDecl();
4753 
4754     // In an implicit copy or move constructor, ignore any in-class initializer.
4755     if (isImplicitCopyOrMove())
4756       return true;
4757 
4758     // If there's no explicit initialization, the field is active only if it
4759     // has an in-class initializer...
4760     if (Field->hasInClassInitializer())
4761       return false;
4762     // ... or it's an anonymous struct or union whose class has an in-class
4763     // initializer.
4764     if (!Field->isAnonymousStructOrUnion())
4765       return true;
4766     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4767     return !FieldRD->hasInClassInitializer();
4768   }
4769 
4770   /// Determine whether the given field is, or is within, a union member
4771   /// that is inactive (because there was an initializer given for a different
4772   /// member of the union, or because the union was not initialized at all).
4773   bool isWithinInactiveUnionMember(FieldDecl *Field,
4774                                    IndirectFieldDecl *Indirect) {
4775     if (!Indirect)
4776       return isInactiveUnionMember(Field);
4777 
4778     for (auto *C : Indirect->chain()) {
4779       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4780       if (Field && isInactiveUnionMember(Field))
4781         return true;
4782     }
4783     return false;
4784   }
4785 };
4786 }
4787 
4788 /// Determine whether the given type is an incomplete or zero-lenfgth
4789 /// array type.
4790 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4791   if (T->isIncompleteArrayType())
4792     return true;
4793 
4794   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4795     if (!ArrayT->getSize())
4796       return true;
4797 
4798     T = ArrayT->getElementType();
4799   }
4800 
4801   return false;
4802 }
4803 
4804 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4805                                     FieldDecl *Field,
4806                                     IndirectFieldDecl *Indirect = nullptr) {
4807   if (Field->isInvalidDecl())
4808     return false;
4809 
4810   // Overwhelmingly common case: we have a direct initializer for this field.
4811   if (CXXCtorInitializer *Init =
4812           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4813     return Info.addFieldInitializer(Init);
4814 
4815   // C++11 [class.base.init]p8:
4816   //   if the entity is a non-static data member that has a
4817   //   brace-or-equal-initializer and either
4818   //   -- the constructor's class is a union and no other variant member of that
4819   //      union is designated by a mem-initializer-id or
4820   //   -- the constructor's class is not a union, and, if the entity is a member
4821   //      of an anonymous union, no other member of that union is designated by
4822   //      a mem-initializer-id,
4823   //   the entity is initialized as specified in [dcl.init].
4824   //
4825   // We also apply the same rules to handle anonymous structs within anonymous
4826   // unions.
4827   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4828     return false;
4829 
4830   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4831     ExprResult DIE =
4832         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4833     if (DIE.isInvalid())
4834       return true;
4835 
4836     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4837     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4838 
4839     CXXCtorInitializer *Init;
4840     if (Indirect)
4841       Init = new (SemaRef.Context)
4842           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4843                              SourceLocation(), DIE.get(), SourceLocation());
4844     else
4845       Init = new (SemaRef.Context)
4846           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4847                              SourceLocation(), DIE.get(), SourceLocation());
4848     return Info.addFieldInitializer(Init);
4849   }
4850 
4851   // Don't initialize incomplete or zero-length arrays.
4852   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4853     return false;
4854 
4855   // Don't try to build an implicit initializer if there were semantic
4856   // errors in any of the initializers (and therefore we might be
4857   // missing some that the user actually wrote).
4858   if (Info.AnyErrorsInInits)
4859     return false;
4860 
4861   CXXCtorInitializer *Init = nullptr;
4862   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4863                                      Indirect, Init))
4864     return true;
4865 
4866   if (!Init)
4867     return false;
4868 
4869   return Info.addFieldInitializer(Init);
4870 }
4871 
4872 bool
4873 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4874                                CXXCtorInitializer *Initializer) {
4875   assert(Initializer->isDelegatingInitializer());
4876   Constructor->setNumCtorInitializers(1);
4877   CXXCtorInitializer **initializer =
4878     new (Context) CXXCtorInitializer*[1];
4879   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4880   Constructor->setCtorInitializers(initializer);
4881 
4882   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4883     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4884     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4885   }
4886 
4887   DelegatingCtorDecls.push_back(Constructor);
4888 
4889   DiagnoseUninitializedFields(*this, Constructor);
4890 
4891   return false;
4892 }
4893 
4894 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4895                                ArrayRef<CXXCtorInitializer *> Initializers) {
4896   if (Constructor->isDependentContext()) {
4897     // Just store the initializers as written, they will be checked during
4898     // instantiation.
4899     if (!Initializers.empty()) {
4900       Constructor->setNumCtorInitializers(Initializers.size());
4901       CXXCtorInitializer **baseOrMemberInitializers =
4902         new (Context) CXXCtorInitializer*[Initializers.size()];
4903       memcpy(baseOrMemberInitializers, Initializers.data(),
4904              Initializers.size() * sizeof(CXXCtorInitializer*));
4905       Constructor->setCtorInitializers(baseOrMemberInitializers);
4906     }
4907 
4908     // Let template instantiation know whether we had errors.
4909     if (AnyErrors)
4910       Constructor->setInvalidDecl();
4911 
4912     return false;
4913   }
4914 
4915   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4916 
4917   // We need to build the initializer AST according to order of construction
4918   // and not what user specified in the Initializers list.
4919   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4920   if (!ClassDecl)
4921     return true;
4922 
4923   bool HadError = false;
4924 
4925   for (unsigned i = 0; i < Initializers.size(); i++) {
4926     CXXCtorInitializer *Member = Initializers[i];
4927 
4928     if (Member->isBaseInitializer())
4929       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4930     else {
4931       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4932 
4933       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4934         for (auto *C : F->chain()) {
4935           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4936           if (FD && FD->getParent()->isUnion())
4937             Info.ActiveUnionMember.insert(std::make_pair(
4938                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4939         }
4940       } else if (FieldDecl *FD = Member->getMember()) {
4941         if (FD->getParent()->isUnion())
4942           Info.ActiveUnionMember.insert(std::make_pair(
4943               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4944       }
4945     }
4946   }
4947 
4948   // Keep track of the direct virtual bases.
4949   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4950   for (auto &I : ClassDecl->bases()) {
4951     if (I.isVirtual())
4952       DirectVBases.insert(&I);
4953   }
4954 
4955   // Push virtual bases before others.
4956   for (auto &VBase : ClassDecl->vbases()) {
4957     if (CXXCtorInitializer *Value
4958         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4959       // [class.base.init]p7, per DR257:
4960       //   A mem-initializer where the mem-initializer-id names a virtual base
4961       //   class is ignored during execution of a constructor of any class that
4962       //   is not the most derived class.
4963       if (ClassDecl->isAbstract()) {
4964         // FIXME: Provide a fixit to remove the base specifier. This requires
4965         // tracking the location of the associated comma for a base specifier.
4966         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4967           << VBase.getType() << ClassDecl;
4968         DiagnoseAbstractType(ClassDecl);
4969       }
4970 
4971       Info.AllToInit.push_back(Value);
4972     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4973       // [class.base.init]p8, per DR257:
4974       //   If a given [...] base class is not named by a mem-initializer-id
4975       //   [...] and the entity is not a virtual base class of an abstract
4976       //   class, then [...] the entity is default-initialized.
4977       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4978       CXXCtorInitializer *CXXBaseInit;
4979       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4980                                        &VBase, IsInheritedVirtualBase,
4981                                        CXXBaseInit)) {
4982         HadError = true;
4983         continue;
4984       }
4985 
4986       Info.AllToInit.push_back(CXXBaseInit);
4987     }
4988   }
4989 
4990   // Non-virtual bases.
4991   for (auto &Base : ClassDecl->bases()) {
4992     // Virtuals are in the virtual base list and already constructed.
4993     if (Base.isVirtual())
4994       continue;
4995 
4996     if (CXXCtorInitializer *Value
4997           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4998       Info.AllToInit.push_back(Value);
4999     } else if (!AnyErrors) {
5000       CXXCtorInitializer *CXXBaseInit;
5001       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5002                                        &Base, /*IsInheritedVirtualBase=*/false,
5003                                        CXXBaseInit)) {
5004         HadError = true;
5005         continue;
5006       }
5007 
5008       Info.AllToInit.push_back(CXXBaseInit);
5009     }
5010   }
5011 
5012   // Fields.
5013   for (auto *Mem : ClassDecl->decls()) {
5014     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5015       // C++ [class.bit]p2:
5016       //   A declaration for a bit-field that omits the identifier declares an
5017       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5018       //   initialized.
5019       if (F->isUnnamedBitfield())
5020         continue;
5021 
5022       // If we're not generating the implicit copy/move constructor, then we'll
5023       // handle anonymous struct/union fields based on their individual
5024       // indirect fields.
5025       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5026         continue;
5027 
5028       if (CollectFieldInitializer(*this, Info, F))
5029         HadError = true;
5030       continue;
5031     }
5032 
5033     // Beyond this point, we only consider default initialization.
5034     if (Info.isImplicitCopyOrMove())
5035       continue;
5036 
5037     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5038       if (F->getType()->isIncompleteArrayType()) {
5039         assert(ClassDecl->hasFlexibleArrayMember() &&
5040                "Incomplete array type is not valid");
5041         continue;
5042       }
5043 
5044       // Initialize each field of an anonymous struct individually.
5045       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5046         HadError = true;
5047 
5048       continue;
5049     }
5050   }
5051 
5052   unsigned NumInitializers = Info.AllToInit.size();
5053   if (NumInitializers > 0) {
5054     Constructor->setNumCtorInitializers(NumInitializers);
5055     CXXCtorInitializer **baseOrMemberInitializers =
5056       new (Context) CXXCtorInitializer*[NumInitializers];
5057     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5058            NumInitializers * sizeof(CXXCtorInitializer*));
5059     Constructor->setCtorInitializers(baseOrMemberInitializers);
5060 
5061     // Constructors implicitly reference the base and member
5062     // destructors.
5063     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5064                                            Constructor->getParent());
5065   }
5066 
5067   return HadError;
5068 }
5069 
5070 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5071   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5072     const RecordDecl *RD = RT->getDecl();
5073     if (RD->isAnonymousStructOrUnion()) {
5074       for (auto *Field : RD->fields())
5075         PopulateKeysForFields(Field, IdealInits);
5076       return;
5077     }
5078   }
5079   IdealInits.push_back(Field->getCanonicalDecl());
5080 }
5081 
5082 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5083   return Context.getCanonicalType(BaseType).getTypePtr();
5084 }
5085 
5086 static const void *GetKeyForMember(ASTContext &Context,
5087                                    CXXCtorInitializer *Member) {
5088   if (!Member->isAnyMemberInitializer())
5089     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5090 
5091   return Member->getAnyMember()->getCanonicalDecl();
5092 }
5093 
5094 static void DiagnoseBaseOrMemInitializerOrder(
5095     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5096     ArrayRef<CXXCtorInitializer *> Inits) {
5097   if (Constructor->getDeclContext()->isDependentContext())
5098     return;
5099 
5100   // Don't check initializers order unless the warning is enabled at the
5101   // location of at least one initializer.
5102   bool ShouldCheckOrder = false;
5103   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5104     CXXCtorInitializer *Init = Inits[InitIndex];
5105     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5106                                  Init->getSourceLocation())) {
5107       ShouldCheckOrder = true;
5108       break;
5109     }
5110   }
5111   if (!ShouldCheckOrder)
5112     return;
5113 
5114   // Build the list of bases and members in the order that they'll
5115   // actually be initialized.  The explicit initializers should be in
5116   // this same order but may be missing things.
5117   SmallVector<const void*, 32> IdealInitKeys;
5118 
5119   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5120 
5121   // 1. Virtual bases.
5122   for (const auto &VBase : ClassDecl->vbases())
5123     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5124 
5125   // 2. Non-virtual bases.
5126   for (const auto &Base : ClassDecl->bases()) {
5127     if (Base.isVirtual())
5128       continue;
5129     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5130   }
5131 
5132   // 3. Direct fields.
5133   for (auto *Field : ClassDecl->fields()) {
5134     if (Field->isUnnamedBitfield())
5135       continue;
5136 
5137     PopulateKeysForFields(Field, IdealInitKeys);
5138   }
5139 
5140   unsigned NumIdealInits = IdealInitKeys.size();
5141   unsigned IdealIndex = 0;
5142 
5143   CXXCtorInitializer *PrevInit = nullptr;
5144   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5145     CXXCtorInitializer *Init = Inits[InitIndex];
5146     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5147 
5148     // Scan forward to try to find this initializer in the idealized
5149     // initializers list.
5150     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5151       if (InitKey == IdealInitKeys[IdealIndex])
5152         break;
5153 
5154     // If we didn't find this initializer, it must be because we
5155     // scanned past it on a previous iteration.  That can only
5156     // happen if we're out of order;  emit a warning.
5157     if (IdealIndex == NumIdealInits && PrevInit) {
5158       Sema::SemaDiagnosticBuilder D =
5159         SemaRef.Diag(PrevInit->getSourceLocation(),
5160                      diag::warn_initializer_out_of_order);
5161 
5162       if (PrevInit->isAnyMemberInitializer())
5163         D << 0 << PrevInit->getAnyMember()->getDeclName();
5164       else
5165         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5166 
5167       if (Init->isAnyMemberInitializer())
5168         D << 0 << Init->getAnyMember()->getDeclName();
5169       else
5170         D << 1 << Init->getTypeSourceInfo()->getType();
5171 
5172       // Move back to the initializer's location in the ideal list.
5173       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5174         if (InitKey == IdealInitKeys[IdealIndex])
5175           break;
5176 
5177       assert(IdealIndex < NumIdealInits &&
5178              "initializer not found in initializer list");
5179     }
5180 
5181     PrevInit = Init;
5182   }
5183 }
5184 
5185 namespace {
5186 bool CheckRedundantInit(Sema &S,
5187                         CXXCtorInitializer *Init,
5188                         CXXCtorInitializer *&PrevInit) {
5189   if (!PrevInit) {
5190     PrevInit = Init;
5191     return false;
5192   }
5193 
5194   if (FieldDecl *Field = Init->getAnyMember())
5195     S.Diag(Init->getSourceLocation(),
5196            diag::err_multiple_mem_initialization)
5197       << Field->getDeclName()
5198       << Init->getSourceRange();
5199   else {
5200     const Type *BaseClass = Init->getBaseClass();
5201     assert(BaseClass && "neither field nor base");
5202     S.Diag(Init->getSourceLocation(),
5203            diag::err_multiple_base_initialization)
5204       << QualType(BaseClass, 0)
5205       << Init->getSourceRange();
5206   }
5207   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5208     << 0 << PrevInit->getSourceRange();
5209 
5210   return true;
5211 }
5212 
5213 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5214 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5215 
5216 bool CheckRedundantUnionInit(Sema &S,
5217                              CXXCtorInitializer *Init,
5218                              RedundantUnionMap &Unions) {
5219   FieldDecl *Field = Init->getAnyMember();
5220   RecordDecl *Parent = Field->getParent();
5221   NamedDecl *Child = Field;
5222 
5223   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5224     if (Parent->isUnion()) {
5225       UnionEntry &En = Unions[Parent];
5226       if (En.first && En.first != Child) {
5227         S.Diag(Init->getSourceLocation(),
5228                diag::err_multiple_mem_union_initialization)
5229           << Field->getDeclName()
5230           << Init->getSourceRange();
5231         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5232           << 0 << En.second->getSourceRange();
5233         return true;
5234       }
5235       if (!En.first) {
5236         En.first = Child;
5237         En.second = Init;
5238       }
5239       if (!Parent->isAnonymousStructOrUnion())
5240         return false;
5241     }
5242 
5243     Child = Parent;
5244     Parent = cast<RecordDecl>(Parent->getDeclContext());
5245   }
5246 
5247   return false;
5248 }
5249 }
5250 
5251 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5252 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5253                                 SourceLocation ColonLoc,
5254                                 ArrayRef<CXXCtorInitializer*> MemInits,
5255                                 bool AnyErrors) {
5256   if (!ConstructorDecl)
5257     return;
5258 
5259   AdjustDeclIfTemplate(ConstructorDecl);
5260 
5261   CXXConstructorDecl *Constructor
5262     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5263 
5264   if (!Constructor) {
5265     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5266     return;
5267   }
5268 
5269   // Mapping for the duplicate initializers check.
5270   // For member initializers, this is keyed with a FieldDecl*.
5271   // For base initializers, this is keyed with a Type*.
5272   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5273 
5274   // Mapping for the inconsistent anonymous-union initializers check.
5275   RedundantUnionMap MemberUnions;
5276 
5277   bool HadError = false;
5278   for (unsigned i = 0; i < MemInits.size(); i++) {
5279     CXXCtorInitializer *Init = MemInits[i];
5280 
5281     // Set the source order index.
5282     Init->setSourceOrder(i);
5283 
5284     if (Init->isAnyMemberInitializer()) {
5285       const void *Key = GetKeyForMember(Context, Init);
5286       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5287           CheckRedundantUnionInit(*this, Init, MemberUnions))
5288         HadError = true;
5289     } else if (Init->isBaseInitializer()) {
5290       const void *Key = GetKeyForMember(Context, Init);
5291       if (CheckRedundantInit(*this, Init, Members[Key]))
5292         HadError = true;
5293     } else {
5294       assert(Init->isDelegatingInitializer());
5295       // This must be the only initializer
5296       if (MemInits.size() != 1) {
5297         Diag(Init->getSourceLocation(),
5298              diag::err_delegating_initializer_alone)
5299           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5300         // We will treat this as being the only initializer.
5301       }
5302       SetDelegatingInitializer(Constructor, MemInits[i]);
5303       // Return immediately as the initializer is set.
5304       return;
5305     }
5306   }
5307 
5308   if (HadError)
5309     return;
5310 
5311   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5312 
5313   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5314 
5315   DiagnoseUninitializedFields(*this, Constructor);
5316 }
5317 
5318 void
5319 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5320                                              CXXRecordDecl *ClassDecl) {
5321   // Ignore dependent contexts. Also ignore unions, since their members never
5322   // have destructors implicitly called.
5323   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5324     return;
5325 
5326   // FIXME: all the access-control diagnostics are positioned on the
5327   // field/base declaration.  That's probably good; that said, the
5328   // user might reasonably want to know why the destructor is being
5329   // emitted, and we currently don't say.
5330 
5331   // Non-static data members.
5332   for (auto *Field : ClassDecl->fields()) {
5333     if (Field->isInvalidDecl())
5334       continue;
5335 
5336     // Don't destroy incomplete or zero-length arrays.
5337     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5338       continue;
5339 
5340     QualType FieldType = Context.getBaseElementType(Field->getType());
5341 
5342     const RecordType* RT = FieldType->getAs<RecordType>();
5343     if (!RT)
5344       continue;
5345 
5346     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5347     if (FieldClassDecl->isInvalidDecl())
5348       continue;
5349     if (FieldClassDecl->hasIrrelevantDestructor())
5350       continue;
5351     // The destructor for an implicit anonymous union member is never invoked.
5352     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5353       continue;
5354 
5355     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5356     assert(Dtor && "No dtor found for FieldClassDecl!");
5357     CheckDestructorAccess(Field->getLocation(), Dtor,
5358                           PDiag(diag::err_access_dtor_field)
5359                             << Field->getDeclName()
5360                             << FieldType);
5361 
5362     MarkFunctionReferenced(Location, Dtor);
5363     DiagnoseUseOfDecl(Dtor, Location);
5364   }
5365 
5366   // We only potentially invoke the destructors of potentially constructed
5367   // subobjects.
5368   bool VisitVirtualBases = !ClassDecl->isAbstract();
5369 
5370   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5371 
5372   // Bases.
5373   for (const auto &Base : ClassDecl->bases()) {
5374     // Bases are always records in a well-formed non-dependent class.
5375     const RecordType *RT = Base.getType()->getAs<RecordType>();
5376 
5377     // Remember direct virtual bases.
5378     if (Base.isVirtual()) {
5379       if (!VisitVirtualBases)
5380         continue;
5381       DirectVirtualBases.insert(RT);
5382     }
5383 
5384     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5385     // If our base class is invalid, we probably can't get its dtor anyway.
5386     if (BaseClassDecl->isInvalidDecl())
5387       continue;
5388     if (BaseClassDecl->hasIrrelevantDestructor())
5389       continue;
5390 
5391     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5392     assert(Dtor && "No dtor found for BaseClassDecl!");
5393 
5394     // FIXME: caret should be on the start of the class name
5395     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5396                           PDiag(diag::err_access_dtor_base)
5397                               << Base.getType() << Base.getSourceRange(),
5398                           Context.getTypeDeclType(ClassDecl));
5399 
5400     MarkFunctionReferenced(Location, Dtor);
5401     DiagnoseUseOfDecl(Dtor, Location);
5402   }
5403 
5404   if (!VisitVirtualBases)
5405     return;
5406 
5407   // Virtual bases.
5408   for (const auto &VBase : ClassDecl->vbases()) {
5409     // Bases are always records in a well-formed non-dependent class.
5410     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5411 
5412     // Ignore direct virtual bases.
5413     if (DirectVirtualBases.count(RT))
5414       continue;
5415 
5416     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5417     // If our base class is invalid, we probably can't get its dtor anyway.
5418     if (BaseClassDecl->isInvalidDecl())
5419       continue;
5420     if (BaseClassDecl->hasIrrelevantDestructor())
5421       continue;
5422 
5423     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5424     assert(Dtor && "No dtor found for BaseClassDecl!");
5425     if (CheckDestructorAccess(
5426             ClassDecl->getLocation(), Dtor,
5427             PDiag(diag::err_access_dtor_vbase)
5428                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5429             Context.getTypeDeclType(ClassDecl)) ==
5430         AR_accessible) {
5431       CheckDerivedToBaseConversion(
5432           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5433           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5434           SourceRange(), DeclarationName(), nullptr);
5435     }
5436 
5437     MarkFunctionReferenced(Location, Dtor);
5438     DiagnoseUseOfDecl(Dtor, Location);
5439   }
5440 }
5441 
5442 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5443   if (!CDtorDecl)
5444     return;
5445 
5446   if (CXXConstructorDecl *Constructor
5447       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5448     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5449     DiagnoseUninitializedFields(*this, Constructor);
5450   }
5451 }
5452 
5453 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5454   if (!getLangOpts().CPlusPlus)
5455     return false;
5456 
5457   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5458   if (!RD)
5459     return false;
5460 
5461   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5462   // class template specialization here, but doing so breaks a lot of code.
5463 
5464   // We can't answer whether something is abstract until it has a
5465   // definition. If it's currently being defined, we'll walk back
5466   // over all the declarations when we have a full definition.
5467   const CXXRecordDecl *Def = RD->getDefinition();
5468   if (!Def || Def->isBeingDefined())
5469     return false;
5470 
5471   return RD->isAbstract();
5472 }
5473 
5474 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5475                                   TypeDiagnoser &Diagnoser) {
5476   if (!isAbstractType(Loc, T))
5477     return false;
5478 
5479   T = Context.getBaseElementType(T);
5480   Diagnoser.diagnose(*this, Loc, T);
5481   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5482   return true;
5483 }
5484 
5485 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5486   // Check if we've already emitted the list of pure virtual functions
5487   // for this class.
5488   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5489     return;
5490 
5491   // If the diagnostic is suppressed, don't emit the notes. We're only
5492   // going to emit them once, so try to attach them to a diagnostic we're
5493   // actually going to show.
5494   if (Diags.isLastDiagnosticIgnored())
5495     return;
5496 
5497   CXXFinalOverriderMap FinalOverriders;
5498   RD->getFinalOverriders(FinalOverriders);
5499 
5500   // Keep a set of seen pure methods so we won't diagnose the same method
5501   // more than once.
5502   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5503 
5504   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5505                                    MEnd = FinalOverriders.end();
5506        M != MEnd;
5507        ++M) {
5508     for (OverridingMethods::iterator SO = M->second.begin(),
5509                                   SOEnd = M->second.end();
5510          SO != SOEnd; ++SO) {
5511       // C++ [class.abstract]p4:
5512       //   A class is abstract if it contains or inherits at least one
5513       //   pure virtual function for which the final overrider is pure
5514       //   virtual.
5515 
5516       //
5517       if (SO->second.size() != 1)
5518         continue;
5519 
5520       if (!SO->second.front().Method->isPure())
5521         continue;
5522 
5523       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5524         continue;
5525 
5526       Diag(SO->second.front().Method->getLocation(),
5527            diag::note_pure_virtual_function)
5528         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5529     }
5530   }
5531 
5532   if (!PureVirtualClassDiagSet)
5533     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5534   PureVirtualClassDiagSet->insert(RD);
5535 }
5536 
5537 namespace {
5538 struct AbstractUsageInfo {
5539   Sema &S;
5540   CXXRecordDecl *Record;
5541   CanQualType AbstractType;
5542   bool Invalid;
5543 
5544   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5545     : S(S), Record(Record),
5546       AbstractType(S.Context.getCanonicalType(
5547                    S.Context.getTypeDeclType(Record))),
5548       Invalid(false) {}
5549 
5550   void DiagnoseAbstractType() {
5551     if (Invalid) return;
5552     S.DiagnoseAbstractType(Record);
5553     Invalid = true;
5554   }
5555 
5556   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5557 };
5558 
5559 struct CheckAbstractUsage {
5560   AbstractUsageInfo &Info;
5561   const NamedDecl *Ctx;
5562 
5563   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5564     : Info(Info), Ctx(Ctx) {}
5565 
5566   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5567     switch (TL.getTypeLocClass()) {
5568 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5569 #define TYPELOC(CLASS, PARENT) \
5570     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5571 #include "clang/AST/TypeLocNodes.def"
5572     }
5573   }
5574 
5575   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5576     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5577     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5578       if (!TL.getParam(I))
5579         continue;
5580 
5581       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5582       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5583     }
5584   }
5585 
5586   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5587     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5588   }
5589 
5590   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5591     // Visit the type parameters from a permissive context.
5592     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5593       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5594       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5595         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5596           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5597       // TODO: other template argument types?
5598     }
5599   }
5600 
5601   // Visit pointee types from a permissive context.
5602 #define CheckPolymorphic(Type) \
5603   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5604     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5605   }
5606   CheckPolymorphic(PointerTypeLoc)
5607   CheckPolymorphic(ReferenceTypeLoc)
5608   CheckPolymorphic(MemberPointerTypeLoc)
5609   CheckPolymorphic(BlockPointerTypeLoc)
5610   CheckPolymorphic(AtomicTypeLoc)
5611 
5612   /// Handle all the types we haven't given a more specific
5613   /// implementation for above.
5614   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5615     // Every other kind of type that we haven't called out already
5616     // that has an inner type is either (1) sugar or (2) contains that
5617     // inner type in some way as a subobject.
5618     if (TypeLoc Next = TL.getNextTypeLoc())
5619       return Visit(Next, Sel);
5620 
5621     // If there's no inner type and we're in a permissive context,
5622     // don't diagnose.
5623     if (Sel == Sema::AbstractNone) return;
5624 
5625     // Check whether the type matches the abstract type.
5626     QualType T = TL.getType();
5627     if (T->isArrayType()) {
5628       Sel = Sema::AbstractArrayType;
5629       T = Info.S.Context.getBaseElementType(T);
5630     }
5631     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5632     if (CT != Info.AbstractType) return;
5633 
5634     // It matched; do some magic.
5635     if (Sel == Sema::AbstractArrayType) {
5636       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5637         << T << TL.getSourceRange();
5638     } else {
5639       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5640         << Sel << T << TL.getSourceRange();
5641     }
5642     Info.DiagnoseAbstractType();
5643   }
5644 };
5645 
5646 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5647                                   Sema::AbstractDiagSelID Sel) {
5648   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5649 }
5650 
5651 }
5652 
5653 /// Check for invalid uses of an abstract type in a method declaration.
5654 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5655                                     CXXMethodDecl *MD) {
5656   // No need to do the check on definitions, which require that
5657   // the return/param types be complete.
5658   if (MD->doesThisDeclarationHaveABody())
5659     return;
5660 
5661   // For safety's sake, just ignore it if we don't have type source
5662   // information.  This should never happen for non-implicit methods,
5663   // but...
5664   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5665     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5666 }
5667 
5668 /// Check for invalid uses of an abstract type within a class definition.
5669 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5670                                     CXXRecordDecl *RD) {
5671   for (auto *D : RD->decls()) {
5672     if (D->isImplicit()) continue;
5673 
5674     // Methods and method templates.
5675     if (isa<CXXMethodDecl>(D)) {
5676       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5677     } else if (isa<FunctionTemplateDecl>(D)) {
5678       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5679       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5680 
5681     // Fields and static variables.
5682     } else if (isa<FieldDecl>(D)) {
5683       FieldDecl *FD = cast<FieldDecl>(D);
5684       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5685         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5686     } else if (isa<VarDecl>(D)) {
5687       VarDecl *VD = cast<VarDecl>(D);
5688       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5689         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5690 
5691     // Nested classes and class templates.
5692     } else if (isa<CXXRecordDecl>(D)) {
5693       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5694     } else if (isa<ClassTemplateDecl>(D)) {
5695       CheckAbstractClassUsage(Info,
5696                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5697     }
5698   }
5699 }
5700 
5701 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5702   Attr *ClassAttr = getDLLAttr(Class);
5703   if (!ClassAttr)
5704     return;
5705 
5706   assert(ClassAttr->getKind() == attr::DLLExport);
5707 
5708   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5709 
5710   if (TSK == TSK_ExplicitInstantiationDeclaration)
5711     // Don't go any further if this is just an explicit instantiation
5712     // declaration.
5713     return;
5714 
5715   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5716     S.MarkVTableUsed(Class->getLocation(), Class, true);
5717 
5718   for (Decl *Member : Class->decls()) {
5719     // Defined static variables that are members of an exported base
5720     // class must be marked export too.
5721     auto *VD = dyn_cast<VarDecl>(Member);
5722     if (VD && Member->getAttr<DLLExportAttr>() &&
5723         VD->getStorageClass() == SC_Static &&
5724         TSK == TSK_ImplicitInstantiation)
5725       S.MarkVariableReferenced(VD->getLocation(), VD);
5726 
5727     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5728     if (!MD)
5729       continue;
5730 
5731     if (Member->getAttr<DLLExportAttr>()) {
5732       if (MD->isUserProvided()) {
5733         // Instantiate non-default class member functions ...
5734 
5735         // .. except for certain kinds of template specializations.
5736         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5737           continue;
5738 
5739         S.MarkFunctionReferenced(Class->getLocation(), MD);
5740 
5741         // The function will be passed to the consumer when its definition is
5742         // encountered.
5743       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5744                  MD->isCopyAssignmentOperator() ||
5745                  MD->isMoveAssignmentOperator()) {
5746         // Synthesize and instantiate non-trivial implicit methods, explicitly
5747         // defaulted methods, and the copy and move assignment operators. The
5748         // latter are exported even if they are trivial, because the address of
5749         // an operator can be taken and should compare equal across libraries.
5750         DiagnosticErrorTrap Trap(S.Diags);
5751         S.MarkFunctionReferenced(Class->getLocation(), MD);
5752         if (Trap.hasErrorOccurred()) {
5753           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5754               << Class << !S.getLangOpts().CPlusPlus11;
5755           break;
5756         }
5757 
5758         // There is no later point when we will see the definition of this
5759         // function, so pass it to the consumer now.
5760         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5761       }
5762     }
5763   }
5764 }
5765 
5766 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5767                                                         CXXRecordDecl *Class) {
5768   // Only the MS ABI has default constructor closures, so we don't need to do
5769   // this semantic checking anywhere else.
5770   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5771     return;
5772 
5773   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5774   for (Decl *Member : Class->decls()) {
5775     // Look for exported default constructors.
5776     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5777     if (!CD || !CD->isDefaultConstructor())
5778       continue;
5779     auto *Attr = CD->getAttr<DLLExportAttr>();
5780     if (!Attr)
5781       continue;
5782 
5783     // If the class is non-dependent, mark the default arguments as ODR-used so
5784     // that we can properly codegen the constructor closure.
5785     if (!Class->isDependentContext()) {
5786       for (ParmVarDecl *PD : CD->parameters()) {
5787         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5788         S.DiscardCleanupsInEvaluationContext();
5789       }
5790     }
5791 
5792     if (LastExportedDefaultCtor) {
5793       S.Diag(LastExportedDefaultCtor->getLocation(),
5794              diag::err_attribute_dll_ambiguous_default_ctor)
5795           << Class;
5796       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5797           << CD->getDeclName();
5798       return;
5799     }
5800     LastExportedDefaultCtor = CD;
5801   }
5802 }
5803 
5804 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5805   // Mark any compiler-generated routines with the implicit code_seg attribute.
5806   for (auto *Method : Class->methods()) {
5807     if (Method->isUserProvided())
5808       continue;
5809     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5810       Method->addAttr(A);
5811   }
5812 }
5813 
5814 /// Check class-level dllimport/dllexport attribute.
5815 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5816   Attr *ClassAttr = getDLLAttr(Class);
5817 
5818   // MSVC inherits DLL attributes to partial class template specializations.
5819   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5820     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5821       if (Attr *TemplateAttr =
5822               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5823         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5824         A->setInherited(true);
5825         ClassAttr = A;
5826       }
5827     }
5828   }
5829 
5830   if (!ClassAttr)
5831     return;
5832 
5833   if (!Class->isExternallyVisible()) {
5834     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5835         << Class << ClassAttr;
5836     return;
5837   }
5838 
5839   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5840       !ClassAttr->isInherited()) {
5841     // Diagnose dll attributes on members of class with dll attribute.
5842     for (Decl *Member : Class->decls()) {
5843       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5844         continue;
5845       InheritableAttr *MemberAttr = getDLLAttr(Member);
5846       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5847         continue;
5848 
5849       Diag(MemberAttr->getLocation(),
5850              diag::err_attribute_dll_member_of_dll_class)
5851           << MemberAttr << ClassAttr;
5852       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5853       Member->setInvalidDecl();
5854     }
5855   }
5856 
5857   if (Class->getDescribedClassTemplate())
5858     // Don't inherit dll attribute until the template is instantiated.
5859     return;
5860 
5861   // The class is either imported or exported.
5862   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5863 
5864   // Check if this was a dllimport attribute propagated from a derived class to
5865   // a base class template specialization. We don't apply these attributes to
5866   // static data members.
5867   const bool PropagatedImport =
5868       !ClassExported &&
5869       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5870 
5871   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5872 
5873   // Ignore explicit dllexport on explicit class template instantiation
5874   // declarations, except in MinGW mode.
5875   if (ClassExported && !ClassAttr->isInherited() &&
5876       TSK == TSK_ExplicitInstantiationDeclaration &&
5877       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5878     Class->dropAttr<DLLExportAttr>();
5879     return;
5880   }
5881 
5882   // Force declaration of implicit members so they can inherit the attribute.
5883   ForceDeclarationOfImplicitMembers(Class);
5884 
5885   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5886   // seem to be true in practice?
5887 
5888   for (Decl *Member : Class->decls()) {
5889     VarDecl *VD = dyn_cast<VarDecl>(Member);
5890     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5891 
5892     // Only methods and static fields inherit the attributes.
5893     if (!VD && !MD)
5894       continue;
5895 
5896     if (MD) {
5897       // Don't process deleted methods.
5898       if (MD->isDeleted())
5899         continue;
5900 
5901       if (MD->isInlined()) {
5902         // MinGW does not import or export inline methods. But do it for
5903         // template instantiations.
5904         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5905             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5906             TSK != TSK_ExplicitInstantiationDeclaration &&
5907             TSK != TSK_ExplicitInstantiationDefinition)
5908           continue;
5909 
5910         // MSVC versions before 2015 don't export the move assignment operators
5911         // and move constructor, so don't attempt to import/export them if
5912         // we have a definition.
5913         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5914         if ((MD->isMoveAssignmentOperator() ||
5915              (Ctor && Ctor->isMoveConstructor())) &&
5916             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5917           continue;
5918 
5919         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5920         // operator is exported anyway.
5921         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5922             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5923           continue;
5924       }
5925     }
5926 
5927     // Don't apply dllimport attributes to static data members of class template
5928     // instantiations when the attribute is propagated from a derived class.
5929     if (VD && PropagatedImport)
5930       continue;
5931 
5932     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5933       continue;
5934 
5935     if (!getDLLAttr(Member)) {
5936       InheritableAttr *NewAttr = nullptr;
5937 
5938       // Do not export/import inline function when -fno-dllexport-inlines is
5939       // passed. But add attribute for later local static var check.
5940       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5941           TSK != TSK_ExplicitInstantiationDeclaration &&
5942           TSK != TSK_ExplicitInstantiationDefinition) {
5943         if (ClassExported) {
5944           NewAttr = ::new (getASTContext())
5945               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
5946         } else {
5947           NewAttr = ::new (getASTContext())
5948               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
5949         }
5950       } else {
5951         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5952       }
5953 
5954       NewAttr->setInherited(true);
5955       Member->addAttr(NewAttr);
5956 
5957       if (MD) {
5958         // Propagate DLLAttr to friend re-declarations of MD that have already
5959         // been constructed.
5960         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5961              FD = FD->getPreviousDecl()) {
5962           if (FD->getFriendObjectKind() == Decl::FOK_None)
5963             continue;
5964           assert(!getDLLAttr(FD) &&
5965                  "friend re-decl should not already have a DLLAttr");
5966           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5967           NewAttr->setInherited(true);
5968           FD->addAttr(NewAttr);
5969         }
5970       }
5971     }
5972   }
5973 
5974   if (ClassExported)
5975     DelayedDllExportClasses.push_back(Class);
5976 }
5977 
5978 /// Perform propagation of DLL attributes from a derived class to a
5979 /// templated base class for MS compatibility.
5980 void Sema::propagateDLLAttrToBaseClassTemplate(
5981     CXXRecordDecl *Class, Attr *ClassAttr,
5982     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5983   if (getDLLAttr(
5984           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5985     // If the base class template has a DLL attribute, don't try to change it.
5986     return;
5987   }
5988 
5989   auto TSK = BaseTemplateSpec->getSpecializationKind();
5990   if (!getDLLAttr(BaseTemplateSpec) &&
5991       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5992        TSK == TSK_ImplicitInstantiation)) {
5993     // The template hasn't been instantiated yet (or it has, but only as an
5994     // explicit instantiation declaration or implicit instantiation, which means
5995     // we haven't codegenned any members yet), so propagate the attribute.
5996     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5997     NewAttr->setInherited(true);
5998     BaseTemplateSpec->addAttr(NewAttr);
5999 
6000     // If this was an import, mark that we propagated it from a derived class to
6001     // a base class template specialization.
6002     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6003       ImportAttr->setPropagatedToBaseTemplate();
6004 
6005     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6006     // needs to be run again to work see the new attribute. Otherwise this will
6007     // get run whenever the template is instantiated.
6008     if (TSK != TSK_Undeclared)
6009       checkClassLevelDLLAttribute(BaseTemplateSpec);
6010 
6011     return;
6012   }
6013 
6014   if (getDLLAttr(BaseTemplateSpec)) {
6015     // The template has already been specialized or instantiated with an
6016     // attribute, explicitly or through propagation. We should not try to change
6017     // it.
6018     return;
6019   }
6020 
6021   // The template was previously instantiated or explicitly specialized without
6022   // a dll attribute, It's too late for us to add an attribute, so warn that
6023   // this is unsupported.
6024   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6025       << BaseTemplateSpec->isExplicitSpecialization();
6026   Diag(ClassAttr->getLocation(), diag::note_attribute);
6027   if (BaseTemplateSpec->isExplicitSpecialization()) {
6028     Diag(BaseTemplateSpec->getLocation(),
6029            diag::note_template_class_explicit_specialization_was_here)
6030         << BaseTemplateSpec;
6031   } else {
6032     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6033            diag::note_template_class_instantiation_was_here)
6034         << BaseTemplateSpec;
6035   }
6036 }
6037 
6038 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
6039                                         SourceLocation DefaultLoc) {
6040   switch (S.getSpecialMember(MD)) {
6041   case Sema::CXXDefaultConstructor:
6042     S.DefineImplicitDefaultConstructor(DefaultLoc,
6043                                        cast<CXXConstructorDecl>(MD));
6044     break;
6045   case Sema::CXXCopyConstructor:
6046     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6047     break;
6048   case Sema::CXXCopyAssignment:
6049     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
6050     break;
6051   case Sema::CXXDestructor:
6052     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
6053     break;
6054   case Sema::CXXMoveConstructor:
6055     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6056     break;
6057   case Sema::CXXMoveAssignment:
6058     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
6059     break;
6060   case Sema::CXXInvalid:
6061     llvm_unreachable("Invalid special member.");
6062   }
6063 }
6064 
6065 /// Determine whether a type is permitted to be passed or returned in
6066 /// registers, per C++ [class.temporary]p3.
6067 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6068                                TargetInfo::CallingConvKind CCK) {
6069   if (D->isDependentType() || D->isInvalidDecl())
6070     return false;
6071 
6072   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6073   // The PS4 platform ABI follows the behavior of Clang 3.2.
6074   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6075     return !D->hasNonTrivialDestructorForCall() &&
6076            !D->hasNonTrivialCopyConstructorForCall();
6077 
6078   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6079     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6080     bool DtorIsTrivialForCall = false;
6081 
6082     // If a class has at least one non-deleted, trivial copy constructor, it
6083     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6084     //
6085     // Note: This permits classes with non-trivial copy or move ctors to be
6086     // passed in registers, so long as they *also* have a trivial copy ctor,
6087     // which is non-conforming.
6088     if (D->needsImplicitCopyConstructor()) {
6089       if (!D->defaultedCopyConstructorIsDeleted()) {
6090         if (D->hasTrivialCopyConstructor())
6091           CopyCtorIsTrivial = true;
6092         if (D->hasTrivialCopyConstructorForCall())
6093           CopyCtorIsTrivialForCall = true;
6094       }
6095     } else {
6096       for (const CXXConstructorDecl *CD : D->ctors()) {
6097         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6098           if (CD->isTrivial())
6099             CopyCtorIsTrivial = true;
6100           if (CD->isTrivialForCall())
6101             CopyCtorIsTrivialForCall = true;
6102         }
6103       }
6104     }
6105 
6106     if (D->needsImplicitDestructor()) {
6107       if (!D->defaultedDestructorIsDeleted() &&
6108           D->hasTrivialDestructorForCall())
6109         DtorIsTrivialForCall = true;
6110     } else if (const auto *DD = D->getDestructor()) {
6111       if (!DD->isDeleted() && DD->isTrivialForCall())
6112         DtorIsTrivialForCall = true;
6113     }
6114 
6115     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6116     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6117       return true;
6118 
6119     // If a class has a destructor, we'd really like to pass it indirectly
6120     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6121     // impossible for small types, which it will pass in a single register or
6122     // stack slot. Most objects with dtors are large-ish, so handle that early.
6123     // We can't call out all large objects as being indirect because there are
6124     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6125     // how we pass large POD types.
6126 
6127     // Note: This permits small classes with nontrivial destructors to be
6128     // passed in registers, which is non-conforming.
6129     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6130     uint64_t TypeSize = isAArch64 ? 128 : 64;
6131 
6132     if (CopyCtorIsTrivial &&
6133         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6134       return true;
6135     return false;
6136   }
6137 
6138   // Per C++ [class.temporary]p3, the relevant condition is:
6139   //   each copy constructor, move constructor, and destructor of X is
6140   //   either trivial or deleted, and X has at least one non-deleted copy
6141   //   or move constructor
6142   bool HasNonDeletedCopyOrMove = false;
6143 
6144   if (D->needsImplicitCopyConstructor() &&
6145       !D->defaultedCopyConstructorIsDeleted()) {
6146     if (!D->hasTrivialCopyConstructorForCall())
6147       return false;
6148     HasNonDeletedCopyOrMove = true;
6149   }
6150 
6151   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6152       !D->defaultedMoveConstructorIsDeleted()) {
6153     if (!D->hasTrivialMoveConstructorForCall())
6154       return false;
6155     HasNonDeletedCopyOrMove = true;
6156   }
6157 
6158   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6159       !D->hasTrivialDestructorForCall())
6160     return false;
6161 
6162   for (const CXXMethodDecl *MD : D->methods()) {
6163     if (MD->isDeleted())
6164       continue;
6165 
6166     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6167     if (CD && CD->isCopyOrMoveConstructor())
6168       HasNonDeletedCopyOrMove = true;
6169     else if (!isa<CXXDestructorDecl>(MD))
6170       continue;
6171 
6172     if (!MD->isTrivialForCall())
6173       return false;
6174   }
6175 
6176   return HasNonDeletedCopyOrMove;
6177 }
6178 
6179 /// Perform semantic checks on a class definition that has been
6180 /// completing, introducing implicitly-declared members, checking for
6181 /// abstract types, etc.
6182 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6183   if (!Record)
6184     return;
6185 
6186   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6187     AbstractUsageInfo Info(*this, Record);
6188     CheckAbstractClassUsage(Info, Record);
6189   }
6190 
6191   // If this is not an aggregate type and has no user-declared constructor,
6192   // complain about any non-static data members of reference or const scalar
6193   // type, since they will never get initializers.
6194   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6195       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6196       !Record->isLambda()) {
6197     bool Complained = false;
6198     for (const auto *F : Record->fields()) {
6199       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6200         continue;
6201 
6202       if (F->getType()->isReferenceType() ||
6203           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6204         if (!Complained) {
6205           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6206             << Record->getTagKind() << Record;
6207           Complained = true;
6208         }
6209 
6210         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6211           << F->getType()->isReferenceType()
6212           << F->getDeclName();
6213       }
6214     }
6215   }
6216 
6217   if (Record->getIdentifier()) {
6218     // C++ [class.mem]p13:
6219     //   If T is the name of a class, then each of the following shall have a
6220     //   name different from T:
6221     //     - every member of every anonymous union that is a member of class T.
6222     //
6223     // C++ [class.mem]p14:
6224     //   In addition, if class T has a user-declared constructor (12.1), every
6225     //   non-static data member of class T shall have a name different from T.
6226     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6227     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6228          ++I) {
6229       NamedDecl *D = (*I)->getUnderlyingDecl();
6230       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6231            Record->hasUserDeclaredConstructor()) ||
6232           isa<IndirectFieldDecl>(D)) {
6233         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6234           << D->getDeclName();
6235         break;
6236       }
6237     }
6238   }
6239 
6240   // Warn if the class has virtual methods but non-virtual public destructor.
6241   if (Record->isPolymorphic() && !Record->isDependentType()) {
6242     CXXDestructorDecl *dtor = Record->getDestructor();
6243     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6244         !Record->hasAttr<FinalAttr>())
6245       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6246            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6247   }
6248 
6249   if (Record->isAbstract()) {
6250     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6251       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6252         << FA->isSpelledAsSealed();
6253       DiagnoseAbstractType(Record);
6254     }
6255   }
6256 
6257   // Warn if the class has a final destructor but is not itself marked final.
6258   if (!Record->hasAttr<FinalAttr>()) {
6259     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6260       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6261         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6262             << FA->isSpelledAsSealed()
6263             << FixItHint::CreateInsertion(
6264                    getLocForEndOfToken(Record->getLocation()),
6265                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6266         Diag(Record->getLocation(),
6267              diag::note_final_dtor_non_final_class_silence)
6268             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6269       }
6270     }
6271   }
6272 
6273   // See if trivial_abi has to be dropped.
6274   if (Record->hasAttr<TrivialABIAttr>())
6275     checkIllFormedTrivialABIStruct(*Record);
6276 
6277   // Set HasTrivialSpecialMemberForCall if the record has attribute
6278   // "trivial_abi".
6279   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6280 
6281   if (HasTrivialABI)
6282     Record->setHasTrivialSpecialMemberForCall();
6283 
6284   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6285     // Check whether the explicitly-defaulted special members are valid.
6286     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6287       CheckExplicitlyDefaultedSpecialMember(M);
6288 
6289     // For an explicitly defaulted or deleted special member, we defer
6290     // determining triviality until the class is complete. That time is now!
6291     CXXSpecialMember CSM = getSpecialMember(M);
6292     if (!M->isImplicit() && !M->isUserProvided()) {
6293       if (CSM != CXXInvalid) {
6294         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6295         // Inform the class that we've finished declaring this member.
6296         Record->finishedDefaultedOrDeletedMember(M);
6297         M->setTrivialForCall(
6298             HasTrivialABI ||
6299             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6300         Record->setTrivialForCallFlags(M);
6301       }
6302     }
6303 
6304     // Set triviality for the purpose of calls if this is a user-provided
6305     // copy/move constructor or destructor.
6306     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6307          CSM == CXXDestructor) && M->isUserProvided()) {
6308       M->setTrivialForCall(HasTrivialABI);
6309       Record->setTrivialForCallFlags(M);
6310     }
6311 
6312     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6313         M->hasAttr<DLLExportAttr>()) {
6314       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6315           M->isTrivial() &&
6316           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6317            CSM == CXXDestructor))
6318         M->dropAttr<DLLExportAttr>();
6319 
6320       if (M->hasAttr<DLLExportAttr>()) {
6321         // Define after any fields with in-class initializers have been parsed.
6322         DelayedDllExportMemberFunctions.push_back(M);
6323       }
6324     }
6325   };
6326 
6327   bool HasMethodWithOverrideControl = false,
6328        HasOverridingMethodWithoutOverrideControl = false;
6329   if (!Record->isDependentType()) {
6330     // Check the destructor before any other member function. We need to
6331     // determine whether it's trivial in order to determine whether the claas
6332     // type is a literal type, which is a prerequisite for determining whether
6333     // other special member functions are valid and whether they're implicitly
6334     // 'constexpr'.
6335     if (CXXDestructorDecl *Dtor = Record->getDestructor())
6336       CompleteMemberFunction(Dtor);
6337 
6338     for (auto *M : Record->methods()) {
6339       // See if a method overloads virtual methods in a base
6340       // class without overriding any.
6341       if (!M->isStatic())
6342         DiagnoseHiddenVirtualMethods(M);
6343       if (M->hasAttr<OverrideAttr>())
6344         HasMethodWithOverrideControl = true;
6345       else if (M->size_overridden_methods() > 0)
6346         HasOverridingMethodWithoutOverrideControl = true;
6347 
6348       if (!isa<CXXDestructorDecl>(M))
6349         CompleteMemberFunction(M);
6350     }
6351   }
6352 
6353   if (HasMethodWithOverrideControl &&
6354       HasOverridingMethodWithoutOverrideControl) {
6355     // At least one method has the 'override' control declared.
6356     // Diagnose all other overridden methods which do not have 'override' specified on them.
6357     for (auto *M : Record->methods())
6358       DiagnoseAbsenceOfOverrideControl(M);
6359   }
6360 
6361   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6362   // whether this class uses any C++ features that are implemented
6363   // completely differently in MSVC, and if so, emit a diagnostic.
6364   // That diagnostic defaults to an error, but we allow projects to
6365   // map it down to a warning (or ignore it).  It's a fairly common
6366   // practice among users of the ms_struct pragma to mass-annotate
6367   // headers, sweeping up a bunch of types that the project doesn't
6368   // really rely on MSVC-compatible layout for.  We must therefore
6369   // support "ms_struct except for C++ stuff" as a secondary ABI.
6370   if (Record->isMsStruct(Context) &&
6371       (Record->isPolymorphic() || Record->getNumBases())) {
6372     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6373   }
6374 
6375   checkClassLevelDLLAttribute(Record);
6376   checkClassLevelCodeSegAttribute(Record);
6377 
6378   bool ClangABICompat4 =
6379       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6380   TargetInfo::CallingConvKind CCK =
6381       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6382   bool CanPass = canPassInRegisters(*this, Record, CCK);
6383 
6384   // Do not change ArgPassingRestrictions if it has already been set to
6385   // APK_CanNeverPassInRegs.
6386   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6387     Record->setArgPassingRestrictions(CanPass
6388                                           ? RecordDecl::APK_CanPassInRegs
6389                                           : RecordDecl::APK_CannotPassInRegs);
6390 
6391   // If canPassInRegisters returns true despite the record having a non-trivial
6392   // destructor, the record is destructed in the callee. This happens only when
6393   // the record or one of its subobjects has a field annotated with trivial_abi
6394   // or a field qualified with ObjC __strong/__weak.
6395   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6396     Record->setParamDestroyedInCallee(true);
6397   else if (Record->hasNonTrivialDestructor())
6398     Record->setParamDestroyedInCallee(CanPass);
6399 
6400   if (getLangOpts().ForceEmitVTables) {
6401     // If we want to emit all the vtables, we need to mark it as used.  This
6402     // is especially required for cases like vtable assumption loads.
6403     MarkVTableUsed(Record->getInnerLocStart(), Record);
6404   }
6405 }
6406 
6407 /// Look up the special member function that would be called by a special
6408 /// member function for a subobject of class type.
6409 ///
6410 /// \param Class The class type of the subobject.
6411 /// \param CSM The kind of special member function.
6412 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6413 /// \param ConstRHS True if this is a copy operation with a const object
6414 ///        on its RHS, that is, if the argument to the outer special member
6415 ///        function is 'const' and this is not a field marked 'mutable'.
6416 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6417     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6418     unsigned FieldQuals, bool ConstRHS) {
6419   unsigned LHSQuals = 0;
6420   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6421     LHSQuals = FieldQuals;
6422 
6423   unsigned RHSQuals = FieldQuals;
6424   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6425     RHSQuals = 0;
6426   else if (ConstRHS)
6427     RHSQuals |= Qualifiers::Const;
6428 
6429   return S.LookupSpecialMember(Class, CSM,
6430                                RHSQuals & Qualifiers::Const,
6431                                RHSQuals & Qualifiers::Volatile,
6432                                false,
6433                                LHSQuals & Qualifiers::Const,
6434                                LHSQuals & Qualifiers::Volatile);
6435 }
6436 
6437 class Sema::InheritedConstructorInfo {
6438   Sema &S;
6439   SourceLocation UseLoc;
6440 
6441   /// A mapping from the base classes through which the constructor was
6442   /// inherited to the using shadow declaration in that base class (or a null
6443   /// pointer if the constructor was declared in that base class).
6444   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6445       InheritedFromBases;
6446 
6447 public:
6448   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6449                            ConstructorUsingShadowDecl *Shadow)
6450       : S(S), UseLoc(UseLoc) {
6451     bool DiagnosedMultipleConstructedBases = false;
6452     CXXRecordDecl *ConstructedBase = nullptr;
6453     UsingDecl *ConstructedBaseUsing = nullptr;
6454 
6455     // Find the set of such base class subobjects and check that there's a
6456     // unique constructed subobject.
6457     for (auto *D : Shadow->redecls()) {
6458       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6459       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6460       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6461 
6462       InheritedFromBases.insert(
6463           std::make_pair(DNominatedBase->getCanonicalDecl(),
6464                          DShadow->getNominatedBaseClassShadowDecl()));
6465       if (DShadow->constructsVirtualBase())
6466         InheritedFromBases.insert(
6467             std::make_pair(DConstructedBase->getCanonicalDecl(),
6468                            DShadow->getConstructedBaseClassShadowDecl()));
6469       else
6470         assert(DNominatedBase == DConstructedBase);
6471 
6472       // [class.inhctor.init]p2:
6473       //   If the constructor was inherited from multiple base class subobjects
6474       //   of type B, the program is ill-formed.
6475       if (!ConstructedBase) {
6476         ConstructedBase = DConstructedBase;
6477         ConstructedBaseUsing = D->getUsingDecl();
6478       } else if (ConstructedBase != DConstructedBase &&
6479                  !Shadow->isInvalidDecl()) {
6480         if (!DiagnosedMultipleConstructedBases) {
6481           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6482               << Shadow->getTargetDecl();
6483           S.Diag(ConstructedBaseUsing->getLocation(),
6484                diag::note_ambiguous_inherited_constructor_using)
6485               << ConstructedBase;
6486           DiagnosedMultipleConstructedBases = true;
6487         }
6488         S.Diag(D->getUsingDecl()->getLocation(),
6489                diag::note_ambiguous_inherited_constructor_using)
6490             << DConstructedBase;
6491       }
6492     }
6493 
6494     if (DiagnosedMultipleConstructedBases)
6495       Shadow->setInvalidDecl();
6496   }
6497 
6498   /// Find the constructor to use for inherited construction of a base class,
6499   /// and whether that base class constructor inherits the constructor from a
6500   /// virtual base class (in which case it won't actually invoke it).
6501   std::pair<CXXConstructorDecl *, bool>
6502   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6503     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6504     if (It == InheritedFromBases.end())
6505       return std::make_pair(nullptr, false);
6506 
6507     // This is an intermediary class.
6508     if (It->second)
6509       return std::make_pair(
6510           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6511           It->second->constructsVirtualBase());
6512 
6513     // This is the base class from which the constructor was inherited.
6514     return std::make_pair(Ctor, false);
6515   }
6516 };
6517 
6518 /// Is the special member function which would be selected to perform the
6519 /// specified operation on the specified class type a constexpr constructor?
6520 static bool
6521 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6522                          Sema::CXXSpecialMember CSM, unsigned Quals,
6523                          bool ConstRHS,
6524                          CXXConstructorDecl *InheritedCtor = nullptr,
6525                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6526   // If we're inheriting a constructor, see if we need to call it for this base
6527   // class.
6528   if (InheritedCtor) {
6529     assert(CSM == Sema::CXXDefaultConstructor);
6530     auto BaseCtor =
6531         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6532     if (BaseCtor)
6533       return BaseCtor->isConstexpr();
6534   }
6535 
6536   if (CSM == Sema::CXXDefaultConstructor)
6537     return ClassDecl->hasConstexprDefaultConstructor();
6538 
6539   Sema::SpecialMemberOverloadResult SMOR =
6540       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6541   if (!SMOR.getMethod())
6542     // A constructor we wouldn't select can't be "involved in initializing"
6543     // anything.
6544     return true;
6545   return SMOR.getMethod()->isConstexpr();
6546 }
6547 
6548 /// Determine whether the specified special member function would be constexpr
6549 /// if it were implicitly defined.
6550 static bool defaultedSpecialMemberIsConstexpr(
6551     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6552     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6553     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6554   if (!S.getLangOpts().CPlusPlus11)
6555     return false;
6556 
6557   // C++11 [dcl.constexpr]p4:
6558   // In the definition of a constexpr constructor [...]
6559   bool Ctor = true;
6560   switch (CSM) {
6561   case Sema::CXXDefaultConstructor:
6562     if (Inherited)
6563       break;
6564     // Since default constructor lookup is essentially trivial (and cannot
6565     // involve, for instance, template instantiation), we compute whether a
6566     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6567     //
6568     // This is important for performance; we need to know whether the default
6569     // constructor is constexpr to determine whether the type is a literal type.
6570     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6571 
6572   case Sema::CXXCopyConstructor:
6573   case Sema::CXXMoveConstructor:
6574     // For copy or move constructors, we need to perform overload resolution.
6575     break;
6576 
6577   case Sema::CXXCopyAssignment:
6578   case Sema::CXXMoveAssignment:
6579     if (!S.getLangOpts().CPlusPlus14)
6580       return false;
6581     // In C++1y, we need to perform overload resolution.
6582     Ctor = false;
6583     break;
6584 
6585   case Sema::CXXDestructor:
6586   case Sema::CXXInvalid:
6587     return false;
6588   }
6589 
6590   //   -- if the class is a non-empty union, or for each non-empty anonymous
6591   //      union member of a non-union class, exactly one non-static data member
6592   //      shall be initialized; [DR1359]
6593   //
6594   // If we squint, this is guaranteed, since exactly one non-static data member
6595   // will be initialized (if the constructor isn't deleted), we just don't know
6596   // which one.
6597   if (Ctor && ClassDecl->isUnion())
6598     return CSM == Sema::CXXDefaultConstructor
6599                ? ClassDecl->hasInClassInitializer() ||
6600                      !ClassDecl->hasVariantMembers()
6601                : true;
6602 
6603   //   -- the class shall not have any virtual base classes;
6604   if (Ctor && ClassDecl->getNumVBases())
6605     return false;
6606 
6607   // C++1y [class.copy]p26:
6608   //   -- [the class] is a literal type, and
6609   if (!Ctor && !ClassDecl->isLiteral())
6610     return false;
6611 
6612   //   -- every constructor involved in initializing [...] base class
6613   //      sub-objects shall be a constexpr constructor;
6614   //   -- the assignment operator selected to copy/move each direct base
6615   //      class is a constexpr function, and
6616   for (const auto &B : ClassDecl->bases()) {
6617     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6618     if (!BaseType) continue;
6619 
6620     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6621     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6622                                   InheritedCtor, Inherited))
6623       return false;
6624   }
6625 
6626   //   -- every constructor involved in initializing non-static data members
6627   //      [...] shall be a constexpr constructor;
6628   //   -- every non-static data member and base class sub-object shall be
6629   //      initialized
6630   //   -- for each non-static data member of X that is of class type (or array
6631   //      thereof), the assignment operator selected to copy/move that member is
6632   //      a constexpr function
6633   for (const auto *F : ClassDecl->fields()) {
6634     if (F->isInvalidDecl())
6635       continue;
6636     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6637       continue;
6638     QualType BaseType = S.Context.getBaseElementType(F->getType());
6639     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6640       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6641       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6642                                     BaseType.getCVRQualifiers(),
6643                                     ConstArg && !F->isMutable()))
6644         return false;
6645     } else if (CSM == Sema::CXXDefaultConstructor) {
6646       return false;
6647     }
6648   }
6649 
6650   // All OK, it's constexpr!
6651   return true;
6652 }
6653 
6654 static Sema::ImplicitExceptionSpecification
6655 ComputeDefaultedSpecialMemberExceptionSpec(
6656     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6657     Sema::InheritedConstructorInfo *ICI);
6658 
6659 static Sema::ImplicitExceptionSpecification
6660 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6661   auto CSM = S.getSpecialMember(MD);
6662   if (CSM != Sema::CXXInvalid)
6663     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6664 
6665   auto *CD = cast<CXXConstructorDecl>(MD);
6666   assert(CD->getInheritedConstructor() &&
6667          "only special members have implicit exception specs");
6668   Sema::InheritedConstructorInfo ICI(
6669       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6670   return ComputeDefaultedSpecialMemberExceptionSpec(
6671       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6672 }
6673 
6674 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6675                                                             CXXMethodDecl *MD) {
6676   FunctionProtoType::ExtProtoInfo EPI;
6677 
6678   // Build an exception specification pointing back at this member.
6679   EPI.ExceptionSpec.Type = EST_Unevaluated;
6680   EPI.ExceptionSpec.SourceDecl = MD;
6681 
6682   // Set the calling convention to the default for C++ instance methods.
6683   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6684       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6685                                             /*IsCXXMethod=*/true));
6686   return EPI;
6687 }
6688 
6689 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6690   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6691   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6692     return;
6693 
6694   // Evaluate the exception specification.
6695   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6696   auto ESI = IES.getExceptionSpec();
6697 
6698   // Update the type of the special member to use it.
6699   UpdateExceptionSpec(MD, ESI);
6700 
6701   // A user-provided destructor can be defined outside the class. When that
6702   // happens, be sure to update the exception specification on both
6703   // declarations.
6704   const FunctionProtoType *CanonicalFPT =
6705     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6706   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6707     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6708 }
6709 
6710 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6711   CXXRecordDecl *RD = MD->getParent();
6712   CXXSpecialMember CSM = getSpecialMember(MD);
6713 
6714   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6715          "not an explicitly-defaulted special member");
6716 
6717   // Whether this was the first-declared instance of the constructor.
6718   // This affects whether we implicitly add an exception spec and constexpr.
6719   bool First = MD == MD->getCanonicalDecl();
6720 
6721   bool HadError = false;
6722 
6723   // C++11 [dcl.fct.def.default]p1:
6724   //   A function that is explicitly defaulted shall
6725   //     -- be a special member function (checked elsewhere),
6726   //     -- have the same type (except for ref-qualifiers, and except that a
6727   //        copy operation can take a non-const reference) as an implicit
6728   //        declaration, and
6729   //     -- not have default arguments.
6730   // C++2a changes the second bullet to instead delete the function if it's
6731   // defaulted on its first declaration, unless it's "an assignment operator,
6732   // and its return type differs or its parameter type is not a reference".
6733   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6734   bool ShouldDeleteForTypeMismatch = false;
6735   unsigned ExpectedParams = 1;
6736   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6737     ExpectedParams = 0;
6738   if (MD->getNumParams() != ExpectedParams) {
6739     // This checks for default arguments: a copy or move constructor with a
6740     // default argument is classified as a default constructor, and assignment
6741     // operations and destructors can't have default arguments.
6742     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6743       << CSM << MD->getSourceRange();
6744     HadError = true;
6745   } else if (MD->isVariadic()) {
6746     if (DeleteOnTypeMismatch)
6747       ShouldDeleteForTypeMismatch = true;
6748     else {
6749       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6750         << CSM << MD->getSourceRange();
6751       HadError = true;
6752     }
6753   }
6754 
6755   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6756 
6757   bool CanHaveConstParam = false;
6758   if (CSM == CXXCopyConstructor)
6759     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6760   else if (CSM == CXXCopyAssignment)
6761     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6762 
6763   QualType ReturnType = Context.VoidTy;
6764   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6765     // Check for return type matching.
6766     ReturnType = Type->getReturnType();
6767 
6768     QualType DeclType = Context.getTypeDeclType(RD);
6769     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6770     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6771 
6772     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6773       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6774         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6775       HadError = true;
6776     }
6777 
6778     // A defaulted special member cannot have cv-qualifiers.
6779     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6780       if (DeleteOnTypeMismatch)
6781         ShouldDeleteForTypeMismatch = true;
6782       else {
6783         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6784           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6785         HadError = true;
6786       }
6787     }
6788   }
6789 
6790   // Check for parameter type matching.
6791   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6792   bool HasConstParam = false;
6793   if (ExpectedParams && ArgType->isReferenceType()) {
6794     // Argument must be reference to possibly-const T.
6795     QualType ReferentType = ArgType->getPointeeType();
6796     HasConstParam = ReferentType.isConstQualified();
6797 
6798     if (ReferentType.isVolatileQualified()) {
6799       if (DeleteOnTypeMismatch)
6800         ShouldDeleteForTypeMismatch = true;
6801       else {
6802         Diag(MD->getLocation(),
6803              diag::err_defaulted_special_member_volatile_param) << CSM;
6804         HadError = true;
6805       }
6806     }
6807 
6808     if (HasConstParam && !CanHaveConstParam) {
6809       if (DeleteOnTypeMismatch)
6810         ShouldDeleteForTypeMismatch = true;
6811       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6812         Diag(MD->getLocation(),
6813              diag::err_defaulted_special_member_copy_const_param)
6814           << (CSM == CXXCopyAssignment);
6815         // FIXME: Explain why this special member can't be const.
6816         HadError = true;
6817       } else {
6818         Diag(MD->getLocation(),
6819              diag::err_defaulted_special_member_move_const_param)
6820           << (CSM == CXXMoveAssignment);
6821         HadError = true;
6822       }
6823     }
6824   } else if (ExpectedParams) {
6825     // A copy assignment operator can take its argument by value, but a
6826     // defaulted one cannot.
6827     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6828     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6829     HadError = true;
6830   }
6831 
6832   // C++11 [dcl.fct.def.default]p2:
6833   //   An explicitly-defaulted function may be declared constexpr only if it
6834   //   would have been implicitly declared as constexpr,
6835   // Do not apply this rule to members of class templates, since core issue 1358
6836   // makes such functions always instantiate to constexpr functions. For
6837   // functions which cannot be constexpr (for non-constructors in C++11 and for
6838   // destructors in C++1y), this is checked elsewhere.
6839   //
6840   // FIXME: This should not apply if the member is deleted.
6841   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6842                                                      HasConstParam);
6843   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6844                                  : isa<CXXConstructorDecl>(MD)) &&
6845       MD->isConstexpr() && !Constexpr &&
6846       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6847     Diag(MD->getBeginLoc(), MD->isConsteval()
6848                                 ? diag::err_incorrect_defaulted_consteval
6849                                 : diag::err_incorrect_defaulted_constexpr)
6850         << CSM;
6851     // FIXME: Explain why the special member can't be constexpr.
6852     HadError = true;
6853   }
6854 
6855   if (First) {
6856     // C++2a [dcl.fct.def.default]p3:
6857     //   If a function is explicitly defaulted on its first declaration, it is
6858     //   implicitly considered to be constexpr if the implicit declaration
6859     //   would be.
6860     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6861 
6862     if (!Type->hasExceptionSpec()) {
6863       // C++2a [except.spec]p3:
6864       //   If a declaration of a function does not have a noexcept-specifier
6865       //   [and] is defaulted on its first declaration, [...] the exception
6866       //   specification is as specified below
6867       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6868       EPI.ExceptionSpec.Type = EST_Unevaluated;
6869       EPI.ExceptionSpec.SourceDecl = MD;
6870       MD->setType(Context.getFunctionType(ReturnType,
6871                                           llvm::makeArrayRef(&ArgType,
6872                                                              ExpectedParams),
6873                                           EPI));
6874     }
6875   }
6876 
6877   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6878     if (First) {
6879       SetDeclDeleted(MD, MD->getLocation());
6880       if (!inTemplateInstantiation() && !HadError) {
6881         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6882         if (ShouldDeleteForTypeMismatch) {
6883           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6884         } else {
6885           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6886         }
6887       }
6888       if (ShouldDeleteForTypeMismatch && !HadError) {
6889         Diag(MD->getLocation(),
6890              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6891       }
6892     } else {
6893       // C++11 [dcl.fct.def.default]p4:
6894       //   [For a] user-provided explicitly-defaulted function [...] if such a
6895       //   function is implicitly defined as deleted, the program is ill-formed.
6896       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6897       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6898       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6899       HadError = true;
6900     }
6901   }
6902 
6903   if (HadError)
6904     MD->setInvalidDecl();
6905 }
6906 
6907 void Sema::CheckDelayedMemberExceptionSpecs() {
6908   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6909   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6910 
6911   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6912   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6913 
6914   // Perform any deferred checking of exception specifications for virtual
6915   // destructors.
6916   for (auto &Check : Overriding)
6917     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6918 
6919   // Perform any deferred checking of exception specifications for befriended
6920   // special members.
6921   for (auto &Check : Equivalent)
6922     CheckEquivalentExceptionSpec(Check.second, Check.first);
6923 }
6924 
6925 namespace {
6926 /// CRTP base class for visiting operations performed by a special member
6927 /// function (or inherited constructor).
6928 template<typename Derived>
6929 struct SpecialMemberVisitor {
6930   Sema &S;
6931   CXXMethodDecl *MD;
6932   Sema::CXXSpecialMember CSM;
6933   Sema::InheritedConstructorInfo *ICI;
6934 
6935   // Properties of the special member, computed for convenience.
6936   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6937 
6938   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6939                        Sema::InheritedConstructorInfo *ICI)
6940       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6941     switch (CSM) {
6942     case Sema::CXXDefaultConstructor:
6943     case Sema::CXXCopyConstructor:
6944     case Sema::CXXMoveConstructor:
6945       IsConstructor = true;
6946       break;
6947     case Sema::CXXCopyAssignment:
6948     case Sema::CXXMoveAssignment:
6949       IsAssignment = true;
6950       break;
6951     case Sema::CXXDestructor:
6952       break;
6953     case Sema::CXXInvalid:
6954       llvm_unreachable("invalid special member kind");
6955     }
6956 
6957     if (MD->getNumParams()) {
6958       if (const ReferenceType *RT =
6959               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6960         ConstArg = RT->getPointeeType().isConstQualified();
6961     }
6962   }
6963 
6964   Derived &getDerived() { return static_cast<Derived&>(*this); }
6965 
6966   /// Is this a "move" special member?
6967   bool isMove() const {
6968     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6969   }
6970 
6971   /// Look up the corresponding special member in the given class.
6972   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6973                                              unsigned Quals, bool IsMutable) {
6974     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6975                                        ConstArg && !IsMutable);
6976   }
6977 
6978   /// Look up the constructor for the specified base class to see if it's
6979   /// overridden due to this being an inherited constructor.
6980   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6981     if (!ICI)
6982       return {};
6983     assert(CSM == Sema::CXXDefaultConstructor);
6984     auto *BaseCtor =
6985       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6986     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6987       return MD;
6988     return {};
6989   }
6990 
6991   /// A base or member subobject.
6992   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6993 
6994   /// Get the location to use for a subobject in diagnostics.
6995   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6996     // FIXME: For an indirect virtual base, the direct base leading to
6997     // the indirect virtual base would be a more useful choice.
6998     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6999       return B->getBaseTypeLoc();
7000     else
7001       return Subobj.get<FieldDecl*>()->getLocation();
7002   }
7003 
7004   enum BasesToVisit {
7005     /// Visit all non-virtual (direct) bases.
7006     VisitNonVirtualBases,
7007     /// Visit all direct bases, virtual or not.
7008     VisitDirectBases,
7009     /// Visit all non-virtual bases, and all virtual bases if the class
7010     /// is not abstract.
7011     VisitPotentiallyConstructedBases,
7012     /// Visit all direct or virtual bases.
7013     VisitAllBases
7014   };
7015 
7016   // Visit the bases and members of the class.
7017   bool visit(BasesToVisit Bases) {
7018     CXXRecordDecl *RD = MD->getParent();
7019 
7020     if (Bases == VisitPotentiallyConstructedBases)
7021       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
7022 
7023     for (auto &B : RD->bases())
7024       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
7025           getDerived().visitBase(&B))
7026         return true;
7027 
7028     if (Bases == VisitAllBases)
7029       for (auto &B : RD->vbases())
7030         if (getDerived().visitBase(&B))
7031           return true;
7032 
7033     for (auto *F : RD->fields())
7034       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
7035           getDerived().visitField(F))
7036         return true;
7037 
7038     return false;
7039   }
7040 };
7041 }
7042 
7043 namespace {
7044 struct SpecialMemberDeletionInfo
7045     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
7046   bool Diagnose;
7047 
7048   SourceLocation Loc;
7049 
7050   bool AllFieldsAreConst;
7051 
7052   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
7053                             Sema::CXXSpecialMember CSM,
7054                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
7055       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
7056         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
7057 
7058   bool inUnion() const { return MD->getParent()->isUnion(); }
7059 
7060   Sema::CXXSpecialMember getEffectiveCSM() {
7061     return ICI ? Sema::CXXInvalid : CSM;
7062   }
7063 
7064   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
7065 
7066   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
7067   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
7068 
7069   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
7070   bool shouldDeleteForField(FieldDecl *FD);
7071   bool shouldDeleteForAllConstMembers();
7072 
7073   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
7074                                      unsigned Quals);
7075   bool shouldDeleteForSubobjectCall(Subobject Subobj,
7076                                     Sema::SpecialMemberOverloadResult SMOR,
7077                                     bool IsDtorCallInCtor);
7078 
7079   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
7080 };
7081 }
7082 
7083 /// Is the given special member inaccessible when used on the given
7084 /// sub-object.
7085 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
7086                                              CXXMethodDecl *target) {
7087   /// If we're operating on a base class, the object type is the
7088   /// type of this special member.
7089   QualType objectTy;
7090   AccessSpecifier access = target->getAccess();
7091   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
7092     objectTy = S.Context.getTypeDeclType(MD->getParent());
7093     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
7094 
7095   // If we're operating on a field, the object type is the type of the field.
7096   } else {
7097     objectTy = S.Context.getTypeDeclType(target->getParent());
7098   }
7099 
7100   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
7101 }
7102 
7103 /// Check whether we should delete a special member due to the implicit
7104 /// definition containing a call to a special member of a subobject.
7105 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
7106     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
7107     bool IsDtorCallInCtor) {
7108   CXXMethodDecl *Decl = SMOR.getMethod();
7109   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7110 
7111   int DiagKind = -1;
7112 
7113   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
7114     DiagKind = !Decl ? 0 : 1;
7115   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7116     DiagKind = 2;
7117   else if (!isAccessible(Subobj, Decl))
7118     DiagKind = 3;
7119   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
7120            !Decl->isTrivial()) {
7121     // A member of a union must have a trivial corresponding special member.
7122     // As a weird special case, a destructor call from a union's constructor
7123     // must be accessible and non-deleted, but need not be trivial. Such a
7124     // destructor is never actually called, but is semantically checked as
7125     // if it were.
7126     DiagKind = 4;
7127   }
7128 
7129   if (DiagKind == -1)
7130     return false;
7131 
7132   if (Diagnose) {
7133     if (Field) {
7134       S.Diag(Field->getLocation(),
7135              diag::note_deleted_special_member_class_subobject)
7136         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
7137         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
7138     } else {
7139       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
7140       S.Diag(Base->getBeginLoc(),
7141              diag::note_deleted_special_member_class_subobject)
7142           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7143           << Base->getType() << DiagKind << IsDtorCallInCtor
7144           << /*IsObjCPtr*/false;
7145     }
7146 
7147     if (DiagKind == 1)
7148       S.NoteDeletedFunction(Decl);
7149     // FIXME: Explain inaccessibility if DiagKind == 3.
7150   }
7151 
7152   return true;
7153 }
7154 
7155 /// Check whether we should delete a special member function due to having a
7156 /// direct or virtual base class or non-static data member of class type M.
7157 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7158     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7159   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7160   bool IsMutable = Field && Field->isMutable();
7161 
7162   // C++11 [class.ctor]p5:
7163   // -- any direct or virtual base class, or non-static data member with no
7164   //    brace-or-equal-initializer, has class type M (or array thereof) and
7165   //    either M has no default constructor or overload resolution as applied
7166   //    to M's default constructor results in an ambiguity or in a function
7167   //    that is deleted or inaccessible
7168   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7169   // -- a direct or virtual base class B that cannot be copied/moved because
7170   //    overload resolution, as applied to B's corresponding special member,
7171   //    results in an ambiguity or a function that is deleted or inaccessible
7172   //    from the defaulted special member
7173   // C++11 [class.dtor]p5:
7174   // -- any direct or virtual base class [...] has a type with a destructor
7175   //    that is deleted or inaccessible
7176   if (!(CSM == Sema::CXXDefaultConstructor &&
7177         Field && Field->hasInClassInitializer()) &&
7178       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7179                                    false))
7180     return true;
7181 
7182   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7183   // -- any direct or virtual base class or non-static data member has a
7184   //    type with a destructor that is deleted or inaccessible
7185   if (IsConstructor) {
7186     Sema::SpecialMemberOverloadResult SMOR =
7187         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7188                               false, false, false, false, false);
7189     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7190       return true;
7191   }
7192 
7193   return false;
7194 }
7195 
7196 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7197     FieldDecl *FD, QualType FieldType) {
7198   // The defaulted special functions are defined as deleted if this is a variant
7199   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7200   // type under ARC.
7201   if (!FieldType.hasNonTrivialObjCLifetime())
7202     return false;
7203 
7204   // Don't make the defaulted default constructor defined as deleted if the
7205   // member has an in-class initializer.
7206   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7207     return false;
7208 
7209   if (Diagnose) {
7210     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7211     S.Diag(FD->getLocation(),
7212            diag::note_deleted_special_member_class_subobject)
7213         << getEffectiveCSM() << ParentClass << /*IsField*/true
7214         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7215   }
7216 
7217   return true;
7218 }
7219 
7220 /// Check whether we should delete a special member function due to the class
7221 /// having a particular direct or virtual base class.
7222 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7223   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7224   // If program is correct, BaseClass cannot be null, but if it is, the error
7225   // must be reported elsewhere.
7226   if (!BaseClass)
7227     return false;
7228   // If we have an inheriting constructor, check whether we're calling an
7229   // inherited constructor instead of a default constructor.
7230   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7231   if (auto *BaseCtor = SMOR.getMethod()) {
7232     // Note that we do not check access along this path; other than that,
7233     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7234     // FIXME: Check that the base has a usable destructor! Sink this into
7235     // shouldDeleteForClassSubobject.
7236     if (BaseCtor->isDeleted() && Diagnose) {
7237       S.Diag(Base->getBeginLoc(),
7238              diag::note_deleted_special_member_class_subobject)
7239           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7240           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7241           << /*IsObjCPtr*/false;
7242       S.NoteDeletedFunction(BaseCtor);
7243     }
7244     return BaseCtor->isDeleted();
7245   }
7246   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7247 }
7248 
7249 /// Check whether we should delete a special member function due to the class
7250 /// having a particular non-static data member.
7251 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7252   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7253   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7254 
7255   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7256     return true;
7257 
7258   if (CSM == Sema::CXXDefaultConstructor) {
7259     // For a default constructor, all references must be initialized in-class
7260     // and, if a union, it must have a non-const member.
7261     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7262       if (Diagnose)
7263         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7264           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7265       return true;
7266     }
7267     // C++11 [class.ctor]p5: any non-variant non-static data member of
7268     // const-qualified type (or array thereof) with no
7269     // brace-or-equal-initializer does not have a user-provided default
7270     // constructor.
7271     if (!inUnion() && FieldType.isConstQualified() &&
7272         !FD->hasInClassInitializer() &&
7273         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7274       if (Diagnose)
7275         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7276           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7277       return true;
7278     }
7279 
7280     if (inUnion() && !FieldType.isConstQualified())
7281       AllFieldsAreConst = false;
7282   } else if (CSM == Sema::CXXCopyConstructor) {
7283     // For a copy constructor, data members must not be of rvalue reference
7284     // type.
7285     if (FieldType->isRValueReferenceType()) {
7286       if (Diagnose)
7287         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7288           << MD->getParent() << FD << FieldType;
7289       return true;
7290     }
7291   } else if (IsAssignment) {
7292     // For an assignment operator, data members must not be of reference type.
7293     if (FieldType->isReferenceType()) {
7294       if (Diagnose)
7295         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7296           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7297       return true;
7298     }
7299     if (!FieldRecord && FieldType.isConstQualified()) {
7300       // C++11 [class.copy]p23:
7301       // -- a non-static data member of const non-class type (or array thereof)
7302       if (Diagnose)
7303         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7304           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7305       return true;
7306     }
7307   }
7308 
7309   if (FieldRecord) {
7310     // Some additional restrictions exist on the variant members.
7311     if (!inUnion() && FieldRecord->isUnion() &&
7312         FieldRecord->isAnonymousStructOrUnion()) {
7313       bool AllVariantFieldsAreConst = true;
7314 
7315       // FIXME: Handle anonymous unions declared within anonymous unions.
7316       for (auto *UI : FieldRecord->fields()) {
7317         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7318 
7319         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7320           return true;
7321 
7322         if (!UnionFieldType.isConstQualified())
7323           AllVariantFieldsAreConst = false;
7324 
7325         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7326         if (UnionFieldRecord &&
7327             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7328                                           UnionFieldType.getCVRQualifiers()))
7329           return true;
7330       }
7331 
7332       // At least one member in each anonymous union must be non-const
7333       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7334           !FieldRecord->field_empty()) {
7335         if (Diagnose)
7336           S.Diag(FieldRecord->getLocation(),
7337                  diag::note_deleted_default_ctor_all_const)
7338             << !!ICI << MD->getParent() << /*anonymous union*/1;
7339         return true;
7340       }
7341 
7342       // Don't check the implicit member of the anonymous union type.
7343       // This is technically non-conformant, but sanity demands it.
7344       return false;
7345     }
7346 
7347     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7348                                       FieldType.getCVRQualifiers()))
7349       return true;
7350   }
7351 
7352   return false;
7353 }
7354 
7355 /// C++11 [class.ctor] p5:
7356 ///   A defaulted default constructor for a class X is defined as deleted if
7357 /// X is a union and all of its variant members are of const-qualified type.
7358 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7359   // This is a silly definition, because it gives an empty union a deleted
7360   // default constructor. Don't do that.
7361   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7362     bool AnyFields = false;
7363     for (auto *F : MD->getParent()->fields())
7364       if ((AnyFields = !F->isUnnamedBitfield()))
7365         break;
7366     if (!AnyFields)
7367       return false;
7368     if (Diagnose)
7369       S.Diag(MD->getParent()->getLocation(),
7370              diag::note_deleted_default_ctor_all_const)
7371         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7372     return true;
7373   }
7374   return false;
7375 }
7376 
7377 /// Determine whether a defaulted special member function should be defined as
7378 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7379 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7380 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7381                                      InheritedConstructorInfo *ICI,
7382                                      bool Diagnose) {
7383   if (MD->isInvalidDecl())
7384     return false;
7385   CXXRecordDecl *RD = MD->getParent();
7386   assert(!RD->isDependentType() && "do deletion after instantiation");
7387   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7388     return false;
7389 
7390   // C++11 [expr.lambda.prim]p19:
7391   //   The closure type associated with a lambda-expression has a
7392   //   deleted (8.4.3) default constructor and a deleted copy
7393   //   assignment operator.
7394   // C++2a adds back these operators if the lambda has no lambda-capture.
7395   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7396       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7397     if (Diagnose)
7398       Diag(RD->getLocation(), diag::note_lambda_decl);
7399     return true;
7400   }
7401 
7402   // For an anonymous struct or union, the copy and assignment special members
7403   // will never be used, so skip the check. For an anonymous union declared at
7404   // namespace scope, the constructor and destructor are used.
7405   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7406       RD->isAnonymousStructOrUnion())
7407     return false;
7408 
7409   // C++11 [class.copy]p7, p18:
7410   //   If the class definition declares a move constructor or move assignment
7411   //   operator, an implicitly declared copy constructor or copy assignment
7412   //   operator is defined as deleted.
7413   if (MD->isImplicit() &&
7414       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7415     CXXMethodDecl *UserDeclaredMove = nullptr;
7416 
7417     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7418     // deletion of the corresponding copy operation, not both copy operations.
7419     // MSVC 2015 has adopted the standards conforming behavior.
7420     bool DeletesOnlyMatchingCopy =
7421         getLangOpts().MSVCCompat &&
7422         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7423 
7424     if (RD->hasUserDeclaredMoveConstructor() &&
7425         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7426       if (!Diagnose) return true;
7427 
7428       // Find any user-declared move constructor.
7429       for (auto *I : RD->ctors()) {
7430         if (I->isMoveConstructor()) {
7431           UserDeclaredMove = I;
7432           break;
7433         }
7434       }
7435       assert(UserDeclaredMove);
7436     } else if (RD->hasUserDeclaredMoveAssignment() &&
7437                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7438       if (!Diagnose) return true;
7439 
7440       // Find any user-declared move assignment operator.
7441       for (auto *I : RD->methods()) {
7442         if (I->isMoveAssignmentOperator()) {
7443           UserDeclaredMove = I;
7444           break;
7445         }
7446       }
7447       assert(UserDeclaredMove);
7448     }
7449 
7450     if (UserDeclaredMove) {
7451       Diag(UserDeclaredMove->getLocation(),
7452            diag::note_deleted_copy_user_declared_move)
7453         << (CSM == CXXCopyAssignment) << RD
7454         << UserDeclaredMove->isMoveAssignmentOperator();
7455       return true;
7456     }
7457   }
7458 
7459   // Do access control from the special member function
7460   ContextRAII MethodContext(*this, MD);
7461 
7462   // C++11 [class.dtor]p5:
7463   // -- for a virtual destructor, lookup of the non-array deallocation function
7464   //    results in an ambiguity or in a function that is deleted or inaccessible
7465   if (CSM == CXXDestructor && MD->isVirtual()) {
7466     FunctionDecl *OperatorDelete = nullptr;
7467     DeclarationName Name =
7468       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7469     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7470                                  OperatorDelete, /*Diagnose*/false)) {
7471       if (Diagnose)
7472         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7473       return true;
7474     }
7475   }
7476 
7477   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7478 
7479   // Per DR1611, do not consider virtual bases of constructors of abstract
7480   // classes, since we are not going to construct them.
7481   // Per DR1658, do not consider virtual bases of destructors of abstract
7482   // classes either.
7483   // Per DR2180, for assignment operators we only assign (and thus only
7484   // consider) direct bases.
7485   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7486                                  : SMI.VisitPotentiallyConstructedBases))
7487     return true;
7488 
7489   if (SMI.shouldDeleteForAllConstMembers())
7490     return true;
7491 
7492   if (getLangOpts().CUDA) {
7493     // We should delete the special member in CUDA mode if target inference
7494     // failed.
7495     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7496     // is treated as certain special member, which may not reflect what special
7497     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7498     // expects CSM to match MD, therefore recalculate CSM.
7499     assert(ICI || CSM == getSpecialMember(MD));
7500     auto RealCSM = CSM;
7501     if (ICI)
7502       RealCSM = getSpecialMember(MD);
7503 
7504     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7505                                                    SMI.ConstArg, Diagnose);
7506   }
7507 
7508   return false;
7509 }
7510 
7511 /// Perform lookup for a special member of the specified kind, and determine
7512 /// whether it is trivial. If the triviality can be determined without the
7513 /// lookup, skip it. This is intended for use when determining whether a
7514 /// special member of a containing object is trivial, and thus does not ever
7515 /// perform overload resolution for default constructors.
7516 ///
7517 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7518 /// member that was most likely to be intended to be trivial, if any.
7519 ///
7520 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7521 /// determine whether the special member is trivial.
7522 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7523                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7524                                      bool ConstRHS,
7525                                      Sema::TrivialABIHandling TAH,
7526                                      CXXMethodDecl **Selected) {
7527   if (Selected)
7528     *Selected = nullptr;
7529 
7530   switch (CSM) {
7531   case Sema::CXXInvalid:
7532     llvm_unreachable("not a special member");
7533 
7534   case Sema::CXXDefaultConstructor:
7535     // C++11 [class.ctor]p5:
7536     //   A default constructor is trivial if:
7537     //    - all the [direct subobjects] have trivial default constructors
7538     //
7539     // Note, no overload resolution is performed in this case.
7540     if (RD->hasTrivialDefaultConstructor())
7541       return true;
7542 
7543     if (Selected) {
7544       // If there's a default constructor which could have been trivial, dig it
7545       // out. Otherwise, if there's any user-provided default constructor, point
7546       // to that as an example of why there's not a trivial one.
7547       CXXConstructorDecl *DefCtor = nullptr;
7548       if (RD->needsImplicitDefaultConstructor())
7549         S.DeclareImplicitDefaultConstructor(RD);
7550       for (auto *CI : RD->ctors()) {
7551         if (!CI->isDefaultConstructor())
7552           continue;
7553         DefCtor = CI;
7554         if (!DefCtor->isUserProvided())
7555           break;
7556       }
7557 
7558       *Selected = DefCtor;
7559     }
7560 
7561     return false;
7562 
7563   case Sema::CXXDestructor:
7564     // C++11 [class.dtor]p5:
7565     //   A destructor is trivial if:
7566     //    - all the direct [subobjects] have trivial destructors
7567     if (RD->hasTrivialDestructor() ||
7568         (TAH == Sema::TAH_ConsiderTrivialABI &&
7569          RD->hasTrivialDestructorForCall()))
7570       return true;
7571 
7572     if (Selected) {
7573       if (RD->needsImplicitDestructor())
7574         S.DeclareImplicitDestructor(RD);
7575       *Selected = RD->getDestructor();
7576     }
7577 
7578     return false;
7579 
7580   case Sema::CXXCopyConstructor:
7581     // C++11 [class.copy]p12:
7582     //   A copy constructor is trivial if:
7583     //    - the constructor selected to copy each direct [subobject] is trivial
7584     if (RD->hasTrivialCopyConstructor() ||
7585         (TAH == Sema::TAH_ConsiderTrivialABI &&
7586          RD->hasTrivialCopyConstructorForCall())) {
7587       if (Quals == Qualifiers::Const)
7588         // We must either select the trivial copy constructor or reach an
7589         // ambiguity; no need to actually perform overload resolution.
7590         return true;
7591     } else if (!Selected) {
7592       return false;
7593     }
7594     // In C++98, we are not supposed to perform overload resolution here, but we
7595     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7596     // cases like B as having a non-trivial copy constructor:
7597     //   struct A { template<typename T> A(T&); };
7598     //   struct B { mutable A a; };
7599     goto NeedOverloadResolution;
7600 
7601   case Sema::CXXCopyAssignment:
7602     // C++11 [class.copy]p25:
7603     //   A copy assignment operator is trivial if:
7604     //    - the assignment operator selected to copy each direct [subobject] is
7605     //      trivial
7606     if (RD->hasTrivialCopyAssignment()) {
7607       if (Quals == Qualifiers::Const)
7608         return true;
7609     } else if (!Selected) {
7610       return false;
7611     }
7612     // In C++98, we are not supposed to perform overload resolution here, but we
7613     // treat that as a language defect.
7614     goto NeedOverloadResolution;
7615 
7616   case Sema::CXXMoveConstructor:
7617   case Sema::CXXMoveAssignment:
7618   NeedOverloadResolution:
7619     Sema::SpecialMemberOverloadResult SMOR =
7620         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7621 
7622     // The standard doesn't describe how to behave if the lookup is ambiguous.
7623     // We treat it as not making the member non-trivial, just like the standard
7624     // mandates for the default constructor. This should rarely matter, because
7625     // the member will also be deleted.
7626     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7627       return true;
7628 
7629     if (!SMOR.getMethod()) {
7630       assert(SMOR.getKind() ==
7631              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7632       return false;
7633     }
7634 
7635     // We deliberately don't check if we found a deleted special member. We're
7636     // not supposed to!
7637     if (Selected)
7638       *Selected = SMOR.getMethod();
7639 
7640     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7641         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7642       return SMOR.getMethod()->isTrivialForCall();
7643     return SMOR.getMethod()->isTrivial();
7644   }
7645 
7646   llvm_unreachable("unknown special method kind");
7647 }
7648 
7649 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7650   for (auto *CI : RD->ctors())
7651     if (!CI->isImplicit())
7652       return CI;
7653 
7654   // Look for constructor templates.
7655   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7656   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7657     if (CXXConstructorDecl *CD =
7658           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7659       return CD;
7660   }
7661 
7662   return nullptr;
7663 }
7664 
7665 /// The kind of subobject we are checking for triviality. The values of this
7666 /// enumeration are used in diagnostics.
7667 enum TrivialSubobjectKind {
7668   /// The subobject is a base class.
7669   TSK_BaseClass,
7670   /// The subobject is a non-static data member.
7671   TSK_Field,
7672   /// The object is actually the complete object.
7673   TSK_CompleteObject
7674 };
7675 
7676 /// Check whether the special member selected for a given type would be trivial.
7677 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7678                                       QualType SubType, bool ConstRHS,
7679                                       Sema::CXXSpecialMember CSM,
7680                                       TrivialSubobjectKind Kind,
7681                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7682   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7683   if (!SubRD)
7684     return true;
7685 
7686   CXXMethodDecl *Selected;
7687   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7688                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7689     return true;
7690 
7691   if (Diagnose) {
7692     if (ConstRHS)
7693       SubType.addConst();
7694 
7695     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7696       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7697         << Kind << SubType.getUnqualifiedType();
7698       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7699         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7700     } else if (!Selected)
7701       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7702         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7703     else if (Selected->isUserProvided()) {
7704       if (Kind == TSK_CompleteObject)
7705         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7706           << Kind << SubType.getUnqualifiedType() << CSM;
7707       else {
7708         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7709           << Kind << SubType.getUnqualifiedType() << CSM;
7710         S.Diag(Selected->getLocation(), diag::note_declared_at);
7711       }
7712     } else {
7713       if (Kind != TSK_CompleteObject)
7714         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7715           << Kind << SubType.getUnqualifiedType() << CSM;
7716 
7717       // Explain why the defaulted or deleted special member isn't trivial.
7718       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7719                                Diagnose);
7720     }
7721   }
7722 
7723   return false;
7724 }
7725 
7726 /// Check whether the members of a class type allow a special member to be
7727 /// trivial.
7728 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7729                                      Sema::CXXSpecialMember CSM,
7730                                      bool ConstArg,
7731                                      Sema::TrivialABIHandling TAH,
7732                                      bool Diagnose) {
7733   for (const auto *FI : RD->fields()) {
7734     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7735       continue;
7736 
7737     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7738 
7739     // Pretend anonymous struct or union members are members of this class.
7740     if (FI->isAnonymousStructOrUnion()) {
7741       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7742                                     CSM, ConstArg, TAH, Diagnose))
7743         return false;
7744       continue;
7745     }
7746 
7747     // C++11 [class.ctor]p5:
7748     //   A default constructor is trivial if [...]
7749     //    -- no non-static data member of its class has a
7750     //       brace-or-equal-initializer
7751     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7752       if (Diagnose)
7753         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7754       return false;
7755     }
7756 
7757     // Objective C ARC 4.3.5:
7758     //   [...] nontrivally ownership-qualified types are [...] not trivially
7759     //   default constructible, copy constructible, move constructible, copy
7760     //   assignable, move assignable, or destructible [...]
7761     if (FieldType.hasNonTrivialObjCLifetime()) {
7762       if (Diagnose)
7763         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7764           << RD << FieldType.getObjCLifetime();
7765       return false;
7766     }
7767 
7768     bool ConstRHS = ConstArg && !FI->isMutable();
7769     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7770                                    CSM, TSK_Field, TAH, Diagnose))
7771       return false;
7772   }
7773 
7774   return true;
7775 }
7776 
7777 /// Diagnose why the specified class does not have a trivial special member of
7778 /// the given kind.
7779 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7780   QualType Ty = Context.getRecordType(RD);
7781 
7782   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7783   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7784                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7785                             /*Diagnose*/true);
7786 }
7787 
7788 /// Determine whether a defaulted or deleted special member function is trivial,
7789 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7790 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7791 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7792                                   TrivialABIHandling TAH, bool Diagnose) {
7793   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7794 
7795   CXXRecordDecl *RD = MD->getParent();
7796 
7797   bool ConstArg = false;
7798 
7799   // C++11 [class.copy]p12, p25: [DR1593]
7800   //   A [special member] is trivial if [...] its parameter-type-list is
7801   //   equivalent to the parameter-type-list of an implicit declaration [...]
7802   switch (CSM) {
7803   case CXXDefaultConstructor:
7804   case CXXDestructor:
7805     // Trivial default constructors and destructors cannot have parameters.
7806     break;
7807 
7808   case CXXCopyConstructor:
7809   case CXXCopyAssignment: {
7810     // Trivial copy operations always have const, non-volatile parameter types.
7811     ConstArg = true;
7812     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7813     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7814     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7815       if (Diagnose)
7816         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7817           << Param0->getSourceRange() << Param0->getType()
7818           << Context.getLValueReferenceType(
7819                Context.getRecordType(RD).withConst());
7820       return false;
7821     }
7822     break;
7823   }
7824 
7825   case CXXMoveConstructor:
7826   case CXXMoveAssignment: {
7827     // Trivial move operations always have non-cv-qualified parameters.
7828     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7829     const RValueReferenceType *RT =
7830       Param0->getType()->getAs<RValueReferenceType>();
7831     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7832       if (Diagnose)
7833         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7834           << Param0->getSourceRange() << Param0->getType()
7835           << Context.getRValueReferenceType(Context.getRecordType(RD));
7836       return false;
7837     }
7838     break;
7839   }
7840 
7841   case CXXInvalid:
7842     llvm_unreachable("not a special member");
7843   }
7844 
7845   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7846     if (Diagnose)
7847       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7848            diag::note_nontrivial_default_arg)
7849         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7850     return false;
7851   }
7852   if (MD->isVariadic()) {
7853     if (Diagnose)
7854       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7855     return false;
7856   }
7857 
7858   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7859   //   A copy/move [constructor or assignment operator] is trivial if
7860   //    -- the [member] selected to copy/move each direct base class subobject
7861   //       is trivial
7862   //
7863   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7864   //   A [default constructor or destructor] is trivial if
7865   //    -- all the direct base classes have trivial [default constructors or
7866   //       destructors]
7867   for (const auto &BI : RD->bases())
7868     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7869                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7870       return false;
7871 
7872   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7873   //   A copy/move [constructor or assignment operator] for a class X is
7874   //   trivial if
7875   //    -- for each non-static data member of X that is of class type (or array
7876   //       thereof), the constructor selected to copy/move that member is
7877   //       trivial
7878   //
7879   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7880   //   A [default constructor or destructor] is trivial if
7881   //    -- for all of the non-static data members of its class that are of class
7882   //       type (or array thereof), each such class has a trivial [default
7883   //       constructor or destructor]
7884   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7885     return false;
7886 
7887   // C++11 [class.dtor]p5:
7888   //   A destructor is trivial if [...]
7889   //    -- the destructor is not virtual
7890   if (CSM == CXXDestructor && MD->isVirtual()) {
7891     if (Diagnose)
7892       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7893     return false;
7894   }
7895 
7896   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7897   //   A [special member] for class X is trivial if [...]
7898   //    -- class X has no virtual functions and no virtual base classes
7899   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7900     if (!Diagnose)
7901       return false;
7902 
7903     if (RD->getNumVBases()) {
7904       // Check for virtual bases. We already know that the corresponding
7905       // member in all bases is trivial, so vbases must all be direct.
7906       CXXBaseSpecifier &BS = *RD->vbases_begin();
7907       assert(BS.isVirtual());
7908       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7909       return false;
7910     }
7911 
7912     // Must have a virtual method.
7913     for (const auto *MI : RD->methods()) {
7914       if (MI->isVirtual()) {
7915         SourceLocation MLoc = MI->getBeginLoc();
7916         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7917         return false;
7918       }
7919     }
7920 
7921     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7922   }
7923 
7924   // Looks like it's trivial!
7925   return true;
7926 }
7927 
7928 namespace {
7929 struct FindHiddenVirtualMethod {
7930   Sema *S;
7931   CXXMethodDecl *Method;
7932   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7933   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7934 
7935 private:
7936   /// Check whether any most overridden method from MD in Methods
7937   static bool CheckMostOverridenMethods(
7938       const CXXMethodDecl *MD,
7939       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7940     if (MD->size_overridden_methods() == 0)
7941       return Methods.count(MD->getCanonicalDecl());
7942     for (const CXXMethodDecl *O : MD->overridden_methods())
7943       if (CheckMostOverridenMethods(O, Methods))
7944         return true;
7945     return false;
7946   }
7947 
7948 public:
7949   /// Member lookup function that determines whether a given C++
7950   /// method overloads virtual methods in a base class without overriding any,
7951   /// to be used with CXXRecordDecl::lookupInBases().
7952   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7953     RecordDecl *BaseRecord =
7954         Specifier->getType()->getAs<RecordType>()->getDecl();
7955 
7956     DeclarationName Name = Method->getDeclName();
7957     assert(Name.getNameKind() == DeclarationName::Identifier);
7958 
7959     bool foundSameNameMethod = false;
7960     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7961     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7962          Path.Decls = Path.Decls.slice(1)) {
7963       NamedDecl *D = Path.Decls.front();
7964       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7965         MD = MD->getCanonicalDecl();
7966         foundSameNameMethod = true;
7967         // Interested only in hidden virtual methods.
7968         if (!MD->isVirtual())
7969           continue;
7970         // If the method we are checking overrides a method from its base
7971         // don't warn about the other overloaded methods. Clang deviates from
7972         // GCC by only diagnosing overloads of inherited virtual functions that
7973         // do not override any other virtual functions in the base. GCC's
7974         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7975         // function from a base class. These cases may be better served by a
7976         // warning (not specific to virtual functions) on call sites when the
7977         // call would select a different function from the base class, were it
7978         // visible.
7979         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7980         if (!S->IsOverload(Method, MD, false))
7981           return true;
7982         // Collect the overload only if its hidden.
7983         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7984           overloadedMethods.push_back(MD);
7985       }
7986     }
7987 
7988     if (foundSameNameMethod)
7989       OverloadedMethods.append(overloadedMethods.begin(),
7990                                overloadedMethods.end());
7991     return foundSameNameMethod;
7992   }
7993 };
7994 } // end anonymous namespace
7995 
7996 /// Add the most overriden methods from MD to Methods
7997 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7998                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7999   if (MD->size_overridden_methods() == 0)
8000     Methods.insert(MD->getCanonicalDecl());
8001   else
8002     for (const CXXMethodDecl *O : MD->overridden_methods())
8003       AddMostOverridenMethods(O, Methods);
8004 }
8005 
8006 /// Check if a method overloads virtual methods in a base class without
8007 /// overriding any.
8008 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
8009                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8010   if (!MD->getDeclName().isIdentifier())
8011     return;
8012 
8013   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
8014                      /*bool RecordPaths=*/false,
8015                      /*bool DetectVirtual=*/false);
8016   FindHiddenVirtualMethod FHVM;
8017   FHVM.Method = MD;
8018   FHVM.S = this;
8019 
8020   // Keep the base methods that were overridden or introduced in the subclass
8021   // by 'using' in a set. A base method not in this set is hidden.
8022   CXXRecordDecl *DC = MD->getParent();
8023   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
8024   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
8025     NamedDecl *ND = *I;
8026     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
8027       ND = shad->getTargetDecl();
8028     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
8029       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
8030   }
8031 
8032   if (DC->lookupInBases(FHVM, Paths))
8033     OverloadedMethods = FHVM.OverloadedMethods;
8034 }
8035 
8036 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
8037                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8038   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
8039     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
8040     PartialDiagnostic PD = PDiag(
8041          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
8042     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
8043     Diag(overloadedMD->getLocation(), PD);
8044   }
8045 }
8046 
8047 /// Diagnose methods which overload virtual methods in a base class
8048 /// without overriding any.
8049 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
8050   if (MD->isInvalidDecl())
8051     return;
8052 
8053   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
8054     return;
8055 
8056   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
8057   FindHiddenVirtualMethods(MD, OverloadedMethods);
8058   if (!OverloadedMethods.empty()) {
8059     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
8060       << MD << (OverloadedMethods.size() > 1);
8061 
8062     NoteHiddenVirtualMethods(MD, OverloadedMethods);
8063   }
8064 }
8065 
8066 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
8067   auto PrintDiagAndRemoveAttr = [&]() {
8068     // No diagnostics if this is a template instantiation.
8069     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
8070       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
8071            diag::ext_cannot_use_trivial_abi) << &RD;
8072     RD.dropAttr<TrivialABIAttr>();
8073   };
8074 
8075   // Ill-formed if the struct has virtual functions.
8076   if (RD.isPolymorphic()) {
8077     PrintDiagAndRemoveAttr();
8078     return;
8079   }
8080 
8081   for (const auto &B : RD.bases()) {
8082     // Ill-formed if the base class is non-trivial for the purpose of calls or a
8083     // virtual base.
8084     if ((!B.getType()->isDependentType() &&
8085          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
8086         B.isVirtual()) {
8087       PrintDiagAndRemoveAttr();
8088       return;
8089     }
8090   }
8091 
8092   for (const auto *FD : RD.fields()) {
8093     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
8094     // non-trivial for the purpose of calls.
8095     QualType FT = FD->getType();
8096     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
8097       PrintDiagAndRemoveAttr();
8098       return;
8099     }
8100 
8101     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
8102       if (!RT->isDependentType() &&
8103           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
8104         PrintDiagAndRemoveAttr();
8105         return;
8106       }
8107   }
8108 }
8109 
8110 void Sema::ActOnFinishCXXMemberSpecification(
8111     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
8112     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
8113   if (!TagDecl)
8114     return;
8115 
8116   AdjustDeclIfTemplate(TagDecl);
8117 
8118   for (const ParsedAttr &AL : AttrList) {
8119     if (AL.getKind() != ParsedAttr::AT_Visibility)
8120       continue;
8121     AL.setInvalid();
8122     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
8123   }
8124 
8125   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
8126               // strict aliasing violation!
8127               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
8128               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
8129 
8130   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
8131 }
8132 
8133 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
8134 /// special functions, such as the default constructor, copy
8135 /// constructor, or destructor, to the given C++ class (C++
8136 /// [special]p1).  This routine can only be executed just before the
8137 /// definition of the class is complete.
8138 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
8139   if (ClassDecl->needsImplicitDefaultConstructor()) {
8140     ++getASTContext().NumImplicitDefaultConstructors;
8141 
8142     if (ClassDecl->hasInheritedConstructor())
8143       DeclareImplicitDefaultConstructor(ClassDecl);
8144   }
8145 
8146   if (ClassDecl->needsImplicitCopyConstructor()) {
8147     ++getASTContext().NumImplicitCopyConstructors;
8148 
8149     // If the properties or semantics of the copy constructor couldn't be
8150     // determined while the class was being declared, force a declaration
8151     // of it now.
8152     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
8153         ClassDecl->hasInheritedConstructor())
8154       DeclareImplicitCopyConstructor(ClassDecl);
8155     // For the MS ABI we need to know whether the copy ctor is deleted. A
8156     // prerequisite for deleting the implicit copy ctor is that the class has a
8157     // move ctor or move assignment that is either user-declared or whose
8158     // semantics are inherited from a subobject. FIXME: We should provide a more
8159     // direct way for CodeGen to ask whether the constructor was deleted.
8160     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8161              (ClassDecl->hasUserDeclaredMoveConstructor() ||
8162               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8163               ClassDecl->hasUserDeclaredMoveAssignment() ||
8164               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8165       DeclareImplicitCopyConstructor(ClassDecl);
8166   }
8167 
8168   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8169     ++getASTContext().NumImplicitMoveConstructors;
8170 
8171     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8172         ClassDecl->hasInheritedConstructor())
8173       DeclareImplicitMoveConstructor(ClassDecl);
8174   }
8175 
8176   if (ClassDecl->needsImplicitCopyAssignment()) {
8177     ++getASTContext().NumImplicitCopyAssignmentOperators;
8178 
8179     // If we have a dynamic class, then the copy assignment operator may be
8180     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8181     // it shows up in the right place in the vtable and that we diagnose
8182     // problems with the implicit exception specification.
8183     if (ClassDecl->isDynamicClass() ||
8184         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8185         ClassDecl->hasInheritedAssignment())
8186       DeclareImplicitCopyAssignment(ClassDecl);
8187   }
8188 
8189   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8190     ++getASTContext().NumImplicitMoveAssignmentOperators;
8191 
8192     // Likewise for the move assignment operator.
8193     if (ClassDecl->isDynamicClass() ||
8194         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8195         ClassDecl->hasInheritedAssignment())
8196       DeclareImplicitMoveAssignment(ClassDecl);
8197   }
8198 
8199   if (ClassDecl->needsImplicitDestructor()) {
8200     ++getASTContext().NumImplicitDestructors;
8201 
8202     // If we have a dynamic class, then the destructor may be virtual, so we
8203     // have to declare the destructor immediately. This ensures that, e.g., it
8204     // shows up in the right place in the vtable and that we diagnose problems
8205     // with the implicit exception specification.
8206     if (ClassDecl->isDynamicClass() ||
8207         ClassDecl->needsOverloadResolutionForDestructor())
8208       DeclareImplicitDestructor(ClassDecl);
8209   }
8210 }
8211 
8212 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8213   if (!D)
8214     return 0;
8215 
8216   // The order of template parameters is not important here. All names
8217   // get added to the same scope.
8218   SmallVector<TemplateParameterList *, 4> ParameterLists;
8219 
8220   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8221     D = TD->getTemplatedDecl();
8222 
8223   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8224     ParameterLists.push_back(PSD->getTemplateParameters());
8225 
8226   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8227     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8228       ParameterLists.push_back(DD->getTemplateParameterList(i));
8229 
8230     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8231       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8232         ParameterLists.push_back(FTD->getTemplateParameters());
8233     }
8234   }
8235 
8236   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8237     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8238       ParameterLists.push_back(TD->getTemplateParameterList(i));
8239 
8240     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8241       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8242         ParameterLists.push_back(CTD->getTemplateParameters());
8243     }
8244   }
8245 
8246   unsigned Count = 0;
8247   for (TemplateParameterList *Params : ParameterLists) {
8248     if (Params->size() > 0)
8249       // Ignore explicit specializations; they don't contribute to the template
8250       // depth.
8251       ++Count;
8252     for (NamedDecl *Param : *Params) {
8253       if (Param->getDeclName()) {
8254         S->AddDecl(Param);
8255         IdResolver.AddDecl(Param);
8256       }
8257     }
8258   }
8259 
8260   return Count;
8261 }
8262 
8263 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8264   if (!RecordD) return;
8265   AdjustDeclIfTemplate(RecordD);
8266   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8267   PushDeclContext(S, Record);
8268 }
8269 
8270 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8271   if (!RecordD) return;
8272   PopDeclContext();
8273 }
8274 
8275 /// This is used to implement the constant expression evaluation part of the
8276 /// attribute enable_if extension. There is nothing in standard C++ which would
8277 /// require reentering parameters.
8278 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8279   if (!Param)
8280     return;
8281 
8282   S->AddDecl(Param);
8283   if (Param->getDeclName())
8284     IdResolver.AddDecl(Param);
8285 }
8286 
8287 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8288 /// parsing a top-level (non-nested) C++ class, and we are now
8289 /// parsing those parts of the given Method declaration that could
8290 /// not be parsed earlier (C++ [class.mem]p2), such as default
8291 /// arguments. This action should enter the scope of the given
8292 /// Method declaration as if we had just parsed the qualified method
8293 /// name. However, it should not bring the parameters into scope;
8294 /// that will be performed by ActOnDelayedCXXMethodParameter.
8295 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8296 }
8297 
8298 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8299 /// C++ method declaration. We're (re-)introducing the given
8300 /// function parameter into scope for use in parsing later parts of
8301 /// the method declaration. For example, we could see an
8302 /// ActOnParamDefaultArgument event for this parameter.
8303 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8304   if (!ParamD)
8305     return;
8306 
8307   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8308 
8309   // If this parameter has an unparsed default argument, clear it out
8310   // to make way for the parsed default argument.
8311   if (Param->hasUnparsedDefaultArg())
8312     Param->setDefaultArg(nullptr);
8313 
8314   S->AddDecl(Param);
8315   if (Param->getDeclName())
8316     IdResolver.AddDecl(Param);
8317 }
8318 
8319 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8320 /// processing the delayed method declaration for Method. The method
8321 /// declaration is now considered finished. There may be a separate
8322 /// ActOnStartOfFunctionDef action later (not necessarily
8323 /// immediately!) for this method, if it was also defined inside the
8324 /// class body.
8325 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8326   if (!MethodD)
8327     return;
8328 
8329   AdjustDeclIfTemplate(MethodD);
8330 
8331   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8332 
8333   // Now that we have our default arguments, check the constructor
8334   // again. It could produce additional diagnostics or affect whether
8335   // the class has implicitly-declared destructors, among other
8336   // things.
8337   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8338     CheckConstructor(Constructor);
8339 
8340   // Check the default arguments, which we may have added.
8341   if (!Method->isInvalidDecl())
8342     CheckCXXDefaultArguments(Method);
8343 }
8344 
8345 // Emit the given diagnostic for each non-address-space qualifier.
8346 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8347 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8348   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8349   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8350     bool DiagOccured = false;
8351     FTI.MethodQualifiers->forEachQualifier(
8352         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8353                                    SourceLocation SL) {
8354           // This diagnostic should be emitted on any qualifier except an addr
8355           // space qualifier. However, forEachQualifier currently doesn't visit
8356           // addr space qualifiers, so there's no way to write this condition
8357           // right now; we just diagnose on everything.
8358           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8359           DiagOccured = true;
8360         });
8361     if (DiagOccured)
8362       D.setInvalidType();
8363   }
8364 }
8365 
8366 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8367 /// the well-formedness of the constructor declarator @p D with type @p
8368 /// R. If there are any errors in the declarator, this routine will
8369 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8370 /// will be updated to reflect a well-formed type for the constructor and
8371 /// returned.
8372 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8373                                           StorageClass &SC) {
8374   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8375 
8376   // C++ [class.ctor]p3:
8377   //   A constructor shall not be virtual (10.3) or static (9.4). A
8378   //   constructor can be invoked for a const, volatile or const
8379   //   volatile object. A constructor shall not be declared const,
8380   //   volatile, or const volatile (9.3.2).
8381   if (isVirtual) {
8382     if (!D.isInvalidType())
8383       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8384         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8385         << SourceRange(D.getIdentifierLoc());
8386     D.setInvalidType();
8387   }
8388   if (SC == SC_Static) {
8389     if (!D.isInvalidType())
8390       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8391         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8392         << SourceRange(D.getIdentifierLoc());
8393     D.setInvalidType();
8394     SC = SC_None;
8395   }
8396 
8397   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8398     diagnoseIgnoredQualifiers(
8399         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8400         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8401         D.getDeclSpec().getRestrictSpecLoc(),
8402         D.getDeclSpec().getAtomicSpecLoc());
8403     D.setInvalidType();
8404   }
8405 
8406   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8407 
8408   // C++0x [class.ctor]p4:
8409   //   A constructor shall not be declared with a ref-qualifier.
8410   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8411   if (FTI.hasRefQualifier()) {
8412     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8413       << FTI.RefQualifierIsLValueRef
8414       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8415     D.setInvalidType();
8416   }
8417 
8418   // Rebuild the function type "R" without any type qualifiers (in
8419   // case any of the errors above fired) and with "void" as the
8420   // return type, since constructors don't have return types.
8421   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8422   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8423     return R;
8424 
8425   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8426   EPI.TypeQuals = Qualifiers();
8427   EPI.RefQualifier = RQ_None;
8428 
8429   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8430 }
8431 
8432 /// CheckConstructor - Checks a fully-formed constructor for
8433 /// well-formedness, issuing any diagnostics required. Returns true if
8434 /// the constructor declarator is invalid.
8435 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8436   CXXRecordDecl *ClassDecl
8437     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8438   if (!ClassDecl)
8439     return Constructor->setInvalidDecl();
8440 
8441   // C++ [class.copy]p3:
8442   //   A declaration of a constructor for a class X is ill-formed if
8443   //   its first parameter is of type (optionally cv-qualified) X and
8444   //   either there are no other parameters or else all other
8445   //   parameters have default arguments.
8446   if (!Constructor->isInvalidDecl() &&
8447       ((Constructor->getNumParams() == 1) ||
8448        (Constructor->getNumParams() > 1 &&
8449         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8450       Constructor->getTemplateSpecializationKind()
8451                                               != TSK_ImplicitInstantiation) {
8452     QualType ParamType = Constructor->getParamDecl(0)->getType();
8453     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8454     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8455       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8456       const char *ConstRef
8457         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8458                                                         : " const &";
8459       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8460         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8461 
8462       // FIXME: Rather that making the constructor invalid, we should endeavor
8463       // to fix the type.
8464       Constructor->setInvalidDecl();
8465     }
8466   }
8467 }
8468 
8469 /// CheckDestructor - Checks a fully-formed destructor definition for
8470 /// well-formedness, issuing any diagnostics required.  Returns true
8471 /// on error.
8472 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8473   CXXRecordDecl *RD = Destructor->getParent();
8474 
8475   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8476     SourceLocation Loc;
8477 
8478     if (!Destructor->isImplicit())
8479       Loc = Destructor->getLocation();
8480     else
8481       Loc = RD->getLocation();
8482 
8483     // If we have a virtual destructor, look up the deallocation function
8484     if (FunctionDecl *OperatorDelete =
8485             FindDeallocationFunctionForDestructor(Loc, RD)) {
8486       Expr *ThisArg = nullptr;
8487 
8488       // If the notional 'delete this' expression requires a non-trivial
8489       // conversion from 'this' to the type of a destroying operator delete's
8490       // first parameter, perform that conversion now.
8491       if (OperatorDelete->isDestroyingOperatorDelete()) {
8492         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8493         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8494           // C++ [class.dtor]p13:
8495           //   ... as if for the expression 'delete this' appearing in a
8496           //   non-virtual destructor of the destructor's class.
8497           ContextRAII SwitchContext(*this, Destructor);
8498           ExprResult This =
8499               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8500           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8501           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8502           if (This.isInvalid()) {
8503             // FIXME: Register this as a context note so that it comes out
8504             // in the right order.
8505             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8506             return true;
8507           }
8508           ThisArg = This.get();
8509         }
8510       }
8511 
8512       DiagnoseUseOfDecl(OperatorDelete, Loc);
8513       MarkFunctionReferenced(Loc, OperatorDelete);
8514       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8515     }
8516   }
8517 
8518   return false;
8519 }
8520 
8521 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8522 /// the well-formednes of the destructor declarator @p D with type @p
8523 /// R. If there are any errors in the declarator, this routine will
8524 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8525 /// will be updated to reflect a well-formed type for the destructor and
8526 /// returned.
8527 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8528                                          StorageClass& SC) {
8529   // C++ [class.dtor]p1:
8530   //   [...] A typedef-name that names a class is a class-name
8531   //   (7.1.3); however, a typedef-name that names a class shall not
8532   //   be used as the identifier in the declarator for a destructor
8533   //   declaration.
8534   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8535   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8536     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8537       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8538   else if (const TemplateSpecializationType *TST =
8539              DeclaratorType->getAs<TemplateSpecializationType>())
8540     if (TST->isTypeAlias())
8541       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8542         << DeclaratorType << 1;
8543 
8544   // C++ [class.dtor]p2:
8545   //   A destructor is used to destroy objects of its class type. A
8546   //   destructor takes no parameters, and no return type can be
8547   //   specified for it (not even void). The address of a destructor
8548   //   shall not be taken. A destructor shall not be static. A
8549   //   destructor can be invoked for a const, volatile or const
8550   //   volatile object. A destructor shall not be declared const,
8551   //   volatile or const volatile (9.3.2).
8552   if (SC == SC_Static) {
8553     if (!D.isInvalidType())
8554       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8555         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8556         << SourceRange(D.getIdentifierLoc())
8557         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8558 
8559     SC = SC_None;
8560   }
8561   if (!D.isInvalidType()) {
8562     // Destructors don't have return types, but the parser will
8563     // happily parse something like:
8564     //
8565     //   class X {
8566     //     float ~X();
8567     //   };
8568     //
8569     // The return type will be eliminated later.
8570     if (D.getDeclSpec().hasTypeSpecifier())
8571       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8572         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8573         << SourceRange(D.getIdentifierLoc());
8574     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8575       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8576                                 SourceLocation(),
8577                                 D.getDeclSpec().getConstSpecLoc(),
8578                                 D.getDeclSpec().getVolatileSpecLoc(),
8579                                 D.getDeclSpec().getRestrictSpecLoc(),
8580                                 D.getDeclSpec().getAtomicSpecLoc());
8581       D.setInvalidType();
8582     }
8583   }
8584 
8585   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8586 
8587   // C++0x [class.dtor]p2:
8588   //   A destructor shall not be declared with a ref-qualifier.
8589   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8590   if (FTI.hasRefQualifier()) {
8591     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8592       << FTI.RefQualifierIsLValueRef
8593       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8594     D.setInvalidType();
8595   }
8596 
8597   // Make sure we don't have any parameters.
8598   if (FTIHasNonVoidParameters(FTI)) {
8599     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8600 
8601     // Delete the parameters.
8602     FTI.freeParams();
8603     D.setInvalidType();
8604   }
8605 
8606   // Make sure the destructor isn't variadic.
8607   if (FTI.isVariadic) {
8608     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8609     D.setInvalidType();
8610   }
8611 
8612   // Rebuild the function type "R" without any type qualifiers or
8613   // parameters (in case any of the errors above fired) and with
8614   // "void" as the return type, since destructors don't have return
8615   // types.
8616   if (!D.isInvalidType())
8617     return R;
8618 
8619   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8620   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8621   EPI.Variadic = false;
8622   EPI.TypeQuals = Qualifiers();
8623   EPI.RefQualifier = RQ_None;
8624   return Context.getFunctionType(Context.VoidTy, None, EPI);
8625 }
8626 
8627 static void extendLeft(SourceRange &R, SourceRange Before) {
8628   if (Before.isInvalid())
8629     return;
8630   R.setBegin(Before.getBegin());
8631   if (R.getEnd().isInvalid())
8632     R.setEnd(Before.getEnd());
8633 }
8634 
8635 static void extendRight(SourceRange &R, SourceRange After) {
8636   if (After.isInvalid())
8637     return;
8638   if (R.getBegin().isInvalid())
8639     R.setBegin(After.getBegin());
8640   R.setEnd(After.getEnd());
8641 }
8642 
8643 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8644 /// well-formednes of the conversion function declarator @p D with
8645 /// type @p R. If there are any errors in the declarator, this routine
8646 /// will emit diagnostics and return true. Otherwise, it will return
8647 /// false. Either way, the type @p R will be updated to reflect a
8648 /// well-formed type for the conversion operator.
8649 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8650                                      StorageClass& SC) {
8651   // C++ [class.conv.fct]p1:
8652   //   Neither parameter types nor return type can be specified. The
8653   //   type of a conversion function (8.3.5) is "function taking no
8654   //   parameter returning conversion-type-id."
8655   if (SC == SC_Static) {
8656     if (!D.isInvalidType())
8657       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8658         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8659         << D.getName().getSourceRange();
8660     D.setInvalidType();
8661     SC = SC_None;
8662   }
8663 
8664   TypeSourceInfo *ConvTSI = nullptr;
8665   QualType ConvType =
8666       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8667 
8668   const DeclSpec &DS = D.getDeclSpec();
8669   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8670     // Conversion functions don't have return types, but the parser will
8671     // happily parse something like:
8672     //
8673     //   class X {
8674     //     float operator bool();
8675     //   };
8676     //
8677     // The return type will be changed later anyway.
8678     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8679       << SourceRange(DS.getTypeSpecTypeLoc())
8680       << SourceRange(D.getIdentifierLoc());
8681     D.setInvalidType();
8682   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8683     // It's also plausible that the user writes type qualifiers in the wrong
8684     // place, such as:
8685     //   struct S { const operator int(); };
8686     // FIXME: we could provide a fixit to move the qualifiers onto the
8687     // conversion type.
8688     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8689         << SourceRange(D.getIdentifierLoc()) << 0;
8690     D.setInvalidType();
8691   }
8692 
8693   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8694 
8695   // Make sure we don't have any parameters.
8696   if (Proto->getNumParams() > 0) {
8697     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8698 
8699     // Delete the parameters.
8700     D.getFunctionTypeInfo().freeParams();
8701     D.setInvalidType();
8702   } else if (Proto->isVariadic()) {
8703     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8704     D.setInvalidType();
8705   }
8706 
8707   // Diagnose "&operator bool()" and other such nonsense.  This
8708   // is actually a gcc extension which we don't support.
8709   if (Proto->getReturnType() != ConvType) {
8710     bool NeedsTypedef = false;
8711     SourceRange Before, After;
8712 
8713     // Walk the chunks and extract information on them for our diagnostic.
8714     bool PastFunctionChunk = false;
8715     for (auto &Chunk : D.type_objects()) {
8716       switch (Chunk.Kind) {
8717       case DeclaratorChunk::Function:
8718         if (!PastFunctionChunk) {
8719           if (Chunk.Fun.HasTrailingReturnType) {
8720             TypeSourceInfo *TRT = nullptr;
8721             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8722             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8723           }
8724           PastFunctionChunk = true;
8725           break;
8726         }
8727         LLVM_FALLTHROUGH;
8728       case DeclaratorChunk::Array:
8729         NeedsTypedef = true;
8730         extendRight(After, Chunk.getSourceRange());
8731         break;
8732 
8733       case DeclaratorChunk::Pointer:
8734       case DeclaratorChunk::BlockPointer:
8735       case DeclaratorChunk::Reference:
8736       case DeclaratorChunk::MemberPointer:
8737       case DeclaratorChunk::Pipe:
8738         extendLeft(Before, Chunk.getSourceRange());
8739         break;
8740 
8741       case DeclaratorChunk::Paren:
8742         extendLeft(Before, Chunk.Loc);
8743         extendRight(After, Chunk.EndLoc);
8744         break;
8745       }
8746     }
8747 
8748     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8749                          After.isValid()  ? After.getBegin() :
8750                                             D.getIdentifierLoc();
8751     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8752     DB << Before << After;
8753 
8754     if (!NeedsTypedef) {
8755       DB << /*don't need a typedef*/0;
8756 
8757       // If we can provide a correct fix-it hint, do so.
8758       if (After.isInvalid() && ConvTSI) {
8759         SourceLocation InsertLoc =
8760             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8761         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8762            << FixItHint::CreateInsertionFromRange(
8763                   InsertLoc, CharSourceRange::getTokenRange(Before))
8764            << FixItHint::CreateRemoval(Before);
8765       }
8766     } else if (!Proto->getReturnType()->isDependentType()) {
8767       DB << /*typedef*/1 << Proto->getReturnType();
8768     } else if (getLangOpts().CPlusPlus11) {
8769       DB << /*alias template*/2 << Proto->getReturnType();
8770     } else {
8771       DB << /*might not be fixable*/3;
8772     }
8773 
8774     // Recover by incorporating the other type chunks into the result type.
8775     // Note, this does *not* change the name of the function. This is compatible
8776     // with the GCC extension:
8777     //   struct S { &operator int(); } s;
8778     //   int &r = s.operator int(); // ok in GCC
8779     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8780     ConvType = Proto->getReturnType();
8781   }
8782 
8783   // C++ [class.conv.fct]p4:
8784   //   The conversion-type-id shall not represent a function type nor
8785   //   an array type.
8786   if (ConvType->isArrayType()) {
8787     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8788     ConvType = Context.getPointerType(ConvType);
8789     D.setInvalidType();
8790   } else if (ConvType->isFunctionType()) {
8791     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8792     ConvType = Context.getPointerType(ConvType);
8793     D.setInvalidType();
8794   }
8795 
8796   // Rebuild the function type "R" without any parameters (in case any
8797   // of the errors above fired) and with the conversion type as the
8798   // return type.
8799   if (D.isInvalidType())
8800     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8801 
8802   // C++0x explicit conversion operators.
8803   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8804     Diag(DS.getExplicitSpecLoc(),
8805          getLangOpts().CPlusPlus11
8806              ? diag::warn_cxx98_compat_explicit_conversion_functions
8807              : diag::ext_explicit_conversion_functions)
8808         << SourceRange(DS.getExplicitSpecRange());
8809 }
8810 
8811 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8812 /// the declaration of the given C++ conversion function. This routine
8813 /// is responsible for recording the conversion function in the C++
8814 /// class, if possible.
8815 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8816   assert(Conversion && "Expected to receive a conversion function declaration");
8817 
8818   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8819 
8820   // Make sure we aren't redeclaring the conversion function.
8821   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8822 
8823   // C++ [class.conv.fct]p1:
8824   //   [...] A conversion function is never used to convert a
8825   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8826   //   same object type (or a reference to it), to a (possibly
8827   //   cv-qualified) base class of that type (or a reference to it),
8828   //   or to (possibly cv-qualified) void.
8829   // FIXME: Suppress this warning if the conversion function ends up being a
8830   // virtual function that overrides a virtual function in a base class.
8831   QualType ClassType
8832     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8833   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8834     ConvType = ConvTypeRef->getPointeeType();
8835   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8836       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8837     /* Suppress diagnostics for instantiations. */;
8838   else if (ConvType->isRecordType()) {
8839     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8840     if (ConvType == ClassType)
8841       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8842         << ClassType;
8843     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8844       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8845         <<  ClassType << ConvType;
8846   } else if (ConvType->isVoidType()) {
8847     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8848       << ClassType << ConvType;
8849   }
8850 
8851   if (FunctionTemplateDecl *ConversionTemplate
8852                                 = Conversion->getDescribedFunctionTemplate())
8853     return ConversionTemplate;
8854 
8855   return Conversion;
8856 }
8857 
8858 namespace {
8859 /// Utility class to accumulate and print a diagnostic listing the invalid
8860 /// specifier(s) on a declaration.
8861 struct BadSpecifierDiagnoser {
8862   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8863       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8864   ~BadSpecifierDiagnoser() {
8865     Diagnostic << Specifiers;
8866   }
8867 
8868   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8869     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8870   }
8871   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8872     return check(SpecLoc,
8873                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8874   }
8875   void check(SourceLocation SpecLoc, const char *Spec) {
8876     if (SpecLoc.isInvalid()) return;
8877     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8878     if (!Specifiers.empty()) Specifiers += " ";
8879     Specifiers += Spec;
8880   }
8881 
8882   Sema &S;
8883   Sema::SemaDiagnosticBuilder Diagnostic;
8884   std::string Specifiers;
8885 };
8886 }
8887 
8888 /// Check the validity of a declarator that we parsed for a deduction-guide.
8889 /// These aren't actually declarators in the grammar, so we need to check that
8890 /// the user didn't specify any pieces that are not part of the deduction-guide
8891 /// grammar.
8892 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8893                                          StorageClass &SC) {
8894   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8895   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8896   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8897 
8898   // C++ [temp.deduct.guide]p3:
8899   //   A deduction-gide shall be declared in the same scope as the
8900   //   corresponding class template.
8901   if (!CurContext->getRedeclContext()->Equals(
8902           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8903     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8904       << GuidedTemplateDecl;
8905     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8906   }
8907 
8908   auto &DS = D.getMutableDeclSpec();
8909   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8910   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8911       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8912       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8913     BadSpecifierDiagnoser Diagnoser(
8914         *this, D.getIdentifierLoc(),
8915         diag::err_deduction_guide_invalid_specifier);
8916 
8917     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8918     DS.ClearStorageClassSpecs();
8919     SC = SC_None;
8920 
8921     // 'explicit' is permitted.
8922     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8923     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8924     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8925     DS.ClearConstexprSpec();
8926 
8927     Diagnoser.check(DS.getConstSpecLoc(), "const");
8928     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8929     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8930     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8931     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8932     DS.ClearTypeQualifiers();
8933 
8934     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8935     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8936     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8937     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8938     DS.ClearTypeSpecType();
8939   }
8940 
8941   if (D.isInvalidType())
8942     return;
8943 
8944   // Check the declarator is simple enough.
8945   bool FoundFunction = false;
8946   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8947     if (Chunk.Kind == DeclaratorChunk::Paren)
8948       continue;
8949     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8950       Diag(D.getDeclSpec().getBeginLoc(),
8951            diag::err_deduction_guide_with_complex_decl)
8952           << D.getSourceRange();
8953       break;
8954     }
8955     if (!Chunk.Fun.hasTrailingReturnType()) {
8956       Diag(D.getName().getBeginLoc(),
8957            diag::err_deduction_guide_no_trailing_return_type);
8958       break;
8959     }
8960 
8961     // Check that the return type is written as a specialization of
8962     // the template specified as the deduction-guide's name.
8963     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8964     TypeSourceInfo *TSI = nullptr;
8965     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8966     assert(TSI && "deduction guide has valid type but invalid return type?");
8967     bool AcceptableReturnType = false;
8968     bool MightInstantiateToSpecialization = false;
8969     if (auto RetTST =
8970             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8971       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8972       bool TemplateMatches =
8973           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8974       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8975         AcceptableReturnType = true;
8976       else {
8977         // This could still instantiate to the right type, unless we know it
8978         // names the wrong class template.
8979         auto *TD = SpecifiedName.getAsTemplateDecl();
8980         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8981                                              !TemplateMatches);
8982       }
8983     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8984       MightInstantiateToSpecialization = true;
8985     }
8986 
8987     if (!AcceptableReturnType) {
8988       Diag(TSI->getTypeLoc().getBeginLoc(),
8989            diag::err_deduction_guide_bad_trailing_return_type)
8990           << GuidedTemplate << TSI->getType()
8991           << MightInstantiateToSpecialization
8992           << TSI->getTypeLoc().getSourceRange();
8993     }
8994 
8995     // Keep going to check that we don't have any inner declarator pieces (we
8996     // could still have a function returning a pointer to a function).
8997     FoundFunction = true;
8998   }
8999 
9000   if (D.isFunctionDefinition())
9001     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
9002 }
9003 
9004 //===----------------------------------------------------------------------===//
9005 // Namespace Handling
9006 //===----------------------------------------------------------------------===//
9007 
9008 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
9009 /// reopened.
9010 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
9011                                             SourceLocation Loc,
9012                                             IdentifierInfo *II, bool *IsInline,
9013                                             NamespaceDecl *PrevNS) {
9014   assert(*IsInline != PrevNS->isInline());
9015 
9016   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
9017   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
9018   // inline namespaces, with the intention of bringing names into namespace std.
9019   //
9020   // We support this just well enough to get that case working; this is not
9021   // sufficient to support reopening namespaces as inline in general.
9022   if (*IsInline && II && II->getName().startswith("__atomic") &&
9023       S.getSourceManager().isInSystemHeader(Loc)) {
9024     // Mark all prior declarations of the namespace as inline.
9025     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
9026          NS = NS->getPreviousDecl())
9027       NS->setInline(*IsInline);
9028     // Patch up the lookup table for the containing namespace. This isn't really
9029     // correct, but it's good enough for this particular case.
9030     for (auto *I : PrevNS->decls())
9031       if (auto *ND = dyn_cast<NamedDecl>(I))
9032         PrevNS->getParent()->makeDeclVisibleInContext(ND);
9033     return;
9034   }
9035 
9036   if (PrevNS->isInline())
9037     // The user probably just forgot the 'inline', so suggest that it
9038     // be added back.
9039     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
9040       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
9041   else
9042     S.Diag(Loc, diag::err_inline_namespace_mismatch);
9043 
9044   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
9045   *IsInline = PrevNS->isInline();
9046 }
9047 
9048 /// ActOnStartNamespaceDef - This is called at the start of a namespace
9049 /// definition.
9050 Decl *Sema::ActOnStartNamespaceDef(
9051     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
9052     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
9053     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
9054   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
9055   // For anonymous namespace, take the location of the left brace.
9056   SourceLocation Loc = II ? IdentLoc : LBrace;
9057   bool IsInline = InlineLoc.isValid();
9058   bool IsInvalid = false;
9059   bool IsStd = false;
9060   bool AddToKnown = false;
9061   Scope *DeclRegionScope = NamespcScope->getParent();
9062 
9063   NamespaceDecl *PrevNS = nullptr;
9064   if (II) {
9065     // C++ [namespace.def]p2:
9066     //   The identifier in an original-namespace-definition shall not
9067     //   have been previously defined in the declarative region in
9068     //   which the original-namespace-definition appears. The
9069     //   identifier in an original-namespace-definition is the name of
9070     //   the namespace. Subsequently in that declarative region, it is
9071     //   treated as an original-namespace-name.
9072     //
9073     // Since namespace names are unique in their scope, and we don't
9074     // look through using directives, just look for any ordinary names
9075     // as if by qualified name lookup.
9076     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
9077                    ForExternalRedeclaration);
9078     LookupQualifiedName(R, CurContext->getRedeclContext());
9079     NamedDecl *PrevDecl =
9080         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
9081     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
9082 
9083     if (PrevNS) {
9084       // This is an extended namespace definition.
9085       if (IsInline != PrevNS->isInline())
9086         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
9087                                         &IsInline, PrevNS);
9088     } else if (PrevDecl) {
9089       // This is an invalid name redefinition.
9090       Diag(Loc, diag::err_redefinition_different_kind)
9091         << II;
9092       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9093       IsInvalid = true;
9094       // Continue on to push Namespc as current DeclContext and return it.
9095     } else if (II->isStr("std") &&
9096                CurContext->getRedeclContext()->isTranslationUnit()) {
9097       // This is the first "real" definition of the namespace "std", so update
9098       // our cache of the "std" namespace to point at this definition.
9099       PrevNS = getStdNamespace();
9100       IsStd = true;
9101       AddToKnown = !IsInline;
9102     } else {
9103       // We've seen this namespace for the first time.
9104       AddToKnown = !IsInline;
9105     }
9106   } else {
9107     // Anonymous namespaces.
9108 
9109     // Determine whether the parent already has an anonymous namespace.
9110     DeclContext *Parent = CurContext->getRedeclContext();
9111     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9112       PrevNS = TU->getAnonymousNamespace();
9113     } else {
9114       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
9115       PrevNS = ND->getAnonymousNamespace();
9116     }
9117 
9118     if (PrevNS && IsInline != PrevNS->isInline())
9119       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
9120                                       &IsInline, PrevNS);
9121   }
9122 
9123   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
9124                                                  StartLoc, Loc, II, PrevNS);
9125   if (IsInvalid)
9126     Namespc->setInvalidDecl();
9127 
9128   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
9129   AddPragmaAttributes(DeclRegionScope, Namespc);
9130 
9131   // FIXME: Should we be merging attributes?
9132   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
9133     PushNamespaceVisibilityAttr(Attr, Loc);
9134 
9135   if (IsStd)
9136     StdNamespace = Namespc;
9137   if (AddToKnown)
9138     KnownNamespaces[Namespc] = false;
9139 
9140   if (II) {
9141     PushOnScopeChains(Namespc, DeclRegionScope);
9142   } else {
9143     // Link the anonymous namespace into its parent.
9144     DeclContext *Parent = CurContext->getRedeclContext();
9145     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9146       TU->setAnonymousNamespace(Namespc);
9147     } else {
9148       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
9149     }
9150 
9151     CurContext->addDecl(Namespc);
9152 
9153     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
9154     //   behaves as if it were replaced by
9155     //     namespace unique { /* empty body */ }
9156     //     using namespace unique;
9157     //     namespace unique { namespace-body }
9158     //   where all occurrences of 'unique' in a translation unit are
9159     //   replaced by the same identifier and this identifier differs
9160     //   from all other identifiers in the entire program.
9161 
9162     // We just create the namespace with an empty name and then add an
9163     // implicit using declaration, just like the standard suggests.
9164     //
9165     // CodeGen enforces the "universally unique" aspect by giving all
9166     // declarations semantically contained within an anonymous
9167     // namespace internal linkage.
9168 
9169     if (!PrevNS) {
9170       UD = UsingDirectiveDecl::Create(Context, Parent,
9171                                       /* 'using' */ LBrace,
9172                                       /* 'namespace' */ SourceLocation(),
9173                                       /* qualifier */ NestedNameSpecifierLoc(),
9174                                       /* identifier */ SourceLocation(),
9175                                       Namespc,
9176                                       /* Ancestor */ Parent);
9177       UD->setImplicit();
9178       Parent->addDecl(UD);
9179     }
9180   }
9181 
9182   ActOnDocumentableDecl(Namespc);
9183 
9184   // Although we could have an invalid decl (i.e. the namespace name is a
9185   // redefinition), push it as current DeclContext and try to continue parsing.
9186   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9187   // for the namespace has the declarations that showed up in that particular
9188   // namespace definition.
9189   PushDeclContext(NamespcScope, Namespc);
9190   return Namespc;
9191 }
9192 
9193 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9194 /// is a namespace alias, returns the namespace it points to.
9195 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9196   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9197     return AD->getNamespace();
9198   return dyn_cast_or_null<NamespaceDecl>(D);
9199 }
9200 
9201 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9202 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9203 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9204   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9205   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9206   Namespc->setRBraceLoc(RBrace);
9207   PopDeclContext();
9208   if (Namespc->hasAttr<VisibilityAttr>())
9209     PopPragmaVisibility(true, RBrace);
9210   // If this namespace contains an export-declaration, export it now.
9211   if (DeferredExportedNamespaces.erase(Namespc))
9212     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9213 }
9214 
9215 CXXRecordDecl *Sema::getStdBadAlloc() const {
9216   return cast_or_null<CXXRecordDecl>(
9217                                   StdBadAlloc.get(Context.getExternalSource()));
9218 }
9219 
9220 EnumDecl *Sema::getStdAlignValT() const {
9221   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9222 }
9223 
9224 NamespaceDecl *Sema::getStdNamespace() const {
9225   return cast_or_null<NamespaceDecl>(
9226                                  StdNamespace.get(Context.getExternalSource()));
9227 }
9228 
9229 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9230   if (!StdExperimentalNamespaceCache) {
9231     if (auto Std = getStdNamespace()) {
9232       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9233                           SourceLocation(), LookupNamespaceName);
9234       if (!LookupQualifiedName(Result, Std) ||
9235           !(StdExperimentalNamespaceCache =
9236                 Result.getAsSingle<NamespaceDecl>()))
9237         Result.suppressDiagnostics();
9238     }
9239   }
9240   return StdExperimentalNamespaceCache;
9241 }
9242 
9243 namespace {
9244 
9245 enum UnsupportedSTLSelect {
9246   USS_InvalidMember,
9247   USS_MissingMember,
9248   USS_NonTrivial,
9249   USS_Other
9250 };
9251 
9252 struct InvalidSTLDiagnoser {
9253   Sema &S;
9254   SourceLocation Loc;
9255   QualType TyForDiags;
9256 
9257   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9258                       const VarDecl *VD = nullptr) {
9259     {
9260       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9261                << TyForDiags << ((int)Sel);
9262       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9263         assert(!Name.empty());
9264         D << Name;
9265       }
9266     }
9267     if (Sel == USS_InvalidMember) {
9268       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9269           << VD << VD->getSourceRange();
9270     }
9271     return QualType();
9272   }
9273 };
9274 } // namespace
9275 
9276 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9277                                            SourceLocation Loc) {
9278   assert(getLangOpts().CPlusPlus &&
9279          "Looking for comparison category type outside of C++.");
9280 
9281   // Check if we've already successfully checked the comparison category type
9282   // before. If so, skip checking it again.
9283   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9284   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9285     return Info->getType();
9286 
9287   // If lookup failed
9288   if (!Info) {
9289     std::string NameForDiags = "std::";
9290     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9291     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9292         << NameForDiags;
9293     return QualType();
9294   }
9295 
9296   assert(Info->Kind == Kind);
9297   assert(Info->Record);
9298 
9299   // Update the Record decl in case we encountered a forward declaration on our
9300   // first pass. FIXME: This is a bit of a hack.
9301   if (Info->Record->hasDefinition())
9302     Info->Record = Info->Record->getDefinition();
9303 
9304   // Use an elaborated type for diagnostics which has a name containing the
9305   // prepended 'std' namespace but not any inline namespace names.
9306   QualType TyForDiags = [&]() {
9307     auto *NNS =
9308         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9309     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9310   }();
9311 
9312   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9313     return QualType();
9314 
9315   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9316 
9317   if (!Info->Record->isTriviallyCopyable())
9318     return UnsupportedSTLError(USS_NonTrivial);
9319 
9320   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9321     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9322     // Tolerate empty base classes.
9323     if (Base->isEmpty())
9324       continue;
9325     // Reject STL implementations which have at least one non-empty base.
9326     return UnsupportedSTLError();
9327   }
9328 
9329   // Check that the STL has implemented the types using a single integer field.
9330   // This expectation allows better codegen for builtin operators. We require:
9331   //   (1) The class has exactly one field.
9332   //   (2) The field is an integral or enumeration type.
9333   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9334   if (std::distance(FIt, FEnd) != 1 ||
9335       !FIt->getType()->isIntegralOrEnumerationType()) {
9336     return UnsupportedSTLError();
9337   }
9338 
9339   // Build each of the require values and store them in Info.
9340   for (ComparisonCategoryResult CCR :
9341        ComparisonCategories::getPossibleResultsForType(Kind)) {
9342     StringRef MemName = ComparisonCategories::getResultString(CCR);
9343     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9344 
9345     if (!ValInfo)
9346       return UnsupportedSTLError(USS_MissingMember, MemName);
9347 
9348     VarDecl *VD = ValInfo->VD;
9349     assert(VD && "should not be null!");
9350 
9351     // Attempt to diagnose reasons why the STL definition of this type
9352     // might be foobar, including it failing to be a constant expression.
9353     // TODO Handle more ways the lookup or result can be invalid.
9354     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9355         !VD->checkInitIsICE())
9356       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9357 
9358     // Attempt to evaluate the var decl as a constant expression and extract
9359     // the value of its first field as a ICE. If this fails, the STL
9360     // implementation is not supported.
9361     if (!ValInfo->hasValidIntValue())
9362       return UnsupportedSTLError();
9363 
9364     MarkVariableReferenced(Loc, VD);
9365   }
9366 
9367   // We've successfully built the required types and expressions. Update
9368   // the cache and return the newly cached value.
9369   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9370   return Info->getType();
9371 }
9372 
9373 /// Retrieve the special "std" namespace, which may require us to
9374 /// implicitly define the namespace.
9375 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9376   if (!StdNamespace) {
9377     // The "std" namespace has not yet been defined, so build one implicitly.
9378     StdNamespace = NamespaceDecl::Create(Context,
9379                                          Context.getTranslationUnitDecl(),
9380                                          /*Inline=*/false,
9381                                          SourceLocation(), SourceLocation(),
9382                                          &PP.getIdentifierTable().get("std"),
9383                                          /*PrevDecl=*/nullptr);
9384     getStdNamespace()->setImplicit(true);
9385   }
9386 
9387   return getStdNamespace();
9388 }
9389 
9390 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9391   assert(getLangOpts().CPlusPlus &&
9392          "Looking for std::initializer_list outside of C++.");
9393 
9394   // We're looking for implicit instantiations of
9395   // template <typename E> class std::initializer_list.
9396 
9397   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9398     return false;
9399 
9400   ClassTemplateDecl *Template = nullptr;
9401   const TemplateArgument *Arguments = nullptr;
9402 
9403   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9404 
9405     ClassTemplateSpecializationDecl *Specialization =
9406         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9407     if (!Specialization)
9408       return false;
9409 
9410     Template = Specialization->getSpecializedTemplate();
9411     Arguments = Specialization->getTemplateArgs().data();
9412   } else if (const TemplateSpecializationType *TST =
9413                  Ty->getAs<TemplateSpecializationType>()) {
9414     Template = dyn_cast_or_null<ClassTemplateDecl>(
9415         TST->getTemplateName().getAsTemplateDecl());
9416     Arguments = TST->getArgs();
9417   }
9418   if (!Template)
9419     return false;
9420 
9421   if (!StdInitializerList) {
9422     // Haven't recognized std::initializer_list yet, maybe this is it.
9423     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9424     if (TemplateClass->getIdentifier() !=
9425             &PP.getIdentifierTable().get("initializer_list") ||
9426         !getStdNamespace()->InEnclosingNamespaceSetOf(
9427             TemplateClass->getDeclContext()))
9428       return false;
9429     // This is a template called std::initializer_list, but is it the right
9430     // template?
9431     TemplateParameterList *Params = Template->getTemplateParameters();
9432     if (Params->getMinRequiredArguments() != 1)
9433       return false;
9434     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9435       return false;
9436 
9437     // It's the right template.
9438     StdInitializerList = Template;
9439   }
9440 
9441   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9442     return false;
9443 
9444   // This is an instance of std::initializer_list. Find the argument type.
9445   if (Element)
9446     *Element = Arguments[0].getAsType();
9447   return true;
9448 }
9449 
9450 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9451   NamespaceDecl *Std = S.getStdNamespace();
9452   if (!Std) {
9453     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9454     return nullptr;
9455   }
9456 
9457   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9458                       Loc, Sema::LookupOrdinaryName);
9459   if (!S.LookupQualifiedName(Result, Std)) {
9460     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9461     return nullptr;
9462   }
9463   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9464   if (!Template) {
9465     Result.suppressDiagnostics();
9466     // We found something weird. Complain about the first thing we found.
9467     NamedDecl *Found = *Result.begin();
9468     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9469     return nullptr;
9470   }
9471 
9472   // We found some template called std::initializer_list. Now verify that it's
9473   // correct.
9474   TemplateParameterList *Params = Template->getTemplateParameters();
9475   if (Params->getMinRequiredArguments() != 1 ||
9476       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9477     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9478     return nullptr;
9479   }
9480 
9481   return Template;
9482 }
9483 
9484 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9485   if (!StdInitializerList) {
9486     StdInitializerList = LookupStdInitializerList(*this, Loc);
9487     if (!StdInitializerList)
9488       return QualType();
9489   }
9490 
9491   TemplateArgumentListInfo Args(Loc, Loc);
9492   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9493                                        Context.getTrivialTypeSourceInfo(Element,
9494                                                                         Loc)));
9495   return Context.getCanonicalType(
9496       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9497 }
9498 
9499 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9500   // C++ [dcl.init.list]p2:
9501   //   A constructor is an initializer-list constructor if its first parameter
9502   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9503   //   std::initializer_list<E> for some type E, and either there are no other
9504   //   parameters or else all other parameters have default arguments.
9505   if (Ctor->getNumParams() < 1 ||
9506       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9507     return false;
9508 
9509   QualType ArgType = Ctor->getParamDecl(0)->getType();
9510   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9511     ArgType = RT->getPointeeType().getUnqualifiedType();
9512 
9513   return isStdInitializerList(ArgType, nullptr);
9514 }
9515 
9516 /// Determine whether a using statement is in a context where it will be
9517 /// apply in all contexts.
9518 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9519   switch (CurContext->getDeclKind()) {
9520     case Decl::TranslationUnit:
9521       return true;
9522     case Decl::LinkageSpec:
9523       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9524     default:
9525       return false;
9526   }
9527 }
9528 
9529 namespace {
9530 
9531 // Callback to only accept typo corrections that are namespaces.
9532 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9533 public:
9534   bool ValidateCandidate(const TypoCorrection &candidate) override {
9535     if (NamedDecl *ND = candidate.getCorrectionDecl())
9536       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9537     return false;
9538   }
9539 
9540   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9541     return std::make_unique<NamespaceValidatorCCC>(*this);
9542   }
9543 };
9544 
9545 }
9546 
9547 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9548                                        CXXScopeSpec &SS,
9549                                        SourceLocation IdentLoc,
9550                                        IdentifierInfo *Ident) {
9551   R.clear();
9552   NamespaceValidatorCCC CCC{};
9553   if (TypoCorrection Corrected =
9554           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9555                         Sema::CTK_ErrorRecovery)) {
9556     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9557       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9558       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9559                               Ident->getName().equals(CorrectedStr);
9560       S.diagnoseTypo(Corrected,
9561                      S.PDiag(diag::err_using_directive_member_suggest)
9562                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9563                      S.PDiag(diag::note_namespace_defined_here));
9564     } else {
9565       S.diagnoseTypo(Corrected,
9566                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9567                      S.PDiag(diag::note_namespace_defined_here));
9568     }
9569     R.addDecl(Corrected.getFoundDecl());
9570     return true;
9571   }
9572   return false;
9573 }
9574 
9575 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9576                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9577                                 SourceLocation IdentLoc,
9578                                 IdentifierInfo *NamespcName,
9579                                 const ParsedAttributesView &AttrList) {
9580   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9581   assert(NamespcName && "Invalid NamespcName.");
9582   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9583 
9584   // This can only happen along a recovery path.
9585   while (S->isTemplateParamScope())
9586     S = S->getParent();
9587   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9588 
9589   UsingDirectiveDecl *UDir = nullptr;
9590   NestedNameSpecifier *Qualifier = nullptr;
9591   if (SS.isSet())
9592     Qualifier = SS.getScopeRep();
9593 
9594   // Lookup namespace name.
9595   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9596   LookupParsedName(R, S, &SS);
9597   if (R.isAmbiguous())
9598     return nullptr;
9599 
9600   if (R.empty()) {
9601     R.clear();
9602     // Allow "using namespace std;" or "using namespace ::std;" even if
9603     // "std" hasn't been defined yet, for GCC compatibility.
9604     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9605         NamespcName->isStr("std")) {
9606       Diag(IdentLoc, diag::ext_using_undefined_std);
9607       R.addDecl(getOrCreateStdNamespace());
9608       R.resolveKind();
9609     }
9610     // Otherwise, attempt typo correction.
9611     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9612   }
9613 
9614   if (!R.empty()) {
9615     NamedDecl *Named = R.getRepresentativeDecl();
9616     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9617     assert(NS && "expected namespace decl");
9618 
9619     // The use of a nested name specifier may trigger deprecation warnings.
9620     DiagnoseUseOfDecl(Named, IdentLoc);
9621 
9622     // C++ [namespace.udir]p1:
9623     //   A using-directive specifies that the names in the nominated
9624     //   namespace can be used in the scope in which the
9625     //   using-directive appears after the using-directive. During
9626     //   unqualified name lookup (3.4.1), the names appear as if they
9627     //   were declared in the nearest enclosing namespace which
9628     //   contains both the using-directive and the nominated
9629     //   namespace. [Note: in this context, "contains" means "contains
9630     //   directly or indirectly". ]
9631 
9632     // Find enclosing context containing both using-directive and
9633     // nominated namespace.
9634     DeclContext *CommonAncestor = NS;
9635     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9636       CommonAncestor = CommonAncestor->getParent();
9637 
9638     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9639                                       SS.getWithLocInContext(Context),
9640                                       IdentLoc, Named, CommonAncestor);
9641 
9642     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9643         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9644       Diag(IdentLoc, diag::warn_using_directive_in_header);
9645     }
9646 
9647     PushUsingDirective(S, UDir);
9648   } else {
9649     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9650   }
9651 
9652   if (UDir)
9653     ProcessDeclAttributeList(S, UDir, AttrList);
9654 
9655   return UDir;
9656 }
9657 
9658 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9659   // If the scope has an associated entity and the using directive is at
9660   // namespace or translation unit scope, add the UsingDirectiveDecl into
9661   // its lookup structure so qualified name lookup can find it.
9662   DeclContext *Ctx = S->getEntity();
9663   if (Ctx && !Ctx->isFunctionOrMethod())
9664     Ctx->addDecl(UDir);
9665   else
9666     // Otherwise, it is at block scope. The using-directives will affect lookup
9667     // only to the end of the scope.
9668     S->PushUsingDirective(UDir);
9669 }
9670 
9671 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9672                                   SourceLocation UsingLoc,
9673                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9674                                   UnqualifiedId &Name,
9675                                   SourceLocation EllipsisLoc,
9676                                   const ParsedAttributesView &AttrList) {
9677   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9678 
9679   if (SS.isEmpty()) {
9680     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9681     return nullptr;
9682   }
9683 
9684   switch (Name.getKind()) {
9685   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9686   case UnqualifiedIdKind::IK_Identifier:
9687   case UnqualifiedIdKind::IK_OperatorFunctionId:
9688   case UnqualifiedIdKind::IK_LiteralOperatorId:
9689   case UnqualifiedIdKind::IK_ConversionFunctionId:
9690     break;
9691 
9692   case UnqualifiedIdKind::IK_ConstructorName:
9693   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9694     // C++11 inheriting constructors.
9695     Diag(Name.getBeginLoc(),
9696          getLangOpts().CPlusPlus11
9697              ? diag::warn_cxx98_compat_using_decl_constructor
9698              : diag::err_using_decl_constructor)
9699         << SS.getRange();
9700 
9701     if (getLangOpts().CPlusPlus11) break;
9702 
9703     return nullptr;
9704 
9705   case UnqualifiedIdKind::IK_DestructorName:
9706     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9707     return nullptr;
9708 
9709   case UnqualifiedIdKind::IK_TemplateId:
9710     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9711         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9712     return nullptr;
9713 
9714   case UnqualifiedIdKind::IK_DeductionGuideName:
9715     llvm_unreachable("cannot parse qualified deduction guide name");
9716   }
9717 
9718   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9719   DeclarationName TargetName = TargetNameInfo.getName();
9720   if (!TargetName)
9721     return nullptr;
9722 
9723   // Warn about access declarations.
9724   if (UsingLoc.isInvalid()) {
9725     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9726                                  ? diag::err_access_decl
9727                                  : diag::warn_access_decl_deprecated)
9728         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9729   }
9730 
9731   if (EllipsisLoc.isInvalid()) {
9732     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9733         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9734       return nullptr;
9735   } else {
9736     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9737         !TargetNameInfo.containsUnexpandedParameterPack()) {
9738       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9739         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9740       EllipsisLoc = SourceLocation();
9741     }
9742   }
9743 
9744   NamedDecl *UD =
9745       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9746                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9747                             /*IsInstantiation*/false);
9748   if (UD)
9749     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9750 
9751   return UD;
9752 }
9753 
9754 /// Determine whether a using declaration considers the given
9755 /// declarations as "equivalent", e.g., if they are redeclarations of
9756 /// the same entity or are both typedefs of the same type.
9757 static bool
9758 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9759   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9760     return true;
9761 
9762   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9763     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9764       return Context.hasSameType(TD1->getUnderlyingType(),
9765                                  TD2->getUnderlyingType());
9766 
9767   return false;
9768 }
9769 
9770 
9771 /// Determines whether to create a using shadow decl for a particular
9772 /// decl, given the set of decls existing prior to this using lookup.
9773 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9774                                 const LookupResult &Previous,
9775                                 UsingShadowDecl *&PrevShadow) {
9776   // Diagnose finding a decl which is not from a base class of the
9777   // current class.  We do this now because there are cases where this
9778   // function will silently decide not to build a shadow decl, which
9779   // will pre-empt further diagnostics.
9780   //
9781   // We don't need to do this in C++11 because we do the check once on
9782   // the qualifier.
9783   //
9784   // FIXME: diagnose the following if we care enough:
9785   //   struct A { int foo; };
9786   //   struct B : A { using A::foo; };
9787   //   template <class T> struct C : A {};
9788   //   template <class T> struct D : C<T> { using B::foo; } // <---
9789   // This is invalid (during instantiation) in C++03 because B::foo
9790   // resolves to the using decl in B, which is not a base class of D<T>.
9791   // We can't diagnose it immediately because C<T> is an unknown
9792   // specialization.  The UsingShadowDecl in D<T> then points directly
9793   // to A::foo, which will look well-formed when we instantiate.
9794   // The right solution is to not collapse the shadow-decl chain.
9795   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9796     DeclContext *OrigDC = Orig->getDeclContext();
9797 
9798     // Handle enums and anonymous structs.
9799     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9800     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9801     while (OrigRec->isAnonymousStructOrUnion())
9802       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9803 
9804     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9805       if (OrigDC == CurContext) {
9806         Diag(Using->getLocation(),
9807              diag::err_using_decl_nested_name_specifier_is_current_class)
9808           << Using->getQualifierLoc().getSourceRange();
9809         Diag(Orig->getLocation(), diag::note_using_decl_target);
9810         Using->setInvalidDecl();
9811         return true;
9812       }
9813 
9814       Diag(Using->getQualifierLoc().getBeginLoc(),
9815            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9816         << Using->getQualifier()
9817         << cast<CXXRecordDecl>(CurContext)
9818         << Using->getQualifierLoc().getSourceRange();
9819       Diag(Orig->getLocation(), diag::note_using_decl_target);
9820       Using->setInvalidDecl();
9821       return true;
9822     }
9823   }
9824 
9825   if (Previous.empty()) return false;
9826 
9827   NamedDecl *Target = Orig;
9828   if (isa<UsingShadowDecl>(Target))
9829     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9830 
9831   // If the target happens to be one of the previous declarations, we
9832   // don't have a conflict.
9833   //
9834   // FIXME: but we might be increasing its access, in which case we
9835   // should redeclare it.
9836   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9837   bool FoundEquivalentDecl = false;
9838   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9839          I != E; ++I) {
9840     NamedDecl *D = (*I)->getUnderlyingDecl();
9841     // We can have UsingDecls in our Previous results because we use the same
9842     // LookupResult for checking whether the UsingDecl itself is a valid
9843     // redeclaration.
9844     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9845       continue;
9846 
9847     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9848       // C++ [class.mem]p19:
9849       //   If T is the name of a class, then [every named member other than
9850       //   a non-static data member] shall have a name different from T
9851       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9852           !isa<IndirectFieldDecl>(Target) &&
9853           !isa<UnresolvedUsingValueDecl>(Target) &&
9854           DiagnoseClassNameShadow(
9855               CurContext,
9856               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9857         return true;
9858     }
9859 
9860     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9861       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9862         PrevShadow = Shadow;
9863       FoundEquivalentDecl = true;
9864     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9865       // We don't conflict with an existing using shadow decl of an equivalent
9866       // declaration, but we're not a redeclaration of it.
9867       FoundEquivalentDecl = true;
9868     }
9869 
9870     if (isVisible(D))
9871       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9872   }
9873 
9874   if (FoundEquivalentDecl)
9875     return false;
9876 
9877   if (FunctionDecl *FD = Target->getAsFunction()) {
9878     NamedDecl *OldDecl = nullptr;
9879     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9880                           /*IsForUsingDecl*/ true)) {
9881     case Ovl_Overload:
9882       return false;
9883 
9884     case Ovl_NonFunction:
9885       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9886       break;
9887 
9888     // We found a decl with the exact signature.
9889     case Ovl_Match:
9890       // If we're in a record, we want to hide the target, so we
9891       // return true (without a diagnostic) to tell the caller not to
9892       // build a shadow decl.
9893       if (CurContext->isRecord())
9894         return true;
9895 
9896       // If we're not in a record, this is an error.
9897       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9898       break;
9899     }
9900 
9901     Diag(Target->getLocation(), diag::note_using_decl_target);
9902     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9903     Using->setInvalidDecl();
9904     return true;
9905   }
9906 
9907   // Target is not a function.
9908 
9909   if (isa<TagDecl>(Target)) {
9910     // No conflict between a tag and a non-tag.
9911     if (!Tag) return false;
9912 
9913     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9914     Diag(Target->getLocation(), diag::note_using_decl_target);
9915     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9916     Using->setInvalidDecl();
9917     return true;
9918   }
9919 
9920   // No conflict between a tag and a non-tag.
9921   if (!NonTag) return false;
9922 
9923   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9924   Diag(Target->getLocation(), diag::note_using_decl_target);
9925   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9926   Using->setInvalidDecl();
9927   return true;
9928 }
9929 
9930 /// Determine whether a direct base class is a virtual base class.
9931 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9932   if (!Derived->getNumVBases())
9933     return false;
9934   for (auto &B : Derived->bases())
9935     if (B.getType()->getAsCXXRecordDecl() == Base)
9936       return B.isVirtual();
9937   llvm_unreachable("not a direct base class");
9938 }
9939 
9940 /// Builds a shadow declaration corresponding to a 'using' declaration.
9941 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9942                                             UsingDecl *UD,
9943                                             NamedDecl *Orig,
9944                                             UsingShadowDecl *PrevDecl) {
9945   // If we resolved to another shadow declaration, just coalesce them.
9946   NamedDecl *Target = Orig;
9947   if (isa<UsingShadowDecl>(Target)) {
9948     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9949     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9950   }
9951 
9952   NamedDecl *NonTemplateTarget = Target;
9953   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9954     NonTemplateTarget = TargetTD->getTemplatedDecl();
9955 
9956   UsingShadowDecl *Shadow;
9957   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
9958     bool IsVirtualBase =
9959         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9960                             UD->getQualifier()->getAsRecordDecl());
9961     Shadow = ConstructorUsingShadowDecl::Create(
9962         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9963   } else {
9964     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9965                                      Target);
9966   }
9967   UD->addShadowDecl(Shadow);
9968 
9969   Shadow->setAccess(UD->getAccess());
9970   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9971     Shadow->setInvalidDecl();
9972 
9973   Shadow->setPreviousDecl(PrevDecl);
9974 
9975   if (S)
9976     PushOnScopeChains(Shadow, S);
9977   else
9978     CurContext->addDecl(Shadow);
9979 
9980 
9981   return Shadow;
9982 }
9983 
9984 /// Hides a using shadow declaration.  This is required by the current
9985 /// using-decl implementation when a resolvable using declaration in a
9986 /// class is followed by a declaration which would hide or override
9987 /// one or more of the using decl's targets; for example:
9988 ///
9989 ///   struct Base { void foo(int); };
9990 ///   struct Derived : Base {
9991 ///     using Base::foo;
9992 ///     void foo(int);
9993 ///   };
9994 ///
9995 /// The governing language is C++03 [namespace.udecl]p12:
9996 ///
9997 ///   When a using-declaration brings names from a base class into a
9998 ///   derived class scope, member functions in the derived class
9999 ///   override and/or hide member functions with the same name and
10000 ///   parameter types in a base class (rather than conflicting).
10001 ///
10002 /// There are two ways to implement this:
10003 ///   (1) optimistically create shadow decls when they're not hidden
10004 ///       by existing declarations, or
10005 ///   (2) don't create any shadow decls (or at least don't make them
10006 ///       visible) until we've fully parsed/instantiated the class.
10007 /// The problem with (1) is that we might have to retroactively remove
10008 /// a shadow decl, which requires several O(n) operations because the
10009 /// decl structures are (very reasonably) not designed for removal.
10010 /// (2) avoids this but is very fiddly and phase-dependent.
10011 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
10012   if (Shadow->getDeclName().getNameKind() ==
10013         DeclarationName::CXXConversionFunctionName)
10014     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
10015 
10016   // Remove it from the DeclContext...
10017   Shadow->getDeclContext()->removeDecl(Shadow);
10018 
10019   // ...and the scope, if applicable...
10020   if (S) {
10021     S->RemoveDecl(Shadow);
10022     IdResolver.RemoveDecl(Shadow);
10023   }
10024 
10025   // ...and the using decl.
10026   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
10027 
10028   // TODO: complain somehow if Shadow was used.  It shouldn't
10029   // be possible for this to happen, because...?
10030 }
10031 
10032 /// Find the base specifier for a base class with the given type.
10033 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
10034                                                 QualType DesiredBase,
10035                                                 bool &AnyDependentBases) {
10036   // Check whether the named type is a direct base class.
10037   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
10038     .getUnqualifiedType();
10039   for (auto &Base : Derived->bases()) {
10040     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
10041     if (CanonicalDesiredBase == BaseType)
10042       return &Base;
10043     if (BaseType->isDependentType())
10044       AnyDependentBases = true;
10045   }
10046   return nullptr;
10047 }
10048 
10049 namespace {
10050 class UsingValidatorCCC final : public CorrectionCandidateCallback {
10051 public:
10052   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
10053                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
10054       : HasTypenameKeyword(HasTypenameKeyword),
10055         IsInstantiation(IsInstantiation), OldNNS(NNS),
10056         RequireMemberOf(RequireMemberOf) {}
10057 
10058   bool ValidateCandidate(const TypoCorrection &Candidate) override {
10059     NamedDecl *ND = Candidate.getCorrectionDecl();
10060 
10061     // Keywords are not valid here.
10062     if (!ND || isa<NamespaceDecl>(ND))
10063       return false;
10064 
10065     // Completely unqualified names are invalid for a 'using' declaration.
10066     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
10067       return false;
10068 
10069     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
10070     // reject.
10071 
10072     if (RequireMemberOf) {
10073       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10074       if (FoundRecord && FoundRecord->isInjectedClassName()) {
10075         // No-one ever wants a using-declaration to name an injected-class-name
10076         // of a base class, unless they're declaring an inheriting constructor.
10077         ASTContext &Ctx = ND->getASTContext();
10078         if (!Ctx.getLangOpts().CPlusPlus11)
10079           return false;
10080         QualType FoundType = Ctx.getRecordType(FoundRecord);
10081 
10082         // Check that the injected-class-name is named as a member of its own
10083         // type; we don't want to suggest 'using Derived::Base;', since that
10084         // means something else.
10085         NestedNameSpecifier *Specifier =
10086             Candidate.WillReplaceSpecifier()
10087                 ? Candidate.getCorrectionSpecifier()
10088                 : OldNNS;
10089         if (!Specifier->getAsType() ||
10090             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
10091           return false;
10092 
10093         // Check that this inheriting constructor declaration actually names a
10094         // direct base class of the current class.
10095         bool AnyDependentBases = false;
10096         if (!findDirectBaseWithType(RequireMemberOf,
10097                                     Ctx.getRecordType(FoundRecord),
10098                                     AnyDependentBases) &&
10099             !AnyDependentBases)
10100           return false;
10101       } else {
10102         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
10103         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
10104           return false;
10105 
10106         // FIXME: Check that the base class member is accessible?
10107       }
10108     } else {
10109       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10110       if (FoundRecord && FoundRecord->isInjectedClassName())
10111         return false;
10112     }
10113 
10114     if (isa<TypeDecl>(ND))
10115       return HasTypenameKeyword || !IsInstantiation;
10116 
10117     return !HasTypenameKeyword;
10118   }
10119 
10120   std::unique_ptr<CorrectionCandidateCallback> clone() override {
10121     return std::make_unique<UsingValidatorCCC>(*this);
10122   }
10123 
10124 private:
10125   bool HasTypenameKeyword;
10126   bool IsInstantiation;
10127   NestedNameSpecifier *OldNNS;
10128   CXXRecordDecl *RequireMemberOf;
10129 };
10130 } // end anonymous namespace
10131 
10132 /// Builds a using declaration.
10133 ///
10134 /// \param IsInstantiation - Whether this call arises from an
10135 ///   instantiation of an unresolved using declaration.  We treat
10136 ///   the lookup differently for these declarations.
10137 NamedDecl *Sema::BuildUsingDeclaration(
10138     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
10139     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
10140     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
10141     const ParsedAttributesView &AttrList, bool IsInstantiation) {
10142   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
10143   SourceLocation IdentLoc = NameInfo.getLoc();
10144   assert(IdentLoc.isValid() && "Invalid TargetName location.");
10145 
10146   // FIXME: We ignore attributes for now.
10147 
10148   // For an inheriting constructor declaration, the name of the using
10149   // declaration is the name of a constructor in this class, not in the
10150   // base class.
10151   DeclarationNameInfo UsingName = NameInfo;
10152   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
10153     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
10154       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10155           Context.getCanonicalType(Context.getRecordType(RD))));
10156 
10157   // Do the redeclaration lookup in the current scope.
10158   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10159                         ForVisibleRedeclaration);
10160   Previous.setHideTags(false);
10161   if (S) {
10162     LookupName(Previous, S);
10163 
10164     // It is really dumb that we have to do this.
10165     LookupResult::Filter F = Previous.makeFilter();
10166     while (F.hasNext()) {
10167       NamedDecl *D = F.next();
10168       if (!isDeclInScope(D, CurContext, S))
10169         F.erase();
10170       // If we found a local extern declaration that's not ordinarily visible,
10171       // and this declaration is being added to a non-block scope, ignore it.
10172       // We're only checking for scope conflicts here, not also for violations
10173       // of the linkage rules.
10174       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10175                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10176         F.erase();
10177     }
10178     F.done();
10179   } else {
10180     assert(IsInstantiation && "no scope in non-instantiation");
10181     if (CurContext->isRecord())
10182       LookupQualifiedName(Previous, CurContext);
10183     else {
10184       // No redeclaration check is needed here; in non-member contexts we
10185       // diagnosed all possible conflicts with other using-declarations when
10186       // building the template:
10187       //
10188       // For a dependent non-type using declaration, the only valid case is
10189       // if we instantiate to a single enumerator. We check for conflicts
10190       // between shadow declarations we introduce, and we check in the template
10191       // definition for conflicts between a non-type using declaration and any
10192       // other declaration, which together covers all cases.
10193       //
10194       // A dependent typename using declaration will never successfully
10195       // instantiate, since it will always name a class member, so we reject
10196       // that in the template definition.
10197     }
10198   }
10199 
10200   // Check for invalid redeclarations.
10201   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10202                                   SS, IdentLoc, Previous))
10203     return nullptr;
10204 
10205   // Check for bad qualifiers.
10206   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10207                               IdentLoc))
10208     return nullptr;
10209 
10210   DeclContext *LookupContext = computeDeclContext(SS);
10211   NamedDecl *D;
10212   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10213   if (!LookupContext || EllipsisLoc.isValid()) {
10214     if (HasTypenameKeyword) {
10215       // FIXME: not all declaration name kinds are legal here
10216       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10217                                               UsingLoc, TypenameLoc,
10218                                               QualifierLoc,
10219                                               IdentLoc, NameInfo.getName(),
10220                                               EllipsisLoc);
10221     } else {
10222       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10223                                            QualifierLoc, NameInfo, EllipsisLoc);
10224     }
10225     D->setAccess(AS);
10226     CurContext->addDecl(D);
10227     return D;
10228   }
10229 
10230   auto Build = [&](bool Invalid) {
10231     UsingDecl *UD =
10232         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10233                           UsingName, HasTypenameKeyword);
10234     UD->setAccess(AS);
10235     CurContext->addDecl(UD);
10236     UD->setInvalidDecl(Invalid);
10237     return UD;
10238   };
10239   auto BuildInvalid = [&]{ return Build(true); };
10240   auto BuildValid = [&]{ return Build(false); };
10241 
10242   if (RequireCompleteDeclContext(SS, LookupContext))
10243     return BuildInvalid();
10244 
10245   // Look up the target name.
10246   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10247 
10248   // Unlike most lookups, we don't always want to hide tag
10249   // declarations: tag names are visible through the using declaration
10250   // even if hidden by ordinary names, *except* in a dependent context
10251   // where it's important for the sanity of two-phase lookup.
10252   if (!IsInstantiation)
10253     R.setHideTags(false);
10254 
10255   // For the purposes of this lookup, we have a base object type
10256   // equal to that of the current context.
10257   if (CurContext->isRecord()) {
10258     R.setBaseObjectType(
10259                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10260   }
10261 
10262   LookupQualifiedName(R, LookupContext);
10263 
10264   // Try to correct typos if possible. If constructor name lookup finds no
10265   // results, that means the named class has no explicit constructors, and we
10266   // suppressed declaring implicit ones (probably because it's dependent or
10267   // invalid).
10268   if (R.empty() &&
10269       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10270     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10271     // it will believe that glibc provides a ::gets in cases where it does not,
10272     // and will try to pull it into namespace std with a using-declaration.
10273     // Just ignore the using-declaration in that case.
10274     auto *II = NameInfo.getName().getAsIdentifierInfo();
10275     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10276         CurContext->isStdNamespace() &&
10277         isa<TranslationUnitDecl>(LookupContext) &&
10278         getSourceManager().isInSystemHeader(UsingLoc))
10279       return nullptr;
10280     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10281                           dyn_cast<CXXRecordDecl>(CurContext));
10282     if (TypoCorrection Corrected =
10283             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10284                         CTK_ErrorRecovery)) {
10285       // We reject candidates where DroppedSpecifier == true, hence the
10286       // literal '0' below.
10287       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10288                                 << NameInfo.getName() << LookupContext << 0
10289                                 << SS.getRange());
10290 
10291       // If we picked a correction with no attached Decl we can't do anything
10292       // useful with it, bail out.
10293       NamedDecl *ND = Corrected.getCorrectionDecl();
10294       if (!ND)
10295         return BuildInvalid();
10296 
10297       // If we corrected to an inheriting constructor, handle it as one.
10298       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10299       if (RD && RD->isInjectedClassName()) {
10300         // The parent of the injected class name is the class itself.
10301         RD = cast<CXXRecordDecl>(RD->getParent());
10302 
10303         // Fix up the information we'll use to build the using declaration.
10304         if (Corrected.WillReplaceSpecifier()) {
10305           NestedNameSpecifierLocBuilder Builder;
10306           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10307                               QualifierLoc.getSourceRange());
10308           QualifierLoc = Builder.getWithLocInContext(Context);
10309         }
10310 
10311         // In this case, the name we introduce is the name of a derived class
10312         // constructor.
10313         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10314         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10315             Context.getCanonicalType(Context.getRecordType(CurClass))));
10316         UsingName.setNamedTypeInfo(nullptr);
10317         for (auto *Ctor : LookupConstructors(RD))
10318           R.addDecl(Ctor);
10319         R.resolveKind();
10320       } else {
10321         // FIXME: Pick up all the declarations if we found an overloaded
10322         // function.
10323         UsingName.setName(ND->getDeclName());
10324         R.addDecl(ND);
10325       }
10326     } else {
10327       Diag(IdentLoc, diag::err_no_member)
10328         << NameInfo.getName() << LookupContext << SS.getRange();
10329       return BuildInvalid();
10330     }
10331   }
10332 
10333   if (R.isAmbiguous())
10334     return BuildInvalid();
10335 
10336   if (HasTypenameKeyword) {
10337     // If we asked for a typename and got a non-type decl, error out.
10338     if (!R.getAsSingle<TypeDecl>()) {
10339       Diag(IdentLoc, diag::err_using_typename_non_type);
10340       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10341         Diag((*I)->getUnderlyingDecl()->getLocation(),
10342              diag::note_using_decl_target);
10343       return BuildInvalid();
10344     }
10345   } else {
10346     // If we asked for a non-typename and we got a type, error out,
10347     // but only if this is an instantiation of an unresolved using
10348     // decl.  Otherwise just silently find the type name.
10349     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10350       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10351       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10352       return BuildInvalid();
10353     }
10354   }
10355 
10356   // C++14 [namespace.udecl]p6:
10357   // A using-declaration shall not name a namespace.
10358   if (R.getAsSingle<NamespaceDecl>()) {
10359     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10360       << SS.getRange();
10361     return BuildInvalid();
10362   }
10363 
10364   // C++14 [namespace.udecl]p7:
10365   // A using-declaration shall not name a scoped enumerator.
10366   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10367     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10368       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10369         << SS.getRange();
10370       return BuildInvalid();
10371     }
10372   }
10373 
10374   UsingDecl *UD = BuildValid();
10375 
10376   // Some additional rules apply to inheriting constructors.
10377   if (UsingName.getName().getNameKind() ==
10378         DeclarationName::CXXConstructorName) {
10379     // Suppress access diagnostics; the access check is instead performed at the
10380     // point of use for an inheriting constructor.
10381     R.suppressDiagnostics();
10382     if (CheckInheritingConstructorUsingDecl(UD))
10383       return UD;
10384   }
10385 
10386   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10387     UsingShadowDecl *PrevDecl = nullptr;
10388     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10389       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10390   }
10391 
10392   return UD;
10393 }
10394 
10395 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10396                                     ArrayRef<NamedDecl *> Expansions) {
10397   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10398          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10399          isa<UsingPackDecl>(InstantiatedFrom));
10400 
10401   auto *UPD =
10402       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10403   UPD->setAccess(InstantiatedFrom->getAccess());
10404   CurContext->addDecl(UPD);
10405   return UPD;
10406 }
10407 
10408 /// Additional checks for a using declaration referring to a constructor name.
10409 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10410   assert(!UD->hasTypename() && "expecting a constructor name");
10411 
10412   const Type *SourceType = UD->getQualifier()->getAsType();
10413   assert(SourceType &&
10414          "Using decl naming constructor doesn't have type in scope spec.");
10415   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10416 
10417   // Check whether the named type is a direct base class.
10418   bool AnyDependentBases = false;
10419   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10420                                       AnyDependentBases);
10421   if (!Base && !AnyDependentBases) {
10422     Diag(UD->getUsingLoc(),
10423          diag::err_using_decl_constructor_not_in_direct_base)
10424       << UD->getNameInfo().getSourceRange()
10425       << QualType(SourceType, 0) << TargetClass;
10426     UD->setInvalidDecl();
10427     return true;
10428   }
10429 
10430   if (Base)
10431     Base->setInheritConstructors();
10432 
10433   return false;
10434 }
10435 
10436 /// Checks that the given using declaration is not an invalid
10437 /// redeclaration.  Note that this is checking only for the using decl
10438 /// itself, not for any ill-formedness among the UsingShadowDecls.
10439 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10440                                        bool HasTypenameKeyword,
10441                                        const CXXScopeSpec &SS,
10442                                        SourceLocation NameLoc,
10443                                        const LookupResult &Prev) {
10444   NestedNameSpecifier *Qual = SS.getScopeRep();
10445 
10446   // C++03 [namespace.udecl]p8:
10447   // C++0x [namespace.udecl]p10:
10448   //   A using-declaration is a declaration and can therefore be used
10449   //   repeatedly where (and only where) multiple declarations are
10450   //   allowed.
10451   //
10452   // That's in non-member contexts.
10453   if (!CurContext->getRedeclContext()->isRecord()) {
10454     // A dependent qualifier outside a class can only ever resolve to an
10455     // enumeration type. Therefore it conflicts with any other non-type
10456     // declaration in the same scope.
10457     // FIXME: How should we check for dependent type-type conflicts at block
10458     // scope?
10459     if (Qual->isDependent() && !HasTypenameKeyword) {
10460       for (auto *D : Prev) {
10461         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10462           bool OldCouldBeEnumerator =
10463               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10464           Diag(NameLoc,
10465                OldCouldBeEnumerator ? diag::err_redefinition
10466                                     : diag::err_redefinition_different_kind)
10467               << Prev.getLookupName();
10468           Diag(D->getLocation(), diag::note_previous_definition);
10469           return true;
10470         }
10471       }
10472     }
10473     return false;
10474   }
10475 
10476   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10477     NamedDecl *D = *I;
10478 
10479     bool DTypename;
10480     NestedNameSpecifier *DQual;
10481     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10482       DTypename = UD->hasTypename();
10483       DQual = UD->getQualifier();
10484     } else if (UnresolvedUsingValueDecl *UD
10485                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10486       DTypename = false;
10487       DQual = UD->getQualifier();
10488     } else if (UnresolvedUsingTypenameDecl *UD
10489                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10490       DTypename = true;
10491       DQual = UD->getQualifier();
10492     } else continue;
10493 
10494     // using decls differ if one says 'typename' and the other doesn't.
10495     // FIXME: non-dependent using decls?
10496     if (HasTypenameKeyword != DTypename) continue;
10497 
10498     // using decls differ if they name different scopes (but note that
10499     // template instantiation can cause this check to trigger when it
10500     // didn't before instantiation).
10501     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10502         Context.getCanonicalNestedNameSpecifier(DQual))
10503       continue;
10504 
10505     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10506     Diag(D->getLocation(), diag::note_using_decl) << 1;
10507     return true;
10508   }
10509 
10510   return false;
10511 }
10512 
10513 
10514 /// Checks that the given nested-name qualifier used in a using decl
10515 /// in the current context is appropriately related to the current
10516 /// scope.  If an error is found, diagnoses it and returns true.
10517 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10518                                    bool HasTypename,
10519                                    const CXXScopeSpec &SS,
10520                                    const DeclarationNameInfo &NameInfo,
10521                                    SourceLocation NameLoc) {
10522   DeclContext *NamedContext = computeDeclContext(SS);
10523 
10524   if (!CurContext->isRecord()) {
10525     // C++03 [namespace.udecl]p3:
10526     // C++0x [namespace.udecl]p8:
10527     //   A using-declaration for a class member shall be a member-declaration.
10528 
10529     // If we weren't able to compute a valid scope, it might validly be a
10530     // dependent class scope or a dependent enumeration unscoped scope. If
10531     // we have a 'typename' keyword, the scope must resolve to a class type.
10532     if ((HasTypename && !NamedContext) ||
10533         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10534       auto *RD = NamedContext
10535                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10536                      : nullptr;
10537       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10538         RD = nullptr;
10539 
10540       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10541         << SS.getRange();
10542 
10543       // If we have a complete, non-dependent source type, try to suggest a
10544       // way to get the same effect.
10545       if (!RD)
10546         return true;
10547 
10548       // Find what this using-declaration was referring to.
10549       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10550       R.setHideTags(false);
10551       R.suppressDiagnostics();
10552       LookupQualifiedName(R, RD);
10553 
10554       if (R.getAsSingle<TypeDecl>()) {
10555         if (getLangOpts().CPlusPlus11) {
10556           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10557           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10558             << 0 // alias declaration
10559             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10560                                           NameInfo.getName().getAsString() +
10561                                               " = ");
10562         } else {
10563           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10564           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10565           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10566             << 1 // typedef declaration
10567             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10568             << FixItHint::CreateInsertion(
10569                    InsertLoc, " " + NameInfo.getName().getAsString());
10570         }
10571       } else if (R.getAsSingle<VarDecl>()) {
10572         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10573         // repeating the type of the static data member here.
10574         FixItHint FixIt;
10575         if (getLangOpts().CPlusPlus11) {
10576           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10577           FixIt = FixItHint::CreateReplacement(
10578               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10579         }
10580 
10581         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10582           << 2 // reference declaration
10583           << FixIt;
10584       } else if (R.getAsSingle<EnumConstantDecl>()) {
10585         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10586         // repeating the type of the enumeration here, and we can't do so if
10587         // the type is anonymous.
10588         FixItHint FixIt;
10589         if (getLangOpts().CPlusPlus11) {
10590           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10591           FixIt = FixItHint::CreateReplacement(
10592               UsingLoc,
10593               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10594         }
10595 
10596         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10597           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10598           << FixIt;
10599       }
10600       return true;
10601     }
10602 
10603     // Otherwise, this might be valid.
10604     return false;
10605   }
10606 
10607   // The current scope is a record.
10608 
10609   // If the named context is dependent, we can't decide much.
10610   if (!NamedContext) {
10611     // FIXME: in C++0x, we can diagnose if we can prove that the
10612     // nested-name-specifier does not refer to a base class, which is
10613     // still possible in some cases.
10614 
10615     // Otherwise we have to conservatively report that things might be
10616     // okay.
10617     return false;
10618   }
10619 
10620   if (!NamedContext->isRecord()) {
10621     // Ideally this would point at the last name in the specifier,
10622     // but we don't have that level of source info.
10623     Diag(SS.getRange().getBegin(),
10624          diag::err_using_decl_nested_name_specifier_is_not_class)
10625       << SS.getScopeRep() << SS.getRange();
10626     return true;
10627   }
10628 
10629   if (!NamedContext->isDependentContext() &&
10630       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10631     return true;
10632 
10633   if (getLangOpts().CPlusPlus11) {
10634     // C++11 [namespace.udecl]p3:
10635     //   In a using-declaration used as a member-declaration, the
10636     //   nested-name-specifier shall name a base class of the class
10637     //   being defined.
10638 
10639     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10640                                  cast<CXXRecordDecl>(NamedContext))) {
10641       if (CurContext == NamedContext) {
10642         Diag(NameLoc,
10643              diag::err_using_decl_nested_name_specifier_is_current_class)
10644           << SS.getRange();
10645         return true;
10646       }
10647 
10648       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10649         Diag(SS.getRange().getBegin(),
10650              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10651           << SS.getScopeRep()
10652           << cast<CXXRecordDecl>(CurContext)
10653           << SS.getRange();
10654       }
10655       return true;
10656     }
10657 
10658     return false;
10659   }
10660 
10661   // C++03 [namespace.udecl]p4:
10662   //   A using-declaration used as a member-declaration shall refer
10663   //   to a member of a base class of the class being defined [etc.].
10664 
10665   // Salient point: SS doesn't have to name a base class as long as
10666   // lookup only finds members from base classes.  Therefore we can
10667   // diagnose here only if we can prove that that can't happen,
10668   // i.e. if the class hierarchies provably don't intersect.
10669 
10670   // TODO: it would be nice if "definitely valid" results were cached
10671   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10672   // need to be repeated.
10673 
10674   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10675   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10676     Bases.insert(Base);
10677     return true;
10678   };
10679 
10680   // Collect all bases. Return false if we find a dependent base.
10681   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10682     return false;
10683 
10684   // Returns true if the base is dependent or is one of the accumulated base
10685   // classes.
10686   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10687     return !Bases.count(Base);
10688   };
10689 
10690   // Return false if the class has a dependent base or if it or one
10691   // of its bases is present in the base set of the current context.
10692   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10693       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10694     return false;
10695 
10696   Diag(SS.getRange().getBegin(),
10697        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10698     << SS.getScopeRep()
10699     << cast<CXXRecordDecl>(CurContext)
10700     << SS.getRange();
10701 
10702   return true;
10703 }
10704 
10705 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10706                                   MultiTemplateParamsArg TemplateParamLists,
10707                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10708                                   const ParsedAttributesView &AttrList,
10709                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10710   // Skip up to the relevant declaration scope.
10711   while (S->isTemplateParamScope())
10712     S = S->getParent();
10713   assert((S->getFlags() & Scope::DeclScope) &&
10714          "got alias-declaration outside of declaration scope");
10715 
10716   if (Type.isInvalid())
10717     return nullptr;
10718 
10719   bool Invalid = false;
10720   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10721   TypeSourceInfo *TInfo = nullptr;
10722   GetTypeFromParser(Type.get(), &TInfo);
10723 
10724   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10725     return nullptr;
10726 
10727   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10728                                       UPPC_DeclarationType)) {
10729     Invalid = true;
10730     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10731                                              TInfo->getTypeLoc().getBeginLoc());
10732   }
10733 
10734   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10735                         TemplateParamLists.size()
10736                             ? forRedeclarationInCurContext()
10737                             : ForVisibleRedeclaration);
10738   LookupName(Previous, S);
10739 
10740   // Warn about shadowing the name of a template parameter.
10741   if (Previous.isSingleResult() &&
10742       Previous.getFoundDecl()->isTemplateParameter()) {
10743     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10744     Previous.clear();
10745   }
10746 
10747   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10748          "name in alias declaration must be an identifier");
10749   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10750                                                Name.StartLocation,
10751                                                Name.Identifier, TInfo);
10752 
10753   NewTD->setAccess(AS);
10754 
10755   if (Invalid)
10756     NewTD->setInvalidDecl();
10757 
10758   ProcessDeclAttributeList(S, NewTD, AttrList);
10759   AddPragmaAttributes(S, NewTD);
10760 
10761   CheckTypedefForVariablyModifiedType(S, NewTD);
10762   Invalid |= NewTD->isInvalidDecl();
10763 
10764   bool Redeclaration = false;
10765 
10766   NamedDecl *NewND;
10767   if (TemplateParamLists.size()) {
10768     TypeAliasTemplateDecl *OldDecl = nullptr;
10769     TemplateParameterList *OldTemplateParams = nullptr;
10770 
10771     if (TemplateParamLists.size() != 1) {
10772       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10773         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10774          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10775     }
10776     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10777 
10778     // Check that we can declare a template here.
10779     if (CheckTemplateDeclScope(S, TemplateParams))
10780       return nullptr;
10781 
10782     // Only consider previous declarations in the same scope.
10783     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10784                          /*ExplicitInstantiationOrSpecialization*/false);
10785     if (!Previous.empty()) {
10786       Redeclaration = true;
10787 
10788       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10789       if (!OldDecl && !Invalid) {
10790         Diag(UsingLoc, diag::err_redefinition_different_kind)
10791           << Name.Identifier;
10792 
10793         NamedDecl *OldD = Previous.getRepresentativeDecl();
10794         if (OldD->getLocation().isValid())
10795           Diag(OldD->getLocation(), diag::note_previous_definition);
10796 
10797         Invalid = true;
10798       }
10799 
10800       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10801         if (TemplateParameterListsAreEqual(TemplateParams,
10802                                            OldDecl->getTemplateParameters(),
10803                                            /*Complain=*/true,
10804                                            TPL_TemplateMatch))
10805           OldTemplateParams =
10806               OldDecl->getMostRecentDecl()->getTemplateParameters();
10807         else
10808           Invalid = true;
10809 
10810         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10811         if (!Invalid &&
10812             !Context.hasSameType(OldTD->getUnderlyingType(),
10813                                  NewTD->getUnderlyingType())) {
10814           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10815           // but we can't reasonably accept it.
10816           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10817             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10818           if (OldTD->getLocation().isValid())
10819             Diag(OldTD->getLocation(), diag::note_previous_definition);
10820           Invalid = true;
10821         }
10822       }
10823     }
10824 
10825     // Merge any previous default template arguments into our parameters,
10826     // and check the parameter list.
10827     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10828                                    TPC_TypeAliasTemplate))
10829       return nullptr;
10830 
10831     TypeAliasTemplateDecl *NewDecl =
10832       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10833                                     Name.Identifier, TemplateParams,
10834                                     NewTD);
10835     NewTD->setDescribedAliasTemplate(NewDecl);
10836 
10837     NewDecl->setAccess(AS);
10838 
10839     if (Invalid)
10840       NewDecl->setInvalidDecl();
10841     else if (OldDecl) {
10842       NewDecl->setPreviousDecl(OldDecl);
10843       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10844     }
10845 
10846     NewND = NewDecl;
10847   } else {
10848     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10849       setTagNameForLinkagePurposes(TD, NewTD);
10850       handleTagNumbering(TD, S);
10851     }
10852     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10853     NewND = NewTD;
10854   }
10855 
10856   PushOnScopeChains(NewND, S);
10857   ActOnDocumentableDecl(NewND);
10858   return NewND;
10859 }
10860 
10861 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10862                                    SourceLocation AliasLoc,
10863                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10864                                    SourceLocation IdentLoc,
10865                                    IdentifierInfo *Ident) {
10866 
10867   // Lookup the namespace name.
10868   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10869   LookupParsedName(R, S, &SS);
10870 
10871   if (R.isAmbiguous())
10872     return nullptr;
10873 
10874   if (R.empty()) {
10875     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10876       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10877       return nullptr;
10878     }
10879   }
10880   assert(!R.isAmbiguous() && !R.empty());
10881   NamedDecl *ND = R.getRepresentativeDecl();
10882 
10883   // Check if we have a previous declaration with the same name.
10884   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10885                      ForVisibleRedeclaration);
10886   LookupName(PrevR, S);
10887 
10888   // Check we're not shadowing a template parameter.
10889   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10890     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10891     PrevR.clear();
10892   }
10893 
10894   // Filter out any other lookup result from an enclosing scope.
10895   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10896                        /*AllowInlineNamespace*/false);
10897 
10898   // Find the previous declaration and check that we can redeclare it.
10899   NamespaceAliasDecl *Prev = nullptr;
10900   if (PrevR.isSingleResult()) {
10901     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10902     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10903       // We already have an alias with the same name that points to the same
10904       // namespace; check that it matches.
10905       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10906         Prev = AD;
10907       } else if (isVisible(PrevDecl)) {
10908         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10909           << Alias;
10910         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10911           << AD->getNamespace();
10912         return nullptr;
10913       }
10914     } else if (isVisible(PrevDecl)) {
10915       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10916                             ? diag::err_redefinition
10917                             : diag::err_redefinition_different_kind;
10918       Diag(AliasLoc, DiagID) << Alias;
10919       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10920       return nullptr;
10921     }
10922   }
10923 
10924   // The use of a nested name specifier may trigger deprecation warnings.
10925   DiagnoseUseOfDecl(ND, IdentLoc);
10926 
10927   NamespaceAliasDecl *AliasDecl =
10928     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10929                                Alias, SS.getWithLocInContext(Context),
10930                                IdentLoc, ND);
10931   if (Prev)
10932     AliasDecl->setPreviousDecl(Prev);
10933 
10934   PushOnScopeChains(AliasDecl, S);
10935   return AliasDecl;
10936 }
10937 
10938 namespace {
10939 struct SpecialMemberExceptionSpecInfo
10940     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10941   SourceLocation Loc;
10942   Sema::ImplicitExceptionSpecification ExceptSpec;
10943 
10944   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10945                                  Sema::CXXSpecialMember CSM,
10946                                  Sema::InheritedConstructorInfo *ICI,
10947                                  SourceLocation Loc)
10948       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10949 
10950   bool visitBase(CXXBaseSpecifier *Base);
10951   bool visitField(FieldDecl *FD);
10952 
10953   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10954                            unsigned Quals);
10955 
10956   void visitSubobjectCall(Subobject Subobj,
10957                           Sema::SpecialMemberOverloadResult SMOR);
10958 };
10959 }
10960 
10961 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10962   auto *RT = Base->getType()->getAs<RecordType>();
10963   if (!RT)
10964     return false;
10965 
10966   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10967   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10968   if (auto *BaseCtor = SMOR.getMethod()) {
10969     visitSubobjectCall(Base, BaseCtor);
10970     return false;
10971   }
10972 
10973   visitClassSubobject(BaseClass, Base, 0);
10974   return false;
10975 }
10976 
10977 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10978   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10979     Expr *E = FD->getInClassInitializer();
10980     if (!E)
10981       // FIXME: It's a little wasteful to build and throw away a
10982       // CXXDefaultInitExpr here.
10983       // FIXME: We should have a single context note pointing at Loc, and
10984       // this location should be MD->getLocation() instead, since that's
10985       // the location where we actually use the default init expression.
10986       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10987     if (E)
10988       ExceptSpec.CalledExpr(E);
10989   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10990                             ->getAs<RecordType>()) {
10991     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10992                         FD->getType().getCVRQualifiers());
10993   }
10994   return false;
10995 }
10996 
10997 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10998                                                          Subobject Subobj,
10999                                                          unsigned Quals) {
11000   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
11001   bool IsMutable = Field && Field->isMutable();
11002   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
11003 }
11004 
11005 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
11006     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
11007   // Note, if lookup fails, it doesn't matter what exception specification we
11008   // choose because the special member will be deleted.
11009   if (CXXMethodDecl *MD = SMOR.getMethod())
11010     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
11011 }
11012 
11013 namespace {
11014 /// RAII object to register a special member as being currently declared.
11015 struct ComputingExceptionSpec {
11016   Sema &S;
11017 
11018   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
11019       : S(S) {
11020     Sema::CodeSynthesisContext Ctx;
11021     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
11022     Ctx.PointOfInstantiation = Loc;
11023     Ctx.Entity = MD;
11024     S.pushCodeSynthesisContext(Ctx);
11025   }
11026   ~ComputingExceptionSpec() {
11027     S.popCodeSynthesisContext();
11028   }
11029 };
11030 }
11031 
11032 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
11033   llvm::APSInt Result;
11034   ExprResult Converted = CheckConvertedConstantExpression(
11035       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
11036   ExplicitSpec.setExpr(Converted.get());
11037   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
11038     ExplicitSpec.setKind(Result.getBoolValue()
11039                              ? ExplicitSpecKind::ResolvedTrue
11040                              : ExplicitSpecKind::ResolvedFalse);
11041     return true;
11042   }
11043   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
11044   return false;
11045 }
11046 
11047 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
11048   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
11049   if (!ExplicitExpr->isTypeDependent())
11050     tryResolveExplicitSpecifier(ES);
11051   return ES;
11052 }
11053 
11054 static Sema::ImplicitExceptionSpecification
11055 ComputeDefaultedSpecialMemberExceptionSpec(
11056     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
11057     Sema::InheritedConstructorInfo *ICI) {
11058   ComputingExceptionSpec CES(S, MD, Loc);
11059 
11060   CXXRecordDecl *ClassDecl = MD->getParent();
11061 
11062   // C++ [except.spec]p14:
11063   //   An implicitly declared special member function (Clause 12) shall have an
11064   //   exception-specification. [...]
11065   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
11066   if (ClassDecl->isInvalidDecl())
11067     return Info.ExceptSpec;
11068 
11069   // FIXME: If this diagnostic fires, we're probably missing a check for
11070   // attempting to resolve an exception specification before it's known
11071   // at a higher level.
11072   if (S.RequireCompleteType(MD->getLocation(),
11073                             S.Context.getRecordType(ClassDecl),
11074                             diag::err_exception_spec_incomplete_type))
11075     return Info.ExceptSpec;
11076 
11077   // C++1z [except.spec]p7:
11078   //   [Look for exceptions thrown by] a constructor selected [...] to
11079   //   initialize a potentially constructed subobject,
11080   // C++1z [except.spec]p8:
11081   //   The exception specification for an implicitly-declared destructor, or a
11082   //   destructor without a noexcept-specifier, is potentially-throwing if and
11083   //   only if any of the destructors for any of its potentially constructed
11084   //   subojects is potentially throwing.
11085   // FIXME: We respect the first rule but ignore the "potentially constructed"
11086   // in the second rule to resolve a core issue (no number yet) that would have
11087   // us reject:
11088   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
11089   //   struct B : A {};
11090   //   struct C : B { void f(); };
11091   // ... due to giving B::~B() a non-throwing exception specification.
11092   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
11093                                 : Info.VisitAllBases);
11094 
11095   return Info.ExceptSpec;
11096 }
11097 
11098 namespace {
11099 /// RAII object to register a special member as being currently declared.
11100 struct DeclaringSpecialMember {
11101   Sema &S;
11102   Sema::SpecialMemberDecl D;
11103   Sema::ContextRAII SavedContext;
11104   bool WasAlreadyBeingDeclared;
11105 
11106   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
11107       : S(S), D(RD, CSM), SavedContext(S, RD) {
11108     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
11109     if (WasAlreadyBeingDeclared)
11110       // This almost never happens, but if it does, ensure that our cache
11111       // doesn't contain a stale result.
11112       S.SpecialMemberCache.clear();
11113     else {
11114       // Register a note to be produced if we encounter an error while
11115       // declaring the special member.
11116       Sema::CodeSynthesisContext Ctx;
11117       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
11118       // FIXME: We don't have a location to use here. Using the class's
11119       // location maintains the fiction that we declare all special members
11120       // with the class, but (1) it's not clear that lying about that helps our
11121       // users understand what's going on, and (2) there may be outer contexts
11122       // on the stack (some of which are relevant) and printing them exposes
11123       // our lies.
11124       Ctx.PointOfInstantiation = RD->getLocation();
11125       Ctx.Entity = RD;
11126       Ctx.SpecialMember = CSM;
11127       S.pushCodeSynthesisContext(Ctx);
11128     }
11129   }
11130   ~DeclaringSpecialMember() {
11131     if (!WasAlreadyBeingDeclared) {
11132       S.SpecialMembersBeingDeclared.erase(D);
11133       S.popCodeSynthesisContext();
11134     }
11135   }
11136 
11137   /// Are we already trying to declare this special member?
11138   bool isAlreadyBeingDeclared() const {
11139     return WasAlreadyBeingDeclared;
11140   }
11141 };
11142 }
11143 
11144 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
11145   // Look up any existing declarations, but don't trigger declaration of all
11146   // implicit special members with this name.
11147   DeclarationName Name = FD->getDeclName();
11148   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
11149                  ForExternalRedeclaration);
11150   for (auto *D : FD->getParent()->lookup(Name))
11151     if (auto *Acceptable = R.getAcceptableDecl(D))
11152       R.addDecl(Acceptable);
11153   R.resolveKind();
11154   R.suppressDiagnostics();
11155 
11156   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11157 }
11158 
11159 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11160                                           QualType ResultTy,
11161                                           ArrayRef<QualType> Args) {
11162   // Build an exception specification pointing back at this constructor.
11163   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11164 
11165   if (getLangOpts().OpenCLCPlusPlus) {
11166     // OpenCL: Implicitly defaulted special member are of the generic address
11167     // space.
11168     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11169   }
11170 
11171   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11172   SpecialMem->setType(QT);
11173 }
11174 
11175 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11176                                                      CXXRecordDecl *ClassDecl) {
11177   // C++ [class.ctor]p5:
11178   //   A default constructor for a class X is a constructor of class X
11179   //   that can be called without an argument. If there is no
11180   //   user-declared constructor for class X, a default constructor is
11181   //   implicitly declared. An implicitly-declared default constructor
11182   //   is an inline public member of its class.
11183   assert(ClassDecl->needsImplicitDefaultConstructor() &&
11184          "Should not build implicit default constructor!");
11185 
11186   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11187   if (DSM.isAlreadyBeingDeclared())
11188     return nullptr;
11189 
11190   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11191                                                      CXXDefaultConstructor,
11192                                                      false);
11193 
11194   // Create the actual constructor declaration.
11195   CanQualType ClassType
11196     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11197   SourceLocation ClassLoc = ClassDecl->getLocation();
11198   DeclarationName Name
11199     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11200   DeclarationNameInfo NameInfo(Name, ClassLoc);
11201   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11202       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11203       /*TInfo=*/nullptr, ExplicitSpecifier(),
11204       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11205       Constexpr ? CSK_constexpr : CSK_unspecified);
11206   DefaultCon->setAccess(AS_public);
11207   DefaultCon->setDefaulted();
11208 
11209   if (getLangOpts().CUDA) {
11210     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11211                                             DefaultCon,
11212                                             /* ConstRHS */ false,
11213                                             /* Diagnose */ false);
11214   }
11215 
11216   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11217 
11218   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11219   // constructors is easy to compute.
11220   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11221 
11222   // Note that we have declared this constructor.
11223   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11224 
11225   Scope *S = getScopeForContext(ClassDecl);
11226   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11227 
11228   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11229     SetDeclDeleted(DefaultCon, ClassLoc);
11230 
11231   if (S)
11232     PushOnScopeChains(DefaultCon, S, false);
11233   ClassDecl->addDecl(DefaultCon);
11234 
11235   return DefaultCon;
11236 }
11237 
11238 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11239                                             CXXConstructorDecl *Constructor) {
11240   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11241           !Constructor->doesThisDeclarationHaveABody() &&
11242           !Constructor->isDeleted()) &&
11243     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11244   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11245     return;
11246 
11247   CXXRecordDecl *ClassDecl = Constructor->getParent();
11248   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11249 
11250   SynthesizedFunctionScope Scope(*this, Constructor);
11251 
11252   // The exception specification is needed because we are defining the
11253   // function.
11254   ResolveExceptionSpec(CurrentLocation,
11255                        Constructor->getType()->castAs<FunctionProtoType>());
11256   MarkVTableUsed(CurrentLocation, ClassDecl);
11257 
11258   // Add a context note for diagnostics produced after this point.
11259   Scope.addContextNote(CurrentLocation);
11260 
11261   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11262     Constructor->setInvalidDecl();
11263     return;
11264   }
11265 
11266   SourceLocation Loc = Constructor->getEndLoc().isValid()
11267                            ? Constructor->getEndLoc()
11268                            : Constructor->getLocation();
11269   Constructor->setBody(new (Context) CompoundStmt(Loc));
11270   Constructor->markUsed(Context);
11271 
11272   if (ASTMutationListener *L = getASTMutationListener()) {
11273     L->CompletedImplicitDefinition(Constructor);
11274   }
11275 
11276   DiagnoseUninitializedFields(*this, Constructor);
11277 }
11278 
11279 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11280   // Perform any delayed checks on exception specifications.
11281   CheckDelayedMemberExceptionSpecs();
11282 }
11283 
11284 /// Find or create the fake constructor we synthesize to model constructing an
11285 /// object of a derived class via a constructor of a base class.
11286 CXXConstructorDecl *
11287 Sema::findInheritingConstructor(SourceLocation Loc,
11288                                 CXXConstructorDecl *BaseCtor,
11289                                 ConstructorUsingShadowDecl *Shadow) {
11290   CXXRecordDecl *Derived = Shadow->getParent();
11291   SourceLocation UsingLoc = Shadow->getLocation();
11292 
11293   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11294   // For now we use the name of the base class constructor as a member of the
11295   // derived class to indicate a (fake) inherited constructor name.
11296   DeclarationName Name = BaseCtor->getDeclName();
11297 
11298   // Check to see if we already have a fake constructor for this inherited
11299   // constructor call.
11300   for (NamedDecl *Ctor : Derived->lookup(Name))
11301     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11302                                ->getInheritedConstructor()
11303                                .getConstructor(),
11304                            BaseCtor))
11305       return cast<CXXConstructorDecl>(Ctor);
11306 
11307   DeclarationNameInfo NameInfo(Name, UsingLoc);
11308   TypeSourceInfo *TInfo =
11309       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11310   FunctionProtoTypeLoc ProtoLoc =
11311       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11312 
11313   // Check the inherited constructor is valid and find the list of base classes
11314   // from which it was inherited.
11315   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11316 
11317   bool Constexpr =
11318       BaseCtor->isConstexpr() &&
11319       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11320                                         false, BaseCtor, &ICI);
11321 
11322   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11323       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11324       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11325       /*isImplicitlyDeclared=*/true,
11326       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11327       InheritedConstructor(Shadow, BaseCtor));
11328   if (Shadow->isInvalidDecl())
11329     DerivedCtor->setInvalidDecl();
11330 
11331   // Build an unevaluated exception specification for this fake constructor.
11332   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11333   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11334   EPI.ExceptionSpec.Type = EST_Unevaluated;
11335   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11336   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11337                                                FPT->getParamTypes(), EPI));
11338 
11339   // Build the parameter declarations.
11340   SmallVector<ParmVarDecl *, 16> ParamDecls;
11341   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11342     TypeSourceInfo *TInfo =
11343         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11344     ParmVarDecl *PD = ParmVarDecl::Create(
11345         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11346         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11347     PD->setScopeInfo(0, I);
11348     PD->setImplicit();
11349     // Ensure attributes are propagated onto parameters (this matters for
11350     // format, pass_object_size, ...).
11351     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11352     ParamDecls.push_back(PD);
11353     ProtoLoc.setParam(I, PD);
11354   }
11355 
11356   // Set up the new constructor.
11357   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11358   DerivedCtor->setAccess(BaseCtor->getAccess());
11359   DerivedCtor->setParams(ParamDecls);
11360   Derived->addDecl(DerivedCtor);
11361 
11362   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11363     SetDeclDeleted(DerivedCtor, UsingLoc);
11364 
11365   return DerivedCtor;
11366 }
11367 
11368 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11369   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11370                                Ctor->getInheritedConstructor().getShadowDecl());
11371   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11372                             /*Diagnose*/true);
11373 }
11374 
11375 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11376                                        CXXConstructorDecl *Constructor) {
11377   CXXRecordDecl *ClassDecl = Constructor->getParent();
11378   assert(Constructor->getInheritedConstructor() &&
11379          !Constructor->doesThisDeclarationHaveABody() &&
11380          !Constructor->isDeleted());
11381   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11382     return;
11383 
11384   // Initializations are performed "as if by a defaulted default constructor",
11385   // so enter the appropriate scope.
11386   SynthesizedFunctionScope Scope(*this, Constructor);
11387 
11388   // The exception specification is needed because we are defining the
11389   // function.
11390   ResolveExceptionSpec(CurrentLocation,
11391                        Constructor->getType()->castAs<FunctionProtoType>());
11392   MarkVTableUsed(CurrentLocation, ClassDecl);
11393 
11394   // Add a context note for diagnostics produced after this point.
11395   Scope.addContextNote(CurrentLocation);
11396 
11397   ConstructorUsingShadowDecl *Shadow =
11398       Constructor->getInheritedConstructor().getShadowDecl();
11399   CXXConstructorDecl *InheritedCtor =
11400       Constructor->getInheritedConstructor().getConstructor();
11401 
11402   // [class.inhctor.init]p1:
11403   //   initialization proceeds as if a defaulted default constructor is used to
11404   //   initialize the D object and each base class subobject from which the
11405   //   constructor was inherited
11406 
11407   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11408   CXXRecordDecl *RD = Shadow->getParent();
11409   SourceLocation InitLoc = Shadow->getLocation();
11410 
11411   // Build explicit initializers for all base classes from which the
11412   // constructor was inherited.
11413   SmallVector<CXXCtorInitializer*, 8> Inits;
11414   for (bool VBase : {false, true}) {
11415     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11416       if (B.isVirtual() != VBase)
11417         continue;
11418 
11419       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11420       if (!BaseRD)
11421         continue;
11422 
11423       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11424       if (!BaseCtor.first)
11425         continue;
11426 
11427       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11428       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11429           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11430 
11431       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11432       Inits.push_back(new (Context) CXXCtorInitializer(
11433           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11434           SourceLocation()));
11435     }
11436   }
11437 
11438   // We now proceed as if for a defaulted default constructor, with the relevant
11439   // initializers replaced.
11440 
11441   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11442     Constructor->setInvalidDecl();
11443     return;
11444   }
11445 
11446   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11447   Constructor->markUsed(Context);
11448 
11449   if (ASTMutationListener *L = getASTMutationListener()) {
11450     L->CompletedImplicitDefinition(Constructor);
11451   }
11452 
11453   DiagnoseUninitializedFields(*this, Constructor);
11454 }
11455 
11456 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11457   // C++ [class.dtor]p2:
11458   //   If a class has no user-declared destructor, a destructor is
11459   //   declared implicitly. An implicitly-declared destructor is an
11460   //   inline public member of its class.
11461   assert(ClassDecl->needsImplicitDestructor());
11462 
11463   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11464   if (DSM.isAlreadyBeingDeclared())
11465     return nullptr;
11466 
11467   // Create the actual destructor declaration.
11468   CanQualType ClassType
11469     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11470   SourceLocation ClassLoc = ClassDecl->getLocation();
11471   DeclarationName Name
11472     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11473   DeclarationNameInfo NameInfo(Name, ClassLoc);
11474   CXXDestructorDecl *Destructor
11475       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11476                                   QualType(), nullptr, /*isInline=*/true,
11477                                   /*isImplicitlyDeclared=*/true);
11478   Destructor->setAccess(AS_public);
11479   Destructor->setDefaulted();
11480 
11481   if (getLangOpts().CUDA) {
11482     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11483                                             Destructor,
11484                                             /* ConstRHS */ false,
11485                                             /* Diagnose */ false);
11486   }
11487 
11488   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11489 
11490   // We don't need to use SpecialMemberIsTrivial here; triviality for
11491   // destructors is easy to compute.
11492   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11493   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11494                                 ClassDecl->hasTrivialDestructorForCall());
11495 
11496   // Note that we have declared this destructor.
11497   ++getASTContext().NumImplicitDestructorsDeclared;
11498 
11499   Scope *S = getScopeForContext(ClassDecl);
11500   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11501 
11502   // We can't check whether an implicit destructor is deleted before we complete
11503   // the definition of the class, because its validity depends on the alignment
11504   // of the class. We'll check this from ActOnFields once the class is complete.
11505   if (ClassDecl->isCompleteDefinition() &&
11506       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11507     SetDeclDeleted(Destructor, ClassLoc);
11508 
11509   // Introduce this destructor into its scope.
11510   if (S)
11511     PushOnScopeChains(Destructor, S, false);
11512   ClassDecl->addDecl(Destructor);
11513 
11514   return Destructor;
11515 }
11516 
11517 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11518                                     CXXDestructorDecl *Destructor) {
11519   assert((Destructor->isDefaulted() &&
11520           !Destructor->doesThisDeclarationHaveABody() &&
11521           !Destructor->isDeleted()) &&
11522          "DefineImplicitDestructor - call it for implicit default dtor");
11523   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11524     return;
11525 
11526   CXXRecordDecl *ClassDecl = Destructor->getParent();
11527   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11528 
11529   SynthesizedFunctionScope Scope(*this, Destructor);
11530 
11531   // The exception specification is needed because we are defining the
11532   // function.
11533   ResolveExceptionSpec(CurrentLocation,
11534                        Destructor->getType()->castAs<FunctionProtoType>());
11535   MarkVTableUsed(CurrentLocation, ClassDecl);
11536 
11537   // Add a context note for diagnostics produced after this point.
11538   Scope.addContextNote(CurrentLocation);
11539 
11540   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11541                                          Destructor->getParent());
11542 
11543   if (CheckDestructor(Destructor)) {
11544     Destructor->setInvalidDecl();
11545     return;
11546   }
11547 
11548   SourceLocation Loc = Destructor->getEndLoc().isValid()
11549                            ? Destructor->getEndLoc()
11550                            : Destructor->getLocation();
11551   Destructor->setBody(new (Context) CompoundStmt(Loc));
11552   Destructor->markUsed(Context);
11553 
11554   if (ASTMutationListener *L = getASTMutationListener()) {
11555     L->CompletedImplicitDefinition(Destructor);
11556   }
11557 }
11558 
11559 /// Perform any semantic analysis which needs to be delayed until all
11560 /// pending class member declarations have been parsed.
11561 void Sema::ActOnFinishCXXMemberDecls() {
11562   // If the context is an invalid C++ class, just suppress these checks.
11563   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11564     if (Record->isInvalidDecl()) {
11565       DelayedOverridingExceptionSpecChecks.clear();
11566       DelayedEquivalentExceptionSpecChecks.clear();
11567       return;
11568     }
11569     checkForMultipleExportedDefaultConstructors(*this, Record);
11570   }
11571 }
11572 
11573 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11574   referenceDLLExportedClassMethods();
11575 
11576   if (!DelayedDllExportMemberFunctions.empty()) {
11577     SmallVector<CXXMethodDecl*, 4> WorkList;
11578     std::swap(DelayedDllExportMemberFunctions, WorkList);
11579     for (CXXMethodDecl *M : WorkList) {
11580       DefineImplicitSpecialMember(*this, M, M->getLocation());
11581 
11582       // Pass the method to the consumer to get emitted. This is not necessary
11583       // for explicit instantiation definitions, as they will get emitted
11584       // anyway.
11585       if (M->getParent()->getTemplateSpecializationKind() !=
11586           TSK_ExplicitInstantiationDefinition)
11587         ActOnFinishInlineFunctionDef(M);
11588     }
11589   }
11590 }
11591 
11592 void Sema::referenceDLLExportedClassMethods() {
11593   if (!DelayedDllExportClasses.empty()) {
11594     // Calling ReferenceDllExportedMembers might cause the current function to
11595     // be called again, so use a local copy of DelayedDllExportClasses.
11596     SmallVector<CXXRecordDecl *, 4> WorkList;
11597     std::swap(DelayedDllExportClasses, WorkList);
11598     for (CXXRecordDecl *Class : WorkList)
11599       ReferenceDllExportedMembers(*this, Class);
11600   }
11601 }
11602 
11603 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11604   assert(getLangOpts().CPlusPlus11 &&
11605          "adjusting dtor exception specs was introduced in c++11");
11606 
11607   if (Destructor->isDependentContext())
11608     return;
11609 
11610   // C++11 [class.dtor]p3:
11611   //   A declaration of a destructor that does not have an exception-
11612   //   specification is implicitly considered to have the same exception-
11613   //   specification as an implicit declaration.
11614   const FunctionProtoType *DtorType = Destructor->getType()->
11615                                         getAs<FunctionProtoType>();
11616   if (DtorType->hasExceptionSpec())
11617     return;
11618 
11619   // Replace the destructor's type, building off the existing one. Fortunately,
11620   // the only thing of interest in the destructor type is its extended info.
11621   // The return and arguments are fixed.
11622   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11623   EPI.ExceptionSpec.Type = EST_Unevaluated;
11624   EPI.ExceptionSpec.SourceDecl = Destructor;
11625   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11626 
11627   // FIXME: If the destructor has a body that could throw, and the newly created
11628   // spec doesn't allow exceptions, we should emit a warning, because this
11629   // change in behavior can break conforming C++03 programs at runtime.
11630   // However, we don't have a body or an exception specification yet, so it
11631   // needs to be done somewhere else.
11632 }
11633 
11634 namespace {
11635 /// An abstract base class for all helper classes used in building the
11636 //  copy/move operators. These classes serve as factory functions and help us
11637 //  avoid using the same Expr* in the AST twice.
11638 class ExprBuilder {
11639   ExprBuilder(const ExprBuilder&) = delete;
11640   ExprBuilder &operator=(const ExprBuilder&) = delete;
11641 
11642 protected:
11643   static Expr *assertNotNull(Expr *E) {
11644     assert(E && "Expression construction must not fail.");
11645     return E;
11646   }
11647 
11648 public:
11649   ExprBuilder() {}
11650   virtual ~ExprBuilder() {}
11651 
11652   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11653 };
11654 
11655 class RefBuilder: public ExprBuilder {
11656   VarDecl *Var;
11657   QualType VarType;
11658 
11659 public:
11660   Expr *build(Sema &S, SourceLocation Loc) const override {
11661     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11662   }
11663 
11664   RefBuilder(VarDecl *Var, QualType VarType)
11665       : Var(Var), VarType(VarType) {}
11666 };
11667 
11668 class ThisBuilder: public ExprBuilder {
11669 public:
11670   Expr *build(Sema &S, SourceLocation Loc) const override {
11671     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11672   }
11673 };
11674 
11675 class CastBuilder: public ExprBuilder {
11676   const ExprBuilder &Builder;
11677   QualType Type;
11678   ExprValueKind Kind;
11679   const CXXCastPath &Path;
11680 
11681 public:
11682   Expr *build(Sema &S, SourceLocation Loc) const override {
11683     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11684                                              CK_UncheckedDerivedToBase, Kind,
11685                                              &Path).get());
11686   }
11687 
11688   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11689               const CXXCastPath &Path)
11690       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11691 };
11692 
11693 class DerefBuilder: public ExprBuilder {
11694   const ExprBuilder &Builder;
11695 
11696 public:
11697   Expr *build(Sema &S, SourceLocation Loc) const override {
11698     return assertNotNull(
11699         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11700   }
11701 
11702   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11703 };
11704 
11705 class MemberBuilder: public ExprBuilder {
11706   const ExprBuilder &Builder;
11707   QualType Type;
11708   CXXScopeSpec SS;
11709   bool IsArrow;
11710   LookupResult &MemberLookup;
11711 
11712 public:
11713   Expr *build(Sema &S, SourceLocation Loc) const override {
11714     return assertNotNull(S.BuildMemberReferenceExpr(
11715         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11716         nullptr, MemberLookup, nullptr, nullptr).get());
11717   }
11718 
11719   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11720                 LookupResult &MemberLookup)
11721       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11722         MemberLookup(MemberLookup) {}
11723 };
11724 
11725 class MoveCastBuilder: public ExprBuilder {
11726   const ExprBuilder &Builder;
11727 
11728 public:
11729   Expr *build(Sema &S, SourceLocation Loc) const override {
11730     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11731   }
11732 
11733   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11734 };
11735 
11736 class LvalueConvBuilder: public ExprBuilder {
11737   const ExprBuilder &Builder;
11738 
11739 public:
11740   Expr *build(Sema &S, SourceLocation Loc) const override {
11741     return assertNotNull(
11742         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11743   }
11744 
11745   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11746 };
11747 
11748 class SubscriptBuilder: public ExprBuilder {
11749   const ExprBuilder &Base;
11750   const ExprBuilder &Index;
11751 
11752 public:
11753   Expr *build(Sema &S, SourceLocation Loc) const override {
11754     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11755         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11756   }
11757 
11758   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11759       : Base(Base), Index(Index) {}
11760 };
11761 
11762 } // end anonymous namespace
11763 
11764 /// When generating a defaulted copy or move assignment operator, if a field
11765 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11766 /// do so. This optimization only applies for arrays of scalars, and for arrays
11767 /// of class type where the selected copy/move-assignment operator is trivial.
11768 static StmtResult
11769 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11770                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11771   // Compute the size of the memory buffer to be copied.
11772   QualType SizeType = S.Context.getSizeType();
11773   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11774                    S.Context.getTypeSizeInChars(T).getQuantity());
11775 
11776   // Take the address of the field references for "from" and "to". We
11777   // directly construct UnaryOperators here because semantic analysis
11778   // does not permit us to take the address of an xvalue.
11779   Expr *From = FromB.build(S, Loc);
11780   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11781                          S.Context.getPointerType(From->getType()),
11782                          VK_RValue, OK_Ordinary, Loc, false);
11783   Expr *To = ToB.build(S, Loc);
11784   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11785                        S.Context.getPointerType(To->getType()),
11786                        VK_RValue, OK_Ordinary, Loc, false);
11787 
11788   const Type *E = T->getBaseElementTypeUnsafe();
11789   bool NeedsCollectableMemCpy =
11790     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11791 
11792   // Create a reference to the __builtin_objc_memmove_collectable function
11793   StringRef MemCpyName = NeedsCollectableMemCpy ?
11794     "__builtin_objc_memmove_collectable" :
11795     "__builtin_memcpy";
11796   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11797                  Sema::LookupOrdinaryName);
11798   S.LookupName(R, S.TUScope, true);
11799 
11800   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11801   if (!MemCpy)
11802     // Something went horribly wrong earlier, and we will have complained
11803     // about it.
11804     return StmtError();
11805 
11806   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11807                                             VK_RValue, Loc, nullptr);
11808   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11809 
11810   Expr *CallArgs[] = {
11811     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11812   };
11813   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11814                                     Loc, CallArgs, Loc);
11815 
11816   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11817   return Call.getAs<Stmt>();
11818 }
11819 
11820 /// Builds a statement that copies/moves the given entity from \p From to
11821 /// \c To.
11822 ///
11823 /// This routine is used to copy/move the members of a class with an
11824 /// implicitly-declared copy/move assignment operator. When the entities being
11825 /// copied are arrays, this routine builds for loops to copy them.
11826 ///
11827 /// \param S The Sema object used for type-checking.
11828 ///
11829 /// \param Loc The location where the implicit copy/move is being generated.
11830 ///
11831 /// \param T The type of the expressions being copied/moved. Both expressions
11832 /// must have this type.
11833 ///
11834 /// \param To The expression we are copying/moving to.
11835 ///
11836 /// \param From The expression we are copying/moving from.
11837 ///
11838 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11839 /// Otherwise, it's a non-static member subobject.
11840 ///
11841 /// \param Copying Whether we're copying or moving.
11842 ///
11843 /// \param Depth Internal parameter recording the depth of the recursion.
11844 ///
11845 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11846 /// if a memcpy should be used instead.
11847 static StmtResult
11848 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11849                                  const ExprBuilder &To, const ExprBuilder &From,
11850                                  bool CopyingBaseSubobject, bool Copying,
11851                                  unsigned Depth = 0) {
11852   // C++11 [class.copy]p28:
11853   //   Each subobject is assigned in the manner appropriate to its type:
11854   //
11855   //     - if the subobject is of class type, as if by a call to operator= with
11856   //       the subobject as the object expression and the corresponding
11857   //       subobject of x as a single function argument (as if by explicit
11858   //       qualification; that is, ignoring any possible virtual overriding
11859   //       functions in more derived classes);
11860   //
11861   // C++03 [class.copy]p13:
11862   //     - if the subobject is of class type, the copy assignment operator for
11863   //       the class is used (as if by explicit qualification; that is,
11864   //       ignoring any possible virtual overriding functions in more derived
11865   //       classes);
11866   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11867     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11868 
11869     // Look for operator=.
11870     DeclarationName Name
11871       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11872     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11873     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11874 
11875     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11876     // operator.
11877     if (!S.getLangOpts().CPlusPlus11) {
11878       LookupResult::Filter F = OpLookup.makeFilter();
11879       while (F.hasNext()) {
11880         NamedDecl *D = F.next();
11881         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11882           if (Method->isCopyAssignmentOperator() ||
11883               (!Copying && Method->isMoveAssignmentOperator()))
11884             continue;
11885 
11886         F.erase();
11887       }
11888       F.done();
11889     }
11890 
11891     // Suppress the protected check (C++ [class.protected]) for each of the
11892     // assignment operators we found. This strange dance is required when
11893     // we're assigning via a base classes's copy-assignment operator. To
11894     // ensure that we're getting the right base class subobject (without
11895     // ambiguities), we need to cast "this" to that subobject type; to
11896     // ensure that we don't go through the virtual call mechanism, we need
11897     // to qualify the operator= name with the base class (see below). However,
11898     // this means that if the base class has a protected copy assignment
11899     // operator, the protected member access check will fail. So, we
11900     // rewrite "protected" access to "public" access in this case, since we
11901     // know by construction that we're calling from a derived class.
11902     if (CopyingBaseSubobject) {
11903       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11904            L != LEnd; ++L) {
11905         if (L.getAccess() == AS_protected)
11906           L.setAccess(AS_public);
11907       }
11908     }
11909 
11910     // Create the nested-name-specifier that will be used to qualify the
11911     // reference to operator=; this is required to suppress the virtual
11912     // call mechanism.
11913     CXXScopeSpec SS;
11914     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11915     SS.MakeTrivial(S.Context,
11916                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11917                                                CanonicalT),
11918                    Loc);
11919 
11920     // Create the reference to operator=.
11921     ExprResult OpEqualRef
11922       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11923                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11924                                    /*FirstQualifierInScope=*/nullptr,
11925                                    OpLookup,
11926                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11927                                    /*SuppressQualifierCheck=*/true);
11928     if (OpEqualRef.isInvalid())
11929       return StmtError();
11930 
11931     // Build the call to the assignment operator.
11932 
11933     Expr *FromInst = From.build(S, Loc);
11934     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11935                                                   OpEqualRef.getAs<Expr>(),
11936                                                   Loc, FromInst, Loc);
11937     if (Call.isInvalid())
11938       return StmtError();
11939 
11940     // If we built a call to a trivial 'operator=' while copying an array,
11941     // bail out. We'll replace the whole shebang with a memcpy.
11942     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11943     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11944       return StmtResult((Stmt*)nullptr);
11945 
11946     // Convert to an expression-statement, and clean up any produced
11947     // temporaries.
11948     return S.ActOnExprStmt(Call);
11949   }
11950 
11951   //     - if the subobject is of scalar type, the built-in assignment
11952   //       operator is used.
11953   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11954   if (!ArrayTy) {
11955     ExprResult Assignment = S.CreateBuiltinBinOp(
11956         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11957     if (Assignment.isInvalid())
11958       return StmtError();
11959     return S.ActOnExprStmt(Assignment);
11960   }
11961 
11962   //     - if the subobject is an array, each element is assigned, in the
11963   //       manner appropriate to the element type;
11964 
11965   // Construct a loop over the array bounds, e.g.,
11966   //
11967   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11968   //
11969   // that will copy each of the array elements.
11970   QualType SizeType = S.Context.getSizeType();
11971 
11972   // Create the iteration variable.
11973   IdentifierInfo *IterationVarName = nullptr;
11974   {
11975     SmallString<8> Str;
11976     llvm::raw_svector_ostream OS(Str);
11977     OS << "__i" << Depth;
11978     IterationVarName = &S.Context.Idents.get(OS.str());
11979   }
11980   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11981                                           IterationVarName, SizeType,
11982                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11983                                           SC_None);
11984 
11985   // Initialize the iteration variable to zero.
11986   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11987   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11988 
11989   // Creates a reference to the iteration variable.
11990   RefBuilder IterationVarRef(IterationVar, SizeType);
11991   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11992 
11993   // Create the DeclStmt that holds the iteration variable.
11994   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11995 
11996   // Subscript the "from" and "to" expressions with the iteration variable.
11997   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11998   MoveCastBuilder FromIndexMove(FromIndexCopy);
11999   const ExprBuilder *FromIndex;
12000   if (Copying)
12001     FromIndex = &FromIndexCopy;
12002   else
12003     FromIndex = &FromIndexMove;
12004 
12005   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
12006 
12007   // Build the copy/move for an individual element of the array.
12008   StmtResult Copy =
12009     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
12010                                      ToIndex, *FromIndex, CopyingBaseSubobject,
12011                                      Copying, Depth + 1);
12012   // Bail out if copying fails or if we determined that we should use memcpy.
12013   if (Copy.isInvalid() || !Copy.get())
12014     return Copy;
12015 
12016   // Create the comparison against the array bound.
12017   llvm::APInt Upper
12018     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
12019   Expr *Comparison
12020     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
12021                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
12022                                      BO_NE, S.Context.BoolTy,
12023                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
12024 
12025   // Create the pre-increment of the iteration variable. We can determine
12026   // whether the increment will overflow based on the value of the array
12027   // bound.
12028   Expr *Increment = new (S.Context)
12029       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
12030                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
12031 
12032   // Construct the loop that copies all elements of this array.
12033   return S.ActOnForStmt(
12034       Loc, Loc, InitStmt,
12035       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
12036       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
12037 }
12038 
12039 static StmtResult
12040 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
12041                       const ExprBuilder &To, const ExprBuilder &From,
12042                       bool CopyingBaseSubobject, bool Copying) {
12043   // Maybe we should use a memcpy?
12044   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
12045       T.isTriviallyCopyableType(S.Context))
12046     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12047 
12048   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
12049                                                      CopyingBaseSubobject,
12050                                                      Copying, 0));
12051 
12052   // If we ended up picking a trivial assignment operator for an array of a
12053   // non-trivially-copyable class type, just emit a memcpy.
12054   if (!Result.isInvalid() && !Result.get())
12055     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12056 
12057   return Result;
12058 }
12059 
12060 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
12061   // Note: The following rules are largely analoguous to the copy
12062   // constructor rules. Note that virtual bases are not taken into account
12063   // for determining the argument type of the operator. Note also that
12064   // operators taking an object instead of a reference are allowed.
12065   assert(ClassDecl->needsImplicitCopyAssignment());
12066 
12067   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
12068   if (DSM.isAlreadyBeingDeclared())
12069     return nullptr;
12070 
12071   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12072   if (Context.getLangOpts().OpenCLCPlusPlus)
12073     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12074   QualType RetType = Context.getLValueReferenceType(ArgType);
12075   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
12076   if (Const)
12077     ArgType = ArgType.withConst();
12078 
12079   ArgType = Context.getLValueReferenceType(ArgType);
12080 
12081   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12082                                                      CXXCopyAssignment,
12083                                                      Const);
12084 
12085   //   An implicitly-declared copy assignment operator is an inline public
12086   //   member of its class.
12087   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12088   SourceLocation ClassLoc = ClassDecl->getLocation();
12089   DeclarationNameInfo NameInfo(Name, ClassLoc);
12090   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
12091       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12092       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12093       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12094       SourceLocation());
12095   CopyAssignment->setAccess(AS_public);
12096   CopyAssignment->setDefaulted();
12097   CopyAssignment->setImplicit();
12098 
12099   if (getLangOpts().CUDA) {
12100     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
12101                                             CopyAssignment,
12102                                             /* ConstRHS */ Const,
12103                                             /* Diagnose */ false);
12104   }
12105 
12106   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
12107 
12108   // Add the parameter to the operator.
12109   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
12110                                                ClassLoc, ClassLoc,
12111                                                /*Id=*/nullptr, ArgType,
12112                                                /*TInfo=*/nullptr, SC_None,
12113                                                nullptr);
12114   CopyAssignment->setParams(FromParam);
12115 
12116   CopyAssignment->setTrivial(
12117     ClassDecl->needsOverloadResolutionForCopyAssignment()
12118       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
12119       : ClassDecl->hasTrivialCopyAssignment());
12120 
12121   // Note that we have added this copy-assignment operator.
12122   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
12123 
12124   Scope *S = getScopeForContext(ClassDecl);
12125   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
12126 
12127   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
12128     SetDeclDeleted(CopyAssignment, ClassLoc);
12129 
12130   if (S)
12131     PushOnScopeChains(CopyAssignment, S, false);
12132   ClassDecl->addDecl(CopyAssignment);
12133 
12134   return CopyAssignment;
12135 }
12136 
12137 /// Diagnose an implicit copy operation for a class which is odr-used, but
12138 /// which is deprecated because the class has a user-declared copy constructor,
12139 /// copy assignment operator, or destructor.
12140 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
12141   assert(CopyOp->isImplicit());
12142 
12143   CXXRecordDecl *RD = CopyOp->getParent();
12144   CXXMethodDecl *UserDeclaredOperation = nullptr;
12145 
12146   // In Microsoft mode, assignment operations don't affect constructors and
12147   // vice versa.
12148   if (RD->hasUserDeclaredDestructor()) {
12149     UserDeclaredOperation = RD->getDestructor();
12150   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
12151              RD->hasUserDeclaredCopyConstructor() &&
12152              !S.getLangOpts().MSVCCompat) {
12153     // Find any user-declared copy constructor.
12154     for (auto *I : RD->ctors()) {
12155       if (I->isCopyConstructor()) {
12156         UserDeclaredOperation = I;
12157         break;
12158       }
12159     }
12160     assert(UserDeclaredOperation);
12161   } else if (isa<CXXConstructorDecl>(CopyOp) &&
12162              RD->hasUserDeclaredCopyAssignment() &&
12163              !S.getLangOpts().MSVCCompat) {
12164     // Find any user-declared move assignment operator.
12165     for (auto *I : RD->methods()) {
12166       if (I->isCopyAssignmentOperator()) {
12167         UserDeclaredOperation = I;
12168         break;
12169       }
12170     }
12171     assert(UserDeclaredOperation);
12172   }
12173 
12174   if (UserDeclaredOperation) {
12175     S.Diag(UserDeclaredOperation->getLocation(),
12176          diag::warn_deprecated_copy_operation)
12177       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12178       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12179   }
12180 }
12181 
12182 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12183                                         CXXMethodDecl *CopyAssignOperator) {
12184   assert((CopyAssignOperator->isDefaulted() &&
12185           CopyAssignOperator->isOverloadedOperator() &&
12186           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12187           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12188           !CopyAssignOperator->isDeleted()) &&
12189          "DefineImplicitCopyAssignment called for wrong function");
12190   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12191     return;
12192 
12193   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12194   if (ClassDecl->isInvalidDecl()) {
12195     CopyAssignOperator->setInvalidDecl();
12196     return;
12197   }
12198 
12199   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12200 
12201   // The exception specification is needed because we are defining the
12202   // function.
12203   ResolveExceptionSpec(CurrentLocation,
12204                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12205 
12206   // Add a context note for diagnostics produced after this point.
12207   Scope.addContextNote(CurrentLocation);
12208 
12209   // C++11 [class.copy]p18:
12210   //   The [definition of an implicitly declared copy assignment operator] is
12211   //   deprecated if the class has a user-declared copy constructor or a
12212   //   user-declared destructor.
12213   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12214     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12215 
12216   // C++0x [class.copy]p30:
12217   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12218   //   for a non-union class X performs memberwise copy assignment of its
12219   //   subobjects. The direct base classes of X are assigned first, in the
12220   //   order of their declaration in the base-specifier-list, and then the
12221   //   immediate non-static data members of X are assigned, in the order in
12222   //   which they were declared in the class definition.
12223 
12224   // The statements that form the synthesized function body.
12225   SmallVector<Stmt*, 8> Statements;
12226 
12227   // The parameter for the "other" object, which we are copying from.
12228   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12229   Qualifiers OtherQuals = Other->getType().getQualifiers();
12230   QualType OtherRefType = Other->getType();
12231   if (const LValueReferenceType *OtherRef
12232                                 = OtherRefType->getAs<LValueReferenceType>()) {
12233     OtherRefType = OtherRef->getPointeeType();
12234     OtherQuals = OtherRefType.getQualifiers();
12235   }
12236 
12237   // Our location for everything implicitly-generated.
12238   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12239                            ? CopyAssignOperator->getEndLoc()
12240                            : CopyAssignOperator->getLocation();
12241 
12242   // Builds a DeclRefExpr for the "other" object.
12243   RefBuilder OtherRef(Other, OtherRefType);
12244 
12245   // Builds the "this" pointer.
12246   ThisBuilder This;
12247 
12248   // Assign base classes.
12249   bool Invalid = false;
12250   for (auto &Base : ClassDecl->bases()) {
12251     // Form the assignment:
12252     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12253     QualType BaseType = Base.getType().getUnqualifiedType();
12254     if (!BaseType->isRecordType()) {
12255       Invalid = true;
12256       continue;
12257     }
12258 
12259     CXXCastPath BasePath;
12260     BasePath.push_back(&Base);
12261 
12262     // Construct the "from" expression, which is an implicit cast to the
12263     // appropriately-qualified base type.
12264     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12265                      VK_LValue, BasePath);
12266 
12267     // Dereference "this".
12268     DerefBuilder DerefThis(This);
12269     CastBuilder To(DerefThis,
12270                    Context.getQualifiedType(
12271                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12272                    VK_LValue, BasePath);
12273 
12274     // Build the copy.
12275     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12276                                             To, From,
12277                                             /*CopyingBaseSubobject=*/true,
12278                                             /*Copying=*/true);
12279     if (Copy.isInvalid()) {
12280       CopyAssignOperator->setInvalidDecl();
12281       return;
12282     }
12283 
12284     // Success! Record the copy.
12285     Statements.push_back(Copy.getAs<Expr>());
12286   }
12287 
12288   // Assign non-static members.
12289   for (auto *Field : ClassDecl->fields()) {
12290     // FIXME: We should form some kind of AST representation for the implied
12291     // memcpy in a union copy operation.
12292     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12293       continue;
12294 
12295     if (Field->isInvalidDecl()) {
12296       Invalid = true;
12297       continue;
12298     }
12299 
12300     // Check for members of reference type; we can't copy those.
12301     if (Field->getType()->isReferenceType()) {
12302       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12303         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12304       Diag(Field->getLocation(), diag::note_declared_at);
12305       Invalid = true;
12306       continue;
12307     }
12308 
12309     // Check for members of const-qualified, non-class type.
12310     QualType BaseType = Context.getBaseElementType(Field->getType());
12311     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12312       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12313         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12314       Diag(Field->getLocation(), diag::note_declared_at);
12315       Invalid = true;
12316       continue;
12317     }
12318 
12319     // Suppress assigning zero-width bitfields.
12320     if (Field->isZeroLengthBitField(Context))
12321       continue;
12322 
12323     QualType FieldType = Field->getType().getNonReferenceType();
12324     if (FieldType->isIncompleteArrayType()) {
12325       assert(ClassDecl->hasFlexibleArrayMember() &&
12326              "Incomplete array type is not valid");
12327       continue;
12328     }
12329 
12330     // Build references to the field in the object we're copying from and to.
12331     CXXScopeSpec SS; // Intentionally empty
12332     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12333                               LookupMemberName);
12334     MemberLookup.addDecl(Field);
12335     MemberLookup.resolveKind();
12336 
12337     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12338 
12339     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12340 
12341     // Build the copy of this field.
12342     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12343                                             To, From,
12344                                             /*CopyingBaseSubobject=*/false,
12345                                             /*Copying=*/true);
12346     if (Copy.isInvalid()) {
12347       CopyAssignOperator->setInvalidDecl();
12348       return;
12349     }
12350 
12351     // Success! Record the copy.
12352     Statements.push_back(Copy.getAs<Stmt>());
12353   }
12354 
12355   if (!Invalid) {
12356     // Add a "return *this;"
12357     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12358 
12359     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12360     if (Return.isInvalid())
12361       Invalid = true;
12362     else
12363       Statements.push_back(Return.getAs<Stmt>());
12364   }
12365 
12366   if (Invalid) {
12367     CopyAssignOperator->setInvalidDecl();
12368     return;
12369   }
12370 
12371   StmtResult Body;
12372   {
12373     CompoundScopeRAII CompoundScope(*this);
12374     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12375                              /*isStmtExpr=*/false);
12376     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12377   }
12378   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12379   CopyAssignOperator->markUsed(Context);
12380 
12381   if (ASTMutationListener *L = getASTMutationListener()) {
12382     L->CompletedImplicitDefinition(CopyAssignOperator);
12383   }
12384 }
12385 
12386 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12387   assert(ClassDecl->needsImplicitMoveAssignment());
12388 
12389   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12390   if (DSM.isAlreadyBeingDeclared())
12391     return nullptr;
12392 
12393   // Note: The following rules are largely analoguous to the move
12394   // constructor rules.
12395 
12396   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12397   if (Context.getLangOpts().OpenCLCPlusPlus)
12398     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12399   QualType RetType = Context.getLValueReferenceType(ArgType);
12400   ArgType = Context.getRValueReferenceType(ArgType);
12401 
12402   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12403                                                      CXXMoveAssignment,
12404                                                      false);
12405 
12406   //   An implicitly-declared move assignment operator is an inline public
12407   //   member of its class.
12408   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12409   SourceLocation ClassLoc = ClassDecl->getLocation();
12410   DeclarationNameInfo NameInfo(Name, ClassLoc);
12411   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12412       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12413       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12414       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12415       SourceLocation());
12416   MoveAssignment->setAccess(AS_public);
12417   MoveAssignment->setDefaulted();
12418   MoveAssignment->setImplicit();
12419 
12420   if (getLangOpts().CUDA) {
12421     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12422                                             MoveAssignment,
12423                                             /* ConstRHS */ false,
12424                                             /* Diagnose */ false);
12425   }
12426 
12427   // Build an exception specification pointing back at this member.
12428   FunctionProtoType::ExtProtoInfo EPI =
12429       getImplicitMethodEPI(*this, MoveAssignment);
12430   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12431 
12432   // Add the parameter to the operator.
12433   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12434                                                ClassLoc, ClassLoc,
12435                                                /*Id=*/nullptr, ArgType,
12436                                                /*TInfo=*/nullptr, SC_None,
12437                                                nullptr);
12438   MoveAssignment->setParams(FromParam);
12439 
12440   MoveAssignment->setTrivial(
12441     ClassDecl->needsOverloadResolutionForMoveAssignment()
12442       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12443       : ClassDecl->hasTrivialMoveAssignment());
12444 
12445   // Note that we have added this copy-assignment operator.
12446   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12447 
12448   Scope *S = getScopeForContext(ClassDecl);
12449   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12450 
12451   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12452     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12453     SetDeclDeleted(MoveAssignment, ClassLoc);
12454   }
12455 
12456   if (S)
12457     PushOnScopeChains(MoveAssignment, S, false);
12458   ClassDecl->addDecl(MoveAssignment);
12459 
12460   return MoveAssignment;
12461 }
12462 
12463 /// Check if we're implicitly defining a move assignment operator for a class
12464 /// with virtual bases. Such a move assignment might move-assign the virtual
12465 /// base multiple times.
12466 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12467                                                SourceLocation CurrentLocation) {
12468   assert(!Class->isDependentContext() && "should not define dependent move");
12469 
12470   // Only a virtual base could get implicitly move-assigned multiple times.
12471   // Only a non-trivial move assignment can observe this. We only want to
12472   // diagnose if we implicitly define an assignment operator that assigns
12473   // two base classes, both of which move-assign the same virtual base.
12474   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12475       Class->getNumBases() < 2)
12476     return;
12477 
12478   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12479   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12480   VBaseMap VBases;
12481 
12482   for (auto &BI : Class->bases()) {
12483     Worklist.push_back(&BI);
12484     while (!Worklist.empty()) {
12485       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12486       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12487 
12488       // If the base has no non-trivial move assignment operators,
12489       // we don't care about moves from it.
12490       if (!Base->hasNonTrivialMoveAssignment())
12491         continue;
12492 
12493       // If there's nothing virtual here, skip it.
12494       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12495         continue;
12496 
12497       // If we're not actually going to call a move assignment for this base,
12498       // or the selected move assignment is trivial, skip it.
12499       Sema::SpecialMemberOverloadResult SMOR =
12500         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12501                               /*ConstArg*/false, /*VolatileArg*/false,
12502                               /*RValueThis*/true, /*ConstThis*/false,
12503                               /*VolatileThis*/false);
12504       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12505           !SMOR.getMethod()->isMoveAssignmentOperator())
12506         continue;
12507 
12508       if (BaseSpec->isVirtual()) {
12509         // We're going to move-assign this virtual base, and its move
12510         // assignment operator is not trivial. If this can happen for
12511         // multiple distinct direct bases of Class, diagnose it. (If it
12512         // only happens in one base, we'll diagnose it when synthesizing
12513         // that base class's move assignment operator.)
12514         CXXBaseSpecifier *&Existing =
12515             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12516                 .first->second;
12517         if (Existing && Existing != &BI) {
12518           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12519             << Class << Base;
12520           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12521               << (Base->getCanonicalDecl() ==
12522                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12523               << Base << Existing->getType() << Existing->getSourceRange();
12524           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12525               << (Base->getCanonicalDecl() ==
12526                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12527               << Base << BI.getType() << BaseSpec->getSourceRange();
12528 
12529           // Only diagnose each vbase once.
12530           Existing = nullptr;
12531         }
12532       } else {
12533         // Only walk over bases that have defaulted move assignment operators.
12534         // We assume that any user-provided move assignment operator handles
12535         // the multiple-moves-of-vbase case itself somehow.
12536         if (!SMOR.getMethod()->isDefaulted())
12537           continue;
12538 
12539         // We're going to move the base classes of Base. Add them to the list.
12540         for (auto &BI : Base->bases())
12541           Worklist.push_back(&BI);
12542       }
12543     }
12544   }
12545 }
12546 
12547 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12548                                         CXXMethodDecl *MoveAssignOperator) {
12549   assert((MoveAssignOperator->isDefaulted() &&
12550           MoveAssignOperator->isOverloadedOperator() &&
12551           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12552           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12553           !MoveAssignOperator->isDeleted()) &&
12554          "DefineImplicitMoveAssignment called for wrong function");
12555   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12556     return;
12557 
12558   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12559   if (ClassDecl->isInvalidDecl()) {
12560     MoveAssignOperator->setInvalidDecl();
12561     return;
12562   }
12563 
12564   // C++0x [class.copy]p28:
12565   //   The implicitly-defined or move assignment operator for a non-union class
12566   //   X performs memberwise move assignment of its subobjects. The direct base
12567   //   classes of X are assigned first, in the order of their declaration in the
12568   //   base-specifier-list, and then the immediate non-static data members of X
12569   //   are assigned, in the order in which they were declared in the class
12570   //   definition.
12571 
12572   // Issue a warning if our implicit move assignment operator will move
12573   // from a virtual base more than once.
12574   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12575 
12576   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12577 
12578   // The exception specification is needed because we are defining the
12579   // function.
12580   ResolveExceptionSpec(CurrentLocation,
12581                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12582 
12583   // Add a context note for diagnostics produced after this point.
12584   Scope.addContextNote(CurrentLocation);
12585 
12586   // The statements that form the synthesized function body.
12587   SmallVector<Stmt*, 8> Statements;
12588 
12589   // The parameter for the "other" object, which we are move from.
12590   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12591   QualType OtherRefType = Other->getType()->
12592       getAs<RValueReferenceType>()->getPointeeType();
12593 
12594   // Our location for everything implicitly-generated.
12595   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12596                            ? MoveAssignOperator->getEndLoc()
12597                            : MoveAssignOperator->getLocation();
12598 
12599   // Builds a reference to the "other" object.
12600   RefBuilder OtherRef(Other, OtherRefType);
12601   // Cast to rvalue.
12602   MoveCastBuilder MoveOther(OtherRef);
12603 
12604   // Builds the "this" pointer.
12605   ThisBuilder This;
12606 
12607   // Assign base classes.
12608   bool Invalid = false;
12609   for (auto &Base : ClassDecl->bases()) {
12610     // C++11 [class.copy]p28:
12611     //   It is unspecified whether subobjects representing virtual base classes
12612     //   are assigned more than once by the implicitly-defined copy assignment
12613     //   operator.
12614     // FIXME: Do not assign to a vbase that will be assigned by some other base
12615     // class. For a move-assignment, this can result in the vbase being moved
12616     // multiple times.
12617 
12618     // Form the assignment:
12619     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12620     QualType BaseType = Base.getType().getUnqualifiedType();
12621     if (!BaseType->isRecordType()) {
12622       Invalid = true;
12623       continue;
12624     }
12625 
12626     CXXCastPath BasePath;
12627     BasePath.push_back(&Base);
12628 
12629     // Construct the "from" expression, which is an implicit cast to the
12630     // appropriately-qualified base type.
12631     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12632 
12633     // Dereference "this".
12634     DerefBuilder DerefThis(This);
12635 
12636     // Implicitly cast "this" to the appropriately-qualified base type.
12637     CastBuilder To(DerefThis,
12638                    Context.getQualifiedType(
12639                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12640                    VK_LValue, BasePath);
12641 
12642     // Build the move.
12643     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12644                                             To, From,
12645                                             /*CopyingBaseSubobject=*/true,
12646                                             /*Copying=*/false);
12647     if (Move.isInvalid()) {
12648       MoveAssignOperator->setInvalidDecl();
12649       return;
12650     }
12651 
12652     // Success! Record the move.
12653     Statements.push_back(Move.getAs<Expr>());
12654   }
12655 
12656   // Assign non-static members.
12657   for (auto *Field : ClassDecl->fields()) {
12658     // FIXME: We should form some kind of AST representation for the implied
12659     // memcpy in a union copy operation.
12660     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12661       continue;
12662 
12663     if (Field->isInvalidDecl()) {
12664       Invalid = true;
12665       continue;
12666     }
12667 
12668     // Check for members of reference type; we can't move those.
12669     if (Field->getType()->isReferenceType()) {
12670       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12671         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12672       Diag(Field->getLocation(), diag::note_declared_at);
12673       Invalid = true;
12674       continue;
12675     }
12676 
12677     // Check for members of const-qualified, non-class type.
12678     QualType BaseType = Context.getBaseElementType(Field->getType());
12679     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12680       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12681         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12682       Diag(Field->getLocation(), diag::note_declared_at);
12683       Invalid = true;
12684       continue;
12685     }
12686 
12687     // Suppress assigning zero-width bitfields.
12688     if (Field->isZeroLengthBitField(Context))
12689       continue;
12690 
12691     QualType FieldType = Field->getType().getNonReferenceType();
12692     if (FieldType->isIncompleteArrayType()) {
12693       assert(ClassDecl->hasFlexibleArrayMember() &&
12694              "Incomplete array type is not valid");
12695       continue;
12696     }
12697 
12698     // Build references to the field in the object we're copying from and to.
12699     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12700                               LookupMemberName);
12701     MemberLookup.addDecl(Field);
12702     MemberLookup.resolveKind();
12703     MemberBuilder From(MoveOther, OtherRefType,
12704                        /*IsArrow=*/false, MemberLookup);
12705     MemberBuilder To(This, getCurrentThisType(),
12706                      /*IsArrow=*/true, MemberLookup);
12707 
12708     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12709         "Member reference with rvalue base must be rvalue except for reference "
12710         "members, which aren't allowed for move assignment.");
12711 
12712     // Build the move of this field.
12713     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12714                                             To, From,
12715                                             /*CopyingBaseSubobject=*/false,
12716                                             /*Copying=*/false);
12717     if (Move.isInvalid()) {
12718       MoveAssignOperator->setInvalidDecl();
12719       return;
12720     }
12721 
12722     // Success! Record the copy.
12723     Statements.push_back(Move.getAs<Stmt>());
12724   }
12725 
12726   if (!Invalid) {
12727     // Add a "return *this;"
12728     ExprResult ThisObj =
12729         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12730 
12731     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12732     if (Return.isInvalid())
12733       Invalid = true;
12734     else
12735       Statements.push_back(Return.getAs<Stmt>());
12736   }
12737 
12738   if (Invalid) {
12739     MoveAssignOperator->setInvalidDecl();
12740     return;
12741   }
12742 
12743   StmtResult Body;
12744   {
12745     CompoundScopeRAII CompoundScope(*this);
12746     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12747                              /*isStmtExpr=*/false);
12748     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12749   }
12750   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12751   MoveAssignOperator->markUsed(Context);
12752 
12753   if (ASTMutationListener *L = getASTMutationListener()) {
12754     L->CompletedImplicitDefinition(MoveAssignOperator);
12755   }
12756 }
12757 
12758 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12759                                                     CXXRecordDecl *ClassDecl) {
12760   // C++ [class.copy]p4:
12761   //   If the class definition does not explicitly declare a copy
12762   //   constructor, one is declared implicitly.
12763   assert(ClassDecl->needsImplicitCopyConstructor());
12764 
12765   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12766   if (DSM.isAlreadyBeingDeclared())
12767     return nullptr;
12768 
12769   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12770   QualType ArgType = ClassType;
12771   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12772   if (Const)
12773     ArgType = ArgType.withConst();
12774 
12775   if (Context.getLangOpts().OpenCLCPlusPlus)
12776     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12777 
12778   ArgType = Context.getLValueReferenceType(ArgType);
12779 
12780   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12781                                                      CXXCopyConstructor,
12782                                                      Const);
12783 
12784   DeclarationName Name
12785     = Context.DeclarationNames.getCXXConstructorName(
12786                                            Context.getCanonicalType(ClassType));
12787   SourceLocation ClassLoc = ClassDecl->getLocation();
12788   DeclarationNameInfo NameInfo(Name, ClassLoc);
12789 
12790   //   An implicitly-declared copy constructor is an inline public
12791   //   member of its class.
12792   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12793       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12794       ExplicitSpecifier(),
12795       /*isInline=*/true,
12796       /*isImplicitlyDeclared=*/true,
12797       Constexpr ? CSK_constexpr : CSK_unspecified);
12798   CopyConstructor->setAccess(AS_public);
12799   CopyConstructor->setDefaulted();
12800 
12801   if (getLangOpts().CUDA) {
12802     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12803                                             CopyConstructor,
12804                                             /* ConstRHS */ Const,
12805                                             /* Diagnose */ false);
12806   }
12807 
12808   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12809 
12810   // Add the parameter to the constructor.
12811   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12812                                                ClassLoc, ClassLoc,
12813                                                /*IdentifierInfo=*/nullptr,
12814                                                ArgType, /*TInfo=*/nullptr,
12815                                                SC_None, nullptr);
12816   CopyConstructor->setParams(FromParam);
12817 
12818   CopyConstructor->setTrivial(
12819       ClassDecl->needsOverloadResolutionForCopyConstructor()
12820           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12821           : ClassDecl->hasTrivialCopyConstructor());
12822 
12823   CopyConstructor->setTrivialForCall(
12824       ClassDecl->hasAttr<TrivialABIAttr>() ||
12825       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12826            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12827              TAH_ConsiderTrivialABI)
12828            : ClassDecl->hasTrivialCopyConstructorForCall()));
12829 
12830   // Note that we have declared this constructor.
12831   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12832 
12833   Scope *S = getScopeForContext(ClassDecl);
12834   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12835 
12836   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12837     ClassDecl->setImplicitCopyConstructorIsDeleted();
12838     SetDeclDeleted(CopyConstructor, ClassLoc);
12839   }
12840 
12841   if (S)
12842     PushOnScopeChains(CopyConstructor, S, false);
12843   ClassDecl->addDecl(CopyConstructor);
12844 
12845   return CopyConstructor;
12846 }
12847 
12848 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12849                                          CXXConstructorDecl *CopyConstructor) {
12850   assert((CopyConstructor->isDefaulted() &&
12851           CopyConstructor->isCopyConstructor() &&
12852           !CopyConstructor->doesThisDeclarationHaveABody() &&
12853           !CopyConstructor->isDeleted()) &&
12854          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12855   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12856     return;
12857 
12858   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12859   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12860 
12861   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12862 
12863   // The exception specification is needed because we are defining the
12864   // function.
12865   ResolveExceptionSpec(CurrentLocation,
12866                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12867   MarkVTableUsed(CurrentLocation, ClassDecl);
12868 
12869   // Add a context note for diagnostics produced after this point.
12870   Scope.addContextNote(CurrentLocation);
12871 
12872   // C++11 [class.copy]p7:
12873   //   The [definition of an implicitly declared copy constructor] is
12874   //   deprecated if the class has a user-declared copy assignment operator
12875   //   or a user-declared destructor.
12876   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12877     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12878 
12879   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12880     CopyConstructor->setInvalidDecl();
12881   }  else {
12882     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12883                              ? CopyConstructor->getEndLoc()
12884                              : CopyConstructor->getLocation();
12885     Sema::CompoundScopeRAII CompoundScope(*this);
12886     CopyConstructor->setBody(
12887         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12888     CopyConstructor->markUsed(Context);
12889   }
12890 
12891   if (ASTMutationListener *L = getASTMutationListener()) {
12892     L->CompletedImplicitDefinition(CopyConstructor);
12893   }
12894 }
12895 
12896 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12897                                                     CXXRecordDecl *ClassDecl) {
12898   assert(ClassDecl->needsImplicitMoveConstructor());
12899 
12900   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12901   if (DSM.isAlreadyBeingDeclared())
12902     return nullptr;
12903 
12904   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12905 
12906   QualType ArgType = ClassType;
12907   if (Context.getLangOpts().OpenCLCPlusPlus)
12908     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12909   ArgType = Context.getRValueReferenceType(ArgType);
12910 
12911   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12912                                                      CXXMoveConstructor,
12913                                                      false);
12914 
12915   DeclarationName Name
12916     = Context.DeclarationNames.getCXXConstructorName(
12917                                            Context.getCanonicalType(ClassType));
12918   SourceLocation ClassLoc = ClassDecl->getLocation();
12919   DeclarationNameInfo NameInfo(Name, ClassLoc);
12920 
12921   // C++11 [class.copy]p11:
12922   //   An implicitly-declared copy/move constructor is an inline public
12923   //   member of its class.
12924   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12925       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12926       ExplicitSpecifier(),
12927       /*isInline=*/true,
12928       /*isImplicitlyDeclared=*/true,
12929       Constexpr ? CSK_constexpr : CSK_unspecified);
12930   MoveConstructor->setAccess(AS_public);
12931   MoveConstructor->setDefaulted();
12932 
12933   if (getLangOpts().CUDA) {
12934     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12935                                             MoveConstructor,
12936                                             /* ConstRHS */ false,
12937                                             /* Diagnose */ false);
12938   }
12939 
12940   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12941 
12942   // Add the parameter to the constructor.
12943   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12944                                                ClassLoc, ClassLoc,
12945                                                /*IdentifierInfo=*/nullptr,
12946                                                ArgType, /*TInfo=*/nullptr,
12947                                                SC_None, nullptr);
12948   MoveConstructor->setParams(FromParam);
12949 
12950   MoveConstructor->setTrivial(
12951       ClassDecl->needsOverloadResolutionForMoveConstructor()
12952           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12953           : ClassDecl->hasTrivialMoveConstructor());
12954 
12955   MoveConstructor->setTrivialForCall(
12956       ClassDecl->hasAttr<TrivialABIAttr>() ||
12957       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12958            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12959                                     TAH_ConsiderTrivialABI)
12960            : ClassDecl->hasTrivialMoveConstructorForCall()));
12961 
12962   // Note that we have declared this constructor.
12963   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12964 
12965   Scope *S = getScopeForContext(ClassDecl);
12966   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12967 
12968   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12969     ClassDecl->setImplicitMoveConstructorIsDeleted();
12970     SetDeclDeleted(MoveConstructor, ClassLoc);
12971   }
12972 
12973   if (S)
12974     PushOnScopeChains(MoveConstructor, S, false);
12975   ClassDecl->addDecl(MoveConstructor);
12976 
12977   return MoveConstructor;
12978 }
12979 
12980 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12981                                          CXXConstructorDecl *MoveConstructor) {
12982   assert((MoveConstructor->isDefaulted() &&
12983           MoveConstructor->isMoveConstructor() &&
12984           !MoveConstructor->doesThisDeclarationHaveABody() &&
12985           !MoveConstructor->isDeleted()) &&
12986          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12987   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12988     return;
12989 
12990   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12991   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12992 
12993   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12994 
12995   // The exception specification is needed because we are defining the
12996   // function.
12997   ResolveExceptionSpec(CurrentLocation,
12998                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12999   MarkVTableUsed(CurrentLocation, ClassDecl);
13000 
13001   // Add a context note for diagnostics produced after this point.
13002   Scope.addContextNote(CurrentLocation);
13003 
13004   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
13005     MoveConstructor->setInvalidDecl();
13006   } else {
13007     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
13008                              ? MoveConstructor->getEndLoc()
13009                              : MoveConstructor->getLocation();
13010     Sema::CompoundScopeRAII CompoundScope(*this);
13011     MoveConstructor->setBody(ActOnCompoundStmt(
13012         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
13013     MoveConstructor->markUsed(Context);
13014   }
13015 
13016   if (ASTMutationListener *L = getASTMutationListener()) {
13017     L->CompletedImplicitDefinition(MoveConstructor);
13018   }
13019 }
13020 
13021 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
13022   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
13023 }
13024 
13025 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
13026                             SourceLocation CurrentLocation,
13027                             CXXConversionDecl *Conv) {
13028   SynthesizedFunctionScope Scope(*this, Conv);
13029   assert(!Conv->getReturnType()->isUndeducedType());
13030 
13031   CXXRecordDecl *Lambda = Conv->getParent();
13032   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
13033   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
13034 
13035   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
13036     CallOp = InstantiateFunctionDeclaration(
13037         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13038     if (!CallOp)
13039       return;
13040 
13041     Invoker = InstantiateFunctionDeclaration(
13042         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13043     if (!Invoker)
13044       return;
13045   }
13046 
13047   if (CallOp->isInvalidDecl())
13048     return;
13049 
13050   // Mark the call operator referenced (and add to pending instantiations
13051   // if necessary).
13052   // For both the conversion and static-invoker template specializations
13053   // we construct their body's in this function, so no need to add them
13054   // to the PendingInstantiations.
13055   MarkFunctionReferenced(CurrentLocation, CallOp);
13056 
13057   // Fill in the __invoke function with a dummy implementation. IR generation
13058   // will fill in the actual details. Update its type in case it contained
13059   // an 'auto'.
13060   Invoker->markUsed(Context);
13061   Invoker->setReferenced();
13062   Invoker->setType(Conv->getReturnType()->getPointeeType());
13063   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
13064 
13065   // Construct the body of the conversion function { return __invoke; }.
13066   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
13067                                        VK_LValue, Conv->getLocation());
13068   assert(FunctionRef && "Can't refer to __invoke function?");
13069   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
13070   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
13071                                      Conv->getLocation()));
13072   Conv->markUsed(Context);
13073   Conv->setReferenced();
13074 
13075   if (ASTMutationListener *L = getASTMutationListener()) {
13076     L->CompletedImplicitDefinition(Conv);
13077     L->CompletedImplicitDefinition(Invoker);
13078   }
13079 }
13080 
13081 
13082 
13083 void Sema::DefineImplicitLambdaToBlockPointerConversion(
13084        SourceLocation CurrentLocation,
13085        CXXConversionDecl *Conv)
13086 {
13087   assert(!Conv->getParent()->isGenericLambda());
13088 
13089   SynthesizedFunctionScope Scope(*this, Conv);
13090 
13091   // Copy-initialize the lambda object as needed to capture it.
13092   Expr *This = ActOnCXXThis(CurrentLocation).get();
13093   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
13094 
13095   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
13096                                                         Conv->getLocation(),
13097                                                         Conv, DerefThis);
13098 
13099   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
13100   // behavior.  Note that only the general conversion function does this
13101   // (since it's unusable otherwise); in the case where we inline the
13102   // block literal, it has block literal lifetime semantics.
13103   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
13104     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
13105                                           CK_CopyAndAutoreleaseBlockObject,
13106                                           BuildBlock.get(), nullptr, VK_RValue);
13107 
13108   if (BuildBlock.isInvalid()) {
13109     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13110     Conv->setInvalidDecl();
13111     return;
13112   }
13113 
13114   // Create the return statement that returns the block from the conversion
13115   // function.
13116   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
13117   if (Return.isInvalid()) {
13118     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13119     Conv->setInvalidDecl();
13120     return;
13121   }
13122 
13123   // Set the body of the conversion function.
13124   Stmt *ReturnS = Return.get();
13125   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
13126                                      Conv->getLocation()));
13127   Conv->markUsed(Context);
13128 
13129   // We're done; notify the mutation listener, if any.
13130   if (ASTMutationListener *L = getASTMutationListener()) {
13131     L->CompletedImplicitDefinition(Conv);
13132   }
13133 }
13134 
13135 /// Determine whether the given list arguments contains exactly one
13136 /// "real" (non-default) argument.
13137 static bool hasOneRealArgument(MultiExprArg Args) {
13138   switch (Args.size()) {
13139   case 0:
13140     return false;
13141 
13142   default:
13143     if (!Args[1]->isDefaultArgument())
13144       return false;
13145 
13146     LLVM_FALLTHROUGH;
13147   case 1:
13148     return !Args[0]->isDefaultArgument();
13149   }
13150 
13151   return false;
13152 }
13153 
13154 ExprResult
13155 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13156                             NamedDecl *FoundDecl,
13157                             CXXConstructorDecl *Constructor,
13158                             MultiExprArg ExprArgs,
13159                             bool HadMultipleCandidates,
13160                             bool IsListInitialization,
13161                             bool IsStdInitListInitialization,
13162                             bool RequiresZeroInit,
13163                             unsigned ConstructKind,
13164                             SourceRange ParenRange) {
13165   bool Elidable = false;
13166 
13167   // C++0x [class.copy]p34:
13168   //   When certain criteria are met, an implementation is allowed to
13169   //   omit the copy/move construction of a class object, even if the
13170   //   copy/move constructor and/or destructor for the object have
13171   //   side effects. [...]
13172   //     - when a temporary class object that has not been bound to a
13173   //       reference (12.2) would be copied/moved to a class object
13174   //       with the same cv-unqualified type, the copy/move operation
13175   //       can be omitted by constructing the temporary object
13176   //       directly into the target of the omitted copy/move
13177   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13178       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13179     Expr *SubExpr = ExprArgs[0];
13180     Elidable = SubExpr->isTemporaryObject(
13181         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13182   }
13183 
13184   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13185                                FoundDecl, Constructor,
13186                                Elidable, ExprArgs, HadMultipleCandidates,
13187                                IsListInitialization,
13188                                IsStdInitListInitialization, RequiresZeroInit,
13189                                ConstructKind, ParenRange);
13190 }
13191 
13192 ExprResult
13193 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13194                             NamedDecl *FoundDecl,
13195                             CXXConstructorDecl *Constructor,
13196                             bool Elidable,
13197                             MultiExprArg ExprArgs,
13198                             bool HadMultipleCandidates,
13199                             bool IsListInitialization,
13200                             bool IsStdInitListInitialization,
13201                             bool RequiresZeroInit,
13202                             unsigned ConstructKind,
13203                             SourceRange ParenRange) {
13204   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13205     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13206     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13207       return ExprError();
13208   }
13209 
13210   return BuildCXXConstructExpr(
13211       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13212       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13213       RequiresZeroInit, ConstructKind, ParenRange);
13214 }
13215 
13216 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13217 /// including handling of its default argument expressions.
13218 ExprResult
13219 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13220                             CXXConstructorDecl *Constructor,
13221                             bool Elidable,
13222                             MultiExprArg ExprArgs,
13223                             bool HadMultipleCandidates,
13224                             bool IsListInitialization,
13225                             bool IsStdInitListInitialization,
13226                             bool RequiresZeroInit,
13227                             unsigned ConstructKind,
13228                             SourceRange ParenRange) {
13229   assert(declaresSameEntity(
13230              Constructor->getParent(),
13231              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13232          "given constructor for wrong type");
13233   MarkFunctionReferenced(ConstructLoc, Constructor);
13234   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13235     return ExprError();
13236 
13237   return CXXConstructExpr::Create(
13238       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13239       ExprArgs, HadMultipleCandidates, IsListInitialization,
13240       IsStdInitListInitialization, RequiresZeroInit,
13241       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13242       ParenRange);
13243 }
13244 
13245 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13246   assert(Field->hasInClassInitializer());
13247 
13248   // If we already have the in-class initializer nothing needs to be done.
13249   if (Field->getInClassInitializer())
13250     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13251 
13252   // If we might have already tried and failed to instantiate, don't try again.
13253   if (Field->isInvalidDecl())
13254     return ExprError();
13255 
13256   // Maybe we haven't instantiated the in-class initializer. Go check the
13257   // pattern FieldDecl to see if it has one.
13258   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13259 
13260   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13261     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13262     DeclContext::lookup_result Lookup =
13263         ClassPattern->lookup(Field->getDeclName());
13264 
13265     // Lookup can return at most two results: the pattern for the field, or the
13266     // injected class name of the parent record. No other member can have the
13267     // same name as the field.
13268     // In modules mode, lookup can return multiple results (coming from
13269     // different modules).
13270     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13271            "more than two lookup results for field name");
13272     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13273     if (!Pattern) {
13274       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13275              "cannot have other non-field member with same name");
13276       for (auto L : Lookup)
13277         if (isa<FieldDecl>(L)) {
13278           Pattern = cast<FieldDecl>(L);
13279           break;
13280         }
13281       assert(Pattern && "We must have set the Pattern!");
13282     }
13283 
13284     if (!Pattern->hasInClassInitializer() ||
13285         InstantiateInClassInitializer(Loc, Field, Pattern,
13286                                       getTemplateInstantiationArgs(Field))) {
13287       // Don't diagnose this again.
13288       Field->setInvalidDecl();
13289       return ExprError();
13290     }
13291     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13292   }
13293 
13294   // DR1351:
13295   //   If the brace-or-equal-initializer of a non-static data member
13296   //   invokes a defaulted default constructor of its class or of an
13297   //   enclosing class in a potentially evaluated subexpression, the
13298   //   program is ill-formed.
13299   //
13300   // This resolution is unworkable: the exception specification of the
13301   // default constructor can be needed in an unevaluated context, in
13302   // particular, in the operand of a noexcept-expression, and we can be
13303   // unable to compute an exception specification for an enclosed class.
13304   //
13305   // Any attempt to resolve the exception specification of a defaulted default
13306   // constructor before the initializer is lexically complete will ultimately
13307   // come here at which point we can diagnose it.
13308   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13309   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13310       << OutermostClass << Field;
13311   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13312   // Recover by marking the field invalid, unless we're in a SFINAE context.
13313   if (!isSFINAEContext())
13314     Field->setInvalidDecl();
13315   return ExprError();
13316 }
13317 
13318 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13319   if (VD->isInvalidDecl()) return;
13320 
13321   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13322   if (ClassDecl->isInvalidDecl()) return;
13323   if (ClassDecl->hasIrrelevantDestructor()) return;
13324   if (ClassDecl->isDependentContext()) return;
13325 
13326   if (VD->isNoDestroy(getASTContext()))
13327     return;
13328 
13329   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13330 
13331   // If this is an array, we'll require the destructor during initialization, so
13332   // we can skip over this. We still want to emit exit-time destructor warnings
13333   // though.
13334   if (!VD->getType()->isArrayType()) {
13335     MarkFunctionReferenced(VD->getLocation(), Destructor);
13336     CheckDestructorAccess(VD->getLocation(), Destructor,
13337                           PDiag(diag::err_access_dtor_var)
13338                               << VD->getDeclName() << VD->getType());
13339     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13340   }
13341 
13342   if (Destructor->isTrivial()) return;
13343   if (!VD->hasGlobalStorage()) return;
13344 
13345   // Emit warning for non-trivial dtor in global scope (a real global,
13346   // class-static, function-static).
13347   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13348 
13349   // TODO: this should be re-enabled for static locals by !CXAAtExit
13350   if (!VD->isStaticLocal())
13351     Diag(VD->getLocation(), diag::warn_global_destructor);
13352 }
13353 
13354 /// Given a constructor and the set of arguments provided for the
13355 /// constructor, convert the arguments and add any required default arguments
13356 /// to form a proper call to this constructor.
13357 ///
13358 /// \returns true if an error occurred, false otherwise.
13359 bool
13360 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13361                               MultiExprArg ArgsPtr,
13362                               SourceLocation Loc,
13363                               SmallVectorImpl<Expr*> &ConvertedArgs,
13364                               bool AllowExplicit,
13365                               bool IsListInitialization) {
13366   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13367   unsigned NumArgs = ArgsPtr.size();
13368   Expr **Args = ArgsPtr.data();
13369 
13370   const FunctionProtoType *Proto
13371     = Constructor->getType()->getAs<FunctionProtoType>();
13372   assert(Proto && "Constructor without a prototype?");
13373   unsigned NumParams = Proto->getNumParams();
13374 
13375   // If too few arguments are available, we'll fill in the rest with defaults.
13376   if (NumArgs < NumParams)
13377     ConvertedArgs.reserve(NumParams);
13378   else
13379     ConvertedArgs.reserve(NumArgs);
13380 
13381   VariadicCallType CallType =
13382     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13383   SmallVector<Expr *, 8> AllArgs;
13384   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13385                                         Proto, 0,
13386                                         llvm::makeArrayRef(Args, NumArgs),
13387                                         AllArgs,
13388                                         CallType, AllowExplicit,
13389                                         IsListInitialization);
13390   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13391 
13392   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13393 
13394   CheckConstructorCall(Constructor,
13395                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13396                        Proto, Loc);
13397 
13398   return Invalid;
13399 }
13400 
13401 static inline bool
13402 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13403                                        const FunctionDecl *FnDecl) {
13404   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13405   if (isa<NamespaceDecl>(DC)) {
13406     return SemaRef.Diag(FnDecl->getLocation(),
13407                         diag::err_operator_new_delete_declared_in_namespace)
13408       << FnDecl->getDeclName();
13409   }
13410 
13411   if (isa<TranslationUnitDecl>(DC) &&
13412       FnDecl->getStorageClass() == SC_Static) {
13413     return SemaRef.Diag(FnDecl->getLocation(),
13414                         diag::err_operator_new_delete_declared_static)
13415       << FnDecl->getDeclName();
13416   }
13417 
13418   return false;
13419 }
13420 
13421 static QualType
13422 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13423   QualType QTy = PtrTy->getPointeeType();
13424   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13425   return SemaRef.Context.getPointerType(QTy);
13426 }
13427 
13428 static inline bool
13429 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13430                             CanQualType ExpectedResultType,
13431                             CanQualType ExpectedFirstParamType,
13432                             unsigned DependentParamTypeDiag,
13433                             unsigned InvalidParamTypeDiag) {
13434   QualType ResultType =
13435       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13436 
13437   // Check that the result type is not dependent.
13438   if (ResultType->isDependentType())
13439     return SemaRef.Diag(FnDecl->getLocation(),
13440                         diag::err_operator_new_delete_dependent_result_type)
13441     << FnDecl->getDeclName() << ExpectedResultType;
13442 
13443   // The operator is valid on any address space for OpenCL.
13444   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13445     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13446       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13447     }
13448   }
13449 
13450   // Check that the result type is what we expect.
13451   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13452     return SemaRef.Diag(FnDecl->getLocation(),
13453                         diag::err_operator_new_delete_invalid_result_type)
13454     << FnDecl->getDeclName() << ExpectedResultType;
13455 
13456   // A function template must have at least 2 parameters.
13457   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13458     return SemaRef.Diag(FnDecl->getLocation(),
13459                       diag::err_operator_new_delete_template_too_few_parameters)
13460         << FnDecl->getDeclName();
13461 
13462   // The function decl must have at least 1 parameter.
13463   if (FnDecl->getNumParams() == 0)
13464     return SemaRef.Diag(FnDecl->getLocation(),
13465                         diag::err_operator_new_delete_too_few_parameters)
13466       << FnDecl->getDeclName();
13467 
13468   // Check the first parameter type is not dependent.
13469   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13470   if (FirstParamType->isDependentType())
13471     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13472       << FnDecl->getDeclName() << ExpectedFirstParamType;
13473 
13474   // Check that the first parameter type is what we expect.
13475   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13476     // The operator is valid on any address space for OpenCL.
13477     if (auto *PtrTy =
13478             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13479       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13480     }
13481   }
13482   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13483       ExpectedFirstParamType)
13484     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13485     << FnDecl->getDeclName() << ExpectedFirstParamType;
13486 
13487   return false;
13488 }
13489 
13490 static bool
13491 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13492   // C++ [basic.stc.dynamic.allocation]p1:
13493   //   A program is ill-formed if an allocation function is declared in a
13494   //   namespace scope other than global scope or declared static in global
13495   //   scope.
13496   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13497     return true;
13498 
13499   CanQualType SizeTy =
13500     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13501 
13502   // C++ [basic.stc.dynamic.allocation]p1:
13503   //  The return type shall be void*. The first parameter shall have type
13504   //  std::size_t.
13505   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13506                                   SizeTy,
13507                                   diag::err_operator_new_dependent_param_type,
13508                                   diag::err_operator_new_param_type))
13509     return true;
13510 
13511   // C++ [basic.stc.dynamic.allocation]p1:
13512   //  The first parameter shall not have an associated default argument.
13513   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13514     return SemaRef.Diag(FnDecl->getLocation(),
13515                         diag::err_operator_new_default_arg)
13516       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13517 
13518   return false;
13519 }
13520 
13521 static bool
13522 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13523   // C++ [basic.stc.dynamic.deallocation]p1:
13524   //   A program is ill-formed if deallocation functions are declared in a
13525   //   namespace scope other than global scope or declared static in global
13526   //   scope.
13527   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13528     return true;
13529 
13530   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13531 
13532   // C++ P0722:
13533   //   Within a class C, the first parameter of a destroying operator delete
13534   //   shall be of type C *. The first parameter of any other deallocation
13535   //   function shall be of type void *.
13536   CanQualType ExpectedFirstParamType =
13537       MD && MD->isDestroyingOperatorDelete()
13538           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13539                 SemaRef.Context.getRecordType(MD->getParent())))
13540           : SemaRef.Context.VoidPtrTy;
13541 
13542   // C++ [basic.stc.dynamic.deallocation]p2:
13543   //   Each deallocation function shall return void
13544   if (CheckOperatorNewDeleteTypes(
13545           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13546           diag::err_operator_delete_dependent_param_type,
13547           diag::err_operator_delete_param_type))
13548     return true;
13549 
13550   // C++ P0722:
13551   //   A destroying operator delete shall be a usual deallocation function.
13552   if (MD && !MD->getParent()->isDependentContext() &&
13553       MD->isDestroyingOperatorDelete() &&
13554       !SemaRef.isUsualDeallocationFunction(MD)) {
13555     SemaRef.Diag(MD->getLocation(),
13556                  diag::err_destroying_operator_delete_not_usual);
13557     return true;
13558   }
13559 
13560   return false;
13561 }
13562 
13563 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13564 /// of this overloaded operator is well-formed. If so, returns false;
13565 /// otherwise, emits appropriate diagnostics and returns true.
13566 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13567   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13568          "Expected an overloaded operator declaration");
13569 
13570   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13571 
13572   // C++ [over.oper]p5:
13573   //   The allocation and deallocation functions, operator new,
13574   //   operator new[], operator delete and operator delete[], are
13575   //   described completely in 3.7.3. The attributes and restrictions
13576   //   found in the rest of this subclause do not apply to them unless
13577   //   explicitly stated in 3.7.3.
13578   if (Op == OO_Delete || Op == OO_Array_Delete)
13579     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13580 
13581   if (Op == OO_New || Op == OO_Array_New)
13582     return CheckOperatorNewDeclaration(*this, FnDecl);
13583 
13584   // C++ [over.oper]p6:
13585   //   An operator function shall either be a non-static member
13586   //   function or be a non-member function and have at least one
13587   //   parameter whose type is a class, a reference to a class, an
13588   //   enumeration, or a reference to an enumeration.
13589   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13590     if (MethodDecl->isStatic())
13591       return Diag(FnDecl->getLocation(),
13592                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13593   } else {
13594     bool ClassOrEnumParam = false;
13595     for (auto Param : FnDecl->parameters()) {
13596       QualType ParamType = Param->getType().getNonReferenceType();
13597       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13598           ParamType->isEnumeralType()) {
13599         ClassOrEnumParam = true;
13600         break;
13601       }
13602     }
13603 
13604     if (!ClassOrEnumParam)
13605       return Diag(FnDecl->getLocation(),
13606                   diag::err_operator_overload_needs_class_or_enum)
13607         << FnDecl->getDeclName();
13608   }
13609 
13610   // C++ [over.oper]p8:
13611   //   An operator function cannot have default arguments (8.3.6),
13612   //   except where explicitly stated below.
13613   //
13614   // Only the function-call operator allows default arguments
13615   // (C++ [over.call]p1).
13616   if (Op != OO_Call) {
13617     for (auto Param : FnDecl->parameters()) {
13618       if (Param->hasDefaultArg())
13619         return Diag(Param->getLocation(),
13620                     diag::err_operator_overload_default_arg)
13621           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13622     }
13623   }
13624 
13625   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13626     { false, false, false }
13627 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13628     , { Unary, Binary, MemberOnly }
13629 #include "clang/Basic/OperatorKinds.def"
13630   };
13631 
13632   bool CanBeUnaryOperator = OperatorUses[Op][0];
13633   bool CanBeBinaryOperator = OperatorUses[Op][1];
13634   bool MustBeMemberOperator = OperatorUses[Op][2];
13635 
13636   // C++ [over.oper]p8:
13637   //   [...] Operator functions cannot have more or fewer parameters
13638   //   than the number required for the corresponding operator, as
13639   //   described in the rest of this subclause.
13640   unsigned NumParams = FnDecl->getNumParams()
13641                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13642   if (Op != OO_Call &&
13643       ((NumParams == 1 && !CanBeUnaryOperator) ||
13644        (NumParams == 2 && !CanBeBinaryOperator) ||
13645        (NumParams < 1) || (NumParams > 2))) {
13646     // We have the wrong number of parameters.
13647     unsigned ErrorKind;
13648     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13649       ErrorKind = 2;  // 2 -> unary or binary.
13650     } else if (CanBeUnaryOperator) {
13651       ErrorKind = 0;  // 0 -> unary
13652     } else {
13653       assert(CanBeBinaryOperator &&
13654              "All non-call overloaded operators are unary or binary!");
13655       ErrorKind = 1;  // 1 -> binary
13656     }
13657 
13658     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13659       << FnDecl->getDeclName() << NumParams << ErrorKind;
13660   }
13661 
13662   // Overloaded operators other than operator() cannot be variadic.
13663   if (Op != OO_Call &&
13664       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13665     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13666       << FnDecl->getDeclName();
13667   }
13668 
13669   // Some operators must be non-static member functions.
13670   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13671     return Diag(FnDecl->getLocation(),
13672                 diag::err_operator_overload_must_be_member)
13673       << FnDecl->getDeclName();
13674   }
13675 
13676   // C++ [over.inc]p1:
13677   //   The user-defined function called operator++ implements the
13678   //   prefix and postfix ++ operator. If this function is a member
13679   //   function with no parameters, or a non-member function with one
13680   //   parameter of class or enumeration type, it defines the prefix
13681   //   increment operator ++ for objects of that type. If the function
13682   //   is a member function with one parameter (which shall be of type
13683   //   int) or a non-member function with two parameters (the second
13684   //   of which shall be of type int), it defines the postfix
13685   //   increment operator ++ for objects of that type.
13686   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13687     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13688     QualType ParamType = LastParam->getType();
13689 
13690     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13691         !ParamType->isDependentType())
13692       return Diag(LastParam->getLocation(),
13693                   diag::err_operator_overload_post_incdec_must_be_int)
13694         << LastParam->getType() << (Op == OO_MinusMinus);
13695   }
13696 
13697   return false;
13698 }
13699 
13700 static bool
13701 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13702                                           FunctionTemplateDecl *TpDecl) {
13703   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13704 
13705   // Must have one or two template parameters.
13706   if (TemplateParams->size() == 1) {
13707     NonTypeTemplateParmDecl *PmDecl =
13708         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13709 
13710     // The template parameter must be a char parameter pack.
13711     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13712         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13713       return false;
13714 
13715   } else if (TemplateParams->size() == 2) {
13716     TemplateTypeParmDecl *PmType =
13717         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13718     NonTypeTemplateParmDecl *PmArgs =
13719         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13720 
13721     // The second template parameter must be a parameter pack with the
13722     // first template parameter as its type.
13723     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13724         PmArgs->isTemplateParameterPack()) {
13725       const TemplateTypeParmType *TArgs =
13726           PmArgs->getType()->getAs<TemplateTypeParmType>();
13727       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13728           TArgs->getIndex() == PmType->getIndex()) {
13729         if (!SemaRef.inTemplateInstantiation())
13730           SemaRef.Diag(TpDecl->getLocation(),
13731                        diag::ext_string_literal_operator_template);
13732         return false;
13733       }
13734     }
13735   }
13736 
13737   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13738                diag::err_literal_operator_template)
13739       << TpDecl->getTemplateParameters()->getSourceRange();
13740   return true;
13741 }
13742 
13743 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13744 /// of this literal operator function is well-formed. If so, returns
13745 /// false; otherwise, emits appropriate diagnostics and returns true.
13746 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13747   if (isa<CXXMethodDecl>(FnDecl)) {
13748     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13749       << FnDecl->getDeclName();
13750     return true;
13751   }
13752 
13753   if (FnDecl->isExternC()) {
13754     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13755     if (const LinkageSpecDecl *LSD =
13756             FnDecl->getDeclContext()->getExternCContext())
13757       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13758     return true;
13759   }
13760 
13761   // This might be the definition of a literal operator template.
13762   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13763 
13764   // This might be a specialization of a literal operator template.
13765   if (!TpDecl)
13766     TpDecl = FnDecl->getPrimaryTemplate();
13767 
13768   // template <char...> type operator "" name() and
13769   // template <class T, T...> type operator "" name() are the only valid
13770   // template signatures, and the only valid signatures with no parameters.
13771   if (TpDecl) {
13772     if (FnDecl->param_size() != 0) {
13773       Diag(FnDecl->getLocation(),
13774            diag::err_literal_operator_template_with_params);
13775       return true;
13776     }
13777 
13778     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13779       return true;
13780 
13781   } else if (FnDecl->param_size() == 1) {
13782     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13783 
13784     QualType ParamType = Param->getType().getUnqualifiedType();
13785 
13786     // Only unsigned long long int, long double, any character type, and const
13787     // char * are allowed as the only parameters.
13788     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13789         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13790         Context.hasSameType(ParamType, Context.CharTy) ||
13791         Context.hasSameType(ParamType, Context.WideCharTy) ||
13792         Context.hasSameType(ParamType, Context.Char8Ty) ||
13793         Context.hasSameType(ParamType, Context.Char16Ty) ||
13794         Context.hasSameType(ParamType, Context.Char32Ty)) {
13795     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13796       QualType InnerType = Ptr->getPointeeType();
13797 
13798       // Pointer parameter must be a const char *.
13799       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13800                                 Context.CharTy) &&
13801             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13802         Diag(Param->getSourceRange().getBegin(),
13803              diag::err_literal_operator_param)
13804             << ParamType << "'const char *'" << Param->getSourceRange();
13805         return true;
13806       }
13807 
13808     } else if (ParamType->isRealFloatingType()) {
13809       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13810           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13811       return true;
13812 
13813     } else if (ParamType->isIntegerType()) {
13814       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13815           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13816       return true;
13817 
13818     } else {
13819       Diag(Param->getSourceRange().getBegin(),
13820            diag::err_literal_operator_invalid_param)
13821           << ParamType << Param->getSourceRange();
13822       return true;
13823     }
13824 
13825   } else if (FnDecl->param_size() == 2) {
13826     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13827 
13828     // First, verify that the first parameter is correct.
13829 
13830     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13831 
13832     // Two parameter function must have a pointer to const as a
13833     // first parameter; let's strip those qualifiers.
13834     const PointerType *PT = FirstParamType->getAs<PointerType>();
13835 
13836     if (!PT) {
13837       Diag((*Param)->getSourceRange().getBegin(),
13838            diag::err_literal_operator_param)
13839           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13840       return true;
13841     }
13842 
13843     QualType PointeeType = PT->getPointeeType();
13844     // First parameter must be const
13845     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13846       Diag((*Param)->getSourceRange().getBegin(),
13847            diag::err_literal_operator_param)
13848           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13849       return true;
13850     }
13851 
13852     QualType InnerType = PointeeType.getUnqualifiedType();
13853     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13854     // const char32_t* are allowed as the first parameter to a two-parameter
13855     // function
13856     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13857           Context.hasSameType(InnerType, Context.WideCharTy) ||
13858           Context.hasSameType(InnerType, Context.Char8Ty) ||
13859           Context.hasSameType(InnerType, Context.Char16Ty) ||
13860           Context.hasSameType(InnerType, Context.Char32Ty))) {
13861       Diag((*Param)->getSourceRange().getBegin(),
13862            diag::err_literal_operator_param)
13863           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13864       return true;
13865     }
13866 
13867     // Move on to the second and final parameter.
13868     ++Param;
13869 
13870     // The second parameter must be a std::size_t.
13871     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13872     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13873       Diag((*Param)->getSourceRange().getBegin(),
13874            diag::err_literal_operator_param)
13875           << SecondParamType << Context.getSizeType()
13876           << (*Param)->getSourceRange();
13877       return true;
13878     }
13879   } else {
13880     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13881     return true;
13882   }
13883 
13884   // Parameters are good.
13885 
13886   // A parameter-declaration-clause containing a default argument is not
13887   // equivalent to any of the permitted forms.
13888   for (auto Param : FnDecl->parameters()) {
13889     if (Param->hasDefaultArg()) {
13890       Diag(Param->getDefaultArgRange().getBegin(),
13891            diag::err_literal_operator_default_argument)
13892         << Param->getDefaultArgRange();
13893       break;
13894     }
13895   }
13896 
13897   StringRef LiteralName
13898     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13899   if (LiteralName[0] != '_' &&
13900       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13901     // C++11 [usrlit.suffix]p1:
13902     //   Literal suffix identifiers that do not start with an underscore
13903     //   are reserved for future standardization.
13904     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13905       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13906   }
13907 
13908   return false;
13909 }
13910 
13911 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13912 /// linkage specification, including the language and (if present)
13913 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13914 /// language string literal. LBraceLoc, if valid, provides the location of
13915 /// the '{' brace. Otherwise, this linkage specification does not
13916 /// have any braces.
13917 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13918                                            Expr *LangStr,
13919                                            SourceLocation LBraceLoc) {
13920   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13921   if (!Lit->isAscii()) {
13922     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13923       << LangStr->getSourceRange();
13924     return nullptr;
13925   }
13926 
13927   StringRef Lang = Lit->getString();
13928   LinkageSpecDecl::LanguageIDs Language;
13929   if (Lang == "C")
13930     Language = LinkageSpecDecl::lang_c;
13931   else if (Lang == "C++")
13932     Language = LinkageSpecDecl::lang_cxx;
13933   else {
13934     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13935       << LangStr->getSourceRange();
13936     return nullptr;
13937   }
13938 
13939   // FIXME: Add all the various semantics of linkage specifications
13940 
13941   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13942                                                LangStr->getExprLoc(), Language,
13943                                                LBraceLoc.isValid());
13944   CurContext->addDecl(D);
13945   PushDeclContext(S, D);
13946   return D;
13947 }
13948 
13949 /// ActOnFinishLinkageSpecification - Complete the definition of
13950 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13951 /// valid, it's the position of the closing '}' brace in a linkage
13952 /// specification that uses braces.
13953 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13954                                             Decl *LinkageSpec,
13955                                             SourceLocation RBraceLoc) {
13956   if (RBraceLoc.isValid()) {
13957     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13958     LSDecl->setRBraceLoc(RBraceLoc);
13959   }
13960   PopDeclContext();
13961   return LinkageSpec;
13962 }
13963 
13964 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13965                                   const ParsedAttributesView &AttrList,
13966                                   SourceLocation SemiLoc) {
13967   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13968   // Attribute declarations appertain to empty declaration so we handle
13969   // them here.
13970   ProcessDeclAttributeList(S, ED, AttrList);
13971 
13972   CurContext->addDecl(ED);
13973   return ED;
13974 }
13975 
13976 /// Perform semantic analysis for the variable declaration that
13977 /// occurs within a C++ catch clause, returning the newly-created
13978 /// variable.
13979 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13980                                          TypeSourceInfo *TInfo,
13981                                          SourceLocation StartLoc,
13982                                          SourceLocation Loc,
13983                                          IdentifierInfo *Name) {
13984   bool Invalid = false;
13985   QualType ExDeclType = TInfo->getType();
13986 
13987   // Arrays and functions decay.
13988   if (ExDeclType->isArrayType())
13989     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13990   else if (ExDeclType->isFunctionType())
13991     ExDeclType = Context.getPointerType(ExDeclType);
13992 
13993   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13994   // The exception-declaration shall not denote a pointer or reference to an
13995   // incomplete type, other than [cv] void*.
13996   // N2844 forbids rvalue references.
13997   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13998     Diag(Loc, diag::err_catch_rvalue_ref);
13999     Invalid = true;
14000   }
14001 
14002   if (ExDeclType->isVariablyModifiedType()) {
14003     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
14004     Invalid = true;
14005   }
14006 
14007   QualType BaseType = ExDeclType;
14008   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
14009   unsigned DK = diag::err_catch_incomplete;
14010   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
14011     BaseType = Ptr->getPointeeType();
14012     Mode = 1;
14013     DK = diag::err_catch_incomplete_ptr;
14014   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
14015     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
14016     BaseType = Ref->getPointeeType();
14017     Mode = 2;
14018     DK = diag::err_catch_incomplete_ref;
14019   }
14020   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
14021       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
14022     Invalid = true;
14023 
14024   if (!Invalid && !ExDeclType->isDependentType() &&
14025       RequireNonAbstractType(Loc, ExDeclType,
14026                              diag::err_abstract_type_in_decl,
14027                              AbstractVariableType))
14028     Invalid = true;
14029 
14030   // Only the non-fragile NeXT runtime currently supports C++ catches
14031   // of ObjC types, and no runtime supports catching ObjC types by value.
14032   if (!Invalid && getLangOpts().ObjC) {
14033     QualType T = ExDeclType;
14034     if (const ReferenceType *RT = T->getAs<ReferenceType>())
14035       T = RT->getPointeeType();
14036 
14037     if (T->isObjCObjectType()) {
14038       Diag(Loc, diag::err_objc_object_catch);
14039       Invalid = true;
14040     } else if (T->isObjCObjectPointerType()) {
14041       // FIXME: should this be a test for macosx-fragile specifically?
14042       if (getLangOpts().ObjCRuntime.isFragile())
14043         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
14044     }
14045   }
14046 
14047   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
14048                                     ExDeclType, TInfo, SC_None);
14049   ExDecl->setExceptionVariable(true);
14050 
14051   // In ARC, infer 'retaining' for variables of retainable type.
14052   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
14053     Invalid = true;
14054 
14055   if (!Invalid && !ExDeclType->isDependentType()) {
14056     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
14057       // Insulate this from anything else we might currently be parsing.
14058       EnterExpressionEvaluationContext scope(
14059           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14060 
14061       // C++ [except.handle]p16:
14062       //   The object declared in an exception-declaration or, if the
14063       //   exception-declaration does not specify a name, a temporary (12.2) is
14064       //   copy-initialized (8.5) from the exception object. [...]
14065       //   The object is destroyed when the handler exits, after the destruction
14066       //   of any automatic objects initialized within the handler.
14067       //
14068       // We just pretend to initialize the object with itself, then make sure
14069       // it can be destroyed later.
14070       QualType initType = Context.getExceptionObjectType(ExDeclType);
14071 
14072       InitializedEntity entity =
14073         InitializedEntity::InitializeVariable(ExDecl);
14074       InitializationKind initKind =
14075         InitializationKind::CreateCopy(Loc, SourceLocation());
14076 
14077       Expr *opaqueValue =
14078         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
14079       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
14080       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
14081       if (result.isInvalid())
14082         Invalid = true;
14083       else {
14084         // If the constructor used was non-trivial, set this as the
14085         // "initializer".
14086         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
14087         if (!construct->getConstructor()->isTrivial()) {
14088           Expr *init = MaybeCreateExprWithCleanups(construct);
14089           ExDecl->setInit(init);
14090         }
14091 
14092         // And make sure it's destructable.
14093         FinalizeVarWithDestructor(ExDecl, recordType);
14094       }
14095     }
14096   }
14097 
14098   if (Invalid)
14099     ExDecl->setInvalidDecl();
14100 
14101   return ExDecl;
14102 }
14103 
14104 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
14105 /// handler.
14106 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
14107   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14108   bool Invalid = D.isInvalidType();
14109 
14110   // Check for unexpanded parameter packs.
14111   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14112                                       UPPC_ExceptionType)) {
14113     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
14114                                              D.getIdentifierLoc());
14115     Invalid = true;
14116   }
14117 
14118   IdentifierInfo *II = D.getIdentifier();
14119   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
14120                                              LookupOrdinaryName,
14121                                              ForVisibleRedeclaration)) {
14122     // The scope should be freshly made just for us. There is just no way
14123     // it contains any previous declaration, except for function parameters in
14124     // a function-try-block's catch statement.
14125     assert(!S->isDeclScope(PrevDecl));
14126     if (isDeclInScope(PrevDecl, CurContext, S)) {
14127       Diag(D.getIdentifierLoc(), diag::err_redefinition)
14128         << D.getIdentifier();
14129       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14130       Invalid = true;
14131     } else if (PrevDecl->isTemplateParameter())
14132       // Maybe we will complain about the shadowed template parameter.
14133       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14134   }
14135 
14136   if (D.getCXXScopeSpec().isSet() && !Invalid) {
14137     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
14138       << D.getCXXScopeSpec().getRange();
14139     Invalid = true;
14140   }
14141 
14142   VarDecl *ExDecl = BuildExceptionDeclaration(
14143       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
14144   if (Invalid)
14145     ExDecl->setInvalidDecl();
14146 
14147   // Add the exception declaration into this scope.
14148   if (II)
14149     PushOnScopeChains(ExDecl, S);
14150   else
14151     CurContext->addDecl(ExDecl);
14152 
14153   ProcessDeclAttributes(S, ExDecl, D);
14154   return ExDecl;
14155 }
14156 
14157 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14158                                          Expr *AssertExpr,
14159                                          Expr *AssertMessageExpr,
14160                                          SourceLocation RParenLoc) {
14161   StringLiteral *AssertMessage =
14162       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14163 
14164   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14165     return nullptr;
14166 
14167   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14168                                       AssertMessage, RParenLoc, false);
14169 }
14170 
14171 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14172                                          Expr *AssertExpr,
14173                                          StringLiteral *AssertMessage,
14174                                          SourceLocation RParenLoc,
14175                                          bool Failed) {
14176   assert(AssertExpr != nullptr && "Expected non-null condition");
14177   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14178       !Failed) {
14179     // In a static_assert-declaration, the constant-expression shall be a
14180     // constant expression that can be contextually converted to bool.
14181     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14182     if (Converted.isInvalid())
14183       Failed = true;
14184 
14185     llvm::APSInt Cond;
14186     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14187           diag::err_static_assert_expression_is_not_constant,
14188           /*AllowFold=*/false).isInvalid())
14189       Failed = true;
14190 
14191     if (!Failed && !Cond) {
14192       SmallString<256> MsgBuffer;
14193       llvm::raw_svector_ostream Msg(MsgBuffer);
14194       if (AssertMessage)
14195         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14196 
14197       Expr *InnerCond = nullptr;
14198       std::string InnerCondDescription;
14199       std::tie(InnerCond, InnerCondDescription) =
14200         findFailedBooleanCondition(Converted.get());
14201       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14202                     && !isa<IntegerLiteral>(InnerCond)) {
14203         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14204           << InnerCondDescription << !AssertMessage
14205           << Msg.str() << InnerCond->getSourceRange();
14206       } else {
14207         Diag(StaticAssertLoc, diag::err_static_assert_failed)
14208           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14209       }
14210       Failed = true;
14211     }
14212   }
14213 
14214   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14215                                                   /*DiscardedValue*/false,
14216                                                   /*IsConstexpr*/true);
14217   if (FullAssertExpr.isInvalid())
14218     Failed = true;
14219   else
14220     AssertExpr = FullAssertExpr.get();
14221 
14222   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14223                                         AssertExpr, AssertMessage, RParenLoc,
14224                                         Failed);
14225 
14226   CurContext->addDecl(Decl);
14227   return Decl;
14228 }
14229 
14230 /// Perform semantic analysis of the given friend type declaration.
14231 ///
14232 /// \returns A friend declaration that.
14233 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14234                                       SourceLocation FriendLoc,
14235                                       TypeSourceInfo *TSInfo) {
14236   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14237 
14238   QualType T = TSInfo->getType();
14239   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14240 
14241   // C++03 [class.friend]p2:
14242   //   An elaborated-type-specifier shall be used in a friend declaration
14243   //   for a class.*
14244   //
14245   //   * The class-key of the elaborated-type-specifier is required.
14246   if (!CodeSynthesisContexts.empty()) {
14247     // Do not complain about the form of friend template types during any kind
14248     // of code synthesis. For template instantiation, we will have complained
14249     // when the template was defined.
14250   } else {
14251     if (!T->isElaboratedTypeSpecifier()) {
14252       // If we evaluated the type to a record type, suggest putting
14253       // a tag in front.
14254       if (const RecordType *RT = T->getAs<RecordType>()) {
14255         RecordDecl *RD = RT->getDecl();
14256 
14257         SmallString<16> InsertionText(" ");
14258         InsertionText += RD->getKindName();
14259 
14260         Diag(TypeRange.getBegin(),
14261              getLangOpts().CPlusPlus11 ?
14262                diag::warn_cxx98_compat_unelaborated_friend_type :
14263                diag::ext_unelaborated_friend_type)
14264           << (unsigned) RD->getTagKind()
14265           << T
14266           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14267                                         InsertionText);
14268       } else {
14269         Diag(FriendLoc,
14270              getLangOpts().CPlusPlus11 ?
14271                diag::warn_cxx98_compat_nonclass_type_friend :
14272                diag::ext_nonclass_type_friend)
14273           << T
14274           << TypeRange;
14275       }
14276     } else if (T->getAs<EnumType>()) {
14277       Diag(FriendLoc,
14278            getLangOpts().CPlusPlus11 ?
14279              diag::warn_cxx98_compat_enum_friend :
14280              diag::ext_enum_friend)
14281         << T
14282         << TypeRange;
14283     }
14284 
14285     // C++11 [class.friend]p3:
14286     //   A friend declaration that does not declare a function shall have one
14287     //   of the following forms:
14288     //     friend elaborated-type-specifier ;
14289     //     friend simple-type-specifier ;
14290     //     friend typename-specifier ;
14291     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14292       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14293   }
14294 
14295   //   If the type specifier in a friend declaration designates a (possibly
14296   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14297   //   the friend declaration is ignored.
14298   return FriendDecl::Create(Context, CurContext,
14299                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14300                             FriendLoc);
14301 }
14302 
14303 /// Handle a friend tag declaration where the scope specifier was
14304 /// templated.
14305 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14306                                     unsigned TagSpec, SourceLocation TagLoc,
14307                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14308                                     SourceLocation NameLoc,
14309                                     const ParsedAttributesView &Attr,
14310                                     MultiTemplateParamsArg TempParamLists) {
14311   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14312 
14313   bool IsMemberSpecialization = false;
14314   bool Invalid = false;
14315 
14316   if (TemplateParameterList *TemplateParams =
14317           MatchTemplateParametersToScopeSpecifier(
14318               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14319               IsMemberSpecialization, Invalid)) {
14320     if (TemplateParams->size() > 0) {
14321       // This is a declaration of a class template.
14322       if (Invalid)
14323         return nullptr;
14324 
14325       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14326                                 NameLoc, Attr, TemplateParams, AS_public,
14327                                 /*ModulePrivateLoc=*/SourceLocation(),
14328                                 FriendLoc, TempParamLists.size() - 1,
14329                                 TempParamLists.data()).get();
14330     } else {
14331       // The "template<>" header is extraneous.
14332       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14333         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14334       IsMemberSpecialization = true;
14335     }
14336   }
14337 
14338   if (Invalid) return nullptr;
14339 
14340   bool isAllExplicitSpecializations = true;
14341   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14342     if (TempParamLists[I]->size()) {
14343       isAllExplicitSpecializations = false;
14344       break;
14345     }
14346   }
14347 
14348   // FIXME: don't ignore attributes.
14349 
14350   // If it's explicit specializations all the way down, just forget
14351   // about the template header and build an appropriate non-templated
14352   // friend.  TODO: for source fidelity, remember the headers.
14353   if (isAllExplicitSpecializations) {
14354     if (SS.isEmpty()) {
14355       bool Owned = false;
14356       bool IsDependent = false;
14357       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14358                       Attr, AS_public,
14359                       /*ModulePrivateLoc=*/SourceLocation(),
14360                       MultiTemplateParamsArg(), Owned, IsDependent,
14361                       /*ScopedEnumKWLoc=*/SourceLocation(),
14362                       /*ScopedEnumUsesClassTag=*/false,
14363                       /*UnderlyingType=*/TypeResult(),
14364                       /*IsTypeSpecifier=*/false,
14365                       /*IsTemplateParamOrArg=*/false);
14366     }
14367 
14368     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14369     ElaboratedTypeKeyword Keyword
14370       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14371     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14372                                    *Name, NameLoc);
14373     if (T.isNull())
14374       return nullptr;
14375 
14376     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14377     if (isa<DependentNameType>(T)) {
14378       DependentNameTypeLoc TL =
14379           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14380       TL.setElaboratedKeywordLoc(TagLoc);
14381       TL.setQualifierLoc(QualifierLoc);
14382       TL.setNameLoc(NameLoc);
14383     } else {
14384       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14385       TL.setElaboratedKeywordLoc(TagLoc);
14386       TL.setQualifierLoc(QualifierLoc);
14387       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14388     }
14389 
14390     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14391                                             TSI, FriendLoc, TempParamLists);
14392     Friend->setAccess(AS_public);
14393     CurContext->addDecl(Friend);
14394     return Friend;
14395   }
14396 
14397   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14398 
14399 
14400 
14401   // Handle the case of a templated-scope friend class.  e.g.
14402   //   template <class T> class A<T>::B;
14403   // FIXME: we don't support these right now.
14404   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14405     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14406   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14407   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14408   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14409   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14410   TL.setElaboratedKeywordLoc(TagLoc);
14411   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14412   TL.setNameLoc(NameLoc);
14413 
14414   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14415                                           TSI, FriendLoc, TempParamLists);
14416   Friend->setAccess(AS_public);
14417   Friend->setUnsupportedFriend(true);
14418   CurContext->addDecl(Friend);
14419   return Friend;
14420 }
14421 
14422 /// Handle a friend type declaration.  This works in tandem with
14423 /// ActOnTag.
14424 ///
14425 /// Notes on friend class templates:
14426 ///
14427 /// We generally treat friend class declarations as if they were
14428 /// declaring a class.  So, for example, the elaborated type specifier
14429 /// in a friend declaration is required to obey the restrictions of a
14430 /// class-head (i.e. no typedefs in the scope chain), template
14431 /// parameters are required to match up with simple template-ids, &c.
14432 /// However, unlike when declaring a template specialization, it's
14433 /// okay to refer to a template specialization without an empty
14434 /// template parameter declaration, e.g.
14435 ///   friend class A<T>::B<unsigned>;
14436 /// We permit this as a special case; if there are any template
14437 /// parameters present at all, require proper matching, i.e.
14438 ///   template <> template \<class T> friend class A<int>::B;
14439 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14440                                 MultiTemplateParamsArg TempParams) {
14441   SourceLocation Loc = DS.getBeginLoc();
14442 
14443   assert(DS.isFriendSpecified());
14444   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14445 
14446   // C++ [class.friend]p3:
14447   // A friend declaration that does not declare a function shall have one of
14448   // the following forms:
14449   //     friend elaborated-type-specifier ;
14450   //     friend simple-type-specifier ;
14451   //     friend typename-specifier ;
14452   //
14453   // Any declaration with a type qualifier does not have that form. (It's
14454   // legal to specify a qualified type as a friend, you just can't write the
14455   // keywords.)
14456   if (DS.getTypeQualifiers()) {
14457     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14458       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14459     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14460       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14461     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14462       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14463     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14464       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14465     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14466       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14467   }
14468 
14469   // Try to convert the decl specifier to a type.  This works for
14470   // friend templates because ActOnTag never produces a ClassTemplateDecl
14471   // for a TUK_Friend.
14472   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14473   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14474   QualType T = TSI->getType();
14475   if (TheDeclarator.isInvalidType())
14476     return nullptr;
14477 
14478   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14479     return nullptr;
14480 
14481   // This is definitely an error in C++98.  It's probably meant to
14482   // be forbidden in C++0x, too, but the specification is just
14483   // poorly written.
14484   //
14485   // The problem is with declarations like the following:
14486   //   template <T> friend A<T>::foo;
14487   // where deciding whether a class C is a friend or not now hinges
14488   // on whether there exists an instantiation of A that causes
14489   // 'foo' to equal C.  There are restrictions on class-heads
14490   // (which we declare (by fiat) elaborated friend declarations to
14491   // be) that makes this tractable.
14492   //
14493   // FIXME: handle "template <> friend class A<T>;", which
14494   // is possibly well-formed?  Who even knows?
14495   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14496     Diag(Loc, diag::err_tagless_friend_type_template)
14497       << DS.getSourceRange();
14498     return nullptr;
14499   }
14500 
14501   // C++98 [class.friend]p1: A friend of a class is a function
14502   //   or class that is not a member of the class . . .
14503   // This is fixed in DR77, which just barely didn't make the C++03
14504   // deadline.  It's also a very silly restriction that seriously
14505   // affects inner classes and which nobody else seems to implement;
14506   // thus we never diagnose it, not even in -pedantic.
14507   //
14508   // But note that we could warn about it: it's always useless to
14509   // friend one of your own members (it's not, however, worthless to
14510   // friend a member of an arbitrary specialization of your template).
14511 
14512   Decl *D;
14513   if (!TempParams.empty())
14514     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14515                                    TempParams,
14516                                    TSI,
14517                                    DS.getFriendSpecLoc());
14518   else
14519     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14520 
14521   if (!D)
14522     return nullptr;
14523 
14524   D->setAccess(AS_public);
14525   CurContext->addDecl(D);
14526 
14527   return D;
14528 }
14529 
14530 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14531                                         MultiTemplateParamsArg TemplateParams) {
14532   const DeclSpec &DS = D.getDeclSpec();
14533 
14534   assert(DS.isFriendSpecified());
14535   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14536 
14537   SourceLocation Loc = D.getIdentifierLoc();
14538   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14539 
14540   // C++ [class.friend]p1
14541   //   A friend of a class is a function or class....
14542   // Note that this sees through typedefs, which is intended.
14543   // It *doesn't* see through dependent types, which is correct
14544   // according to [temp.arg.type]p3:
14545   //   If a declaration acquires a function type through a
14546   //   type dependent on a template-parameter and this causes
14547   //   a declaration that does not use the syntactic form of a
14548   //   function declarator to have a function type, the program
14549   //   is ill-formed.
14550   if (!TInfo->getType()->isFunctionType()) {
14551     Diag(Loc, diag::err_unexpected_friend);
14552 
14553     // It might be worthwhile to try to recover by creating an
14554     // appropriate declaration.
14555     return nullptr;
14556   }
14557 
14558   // C++ [namespace.memdef]p3
14559   //  - If a friend declaration in a non-local class first declares a
14560   //    class or function, the friend class or function is a member
14561   //    of the innermost enclosing namespace.
14562   //  - The name of the friend is not found by simple name lookup
14563   //    until a matching declaration is provided in that namespace
14564   //    scope (either before or after the class declaration granting
14565   //    friendship).
14566   //  - If a friend function is called, its name may be found by the
14567   //    name lookup that considers functions from namespaces and
14568   //    classes associated with the types of the function arguments.
14569   //  - When looking for a prior declaration of a class or a function
14570   //    declared as a friend, scopes outside the innermost enclosing
14571   //    namespace scope are not considered.
14572 
14573   CXXScopeSpec &SS = D.getCXXScopeSpec();
14574   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14575   assert(NameInfo.getName());
14576 
14577   // Check for unexpanded parameter packs.
14578   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14579       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14580       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14581     return nullptr;
14582 
14583   // The context we found the declaration in, or in which we should
14584   // create the declaration.
14585   DeclContext *DC;
14586   Scope *DCScope = S;
14587   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14588                         ForExternalRedeclaration);
14589 
14590   // There are five cases here.
14591   //   - There's no scope specifier and we're in a local class. Only look
14592   //     for functions declared in the immediately-enclosing block scope.
14593   // We recover from invalid scope qualifiers as if they just weren't there.
14594   FunctionDecl *FunctionContainingLocalClass = nullptr;
14595   if ((SS.isInvalid() || !SS.isSet()) &&
14596       (FunctionContainingLocalClass =
14597            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14598     // C++11 [class.friend]p11:
14599     //   If a friend declaration appears in a local class and the name
14600     //   specified is an unqualified name, a prior declaration is
14601     //   looked up without considering scopes that are outside the
14602     //   innermost enclosing non-class scope. For a friend function
14603     //   declaration, if there is no prior declaration, the program is
14604     //   ill-formed.
14605 
14606     // Find the innermost enclosing non-class scope. This is the block
14607     // scope containing the local class definition (or for a nested class,
14608     // the outer local class).
14609     DCScope = S->getFnParent();
14610 
14611     // Look up the function name in the scope.
14612     Previous.clear(LookupLocalFriendName);
14613     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14614 
14615     if (!Previous.empty()) {
14616       // All possible previous declarations must have the same context:
14617       // either they were declared at block scope or they are members of
14618       // one of the enclosing local classes.
14619       DC = Previous.getRepresentativeDecl()->getDeclContext();
14620     } else {
14621       // This is ill-formed, but provide the context that we would have
14622       // declared the function in, if we were permitted to, for error recovery.
14623       DC = FunctionContainingLocalClass;
14624     }
14625     adjustContextForLocalExternDecl(DC);
14626 
14627     // C++ [class.friend]p6:
14628     //   A function can be defined in a friend declaration of a class if and
14629     //   only if the class is a non-local class (9.8), the function name is
14630     //   unqualified, and the function has namespace scope.
14631     if (D.isFunctionDefinition()) {
14632       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14633     }
14634 
14635   //   - There's no scope specifier, in which case we just go to the
14636   //     appropriate scope and look for a function or function template
14637   //     there as appropriate.
14638   } else if (SS.isInvalid() || !SS.isSet()) {
14639     // C++11 [namespace.memdef]p3:
14640     //   If the name in a friend declaration is neither qualified nor
14641     //   a template-id and the declaration is a function or an
14642     //   elaborated-type-specifier, the lookup to determine whether
14643     //   the entity has been previously declared shall not consider
14644     //   any scopes outside the innermost enclosing namespace.
14645     bool isTemplateId =
14646         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14647 
14648     // Find the appropriate context according to the above.
14649     DC = CurContext;
14650 
14651     // Skip class contexts.  If someone can cite chapter and verse
14652     // for this behavior, that would be nice --- it's what GCC and
14653     // EDG do, and it seems like a reasonable intent, but the spec
14654     // really only says that checks for unqualified existing
14655     // declarations should stop at the nearest enclosing namespace,
14656     // not that they should only consider the nearest enclosing
14657     // namespace.
14658     while (DC->isRecord())
14659       DC = DC->getParent();
14660 
14661     DeclContext *LookupDC = DC;
14662     while (LookupDC->isTransparentContext())
14663       LookupDC = LookupDC->getParent();
14664 
14665     while (true) {
14666       LookupQualifiedName(Previous, LookupDC);
14667 
14668       if (!Previous.empty()) {
14669         DC = LookupDC;
14670         break;
14671       }
14672 
14673       if (isTemplateId) {
14674         if (isa<TranslationUnitDecl>(LookupDC)) break;
14675       } else {
14676         if (LookupDC->isFileContext()) break;
14677       }
14678       LookupDC = LookupDC->getParent();
14679     }
14680 
14681     DCScope = getScopeForDeclContext(S, DC);
14682 
14683   //   - There's a non-dependent scope specifier, in which case we
14684   //     compute it and do a previous lookup there for a function
14685   //     or function template.
14686   } else if (!SS.getScopeRep()->isDependent()) {
14687     DC = computeDeclContext(SS);
14688     if (!DC) return nullptr;
14689 
14690     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14691 
14692     LookupQualifiedName(Previous, DC);
14693 
14694     // C++ [class.friend]p1: A friend of a class is a function or
14695     //   class that is not a member of the class . . .
14696     if (DC->Equals(CurContext))
14697       Diag(DS.getFriendSpecLoc(),
14698            getLangOpts().CPlusPlus11 ?
14699              diag::warn_cxx98_compat_friend_is_member :
14700              diag::err_friend_is_member);
14701 
14702     if (D.isFunctionDefinition()) {
14703       // C++ [class.friend]p6:
14704       //   A function can be defined in a friend declaration of a class if and
14705       //   only if the class is a non-local class (9.8), the function name is
14706       //   unqualified, and the function has namespace scope.
14707       //
14708       // FIXME: We should only do this if the scope specifier names the
14709       // innermost enclosing namespace; otherwise the fixit changes the
14710       // meaning of the code.
14711       SemaDiagnosticBuilder DB
14712         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14713 
14714       DB << SS.getScopeRep();
14715       if (DC->isFileContext())
14716         DB << FixItHint::CreateRemoval(SS.getRange());
14717       SS.clear();
14718     }
14719 
14720   //   - There's a scope specifier that does not match any template
14721   //     parameter lists, in which case we use some arbitrary context,
14722   //     create a method or method template, and wait for instantiation.
14723   //   - There's a scope specifier that does match some template
14724   //     parameter lists, which we don't handle right now.
14725   } else {
14726     if (D.isFunctionDefinition()) {
14727       // C++ [class.friend]p6:
14728       //   A function can be defined in a friend declaration of a class if and
14729       //   only if the class is a non-local class (9.8), the function name is
14730       //   unqualified, and the function has namespace scope.
14731       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14732         << SS.getScopeRep();
14733     }
14734 
14735     DC = CurContext;
14736     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14737   }
14738 
14739   if (!DC->isRecord()) {
14740     int DiagArg = -1;
14741     switch (D.getName().getKind()) {
14742     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14743     case UnqualifiedIdKind::IK_ConstructorName:
14744       DiagArg = 0;
14745       break;
14746     case UnqualifiedIdKind::IK_DestructorName:
14747       DiagArg = 1;
14748       break;
14749     case UnqualifiedIdKind::IK_ConversionFunctionId:
14750       DiagArg = 2;
14751       break;
14752     case UnqualifiedIdKind::IK_DeductionGuideName:
14753       DiagArg = 3;
14754       break;
14755     case UnqualifiedIdKind::IK_Identifier:
14756     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14757     case UnqualifiedIdKind::IK_LiteralOperatorId:
14758     case UnqualifiedIdKind::IK_OperatorFunctionId:
14759     case UnqualifiedIdKind::IK_TemplateId:
14760       break;
14761     }
14762     // This implies that it has to be an operator or function.
14763     if (DiagArg >= 0) {
14764       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14765       return nullptr;
14766     }
14767   }
14768 
14769   // FIXME: This is an egregious hack to cope with cases where the scope stack
14770   // does not contain the declaration context, i.e., in an out-of-line
14771   // definition of a class.
14772   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14773   if (!DCScope) {
14774     FakeDCScope.setEntity(DC);
14775     DCScope = &FakeDCScope;
14776   }
14777 
14778   bool AddToScope = true;
14779   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14780                                           TemplateParams, AddToScope);
14781   if (!ND) return nullptr;
14782 
14783   assert(ND->getLexicalDeclContext() == CurContext);
14784 
14785   // If we performed typo correction, we might have added a scope specifier
14786   // and changed the decl context.
14787   DC = ND->getDeclContext();
14788 
14789   // Add the function declaration to the appropriate lookup tables,
14790   // adjusting the redeclarations list as necessary.  We don't
14791   // want to do this yet if the friending class is dependent.
14792   //
14793   // Also update the scope-based lookup if the target context's
14794   // lookup context is in lexical scope.
14795   if (!CurContext->isDependentContext()) {
14796     DC = DC->getRedeclContext();
14797     DC->makeDeclVisibleInContext(ND);
14798     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14799       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14800   }
14801 
14802   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14803                                        D.getIdentifierLoc(), ND,
14804                                        DS.getFriendSpecLoc());
14805   FrD->setAccess(AS_public);
14806   CurContext->addDecl(FrD);
14807 
14808   if (ND->isInvalidDecl()) {
14809     FrD->setInvalidDecl();
14810   } else {
14811     if (DC->isRecord()) CheckFriendAccess(ND);
14812 
14813     FunctionDecl *FD;
14814     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14815       FD = FTD->getTemplatedDecl();
14816     else
14817       FD = cast<FunctionDecl>(ND);
14818 
14819     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14820     // default argument expression, that declaration shall be a definition
14821     // and shall be the only declaration of the function or function
14822     // template in the translation unit.
14823     if (functionDeclHasDefaultArgument(FD)) {
14824       // We can't look at FD->getPreviousDecl() because it may not have been set
14825       // if we're in a dependent context. If the function is known to be a
14826       // redeclaration, we will have narrowed Previous down to the right decl.
14827       if (D.isRedeclaration()) {
14828         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14829         Diag(Previous.getRepresentativeDecl()->getLocation(),
14830              diag::note_previous_declaration);
14831       } else if (!D.isFunctionDefinition())
14832         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14833     }
14834 
14835     // Mark templated-scope function declarations as unsupported.
14836     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14837       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14838         << SS.getScopeRep() << SS.getRange()
14839         << cast<CXXRecordDecl>(CurContext);
14840       FrD->setUnsupportedFriend(true);
14841     }
14842   }
14843 
14844   return ND;
14845 }
14846 
14847 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14848   AdjustDeclIfTemplate(Dcl);
14849 
14850   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14851   if (!Fn) {
14852     Diag(DelLoc, diag::err_deleted_non_function);
14853     return;
14854   }
14855 
14856   // Deleted function does not have a body.
14857   Fn->setWillHaveBody(false);
14858 
14859   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14860     // Don't consider the implicit declaration we generate for explicit
14861     // specializations. FIXME: Do not generate these implicit declarations.
14862     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14863          Prev->getPreviousDecl()) &&
14864         !Prev->isDefined()) {
14865       Diag(DelLoc, diag::err_deleted_decl_not_first);
14866       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14867            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14868                               : diag::note_previous_declaration);
14869     }
14870     // If the declaration wasn't the first, we delete the function anyway for
14871     // recovery.
14872     Fn = Fn->getCanonicalDecl();
14873   }
14874 
14875   // dllimport/dllexport cannot be deleted.
14876   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14877     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14878     Fn->setInvalidDecl();
14879   }
14880 
14881   if (Fn->isDeleted())
14882     return;
14883 
14884   // See if we're deleting a function which is already known to override a
14885   // non-deleted virtual function.
14886   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14887     bool IssuedDiagnostic = false;
14888     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14889       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14890         if (!IssuedDiagnostic) {
14891           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14892           IssuedDiagnostic = true;
14893         }
14894         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14895       }
14896     }
14897     // If this function was implicitly deleted because it was defaulted,
14898     // explain why it was deleted.
14899     if (IssuedDiagnostic && MD->isDefaulted())
14900       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14901                                 /*Diagnose*/true);
14902   }
14903 
14904   // C++11 [basic.start.main]p3:
14905   //   A program that defines main as deleted [...] is ill-formed.
14906   if (Fn->isMain())
14907     Diag(DelLoc, diag::err_deleted_main);
14908 
14909   // C++11 [dcl.fct.def.delete]p4:
14910   //  A deleted function is implicitly inline.
14911   Fn->setImplicitlyInline();
14912   Fn->setDeletedAsWritten();
14913 }
14914 
14915 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14916   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14917 
14918   if (MD) {
14919     if (MD->getParent()->isDependentType()) {
14920       MD->setDefaulted();
14921       MD->setExplicitlyDefaulted();
14922       return;
14923     }
14924 
14925     CXXSpecialMember Member = getSpecialMember(MD);
14926     if (Member == CXXInvalid) {
14927       if (!MD->isInvalidDecl())
14928         Diag(DefaultLoc, diag::err_default_special_members);
14929       return;
14930     }
14931 
14932     MD->setDefaulted();
14933     MD->setExplicitlyDefaulted();
14934 
14935     // Unset that we will have a body for this function. We might not,
14936     // if it turns out to be trivial, and we don't need this marking now
14937     // that we've marked it as defaulted.
14938     MD->setWillHaveBody(false);
14939 
14940     // If this definition appears within the record, do the checking when
14941     // the record is complete.
14942     const FunctionDecl *Primary = MD;
14943     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14944       // Ask the template instantiation pattern that actually had the
14945       // '= default' on it.
14946       Primary = Pattern;
14947 
14948     // If the method was defaulted on its first declaration, we will have
14949     // already performed the checking in CheckCompletedCXXClass. Such a
14950     // declaration doesn't trigger an implicit definition.
14951     if (Primary->getCanonicalDecl()->isDefaulted())
14952       return;
14953 
14954     CheckExplicitlyDefaultedSpecialMember(MD);
14955 
14956     if (!MD->isInvalidDecl())
14957       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14958   } else {
14959     Diag(DefaultLoc, diag::err_default_special_members);
14960   }
14961 }
14962 
14963 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14964   for (Stmt *SubStmt : S->children()) {
14965     if (!SubStmt)
14966       continue;
14967     if (isa<ReturnStmt>(SubStmt))
14968       Self.Diag(SubStmt->getBeginLoc(),
14969                 diag::err_return_in_constructor_handler);
14970     if (!isa<Expr>(SubStmt))
14971       SearchForReturnInStmt(Self, SubStmt);
14972   }
14973 }
14974 
14975 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14976   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14977     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14978     SearchForReturnInStmt(*this, Handler);
14979   }
14980 }
14981 
14982 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14983                                              const CXXMethodDecl *Old) {
14984   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14985   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14986 
14987   if (OldFT->hasExtParameterInfos()) {
14988     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14989       // A parameter of the overriding method should be annotated with noescape
14990       // if the corresponding parameter of the overridden method is annotated.
14991       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14992           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14993         Diag(New->getParamDecl(I)->getLocation(),
14994              diag::warn_overriding_method_missing_noescape);
14995         Diag(Old->getParamDecl(I)->getLocation(),
14996              diag::note_overridden_marked_noescape);
14997       }
14998   }
14999 
15000   // Virtual overrides must have the same code_seg.
15001   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
15002   const auto *NewCSA = New->getAttr<CodeSegAttr>();
15003   if ((NewCSA || OldCSA) &&
15004       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
15005     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
15006     Diag(Old->getLocation(), diag::note_previous_declaration);
15007     return true;
15008   }
15009 
15010   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
15011 
15012   // If the calling conventions match, everything is fine
15013   if (NewCC == OldCC)
15014     return false;
15015 
15016   // If the calling conventions mismatch because the new function is static,
15017   // suppress the calling convention mismatch error; the error about static
15018   // function override (err_static_overrides_virtual from
15019   // Sema::CheckFunctionDeclaration) is more clear.
15020   if (New->getStorageClass() == SC_Static)
15021     return false;
15022 
15023   Diag(New->getLocation(),
15024        diag::err_conflicting_overriding_cc_attributes)
15025     << New->getDeclName() << New->getType() << Old->getType();
15026   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
15027   return true;
15028 }
15029 
15030 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
15031                                              const CXXMethodDecl *Old) {
15032   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
15033   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
15034 
15035   if (Context.hasSameType(NewTy, OldTy) ||
15036       NewTy->isDependentType() || OldTy->isDependentType())
15037     return false;
15038 
15039   // Check if the return types are covariant
15040   QualType NewClassTy, OldClassTy;
15041 
15042   /// Both types must be pointers or references to classes.
15043   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
15044     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
15045       NewClassTy = NewPT->getPointeeType();
15046       OldClassTy = OldPT->getPointeeType();
15047     }
15048   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
15049     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
15050       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
15051         NewClassTy = NewRT->getPointeeType();
15052         OldClassTy = OldRT->getPointeeType();
15053       }
15054     }
15055   }
15056 
15057   // The return types aren't either both pointers or references to a class type.
15058   if (NewClassTy.isNull()) {
15059     Diag(New->getLocation(),
15060          diag::err_different_return_type_for_overriding_virtual_function)
15061         << New->getDeclName() << NewTy << OldTy
15062         << New->getReturnTypeSourceRange();
15063     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15064         << Old->getReturnTypeSourceRange();
15065 
15066     return true;
15067   }
15068 
15069   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
15070     // C++14 [class.virtual]p8:
15071     //   If the class type in the covariant return type of D::f differs from
15072     //   that of B::f, the class type in the return type of D::f shall be
15073     //   complete at the point of declaration of D::f or shall be the class
15074     //   type D.
15075     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
15076       if (!RT->isBeingDefined() &&
15077           RequireCompleteType(New->getLocation(), NewClassTy,
15078                               diag::err_covariant_return_incomplete,
15079                               New->getDeclName()))
15080         return true;
15081     }
15082 
15083     // Check if the new class derives from the old class.
15084     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
15085       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
15086           << New->getDeclName() << NewTy << OldTy
15087           << New->getReturnTypeSourceRange();
15088       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15089           << Old->getReturnTypeSourceRange();
15090       return true;
15091     }
15092 
15093     // Check if we the conversion from derived to base is valid.
15094     if (CheckDerivedToBaseConversion(
15095             NewClassTy, OldClassTy,
15096             diag::err_covariant_return_inaccessible_base,
15097             diag::err_covariant_return_ambiguous_derived_to_base_conv,
15098             New->getLocation(), New->getReturnTypeSourceRange(),
15099             New->getDeclName(), nullptr)) {
15100       // FIXME: this note won't trigger for delayed access control
15101       // diagnostics, and it's impossible to get an undelayed error
15102       // here from access control during the original parse because
15103       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
15104       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15105           << Old->getReturnTypeSourceRange();
15106       return true;
15107     }
15108   }
15109 
15110   // The qualifiers of the return types must be the same.
15111   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
15112     Diag(New->getLocation(),
15113          diag::err_covariant_return_type_different_qualifications)
15114         << New->getDeclName() << NewTy << OldTy
15115         << New->getReturnTypeSourceRange();
15116     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15117         << Old->getReturnTypeSourceRange();
15118     return true;
15119   }
15120 
15121 
15122   // The new class type must have the same or less qualifiers as the old type.
15123   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
15124     Diag(New->getLocation(),
15125          diag::err_covariant_return_type_class_type_more_qualified)
15126         << New->getDeclName() << NewTy << OldTy
15127         << New->getReturnTypeSourceRange();
15128     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15129         << Old->getReturnTypeSourceRange();
15130     return true;
15131   }
15132 
15133   return false;
15134 }
15135 
15136 /// Mark the given method pure.
15137 ///
15138 /// \param Method the method to be marked pure.
15139 ///
15140 /// \param InitRange the source range that covers the "0" initializer.
15141 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
15142   SourceLocation EndLoc = InitRange.getEnd();
15143   if (EndLoc.isValid())
15144     Method->setRangeEnd(EndLoc);
15145 
15146   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
15147     Method->setPure();
15148     return false;
15149   }
15150 
15151   if (!Method->isInvalidDecl())
15152     Diag(Method->getLocation(), diag::err_non_virtual_pure)
15153       << Method->getDeclName() << InitRange;
15154   return true;
15155 }
15156 
15157 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15158   if (D->getFriendObjectKind())
15159     Diag(D->getLocation(), diag::err_pure_friend);
15160   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15161     CheckPureMethod(M, ZeroLoc);
15162   else
15163     Diag(D->getLocation(), diag::err_illegal_initializer);
15164 }
15165 
15166 /// Determine whether the given declaration is a global variable or
15167 /// static data member.
15168 static bool isNonlocalVariable(const Decl *D) {
15169   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15170     return Var->hasGlobalStorage();
15171 
15172   return false;
15173 }
15174 
15175 /// Invoked when we are about to parse an initializer for the declaration
15176 /// 'Dcl'.
15177 ///
15178 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15179 /// static data member of class X, names should be looked up in the scope of
15180 /// class X. If the declaration had a scope specifier, a scope will have
15181 /// been created and passed in for this purpose. Otherwise, S will be null.
15182 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15183   // If there is no declaration, there was an error parsing it.
15184   if (!D || D->isInvalidDecl())
15185     return;
15186 
15187   // We will always have a nested name specifier here, but this declaration
15188   // might not be out of line if the specifier names the current namespace:
15189   //   extern int n;
15190   //   int ::n = 0;
15191   if (S && D->isOutOfLine())
15192     EnterDeclaratorContext(S, D->getDeclContext());
15193 
15194   // If we are parsing the initializer for a static data member, push a
15195   // new expression evaluation context that is associated with this static
15196   // data member.
15197   if (isNonlocalVariable(D))
15198     PushExpressionEvaluationContext(
15199         ExpressionEvaluationContext::PotentiallyEvaluated, D);
15200 }
15201 
15202 /// Invoked after we are finished parsing an initializer for the declaration D.
15203 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15204   // If there is no declaration, there was an error parsing it.
15205   if (!D || D->isInvalidDecl())
15206     return;
15207 
15208   if (isNonlocalVariable(D))
15209     PopExpressionEvaluationContext();
15210 
15211   if (S && D->isOutOfLine())
15212     ExitDeclaratorContext(S);
15213 }
15214 
15215 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15216 /// C++ if/switch/while/for statement.
15217 /// e.g: "if (int x = f()) {...}"
15218 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15219   // C++ 6.4p2:
15220   // The declarator shall not specify a function or an array.
15221   // The type-specifier-seq shall not contain typedef and shall not declare a
15222   // new class or enumeration.
15223   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15224          "Parser allowed 'typedef' as storage class of condition decl.");
15225 
15226   Decl *Dcl = ActOnDeclarator(S, D);
15227   if (!Dcl)
15228     return true;
15229 
15230   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15231     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15232       << D.getSourceRange();
15233     return true;
15234   }
15235 
15236   return Dcl;
15237 }
15238 
15239 void Sema::LoadExternalVTableUses() {
15240   if (!ExternalSource)
15241     return;
15242 
15243   SmallVector<ExternalVTableUse, 4> VTables;
15244   ExternalSource->ReadUsedVTables(VTables);
15245   SmallVector<VTableUse, 4> NewUses;
15246   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15247     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15248       = VTablesUsed.find(VTables[I].Record);
15249     // Even if a definition wasn't required before, it may be required now.
15250     if (Pos != VTablesUsed.end()) {
15251       if (!Pos->second && VTables[I].DefinitionRequired)
15252         Pos->second = true;
15253       continue;
15254     }
15255 
15256     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15257     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15258   }
15259 
15260   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15261 }
15262 
15263 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15264                           bool DefinitionRequired) {
15265   // Ignore any vtable uses in unevaluated operands or for classes that do
15266   // not have a vtable.
15267   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15268       CurContext->isDependentContext() || isUnevaluatedContext())
15269     return;
15270   // Do not mark as used if compiling for the device outside of the target
15271   // region.
15272   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15273       !isInOpenMPDeclareTargetContext() &&
15274       !isInOpenMPTargetExecutionDirective()) {
15275     if (!DefinitionRequired)
15276       MarkVirtualMembersReferenced(Loc, Class);
15277     return;
15278   }
15279 
15280   // Try to insert this class into the map.
15281   LoadExternalVTableUses();
15282   Class = Class->getCanonicalDecl();
15283   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15284     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15285   if (!Pos.second) {
15286     // If we already had an entry, check to see if we are promoting this vtable
15287     // to require a definition. If so, we need to reappend to the VTableUses
15288     // list, since we may have already processed the first entry.
15289     if (DefinitionRequired && !Pos.first->second) {
15290       Pos.first->second = true;
15291     } else {
15292       // Otherwise, we can early exit.
15293       return;
15294     }
15295   } else {
15296     // The Microsoft ABI requires that we perform the destructor body
15297     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15298     // the deleting destructor is emitted with the vtable, not with the
15299     // destructor definition as in the Itanium ABI.
15300     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15301       CXXDestructorDecl *DD = Class->getDestructor();
15302       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15303         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15304           // If this is an out-of-line declaration, marking it referenced will
15305           // not do anything. Manually call CheckDestructor to look up operator
15306           // delete().
15307           ContextRAII SavedContext(*this, DD);
15308           CheckDestructor(DD);
15309         } else {
15310           MarkFunctionReferenced(Loc, Class->getDestructor());
15311         }
15312       }
15313     }
15314   }
15315 
15316   // Local classes need to have their virtual members marked
15317   // immediately. For all other classes, we mark their virtual members
15318   // at the end of the translation unit.
15319   if (Class->isLocalClass())
15320     MarkVirtualMembersReferenced(Loc, Class);
15321   else
15322     VTableUses.push_back(std::make_pair(Class, Loc));
15323 }
15324 
15325 bool Sema::DefineUsedVTables() {
15326   LoadExternalVTableUses();
15327   if (VTableUses.empty())
15328     return false;
15329 
15330   // Note: The VTableUses vector could grow as a result of marking
15331   // the members of a class as "used", so we check the size each
15332   // time through the loop and prefer indices (which are stable) to
15333   // iterators (which are not).
15334   bool DefinedAnything = false;
15335   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15336     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15337     if (!Class)
15338       continue;
15339     TemplateSpecializationKind ClassTSK =
15340         Class->getTemplateSpecializationKind();
15341 
15342     SourceLocation Loc = VTableUses[I].second;
15343 
15344     bool DefineVTable = true;
15345 
15346     // If this class has a key function, but that key function is
15347     // defined in another translation unit, we don't need to emit the
15348     // vtable even though we're using it.
15349     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15350     if (KeyFunction && !KeyFunction->hasBody()) {
15351       // The key function is in another translation unit.
15352       DefineVTable = false;
15353       TemplateSpecializationKind TSK =
15354           KeyFunction->getTemplateSpecializationKind();
15355       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15356              TSK != TSK_ImplicitInstantiation &&
15357              "Instantiations don't have key functions");
15358       (void)TSK;
15359     } else if (!KeyFunction) {
15360       // If we have a class with no key function that is the subject
15361       // of an explicit instantiation declaration, suppress the
15362       // vtable; it will live with the explicit instantiation
15363       // definition.
15364       bool IsExplicitInstantiationDeclaration =
15365           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15366       for (auto R : Class->redecls()) {
15367         TemplateSpecializationKind TSK
15368           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15369         if (TSK == TSK_ExplicitInstantiationDeclaration)
15370           IsExplicitInstantiationDeclaration = true;
15371         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15372           IsExplicitInstantiationDeclaration = false;
15373           break;
15374         }
15375       }
15376 
15377       if (IsExplicitInstantiationDeclaration)
15378         DefineVTable = false;
15379     }
15380 
15381     // The exception specifications for all virtual members may be needed even
15382     // if we are not providing an authoritative form of the vtable in this TU.
15383     // We may choose to emit it available_externally anyway.
15384     if (!DefineVTable) {
15385       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15386       continue;
15387     }
15388 
15389     // Mark all of the virtual members of this class as referenced, so
15390     // that we can build a vtable. Then, tell the AST consumer that a
15391     // vtable for this class is required.
15392     DefinedAnything = true;
15393     MarkVirtualMembersReferenced(Loc, Class);
15394     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15395     if (VTablesUsed[Canonical])
15396       Consumer.HandleVTable(Class);
15397 
15398     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15399     // no key function or the key function is inlined. Don't warn in C++ ABIs
15400     // that lack key functions, since the user won't be able to make one.
15401     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15402         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15403       const FunctionDecl *KeyFunctionDef = nullptr;
15404       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15405                            KeyFunctionDef->isInlined())) {
15406         Diag(Class->getLocation(),
15407              ClassTSK == TSK_ExplicitInstantiationDefinition
15408                  ? diag::warn_weak_template_vtable
15409                  : diag::warn_weak_vtable)
15410             << Class;
15411       }
15412     }
15413   }
15414   VTableUses.clear();
15415 
15416   return DefinedAnything;
15417 }
15418 
15419 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15420                                                  const CXXRecordDecl *RD) {
15421   for (const auto *I : RD->methods())
15422     if (I->isVirtual() && !I->isPure())
15423       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15424 }
15425 
15426 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15427                                         const CXXRecordDecl *RD,
15428                                         bool ConstexprOnly) {
15429   // Mark all functions which will appear in RD's vtable as used.
15430   CXXFinalOverriderMap FinalOverriders;
15431   RD->getFinalOverriders(FinalOverriders);
15432   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15433                                             E = FinalOverriders.end();
15434        I != E; ++I) {
15435     for (OverridingMethods::const_iterator OI = I->second.begin(),
15436                                            OE = I->second.end();
15437          OI != OE; ++OI) {
15438       assert(OI->second.size() > 0 && "no final overrider");
15439       CXXMethodDecl *Overrider = OI->second.front().Method;
15440 
15441       // C++ [basic.def.odr]p2:
15442       //   [...] A virtual member function is used if it is not pure. [...]
15443       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15444         MarkFunctionReferenced(Loc, Overrider);
15445     }
15446   }
15447 
15448   // Only classes that have virtual bases need a VTT.
15449   if (RD->getNumVBases() == 0)
15450     return;
15451 
15452   for (const auto &I : RD->bases()) {
15453     const CXXRecordDecl *Base =
15454         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15455     if (Base->getNumVBases() == 0)
15456       continue;
15457     MarkVirtualMembersReferenced(Loc, Base);
15458   }
15459 }
15460 
15461 /// SetIvarInitializers - This routine builds initialization ASTs for the
15462 /// Objective-C implementation whose ivars need be initialized.
15463 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15464   if (!getLangOpts().CPlusPlus)
15465     return;
15466   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15467     SmallVector<ObjCIvarDecl*, 8> ivars;
15468     CollectIvarsToConstructOrDestruct(OID, ivars);
15469     if (ivars.empty())
15470       return;
15471     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15472     for (unsigned i = 0; i < ivars.size(); i++) {
15473       FieldDecl *Field = ivars[i];
15474       if (Field->isInvalidDecl())
15475         continue;
15476 
15477       CXXCtorInitializer *Member;
15478       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15479       InitializationKind InitKind =
15480         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15481 
15482       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15483       ExprResult MemberInit =
15484         InitSeq.Perform(*this, InitEntity, InitKind, None);
15485       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15486       // Note, MemberInit could actually come back empty if no initialization
15487       // is required (e.g., because it would call a trivial default constructor)
15488       if (!MemberInit.get() || MemberInit.isInvalid())
15489         continue;
15490 
15491       Member =
15492         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15493                                          SourceLocation(),
15494                                          MemberInit.getAs<Expr>(),
15495                                          SourceLocation());
15496       AllToInit.push_back(Member);
15497 
15498       // Be sure that the destructor is accessible and is marked as referenced.
15499       if (const RecordType *RecordTy =
15500               Context.getBaseElementType(Field->getType())
15501                   ->getAs<RecordType>()) {
15502         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15503         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15504           MarkFunctionReferenced(Field->getLocation(), Destructor);
15505           CheckDestructorAccess(Field->getLocation(), Destructor,
15506                             PDiag(diag::err_access_dtor_ivar)
15507                               << Context.getBaseElementType(Field->getType()));
15508         }
15509       }
15510     }
15511     ObjCImplementation->setIvarInitializers(Context,
15512                                             AllToInit.data(), AllToInit.size());
15513   }
15514 }
15515 
15516 static
15517 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15518                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15519                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15520                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15521                            Sema &S) {
15522   if (Ctor->isInvalidDecl())
15523     return;
15524 
15525   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15526 
15527   // Target may not be determinable yet, for instance if this is a dependent
15528   // call in an uninstantiated template.
15529   if (Target) {
15530     const FunctionDecl *FNTarget = nullptr;
15531     (void)Target->hasBody(FNTarget);
15532     Target = const_cast<CXXConstructorDecl*>(
15533       cast_or_null<CXXConstructorDecl>(FNTarget));
15534   }
15535 
15536   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15537                      // Avoid dereferencing a null pointer here.
15538                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15539 
15540   if (!Current.insert(Canonical).second)
15541     return;
15542 
15543   // We know that beyond here, we aren't chaining into a cycle.
15544   if (!Target || !Target->isDelegatingConstructor() ||
15545       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15546     Valid.insert(Current.begin(), Current.end());
15547     Current.clear();
15548   // We've hit a cycle.
15549   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15550              Current.count(TCanonical)) {
15551     // If we haven't diagnosed this cycle yet, do so now.
15552     if (!Invalid.count(TCanonical)) {
15553       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15554              diag::warn_delegating_ctor_cycle)
15555         << Ctor;
15556 
15557       // Don't add a note for a function delegating directly to itself.
15558       if (TCanonical != Canonical)
15559         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15560 
15561       CXXConstructorDecl *C = Target;
15562       while (C->getCanonicalDecl() != Canonical) {
15563         const FunctionDecl *FNTarget = nullptr;
15564         (void)C->getTargetConstructor()->hasBody(FNTarget);
15565         assert(FNTarget && "Ctor cycle through bodiless function");
15566 
15567         C = const_cast<CXXConstructorDecl*>(
15568           cast<CXXConstructorDecl>(FNTarget));
15569         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15570       }
15571     }
15572 
15573     Invalid.insert(Current.begin(), Current.end());
15574     Current.clear();
15575   } else {
15576     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15577   }
15578 }
15579 
15580 
15581 void Sema::CheckDelegatingCtorCycles() {
15582   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15583 
15584   for (DelegatingCtorDeclsType::iterator
15585          I = DelegatingCtorDecls.begin(ExternalSource),
15586          E = DelegatingCtorDecls.end();
15587        I != E; ++I)
15588     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15589 
15590   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15591     (*CI)->setInvalidDecl();
15592 }
15593 
15594 namespace {
15595   /// AST visitor that finds references to the 'this' expression.
15596   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15597     Sema &S;
15598 
15599   public:
15600     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15601 
15602     bool VisitCXXThisExpr(CXXThisExpr *E) {
15603       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15604         << E->isImplicit();
15605       return false;
15606     }
15607   };
15608 }
15609 
15610 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15611   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15612   if (!TSInfo)
15613     return false;
15614 
15615   TypeLoc TL = TSInfo->getTypeLoc();
15616   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15617   if (!ProtoTL)
15618     return false;
15619 
15620   // C++11 [expr.prim.general]p3:
15621   //   [The expression this] shall not appear before the optional
15622   //   cv-qualifier-seq and it shall not appear within the declaration of a
15623   //   static member function (although its type and value category are defined
15624   //   within a static member function as they are within a non-static member
15625   //   function). [ Note: this is because declaration matching does not occur
15626   //  until the complete declarator is known. - end note ]
15627   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15628   FindCXXThisExpr Finder(*this);
15629 
15630   // If the return type came after the cv-qualifier-seq, check it now.
15631   if (Proto->hasTrailingReturn() &&
15632       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15633     return true;
15634 
15635   // Check the exception specification.
15636   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15637     return true;
15638 
15639   return checkThisInStaticMemberFunctionAttributes(Method);
15640 }
15641 
15642 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15643   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15644   if (!TSInfo)
15645     return false;
15646 
15647   TypeLoc TL = TSInfo->getTypeLoc();
15648   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15649   if (!ProtoTL)
15650     return false;
15651 
15652   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15653   FindCXXThisExpr Finder(*this);
15654 
15655   switch (Proto->getExceptionSpecType()) {
15656   case EST_Unparsed:
15657   case EST_Uninstantiated:
15658   case EST_Unevaluated:
15659   case EST_BasicNoexcept:
15660   case EST_NoThrow:
15661   case EST_DynamicNone:
15662   case EST_MSAny:
15663   case EST_None:
15664     break;
15665 
15666   case EST_DependentNoexcept:
15667   case EST_NoexceptFalse:
15668   case EST_NoexceptTrue:
15669     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15670       return true;
15671     LLVM_FALLTHROUGH;
15672 
15673   case EST_Dynamic:
15674     for (const auto &E : Proto->exceptions()) {
15675       if (!Finder.TraverseType(E))
15676         return true;
15677     }
15678     break;
15679   }
15680 
15681   return false;
15682 }
15683 
15684 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15685   FindCXXThisExpr Finder(*this);
15686 
15687   // Check attributes.
15688   for (const auto *A : Method->attrs()) {
15689     // FIXME: This should be emitted by tblgen.
15690     Expr *Arg = nullptr;
15691     ArrayRef<Expr *> Args;
15692     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15693       Arg = G->getArg();
15694     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15695       Arg = G->getArg();
15696     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15697       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15698     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15699       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15700     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15701       Arg = ETLF->getSuccessValue();
15702       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15703     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15704       Arg = STLF->getSuccessValue();
15705       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15706     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15707       Arg = LR->getArg();
15708     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15709       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15710     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15711       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15712     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15713       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15714     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15715       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15716     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15717       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15718 
15719     if (Arg && !Finder.TraverseStmt(Arg))
15720       return true;
15721 
15722     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15723       if (!Finder.TraverseStmt(Args[I]))
15724         return true;
15725     }
15726   }
15727 
15728   return false;
15729 }
15730 
15731 void Sema::checkExceptionSpecification(
15732     bool IsTopLevel, ExceptionSpecificationType EST,
15733     ArrayRef<ParsedType> DynamicExceptions,
15734     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15735     SmallVectorImpl<QualType> &Exceptions,
15736     FunctionProtoType::ExceptionSpecInfo &ESI) {
15737   Exceptions.clear();
15738   ESI.Type = EST;
15739   if (EST == EST_Dynamic) {
15740     Exceptions.reserve(DynamicExceptions.size());
15741     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15742       // FIXME: Preserve type source info.
15743       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15744 
15745       if (IsTopLevel) {
15746         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15747         collectUnexpandedParameterPacks(ET, Unexpanded);
15748         if (!Unexpanded.empty()) {
15749           DiagnoseUnexpandedParameterPacks(
15750               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15751               Unexpanded);
15752           continue;
15753         }
15754       }
15755 
15756       // Check that the type is valid for an exception spec, and
15757       // drop it if not.
15758       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15759         Exceptions.push_back(ET);
15760     }
15761     ESI.Exceptions = Exceptions;
15762     return;
15763   }
15764 
15765   if (isComputedNoexcept(EST)) {
15766     assert((NoexceptExpr->isTypeDependent() ||
15767             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15768             Context.BoolTy) &&
15769            "Parser should have made sure that the expression is boolean");
15770     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15771       ESI.Type = EST_BasicNoexcept;
15772       return;
15773     }
15774 
15775     ESI.NoexceptExpr = NoexceptExpr;
15776     return;
15777   }
15778 }
15779 
15780 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15781              ExceptionSpecificationType EST,
15782              SourceRange SpecificationRange,
15783              ArrayRef<ParsedType> DynamicExceptions,
15784              ArrayRef<SourceRange> DynamicExceptionRanges,
15785              Expr *NoexceptExpr) {
15786   if (!MethodD)
15787     return;
15788 
15789   // Dig out the method we're referring to.
15790   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15791     MethodD = FunTmpl->getTemplatedDecl();
15792 
15793   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15794   if (!Method)
15795     return;
15796 
15797   // Check the exception specification.
15798   llvm::SmallVector<QualType, 4> Exceptions;
15799   FunctionProtoType::ExceptionSpecInfo ESI;
15800   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15801                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15802                               ESI);
15803 
15804   // Update the exception specification on the function type.
15805   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15806 
15807   if (Method->isStatic())
15808     checkThisInStaticMemberFunctionExceptionSpec(Method);
15809 
15810   if (Method->isVirtual()) {
15811     // Check overrides, which we previously had to delay.
15812     for (const CXXMethodDecl *O : Method->overridden_methods())
15813       CheckOverridingFunctionExceptionSpec(Method, O);
15814   }
15815 }
15816 
15817 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15818 ///
15819 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15820                                        SourceLocation DeclStart, Declarator &D,
15821                                        Expr *BitWidth,
15822                                        InClassInitStyle InitStyle,
15823                                        AccessSpecifier AS,
15824                                        const ParsedAttr &MSPropertyAttr) {
15825   IdentifierInfo *II = D.getIdentifier();
15826   if (!II) {
15827     Diag(DeclStart, diag::err_anonymous_property);
15828     return nullptr;
15829   }
15830   SourceLocation Loc = D.getIdentifierLoc();
15831 
15832   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15833   QualType T = TInfo->getType();
15834   if (getLangOpts().CPlusPlus) {
15835     CheckExtraCXXDefaultArguments(D);
15836 
15837     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15838                                         UPPC_DataMemberType)) {
15839       D.setInvalidType();
15840       T = Context.IntTy;
15841       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15842     }
15843   }
15844 
15845   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15846 
15847   if (D.getDeclSpec().isInlineSpecified())
15848     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15849         << getLangOpts().CPlusPlus17;
15850   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15851     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15852          diag::err_invalid_thread)
15853       << DeclSpec::getSpecifierName(TSCS);
15854 
15855   // Check to see if this name was declared as a member previously
15856   NamedDecl *PrevDecl = nullptr;
15857   LookupResult Previous(*this, II, Loc, LookupMemberName,
15858                         ForVisibleRedeclaration);
15859   LookupName(Previous, S);
15860   switch (Previous.getResultKind()) {
15861   case LookupResult::Found:
15862   case LookupResult::FoundUnresolvedValue:
15863     PrevDecl = Previous.getAsSingle<NamedDecl>();
15864     break;
15865 
15866   case LookupResult::FoundOverloaded:
15867     PrevDecl = Previous.getRepresentativeDecl();
15868     break;
15869 
15870   case LookupResult::NotFound:
15871   case LookupResult::NotFoundInCurrentInstantiation:
15872   case LookupResult::Ambiguous:
15873     break;
15874   }
15875 
15876   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15877     // Maybe we will complain about the shadowed template parameter.
15878     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15879     // Just pretend that we didn't see the previous declaration.
15880     PrevDecl = nullptr;
15881   }
15882 
15883   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15884     PrevDecl = nullptr;
15885 
15886   SourceLocation TSSL = D.getBeginLoc();
15887   MSPropertyDecl *NewPD =
15888       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15889                              MSPropertyAttr.getPropertyDataGetter(),
15890                              MSPropertyAttr.getPropertyDataSetter());
15891   ProcessDeclAttributes(TUScope, NewPD, D);
15892   NewPD->setAccess(AS);
15893 
15894   if (NewPD->isInvalidDecl())
15895     Record->setInvalidDecl();
15896 
15897   if (D.getDeclSpec().isModulePrivateSpecified())
15898     NewPD->setModulePrivate();
15899 
15900   if (NewPD->isInvalidDecl() && PrevDecl) {
15901     // Don't introduce NewFD into scope; there's already something
15902     // with the same name in the same scope.
15903   } else if (II) {
15904     PushOnScopeChains(NewPD, S);
15905   } else
15906     Record->addDecl(NewPD);
15907 
15908   return NewPD;
15909 }
15910