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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65         : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getBeginLoc(),
97                      diag::err_param_default_argument_references_param)
98              << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getBeginLoc(),
105                        diag::err_param_default_argument_references_local)
106                << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getBeginLoc(),
118                    diag::err_param_default_argument_references_this)
119            << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168 
169   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170     EST = EST_BasicNoexcept;
171 
172   switch (EST) {
173   case EST_Unparsed:
174   case EST_Uninstantiated:
175   case EST_Unevaluated:
176     llvm_unreachable("should not see unresolved exception specs here");
177 
178   // If this function can throw any exceptions, make a note of that.
179   case EST_MSAny:
180   case EST_None:
181     // FIXME: Whichever we see last of MSAny and None determines our result.
182     // We should make a consistent, order-independent choice here.
183     ClearExceptions();
184     ComputedEST = EST;
185     return;
186   case EST_NoexceptFalse:
187     ClearExceptions();
188     ComputedEST = EST_None;
189     return;
190   // FIXME: If the call to this decl is using any of its default arguments, we
191   // need to search them for potentially-throwing calls.
192   // If this function has a basic noexcept, it doesn't affect the outcome.
193   case EST_BasicNoexcept:
194   case EST_NoexceptTrue:
195   case EST_NoThrow:
196     return;
197   // If we're still at noexcept(true) and there's a throw() callee,
198   // change to that specification.
199   case EST_DynamicNone:
200     if (ComputedEST == EST_BasicNoexcept)
201       ComputedEST = EST_DynamicNone;
202     return;
203   case EST_DependentNoexcept:
204     llvm_unreachable(
205         "should not generate implicit declarations for dependent cases");
206   case EST_Dynamic:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficient, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found the right previous declaration.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter unless the new
551       // function is a friend declaration in a template class. In the latter
552       // case the default arguments will be inherited when the friend
553       // declaration will be instantiated.
554       if (New->getFriendObjectKind() == Decl::FOK_None ||
555           !New->getLexicalDeclContext()->isDependentContext()) {
556         // It's important to use getInit() here;  getDefaultArg()
557         // strips off any top-level ExprWithCleanups.
558         NewParam->setHasInheritedDefaultArg();
559         if (OldParam->hasUnparsedDefaultArg())
560           NewParam->setUnparsedDefaultArg();
561         else if (OldParam->hasUninstantiatedDefaultArg())
562           NewParam->setUninstantiatedDefaultArg(
563                                        OldParam->getUninstantiatedDefaultArg());
564         else
565           NewParam->setDefaultArg(OldParam->getInit());
566       }
567     } else if (NewParamHasDfl) {
568       if (New->getDescribedFunctionTemplate()) {
569         // Paragraph 4, quoted above, only applies to non-template functions.
570         Diag(NewParam->getLocation(),
571              diag::err_param_default_argument_template_redecl)
572           << NewParam->getDefaultArgRange();
573         Diag(PrevForDefaultArgs->getLocation(),
574              diag::note_template_prev_declaration)
575             << false;
576       } else if (New->getTemplateSpecializationKind()
577                    != TSK_ImplicitInstantiation &&
578                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
579         // C++ [temp.expr.spec]p21:
580         //   Default function arguments shall not be specified in a declaration
581         //   or a definition for one of the following explicit specializations:
582         //     - the explicit specialization of a function template;
583         //     - the explicit specialization of a member function template;
584         //     - the explicit specialization of a member function of a class
585         //       template where the class template specialization to which the
586         //       member function specialization belongs is implicitly
587         //       instantiated.
588         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590           << New->getDeclName()
591           << NewParam->getDefaultArgRange();
592       } else if (New->getDeclContext()->isDependentContext()) {
593         // C++ [dcl.fct.default]p6 (DR217):
594         //   Default arguments for a member function of a class template shall
595         //   be specified on the initial declaration of the member function
596         //   within the class template.
597         //
598         // Reading the tea leaves a bit in DR217 and its reference to DR205
599         // leads me to the conclusion that one cannot add default function
600         // arguments for an out-of-line definition of a member function of a
601         // dependent type.
602         int WhichKind = 2;
603         if (CXXRecordDecl *Record
604               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605           if (Record->getDescribedClassTemplate())
606             WhichKind = 0;
607           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608             WhichKind = 1;
609           else
610             WhichKind = 2;
611         }
612 
613         Diag(NewParam->getLocation(),
614              diag::err_param_default_argument_member_template_redecl)
615           << WhichKind
616           << NewParam->getDefaultArgRange();
617       }
618     }
619   }
620 
621   // DR1344: If a default argument is added outside a class definition and that
622   // default argument makes the function a special member function, the program
623   // is ill-formed. This can only happen for constructors.
624   if (isa<CXXConstructorDecl>(New) &&
625       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628     if (NewSM != OldSM) {
629       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630       assert(NewParam->hasDefaultArg());
631       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632         << NewParam->getDefaultArgRange() << NewSM;
633       Diag(Old->getLocation(), diag::note_previous_declaration);
634     }
635   }
636 
637   const FunctionDecl *Def;
638   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639   // template has a constexpr specifier then all its declarations shall
640   // contain the constexpr specifier.
641   if (New->getConstexprKind() != Old->getConstexprKind()) {
642     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643         << New << New->getConstexprKind() << Old->getConstexprKind();
644     Diag(Old->getLocation(), diag::note_previous_declaration);
645     Invalid = true;
646   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647              Old->isDefined(Def) &&
648              // If a friend function is inlined but does not have 'inline'
649              // specifier, it is a definition. Do not report attribute conflict
650              // in this case, redefinition will be diagnosed later.
651              (New->isInlineSpecified() ||
652               New->getFriendObjectKind() == Decl::FOK_None)) {
653     // C++11 [dcl.fcn.spec]p4:
654     //   If the definition of a function appears in a translation unit before its
655     //   first declaration as inline, the program is ill-formed.
656     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657     Diag(Def->getLocation(), diag::note_previous_definition);
658     Invalid = true;
659   }
660 
661   // C++17 [temp.deduct.guide]p3:
662   //   Two deduction guide declarations in the same translation unit
663   //   for the same class template shall not have equivalent
664   //   parameter-declaration-clauses.
665   if (isa<CXXDeductionGuideDecl>(New) &&
666       !New->isFunctionTemplateSpecialization()) {
667     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
668     Diag(Old->getLocation(), diag::note_previous_declaration);
669   }
670 
671   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
672   // argument expression, that declaration shall be a definition and shall be
673   // the only declaration of the function or function template in the
674   // translation unit.
675   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
676       functionDeclHasDefaultArgument(Old)) {
677     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
678     Diag(Old->getLocation(), diag::note_previous_declaration);
679     Invalid = true;
680   }
681 
682   return Invalid;
683 }
684 
685 NamedDecl *
686 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
687                                    MultiTemplateParamsArg TemplateParamLists) {
688   assert(D.isDecompositionDeclarator());
689   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
690 
691   // The syntax only allows a decomposition declarator as a simple-declaration,
692   // a for-range-declaration, or a condition in Clang, but we parse it in more
693   // cases than that.
694   if (!D.mayHaveDecompositionDeclarator()) {
695     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
696       << Decomp.getSourceRange();
697     return nullptr;
698   }
699 
700   if (!TemplateParamLists.empty()) {
701     // FIXME: There's no rule against this, but there are also no rules that
702     // would actually make it usable, so we reject it for now.
703     Diag(TemplateParamLists.front()->getTemplateLoc(),
704          diag::err_decomp_decl_template);
705     return nullptr;
706   }
707 
708   Diag(Decomp.getLSquareLoc(),
709        !getLangOpts().CPlusPlus17
710            ? diag::ext_decomp_decl
711            : D.getContext() == DeclaratorContext::ConditionContext
712                  ? diag::ext_decomp_decl_cond
713                  : diag::warn_cxx14_compat_decomp_decl)
714       << Decomp.getSourceRange();
715 
716   // The semantic context is always just the current context.
717   DeclContext *const DC = CurContext;
718 
719   // C++17 [dcl.dcl]/8:
720   //   The decl-specifier-seq shall contain only the type-specifier auto
721   //   and cv-qualifiers.
722   // C++2a [dcl.dcl]/8:
723   //   If decl-specifier-seq contains any decl-specifier other than static,
724   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
725   auto &DS = D.getDeclSpec();
726   {
727     SmallVector<StringRef, 8> BadSpecifiers;
728     SmallVector<SourceLocation, 8> BadSpecifierLocs;
729     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
730     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
731     if (auto SCS = DS.getStorageClassSpec()) {
732       if (SCS == DeclSpec::SCS_static) {
733         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
734         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
735       } else {
736         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
737         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
738       }
739     }
740     if (auto TSCS = DS.getThreadStorageClassSpec()) {
741       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
742       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
743     }
744     if (DS.hasConstexprSpecifier()) {
745       BadSpecifiers.push_back(
746           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
747       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
748     }
749     if (DS.isInlineSpecified()) {
750       BadSpecifiers.push_back("inline");
751       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
752     }
753     if (!BadSpecifiers.empty()) {
754       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
755       Err << (int)BadSpecifiers.size()
756           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
757       // Don't add FixItHints to remove the specifiers; we do still respect
758       // them when building the underlying variable.
759       for (auto Loc : BadSpecifierLocs)
760         Err << SourceRange(Loc, Loc);
761     } else if (!CPlusPlus20Specifiers.empty()) {
762       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
763                          getLangOpts().CPlusPlus2a
764                              ? diag::warn_cxx17_compat_decomp_decl_spec
765                              : diag::ext_decomp_decl_spec);
766       Warn << (int)CPlusPlus20Specifiers.size()
767            << llvm::join(CPlusPlus20Specifiers.begin(),
768                          CPlusPlus20Specifiers.end(), " ");
769       for (auto Loc : CPlusPlus20SpecifierLocs)
770         Warn << SourceRange(Loc, Loc);
771     }
772     // We can't recover from it being declared as a typedef.
773     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
774       return nullptr;
775   }
776 
777   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
778   QualType R = TInfo->getType();
779 
780   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
781                                       UPPC_DeclarationType))
782     D.setInvalidType();
783 
784   // The syntax only allows a single ref-qualifier prior to the decomposition
785   // declarator. No other declarator chunks are permitted. Also check the type
786   // specifier here.
787   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
788       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
789       (D.getNumTypeObjects() == 1 &&
790        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
791     Diag(Decomp.getLSquareLoc(),
792          (D.hasGroupingParens() ||
793           (D.getNumTypeObjects() &&
794            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
795              ? diag::err_decomp_decl_parens
796              : diag::err_decomp_decl_type)
797         << R;
798 
799     // In most cases, there's no actual problem with an explicitly-specified
800     // type, but a function type won't work here, and ActOnVariableDeclarator
801     // shouldn't be called for such a type.
802     if (R->isFunctionType())
803       D.setInvalidType();
804   }
805 
806   // Build the BindingDecls.
807   SmallVector<BindingDecl*, 8> Bindings;
808 
809   // Build the BindingDecls.
810   for (auto &B : D.getDecompositionDeclarator().bindings()) {
811     // Check for name conflicts.
812     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
813     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
814                           ForVisibleRedeclaration);
815     LookupName(Previous, S,
816                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
817 
818     // It's not permitted to shadow a template parameter name.
819     if (Previous.isSingleResult() &&
820         Previous.getFoundDecl()->isTemplateParameter()) {
821       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
822                                       Previous.getFoundDecl());
823       Previous.clear();
824     }
825 
826     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
827                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
828     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
829                          /*AllowInlineNamespace*/false);
830     if (!Previous.empty()) {
831       auto *Old = Previous.getRepresentativeDecl();
832       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
833       Diag(Old->getLocation(), diag::note_previous_definition);
834     }
835 
836     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
837     PushOnScopeChains(BD, S, true);
838     Bindings.push_back(BD);
839     ParsingInitForAutoVars.insert(BD);
840   }
841 
842   // There are no prior lookup results for the variable itself, because it
843   // is unnamed.
844   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
845                                Decomp.getLSquareLoc());
846   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847                         ForVisibleRedeclaration);
848 
849   // Build the variable that holds the non-decomposed object.
850   bool AddToScope = true;
851   NamedDecl *New =
852       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
853                               MultiTemplateParamsArg(), AddToScope, Bindings);
854   if (AddToScope) {
855     S->AddDecl(New);
856     CurContext->addHiddenDecl(New);
857   }
858 
859   if (isInOpenMPDeclareTargetContext())
860     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
861 
862   return New;
863 }
864 
865 static bool checkSimpleDecomposition(
866     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
867     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
868     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
869   if ((int64_t)Bindings.size() != NumElems) {
870     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
871         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
872         << (NumElems < Bindings.size());
873     return true;
874   }
875 
876   unsigned I = 0;
877   for (auto *B : Bindings) {
878     SourceLocation Loc = B->getLocation();
879     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
880     if (E.isInvalid())
881       return true;
882     E = GetInit(Loc, E.get(), I++);
883     if (E.isInvalid())
884       return true;
885     B->setBinding(ElemType, E.get());
886   }
887 
888   return false;
889 }
890 
891 static bool checkArrayLikeDecomposition(Sema &S,
892                                         ArrayRef<BindingDecl *> Bindings,
893                                         ValueDecl *Src, QualType DecompType,
894                                         const llvm::APSInt &NumElems,
895                                         QualType ElemType) {
896   return checkSimpleDecomposition(
897       S, Bindings, Src, DecompType, NumElems, ElemType,
898       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
899         ExprResult E = S.ActOnIntegerConstant(Loc, I);
900         if (E.isInvalid())
901           return ExprError();
902         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
903       });
904 }
905 
906 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
907                                     ValueDecl *Src, QualType DecompType,
908                                     const ConstantArrayType *CAT) {
909   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
910                                      llvm::APSInt(CAT->getSize()),
911                                      CAT->getElementType());
912 }
913 
914 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
915                                      ValueDecl *Src, QualType DecompType,
916                                      const VectorType *VT) {
917   return checkArrayLikeDecomposition(
918       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
919       S.Context.getQualifiedType(VT->getElementType(),
920                                  DecompType.getQualifiers()));
921 }
922 
923 static bool checkComplexDecomposition(Sema &S,
924                                       ArrayRef<BindingDecl *> Bindings,
925                                       ValueDecl *Src, QualType DecompType,
926                                       const ComplexType *CT) {
927   return checkSimpleDecomposition(
928       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
929       S.Context.getQualifiedType(CT->getElementType(),
930                                  DecompType.getQualifiers()),
931       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
932         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
933       });
934 }
935 
936 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
937                                      TemplateArgumentListInfo &Args) {
938   SmallString<128> SS;
939   llvm::raw_svector_ostream OS(SS);
940   bool First = true;
941   for (auto &Arg : Args.arguments()) {
942     if (!First)
943       OS << ", ";
944     Arg.getArgument().print(PrintingPolicy, OS);
945     First = false;
946   }
947   return OS.str();
948 }
949 
950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
951                                      SourceLocation Loc, StringRef Trait,
952                                      TemplateArgumentListInfo &Args,
953                                      unsigned DiagID) {
954   auto DiagnoseMissing = [&] {
955     if (DiagID)
956       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
957                                                Args);
958     return true;
959   };
960 
961   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
962   NamespaceDecl *Std = S.getStdNamespace();
963   if (!Std)
964     return DiagnoseMissing();
965 
966   // Look up the trait itself, within namespace std. We can diagnose various
967   // problems with this lookup even if we've been asked to not diagnose a
968   // missing specialization, because this can only fail if the user has been
969   // declaring their own names in namespace std or we don't support the
970   // standard library implementation in use.
971   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
972                       Loc, Sema::LookupOrdinaryName);
973   if (!S.LookupQualifiedName(Result, Std))
974     return DiagnoseMissing();
975   if (Result.isAmbiguous())
976     return true;
977 
978   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
979   if (!TraitTD) {
980     Result.suppressDiagnostics();
981     NamedDecl *Found = *Result.begin();
982     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
983     S.Diag(Found->getLocation(), diag::note_declared_at);
984     return true;
985   }
986 
987   // Build the template-id.
988   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
989   if (TraitTy.isNull())
990     return true;
991   if (!S.isCompleteType(Loc, TraitTy)) {
992     if (DiagID)
993       S.RequireCompleteType(
994           Loc, TraitTy, DiagID,
995           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
996     return true;
997   }
998 
999   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1000   assert(RD && "specialization of class template is not a class?");
1001 
1002   // Look up the member of the trait type.
1003   S.LookupQualifiedName(TraitMemberLookup, RD);
1004   return TraitMemberLookup.isAmbiguous();
1005 }
1006 
1007 static TemplateArgumentLoc
1008 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1009                                    uint64_t I) {
1010   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1011   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1012 }
1013 
1014 static TemplateArgumentLoc
1015 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1016   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1017 }
1018 
1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1020 
1021 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1022                                llvm::APSInt &Size) {
1023   EnterExpressionEvaluationContext ContextRAII(
1024       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1025 
1026   DeclarationName Value = S.PP.getIdentifierInfo("value");
1027   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1028 
1029   // Form template argument list for tuple_size<T>.
1030   TemplateArgumentListInfo Args(Loc, Loc);
1031   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1032 
1033   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1034   // it's not tuple-like.
1035   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1036       R.empty())
1037     return IsTupleLike::NotTupleLike;
1038 
1039   // If we get this far, we've committed to the tuple interpretation, but
1040   // we can still fail if there actually isn't a usable ::value.
1041 
1042   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1043     LookupResult &R;
1044     TemplateArgumentListInfo &Args;
1045     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1046         : R(R), Args(Args) {}
1047     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1048       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1049           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1050     }
1051   } Diagnoser(R, Args);
1052 
1053   ExprResult E =
1054       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1055   if (E.isInvalid())
1056     return IsTupleLike::Error;
1057 
1058   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1059   if (E.isInvalid())
1060     return IsTupleLike::Error;
1061 
1062   return IsTupleLike::TupleLike;
1063 }
1064 
1065 /// \return std::tuple_element<I, T>::type.
1066 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1067                                         unsigned I, QualType T) {
1068   // Form template argument list for tuple_element<I, T>.
1069   TemplateArgumentListInfo Args(Loc, Loc);
1070   Args.addArgument(
1071       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1072   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1073 
1074   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1075   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1076   if (lookupStdTypeTraitMember(
1077           S, R, Loc, "tuple_element", Args,
1078           diag::err_decomp_decl_std_tuple_element_not_specialized))
1079     return QualType();
1080 
1081   auto *TD = R.getAsSingle<TypeDecl>();
1082   if (!TD) {
1083     R.suppressDiagnostics();
1084     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1085       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1086     if (!R.empty())
1087       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1088     return QualType();
1089   }
1090 
1091   return S.Context.getTypeDeclType(TD);
1092 }
1093 
1094 namespace {
1095 struct BindingDiagnosticTrap {
1096   Sema &S;
1097   DiagnosticErrorTrap Trap;
1098   BindingDecl *BD;
1099 
1100   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1101       : S(S), Trap(S.Diags), BD(BD) {}
1102   ~BindingDiagnosticTrap() {
1103     if (Trap.hasErrorOccurred())
1104       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1105   }
1106 };
1107 }
1108 
1109 static bool checkTupleLikeDecomposition(Sema &S,
1110                                         ArrayRef<BindingDecl *> Bindings,
1111                                         VarDecl *Src, QualType DecompType,
1112                                         const llvm::APSInt &TupleSize) {
1113   if ((int64_t)Bindings.size() != TupleSize) {
1114     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1115         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1116         << (TupleSize < Bindings.size());
1117     return true;
1118   }
1119 
1120   if (Bindings.empty())
1121     return false;
1122 
1123   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1124 
1125   // [dcl.decomp]p3:
1126   //   The unqualified-id get is looked up in the scope of E by class member
1127   //   access lookup ...
1128   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1129   bool UseMemberGet = false;
1130   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1131     if (auto *RD = DecompType->getAsCXXRecordDecl())
1132       S.LookupQualifiedName(MemberGet, RD);
1133     if (MemberGet.isAmbiguous())
1134       return true;
1135     //   ... and if that finds at least one declaration that is a function
1136     //   template whose first template parameter is a non-type parameter ...
1137     for (NamedDecl *D : MemberGet) {
1138       if (FunctionTemplateDecl *FTD =
1139               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1140         TemplateParameterList *TPL = FTD->getTemplateParameters();
1141         if (TPL->size() != 0 &&
1142             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1143           //   ... the initializer is e.get<i>().
1144           UseMemberGet = true;
1145           break;
1146         }
1147       }
1148     }
1149   }
1150 
1151   unsigned I = 0;
1152   for (auto *B : Bindings) {
1153     BindingDiagnosticTrap Trap(S, B);
1154     SourceLocation Loc = B->getLocation();
1155 
1156     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1157     if (E.isInvalid())
1158       return true;
1159 
1160     //   e is an lvalue if the type of the entity is an lvalue reference and
1161     //   an xvalue otherwise
1162     if (!Src->getType()->isLValueReferenceType())
1163       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1164                                    E.get(), nullptr, VK_XValue);
1165 
1166     TemplateArgumentListInfo Args(Loc, Loc);
1167     Args.addArgument(
1168         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1169 
1170     if (UseMemberGet) {
1171       //   if [lookup of member get] finds at least one declaration, the
1172       //   initializer is e.get<i-1>().
1173       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1174                                      CXXScopeSpec(), SourceLocation(), nullptr,
1175                                      MemberGet, &Args, nullptr);
1176       if (E.isInvalid())
1177         return true;
1178 
1179       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1180     } else {
1181       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1182       //   in the associated namespaces.
1183       Expr *Get = UnresolvedLookupExpr::Create(
1184           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1185           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1186           UnresolvedSetIterator(), UnresolvedSetIterator());
1187 
1188       Expr *Arg = E.get();
1189       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1190     }
1191     if (E.isInvalid())
1192       return true;
1193     Expr *Init = E.get();
1194 
1195     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1196     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1197     if (T.isNull())
1198       return true;
1199 
1200     //   each vi is a variable of type "reference to T" initialized with the
1201     //   initializer, where the reference is an lvalue reference if the
1202     //   initializer is an lvalue and an rvalue reference otherwise
1203     QualType RefType =
1204         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1205     if (RefType.isNull())
1206       return true;
1207     auto *RefVD = VarDecl::Create(
1208         S.Context, Src->getDeclContext(), Loc, Loc,
1209         B->getDeclName().getAsIdentifierInfo(), RefType,
1210         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1211     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1212     RefVD->setTSCSpec(Src->getTSCSpec());
1213     RefVD->setImplicit();
1214     if (Src->isInlineSpecified())
1215       RefVD->setInlineSpecified();
1216     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1217 
1218     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1219     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1220     InitializationSequence Seq(S, Entity, Kind, Init);
1221     E = Seq.Perform(S, Entity, Kind, Init);
1222     if (E.isInvalid())
1223       return true;
1224     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1225     if (E.isInvalid())
1226       return true;
1227     RefVD->setInit(E.get());
1228     if (!E.get()->isValueDependent())
1229       RefVD->checkInitIsICE();
1230 
1231     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1232                                    DeclarationNameInfo(B->getDeclName(), Loc),
1233                                    RefVD);
1234     if (E.isInvalid())
1235       return true;
1236 
1237     B->setBinding(T, E.get());
1238     I++;
1239   }
1240 
1241   return false;
1242 }
1243 
1244 /// Find the base class to decompose in a built-in decomposition of a class type.
1245 /// This base class search is, unfortunately, not quite like any other that we
1246 /// perform anywhere else in C++.
1247 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1248                                                 const CXXRecordDecl *RD,
1249                                                 CXXCastPath &BasePath) {
1250   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1251                           CXXBasePath &Path) {
1252     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1253   };
1254 
1255   const CXXRecordDecl *ClassWithFields = nullptr;
1256   AccessSpecifier AS = AS_public;
1257   if (RD->hasDirectFields())
1258     // [dcl.decomp]p4:
1259     //   Otherwise, all of E's non-static data members shall be public direct
1260     //   members of E ...
1261     ClassWithFields = RD;
1262   else {
1263     //   ... or of ...
1264     CXXBasePaths Paths;
1265     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1266     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1267       // If no classes have fields, just decompose RD itself. (This will work
1268       // if and only if zero bindings were provided.)
1269       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1270     }
1271 
1272     CXXBasePath *BestPath = nullptr;
1273     for (auto &P : Paths) {
1274       if (!BestPath)
1275         BestPath = &P;
1276       else if (!S.Context.hasSameType(P.back().Base->getType(),
1277                                       BestPath->back().Base->getType())) {
1278         //   ... the same ...
1279         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1280           << false << RD << BestPath->back().Base->getType()
1281           << P.back().Base->getType();
1282         return DeclAccessPair();
1283       } else if (P.Access < BestPath->Access) {
1284         BestPath = &P;
1285       }
1286     }
1287 
1288     //   ... unambiguous ...
1289     QualType BaseType = BestPath->back().Base->getType();
1290     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1291       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1292         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1293       return DeclAccessPair();
1294     }
1295 
1296     //   ... [accessible, implied by other rules] base class of E.
1297     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1298                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1299     AS = BestPath->Access;
1300 
1301     ClassWithFields = BaseType->getAsCXXRecordDecl();
1302     S.BuildBasePathArray(Paths, BasePath);
1303   }
1304 
1305   // The above search did not check whether the selected class itself has base
1306   // classes with fields, so check that now.
1307   CXXBasePaths Paths;
1308   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1309     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1310       << (ClassWithFields == RD) << RD << ClassWithFields
1311       << Paths.front().back().Base->getType();
1312     return DeclAccessPair();
1313   }
1314 
1315   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1316 }
1317 
1318 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1319                                      ValueDecl *Src, QualType DecompType,
1320                                      const CXXRecordDecl *OrigRD) {
1321   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1322                             diag::err_incomplete_type))
1323     return true;
1324 
1325   CXXCastPath BasePath;
1326   DeclAccessPair BasePair =
1327       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1328   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1329   if (!RD)
1330     return true;
1331   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1332                                                  DecompType.getQualifiers());
1333 
1334   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1335     unsigned NumFields =
1336         std::count_if(RD->field_begin(), RD->field_end(),
1337                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1338     assert(Bindings.size() != NumFields);
1339     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1340         << DecompType << (unsigned)Bindings.size() << NumFields
1341         << (NumFields < Bindings.size());
1342     return true;
1343   };
1344 
1345   //   all of E's non-static data members shall be [...] well-formed
1346   //   when named as e.name in the context of the structured binding,
1347   //   E shall not have an anonymous union member, ...
1348   unsigned I = 0;
1349   for (auto *FD : RD->fields()) {
1350     if (FD->isUnnamedBitfield())
1351       continue;
1352 
1353     if (FD->isAnonymousStructOrUnion()) {
1354       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1355         << DecompType << FD->getType()->isUnionType();
1356       S.Diag(FD->getLocation(), diag::note_declared_at);
1357       return true;
1358     }
1359 
1360     // We have a real field to bind.
1361     if (I >= Bindings.size())
1362       return DiagnoseBadNumberOfBindings();
1363     auto *B = Bindings[I++];
1364     SourceLocation Loc = B->getLocation();
1365 
1366     // The field must be accessible in the context of the structured binding.
1367     // We already checked that the base class is accessible.
1368     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1369     // const_cast here.
1370     S.CheckStructuredBindingMemberAccess(
1371         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1372         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1373                                      BasePair.getAccess(), FD->getAccess())));
1374 
1375     // Initialize the binding to Src.FD.
1376     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1377     if (E.isInvalid())
1378       return true;
1379     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1380                             VK_LValue, &BasePath);
1381     if (E.isInvalid())
1382       return true;
1383     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1384                                   CXXScopeSpec(), FD,
1385                                   DeclAccessPair::make(FD, FD->getAccess()),
1386                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1387     if (E.isInvalid())
1388       return true;
1389 
1390     // If the type of the member is T, the referenced type is cv T, where cv is
1391     // the cv-qualification of the decomposition expression.
1392     //
1393     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1394     // 'const' to the type of the field.
1395     Qualifiers Q = DecompType.getQualifiers();
1396     if (FD->isMutable())
1397       Q.removeConst();
1398     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1399   }
1400 
1401   if (I != Bindings.size())
1402     return DiagnoseBadNumberOfBindings();
1403 
1404   return false;
1405 }
1406 
1407 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1408   QualType DecompType = DD->getType();
1409 
1410   // If the type of the decomposition is dependent, then so is the type of
1411   // each binding.
1412   if (DecompType->isDependentType()) {
1413     for (auto *B : DD->bindings())
1414       B->setType(Context.DependentTy);
1415     return;
1416   }
1417 
1418   DecompType = DecompType.getNonReferenceType();
1419   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1420 
1421   // C++1z [dcl.decomp]/2:
1422   //   If E is an array type [...]
1423   // As an extension, we also support decomposition of built-in complex and
1424   // vector types.
1425   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1426     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1427       DD->setInvalidDecl();
1428     return;
1429   }
1430   if (auto *VT = DecompType->getAs<VectorType>()) {
1431     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1432       DD->setInvalidDecl();
1433     return;
1434   }
1435   if (auto *CT = DecompType->getAs<ComplexType>()) {
1436     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1437       DD->setInvalidDecl();
1438     return;
1439   }
1440 
1441   // C++1z [dcl.decomp]/3:
1442   //   if the expression std::tuple_size<E>::value is a well-formed integral
1443   //   constant expression, [...]
1444   llvm::APSInt TupleSize(32);
1445   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1446   case IsTupleLike::Error:
1447     DD->setInvalidDecl();
1448     return;
1449 
1450   case IsTupleLike::TupleLike:
1451     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1452       DD->setInvalidDecl();
1453     return;
1454 
1455   case IsTupleLike::NotTupleLike:
1456     break;
1457   }
1458 
1459   // C++1z [dcl.dcl]/8:
1460   //   [E shall be of array or non-union class type]
1461   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1462   if (!RD || RD->isUnion()) {
1463     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1464         << DD << !RD << DecompType;
1465     DD->setInvalidDecl();
1466     return;
1467   }
1468 
1469   // C++1z [dcl.decomp]/4:
1470   //   all of E's non-static data members shall be [...] direct members of
1471   //   E or of the same unambiguous public base class of E, ...
1472   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1473     DD->setInvalidDecl();
1474 }
1475 
1476 /// Merge the exception specifications of two variable declarations.
1477 ///
1478 /// This is called when there's a redeclaration of a VarDecl. The function
1479 /// checks if the redeclaration might have an exception specification and
1480 /// validates compatibility and merges the specs if necessary.
1481 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1482   // Shortcut if exceptions are disabled.
1483   if (!getLangOpts().CXXExceptions)
1484     return;
1485 
1486   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1487          "Should only be called if types are otherwise the same.");
1488 
1489   QualType NewType = New->getType();
1490   QualType OldType = Old->getType();
1491 
1492   // We're only interested in pointers and references to functions, as well
1493   // as pointers to member functions.
1494   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1495     NewType = R->getPointeeType();
1496     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1497   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1498     NewType = P->getPointeeType();
1499     OldType = OldType->getAs<PointerType>()->getPointeeType();
1500   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1501     NewType = M->getPointeeType();
1502     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1503   }
1504 
1505   if (!NewType->isFunctionProtoType())
1506     return;
1507 
1508   // There's lots of special cases for functions. For function pointers, system
1509   // libraries are hopefully not as broken so that we don't need these
1510   // workarounds.
1511   if (CheckEquivalentExceptionSpec(
1512         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1513         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1514     New->setInvalidDecl();
1515   }
1516 }
1517 
1518 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1519 /// function declaration are well-formed according to C++
1520 /// [dcl.fct.default].
1521 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1522   unsigned NumParams = FD->getNumParams();
1523   unsigned p;
1524 
1525   // Find first parameter with a default argument
1526   for (p = 0; p < NumParams; ++p) {
1527     ParmVarDecl *Param = FD->getParamDecl(p);
1528     if (Param->hasDefaultArg())
1529       break;
1530   }
1531 
1532   // C++11 [dcl.fct.default]p4:
1533   //   In a given function declaration, each parameter subsequent to a parameter
1534   //   with a default argument shall have a default argument supplied in this or
1535   //   a previous declaration or shall be a function parameter pack. A default
1536   //   argument shall not be redefined by a later declaration (not even to the
1537   //   same value).
1538   unsigned LastMissingDefaultArg = 0;
1539   for (; p < NumParams; ++p) {
1540     ParmVarDecl *Param = FD->getParamDecl(p);
1541     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1542       if (Param->isInvalidDecl())
1543         /* We already complained about this parameter. */;
1544       else if (Param->getIdentifier())
1545         Diag(Param->getLocation(),
1546              diag::err_param_default_argument_missing_name)
1547           << Param->getIdentifier();
1548       else
1549         Diag(Param->getLocation(),
1550              diag::err_param_default_argument_missing);
1551 
1552       LastMissingDefaultArg = p;
1553     }
1554   }
1555 
1556   if (LastMissingDefaultArg > 0) {
1557     // Some default arguments were missing. Clear out all of the
1558     // default arguments up to (and including) the last missing
1559     // default argument, so that we leave the function parameters
1560     // in a semantically valid state.
1561     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1562       ParmVarDecl *Param = FD->getParamDecl(p);
1563       if (Param->hasDefaultArg()) {
1564         Param->setDefaultArg(nullptr);
1565       }
1566     }
1567   }
1568 }
1569 
1570 /// Check that the given type is a literal type. Issue a diagnostic if not,
1571 /// if Kind is Diagnose.
1572 /// \return \c true if a problem has been found (and optionally diagnosed).
1573 template <typename... Ts>
1574 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1575                              SourceLocation Loc, QualType T, unsigned DiagID,
1576                              Ts &&...DiagArgs) {
1577   if (T->isDependentType())
1578     return false;
1579 
1580   switch (Kind) {
1581   case Sema::CheckConstexprKind::Diagnose:
1582     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1583                                       std::forward<Ts>(DiagArgs)...);
1584 
1585   case Sema::CheckConstexprKind::CheckValid:
1586     return !T->isLiteralType(SemaRef.Context);
1587   }
1588 
1589   llvm_unreachable("unknown CheckConstexprKind");
1590 }
1591 
1592 // CheckConstexprParameterTypes - Check whether a function's parameter types
1593 // are all literal types. If so, return true. If not, produce a suitable
1594 // diagnostic and return false.
1595 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1596                                          const FunctionDecl *FD,
1597                                          Sema::CheckConstexprKind Kind) {
1598   unsigned ArgIndex = 0;
1599   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1600   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1601                                               e = FT->param_type_end();
1602        i != e; ++i, ++ArgIndex) {
1603     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1604     SourceLocation ParamLoc = PD->getLocation();
1605     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1606                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1607                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1608                          FD->isConsteval()))
1609       return false;
1610   }
1611   return true;
1612 }
1613 
1614 /// Get diagnostic %select index for tag kind for
1615 /// record diagnostic message.
1616 /// WARNING: Indexes apply to particular diagnostics only!
1617 ///
1618 /// \returns diagnostic %select index.
1619 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1620   switch (Tag) {
1621   case TTK_Struct: return 0;
1622   case TTK_Interface: return 1;
1623   case TTK_Class:  return 2;
1624   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1625   }
1626 }
1627 
1628 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1629                                        Stmt *Body,
1630                                        Sema::CheckConstexprKind Kind);
1631 
1632 // Check whether a function declaration satisfies the requirements of a
1633 // constexpr function definition or a constexpr constructor definition. If so,
1634 // return true. If not, produce appropriate diagnostics (unless asked not to by
1635 // Kind) and return false.
1636 //
1637 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1638 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1639                                             CheckConstexprKind Kind) {
1640   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1641   if (MD && MD->isInstance()) {
1642     // C++11 [dcl.constexpr]p4:
1643     //  The definition of a constexpr constructor shall satisfy the following
1644     //  constraints:
1645     //  - the class shall not have any virtual base classes;
1646     //
1647     // FIXME: This only applies to constructors, not arbitrary member
1648     // functions.
1649     const CXXRecordDecl *RD = MD->getParent();
1650     if (RD->getNumVBases()) {
1651       if (Kind == CheckConstexprKind::CheckValid)
1652         return false;
1653 
1654       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1655         << isa<CXXConstructorDecl>(NewFD)
1656         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1657       for (const auto &I : RD->vbases())
1658         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1659             << I.getSourceRange();
1660       return false;
1661     }
1662   }
1663 
1664   if (!isa<CXXConstructorDecl>(NewFD)) {
1665     // C++11 [dcl.constexpr]p3:
1666     //  The definition of a constexpr function shall satisfy the following
1667     //  constraints:
1668     // - it shall not be virtual; (removed in C++20)
1669     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1670     if (Method && Method->isVirtual()) {
1671       if (getLangOpts().CPlusPlus2a) {
1672         if (Kind == CheckConstexprKind::Diagnose)
1673           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1674       } else {
1675         if (Kind == CheckConstexprKind::CheckValid)
1676           return false;
1677 
1678         Method = Method->getCanonicalDecl();
1679         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1680 
1681         // If it's not obvious why this function is virtual, find an overridden
1682         // function which uses the 'virtual' keyword.
1683         const CXXMethodDecl *WrittenVirtual = Method;
1684         while (!WrittenVirtual->isVirtualAsWritten())
1685           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1686         if (WrittenVirtual != Method)
1687           Diag(WrittenVirtual->getLocation(),
1688                diag::note_overridden_virtual_function);
1689         return false;
1690       }
1691     }
1692 
1693     // - its return type shall be a literal type;
1694     QualType RT = NewFD->getReturnType();
1695     if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
1696                          diag::err_constexpr_non_literal_return,
1697                          NewFD->isConsteval()))
1698       return false;
1699   }
1700 
1701   // - each of its parameter types shall be a literal type;
1702   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1703     return false;
1704 
1705   Stmt *Body = NewFD->getBody();
1706   assert(Body &&
1707          "CheckConstexprFunctionDefinition called on function with no body");
1708   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1709 }
1710 
1711 /// Check the given declaration statement is legal within a constexpr function
1712 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1713 ///
1714 /// \return true if the body is OK (maybe only as an extension), false if we
1715 ///         have diagnosed a problem.
1716 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1717                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1718                                    Sema::CheckConstexprKind Kind) {
1719   // C++11 [dcl.constexpr]p3 and p4:
1720   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1721   //  contain only
1722   for (const auto *DclIt : DS->decls()) {
1723     switch (DclIt->getKind()) {
1724     case Decl::StaticAssert:
1725     case Decl::Using:
1726     case Decl::UsingShadow:
1727     case Decl::UsingDirective:
1728     case Decl::UnresolvedUsingTypename:
1729     case Decl::UnresolvedUsingValue:
1730       //   - static_assert-declarations
1731       //   - using-declarations,
1732       //   - using-directives,
1733       continue;
1734 
1735     case Decl::Typedef:
1736     case Decl::TypeAlias: {
1737       //   - typedef declarations and alias-declarations that do not define
1738       //     classes or enumerations,
1739       const auto *TN = cast<TypedefNameDecl>(DclIt);
1740       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1741         // Don't allow variably-modified types in constexpr functions.
1742         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1743           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1744           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1745             << TL.getSourceRange() << TL.getType()
1746             << isa<CXXConstructorDecl>(Dcl);
1747         }
1748         return false;
1749       }
1750       continue;
1751     }
1752 
1753     case Decl::Enum:
1754     case Decl::CXXRecord:
1755       // C++1y allows types to be defined, not just declared.
1756       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1757         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1758           SemaRef.Diag(DS->getBeginLoc(),
1759                        SemaRef.getLangOpts().CPlusPlus14
1760                            ? diag::warn_cxx11_compat_constexpr_type_definition
1761                            : diag::ext_constexpr_type_definition)
1762               << isa<CXXConstructorDecl>(Dcl);
1763         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1764           return false;
1765         }
1766       }
1767       continue;
1768 
1769     case Decl::EnumConstant:
1770     case Decl::IndirectField:
1771     case Decl::ParmVar:
1772       // These can only appear with other declarations which are banned in
1773       // C++11 and permitted in C++1y, so ignore them.
1774       continue;
1775 
1776     case Decl::Var:
1777     case Decl::Decomposition: {
1778       // C++1y [dcl.constexpr]p3 allows anything except:
1779       //   a definition of a variable of non-literal type or of static or
1780       //   thread storage duration or for which no initialization is performed.
1781       const auto *VD = cast<VarDecl>(DclIt);
1782       if (VD->isThisDeclarationADefinition()) {
1783         if (VD->isStaticLocal()) {
1784           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1785             SemaRef.Diag(VD->getLocation(),
1786                          diag::err_constexpr_local_var_static)
1787               << isa<CXXConstructorDecl>(Dcl)
1788               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1789           }
1790           return false;
1791         }
1792         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1793                              diag::err_constexpr_local_var_non_literal_type,
1794                              isa<CXXConstructorDecl>(Dcl)))
1795           return false;
1796         if (!VD->getType()->isDependentType() &&
1797             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1798           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1799             SemaRef.Diag(VD->getLocation(),
1800                          diag::err_constexpr_local_var_no_init)
1801               << isa<CXXConstructorDecl>(Dcl);
1802           }
1803           return false;
1804         }
1805       }
1806       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1807         SemaRef.Diag(VD->getLocation(),
1808                      SemaRef.getLangOpts().CPlusPlus14
1809                       ? diag::warn_cxx11_compat_constexpr_local_var
1810                       : diag::ext_constexpr_local_var)
1811           << isa<CXXConstructorDecl>(Dcl);
1812       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1813         return false;
1814       }
1815       continue;
1816     }
1817 
1818     case Decl::NamespaceAlias:
1819     case Decl::Function:
1820       // These are disallowed in C++11 and permitted in C++1y. Allow them
1821       // everywhere as an extension.
1822       if (!Cxx1yLoc.isValid())
1823         Cxx1yLoc = DS->getBeginLoc();
1824       continue;
1825 
1826     default:
1827       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1828         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1829             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1830       }
1831       return false;
1832     }
1833   }
1834 
1835   return true;
1836 }
1837 
1838 /// Check that the given field is initialized within a constexpr constructor.
1839 ///
1840 /// \param Dcl The constexpr constructor being checked.
1841 /// \param Field The field being checked. This may be a member of an anonymous
1842 ///        struct or union nested within the class being checked.
1843 /// \param Inits All declarations, including anonymous struct/union members and
1844 ///        indirect members, for which any initialization was provided.
1845 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1846 ///        multiple notes for different members to the same error.
1847 /// \param Kind Whether we're diagnosing a constructor as written or determining
1848 ///        whether the formal requirements are satisfied.
1849 /// \return \c false if we're checking for validity and the constructor does
1850 ///         not satisfy the requirements on a constexpr constructor.
1851 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1852                                           const FunctionDecl *Dcl,
1853                                           FieldDecl *Field,
1854                                           llvm::SmallSet<Decl*, 16> &Inits,
1855                                           bool &Diagnosed,
1856                                           Sema::CheckConstexprKind Kind) {
1857   if (Field->isInvalidDecl())
1858     return true;
1859 
1860   if (Field->isUnnamedBitfield())
1861     return true;
1862 
1863   // Anonymous unions with no variant members and empty anonymous structs do not
1864   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1865   // indirect fields don't need initializing.
1866   if (Field->isAnonymousStructOrUnion() &&
1867       (Field->getType()->isUnionType()
1868            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1869            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1870     return true;
1871 
1872   if (!Inits.count(Field)) {
1873     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1874       if (!Diagnosed) {
1875         SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1876         Diagnosed = true;
1877       }
1878       SemaRef.Diag(Field->getLocation(),
1879                    diag::note_constexpr_ctor_missing_init);
1880     } else {
1881       return false;
1882     }
1883   } else if (Field->isAnonymousStructOrUnion()) {
1884     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1885     for (auto *I : RD->fields())
1886       // If an anonymous union contains an anonymous struct of which any member
1887       // is initialized, all members must be initialized.
1888       if (!RD->isUnion() || Inits.count(I))
1889         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1890                                            Kind))
1891           return false;
1892   }
1893   return true;
1894 }
1895 
1896 /// Check the provided statement is allowed in a constexpr function
1897 /// definition.
1898 static bool
1899 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1900                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1901                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1902                            Sema::CheckConstexprKind Kind) {
1903   // - its function-body shall be [...] a compound-statement that contains only
1904   switch (S->getStmtClass()) {
1905   case Stmt::NullStmtClass:
1906     //   - null statements,
1907     return true;
1908 
1909   case Stmt::DeclStmtClass:
1910     //   - static_assert-declarations
1911     //   - using-declarations,
1912     //   - using-directives,
1913     //   - typedef declarations and alias-declarations that do not define
1914     //     classes or enumerations,
1915     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1916       return false;
1917     return true;
1918 
1919   case Stmt::ReturnStmtClass:
1920     //   - and exactly one return statement;
1921     if (isa<CXXConstructorDecl>(Dcl)) {
1922       // C++1y allows return statements in constexpr constructors.
1923       if (!Cxx1yLoc.isValid())
1924         Cxx1yLoc = S->getBeginLoc();
1925       return true;
1926     }
1927 
1928     ReturnStmts.push_back(S->getBeginLoc());
1929     return true;
1930 
1931   case Stmt::CompoundStmtClass: {
1932     // C++1y allows compound-statements.
1933     if (!Cxx1yLoc.isValid())
1934       Cxx1yLoc = S->getBeginLoc();
1935 
1936     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1937     for (auto *BodyIt : CompStmt->body()) {
1938       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1939                                       Cxx1yLoc, Cxx2aLoc, Kind))
1940         return false;
1941     }
1942     return true;
1943   }
1944 
1945   case Stmt::AttributedStmtClass:
1946     if (!Cxx1yLoc.isValid())
1947       Cxx1yLoc = S->getBeginLoc();
1948     return true;
1949 
1950   case Stmt::IfStmtClass: {
1951     // C++1y allows if-statements.
1952     if (!Cxx1yLoc.isValid())
1953       Cxx1yLoc = S->getBeginLoc();
1954 
1955     IfStmt *If = cast<IfStmt>(S);
1956     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1957                                     Cxx1yLoc, Cxx2aLoc, Kind))
1958       return false;
1959     if (If->getElse() &&
1960         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1961                                     Cxx1yLoc, Cxx2aLoc, Kind))
1962       return false;
1963     return true;
1964   }
1965 
1966   case Stmt::WhileStmtClass:
1967   case Stmt::DoStmtClass:
1968   case Stmt::ForStmtClass:
1969   case Stmt::CXXForRangeStmtClass:
1970   case Stmt::ContinueStmtClass:
1971     // C++1y allows all of these. We don't allow them as extensions in C++11,
1972     // because they don't make sense without variable mutation.
1973     if (!SemaRef.getLangOpts().CPlusPlus14)
1974       break;
1975     if (!Cxx1yLoc.isValid())
1976       Cxx1yLoc = S->getBeginLoc();
1977     for (Stmt *SubStmt : S->children())
1978       if (SubStmt &&
1979           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1980                                       Cxx1yLoc, Cxx2aLoc, Kind))
1981         return false;
1982     return true;
1983 
1984   case Stmt::SwitchStmtClass:
1985   case Stmt::CaseStmtClass:
1986   case Stmt::DefaultStmtClass:
1987   case Stmt::BreakStmtClass:
1988     // C++1y allows switch-statements, and since they don't need variable
1989     // mutation, we can reasonably allow them in C++11 as an extension.
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::GCCAsmStmtClass:
2000   case Stmt::MSAsmStmtClass:
2001     // C++2a allows inline assembly statements.
2002   case Stmt::CXXTryStmtClass:
2003     if (Cxx2aLoc.isInvalid())
2004       Cxx2aLoc = S->getBeginLoc();
2005     for (Stmt *SubStmt : S->children()) {
2006       if (SubStmt &&
2007           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2008                                       Cxx1yLoc, Cxx2aLoc, Kind))
2009         return false;
2010     }
2011     return true;
2012 
2013   case Stmt::CXXCatchStmtClass:
2014     // Do not bother checking the language mode (already covered by the
2015     // try block check).
2016     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2017                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2018                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2019       return false;
2020     return true;
2021 
2022   default:
2023     if (!isa<Expr>(S))
2024       break;
2025 
2026     // C++1y allows expression-statements.
2027     if (!Cxx1yLoc.isValid())
2028       Cxx1yLoc = S->getBeginLoc();
2029     return true;
2030   }
2031 
2032   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2033     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2034         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2035   }
2036   return false;
2037 }
2038 
2039 /// Check the body for the given constexpr function declaration only contains
2040 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2041 ///
2042 /// \return true if the body is OK, false if we have found or diagnosed a
2043 /// problem.
2044 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2045                                        Stmt *Body,
2046                                        Sema::CheckConstexprKind Kind) {
2047   SmallVector<SourceLocation, 4> ReturnStmts;
2048 
2049   if (isa<CXXTryStmt>(Body)) {
2050     // C++11 [dcl.constexpr]p3:
2051     //  The definition of a constexpr function shall satisfy the following
2052     //  constraints: [...]
2053     // - its function-body shall be = delete, = default, or a
2054     //   compound-statement
2055     //
2056     // C++11 [dcl.constexpr]p4:
2057     //  In the definition of a constexpr constructor, [...]
2058     // - its function-body shall not be a function-try-block;
2059     //
2060     // This restriction is lifted in C++2a, as long as inner statements also
2061     // apply the general constexpr rules.
2062     switch (Kind) {
2063     case Sema::CheckConstexprKind::CheckValid:
2064       if (!SemaRef.getLangOpts().CPlusPlus2a)
2065         return false;
2066       break;
2067 
2068     case Sema::CheckConstexprKind::Diagnose:
2069       SemaRef.Diag(Body->getBeginLoc(),
2070            !SemaRef.getLangOpts().CPlusPlus2a
2071                ? diag::ext_constexpr_function_try_block_cxx2a
2072                : diag::warn_cxx17_compat_constexpr_function_try_block)
2073           << isa<CXXConstructorDecl>(Dcl);
2074       break;
2075     }
2076   }
2077 
2078   // - its function-body shall be [...] a compound-statement that contains only
2079   //   [... list of cases ...]
2080   //
2081   // Note that walking the children here is enough to properly check for
2082   // CompoundStmt and CXXTryStmt body.
2083   SourceLocation Cxx1yLoc, Cxx2aLoc;
2084   for (Stmt *SubStmt : Body->children()) {
2085     if (SubStmt &&
2086         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2087                                     Cxx1yLoc, Cxx2aLoc, Kind))
2088       return false;
2089   }
2090 
2091   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2092     // If this is only valid as an extension, report that we don't satisfy the
2093     // constraints of the current language.
2094     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
2095         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2096       return false;
2097   } else if (Cxx2aLoc.isValid()) {
2098     SemaRef.Diag(Cxx2aLoc,
2099          SemaRef.getLangOpts().CPlusPlus2a
2100            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2101            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2102       << isa<CXXConstructorDecl>(Dcl);
2103   } else if (Cxx1yLoc.isValid()) {
2104     SemaRef.Diag(Cxx1yLoc,
2105          SemaRef.getLangOpts().CPlusPlus14
2106            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2107            : diag::ext_constexpr_body_invalid_stmt)
2108       << isa<CXXConstructorDecl>(Dcl);
2109   }
2110 
2111   if (const CXXConstructorDecl *Constructor
2112         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2113     const CXXRecordDecl *RD = Constructor->getParent();
2114     // DR1359:
2115     // - every non-variant non-static data member and base class sub-object
2116     //   shall be initialized;
2117     // DR1460:
2118     // - if the class is a union having variant members, exactly one of them
2119     //   shall be initialized;
2120     if (RD->isUnion()) {
2121       if (Constructor->getNumCtorInitializers() == 0 &&
2122           RD->hasVariantMembers()) {
2123         if (Kind == Sema::CheckConstexprKind::Diagnose)
2124           SemaRef.Diag(Dcl->getLocation(),
2125                        diag::err_constexpr_union_ctor_no_init);
2126         return false;
2127       }
2128     } else if (!Constructor->isDependentContext() &&
2129                !Constructor->isDelegatingConstructor()) {
2130       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2131 
2132       // Skip detailed checking if we have enough initializers, and we would
2133       // allow at most one initializer per member.
2134       bool AnyAnonStructUnionMembers = false;
2135       unsigned Fields = 0;
2136       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2137            E = RD->field_end(); I != E; ++I, ++Fields) {
2138         if (I->isAnonymousStructOrUnion()) {
2139           AnyAnonStructUnionMembers = true;
2140           break;
2141         }
2142       }
2143       // DR1460:
2144       // - if the class is a union-like class, but is not a union, for each of
2145       //   its anonymous union members having variant members, exactly one of
2146       //   them shall be initialized;
2147       if (AnyAnonStructUnionMembers ||
2148           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2149         // Check initialization of non-static data members. Base classes are
2150         // always initialized so do not need to be checked. Dependent bases
2151         // might not have initializers in the member initializer list.
2152         llvm::SmallSet<Decl*, 16> Inits;
2153         for (const auto *I: Constructor->inits()) {
2154           if (FieldDecl *FD = I->getMember())
2155             Inits.insert(FD);
2156           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2157             Inits.insert(ID->chain_begin(), ID->chain_end());
2158         }
2159 
2160         bool Diagnosed = false;
2161         for (auto *I : RD->fields())
2162           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2163                                              Kind))
2164             return false;
2165       }
2166     }
2167   } else {
2168     if (ReturnStmts.empty()) {
2169       // C++1y doesn't require constexpr functions to contain a 'return'
2170       // statement. We still do, unless the return type might be void, because
2171       // otherwise if there's no return statement, the function cannot
2172       // be used in a core constant expression.
2173       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2174                 (Dcl->getReturnType()->isVoidType() ||
2175                  Dcl->getReturnType()->isDependentType());
2176       switch (Kind) {
2177       case Sema::CheckConstexprKind::Diagnose:
2178         SemaRef.Diag(Dcl->getLocation(),
2179                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2180                         : diag::err_constexpr_body_no_return)
2181             << Dcl->isConsteval();
2182         if (!OK)
2183           return false;
2184         break;
2185 
2186       case Sema::CheckConstexprKind::CheckValid:
2187         // The formal requirements don't include this rule in C++14, even
2188         // though the "must be able to produce a constant expression" rules
2189         // still imply it in some cases.
2190         if (!SemaRef.getLangOpts().CPlusPlus14)
2191           return false;
2192         break;
2193       }
2194     } else if (ReturnStmts.size() > 1) {
2195       switch (Kind) {
2196       case Sema::CheckConstexprKind::Diagnose:
2197         SemaRef.Diag(
2198             ReturnStmts.back(),
2199             SemaRef.getLangOpts().CPlusPlus14
2200                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2201                 : diag::ext_constexpr_body_multiple_return);
2202         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2203           SemaRef.Diag(ReturnStmts[I],
2204                        diag::note_constexpr_body_previous_return);
2205         break;
2206 
2207       case Sema::CheckConstexprKind::CheckValid:
2208         if (!SemaRef.getLangOpts().CPlusPlus14)
2209           return false;
2210         break;
2211       }
2212     }
2213   }
2214 
2215   // C++11 [dcl.constexpr]p5:
2216   //   if no function argument values exist such that the function invocation
2217   //   substitution would produce a constant expression, the program is
2218   //   ill-formed; no diagnostic required.
2219   // C++11 [dcl.constexpr]p3:
2220   //   - every constructor call and implicit conversion used in initializing the
2221   //     return value shall be one of those allowed in a constant expression.
2222   // C++11 [dcl.constexpr]p4:
2223   //   - every constructor involved in initializing non-static data members and
2224   //     base class sub-objects shall be a constexpr constructor.
2225   //
2226   // Note that this rule is distinct from the "requirements for a constexpr
2227   // function", so is not checked in CheckValid mode.
2228   SmallVector<PartialDiagnosticAt, 8> Diags;
2229   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2230       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2231     SemaRef.Diag(Dcl->getLocation(),
2232                  diag::ext_constexpr_function_never_constant_expr)
2233         << isa<CXXConstructorDecl>(Dcl);
2234     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2235       SemaRef.Diag(Diags[I].first, Diags[I].second);
2236     // Don't return false here: we allow this for compatibility in
2237     // system headers.
2238   }
2239 
2240   return true;
2241 }
2242 
2243 /// Get the class that is directly named by the current context. This is the
2244 /// class for which an unqualified-id in this scope could name a constructor
2245 /// or destructor.
2246 ///
2247 /// If the scope specifier denotes a class, this will be that class.
2248 /// If the scope specifier is empty, this will be the class whose
2249 /// member-specification we are currently within. Otherwise, there
2250 /// is no such class.
2251 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2252   assert(getLangOpts().CPlusPlus && "No class names in C!");
2253 
2254   if (SS && SS->isInvalid())
2255     return nullptr;
2256 
2257   if (SS && SS->isNotEmpty()) {
2258     DeclContext *DC = computeDeclContext(*SS, true);
2259     return dyn_cast_or_null<CXXRecordDecl>(DC);
2260   }
2261 
2262   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2263 }
2264 
2265 /// isCurrentClassName - Determine whether the identifier II is the
2266 /// name of the class type currently being defined. In the case of
2267 /// nested classes, this will only return true if II is the name of
2268 /// the innermost class.
2269 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2270                               const CXXScopeSpec *SS) {
2271   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2272   return CurDecl && &II == CurDecl->getIdentifier();
2273 }
2274 
2275 /// Determine whether the identifier II is a typo for the name of
2276 /// the class type currently being defined. If so, update it to the identifier
2277 /// that should have been used.
2278 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2279   assert(getLangOpts().CPlusPlus && "No class names in C!");
2280 
2281   if (!getLangOpts().SpellChecking)
2282     return false;
2283 
2284   CXXRecordDecl *CurDecl;
2285   if (SS && SS->isSet() && !SS->isInvalid()) {
2286     DeclContext *DC = computeDeclContext(*SS, true);
2287     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2288   } else
2289     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2290 
2291   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2292       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2293           < II->getLength()) {
2294     II = CurDecl->getIdentifier();
2295     return true;
2296   }
2297 
2298   return false;
2299 }
2300 
2301 /// Determine whether the given class is a base class of the given
2302 /// class, including looking at dependent bases.
2303 static bool findCircularInheritance(const CXXRecordDecl *Class,
2304                                     const CXXRecordDecl *Current) {
2305   SmallVector<const CXXRecordDecl*, 8> Queue;
2306 
2307   Class = Class->getCanonicalDecl();
2308   while (true) {
2309     for (const auto &I : Current->bases()) {
2310       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2311       if (!Base)
2312         continue;
2313 
2314       Base = Base->getDefinition();
2315       if (!Base)
2316         continue;
2317 
2318       if (Base->getCanonicalDecl() == Class)
2319         return true;
2320 
2321       Queue.push_back(Base);
2322     }
2323 
2324     if (Queue.empty())
2325       return false;
2326 
2327     Current = Queue.pop_back_val();
2328   }
2329 
2330   return false;
2331 }
2332 
2333 /// Check the validity of a C++ base class specifier.
2334 ///
2335 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2336 /// and returns NULL otherwise.
2337 CXXBaseSpecifier *
2338 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2339                          SourceRange SpecifierRange,
2340                          bool Virtual, AccessSpecifier Access,
2341                          TypeSourceInfo *TInfo,
2342                          SourceLocation EllipsisLoc) {
2343   QualType BaseType = TInfo->getType();
2344 
2345   // C++ [class.union]p1:
2346   //   A union shall not have base classes.
2347   if (Class->isUnion()) {
2348     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2349       << SpecifierRange;
2350     return nullptr;
2351   }
2352 
2353   if (EllipsisLoc.isValid() &&
2354       !TInfo->getType()->containsUnexpandedParameterPack()) {
2355     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2356       << TInfo->getTypeLoc().getSourceRange();
2357     EllipsisLoc = SourceLocation();
2358   }
2359 
2360   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2361 
2362   if (BaseType->isDependentType()) {
2363     // Make sure that we don't have circular inheritance among our dependent
2364     // bases. For non-dependent bases, the check for completeness below handles
2365     // this.
2366     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2367       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2368           ((BaseDecl = BaseDecl->getDefinition()) &&
2369            findCircularInheritance(Class, BaseDecl))) {
2370         Diag(BaseLoc, diag::err_circular_inheritance)
2371           << BaseType << Context.getTypeDeclType(Class);
2372 
2373         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2374           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2375             << BaseType;
2376 
2377         return nullptr;
2378       }
2379     }
2380 
2381     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2382                                           Class->getTagKind() == TTK_Class,
2383                                           Access, TInfo, EllipsisLoc);
2384   }
2385 
2386   // Base specifiers must be record types.
2387   if (!BaseType->isRecordType()) {
2388     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2389     return nullptr;
2390   }
2391 
2392   // C++ [class.union]p1:
2393   //   A union shall not be used as a base class.
2394   if (BaseType->isUnionType()) {
2395     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2396     return nullptr;
2397   }
2398 
2399   // For the MS ABI, propagate DLL attributes to base class templates.
2400   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2401     if (Attr *ClassAttr = getDLLAttr(Class)) {
2402       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2403               BaseType->getAsCXXRecordDecl())) {
2404         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2405                                             BaseLoc);
2406       }
2407     }
2408   }
2409 
2410   // C++ [class.derived]p2:
2411   //   The class-name in a base-specifier shall not be an incompletely
2412   //   defined class.
2413   if (RequireCompleteType(BaseLoc, BaseType,
2414                           diag::err_incomplete_base_class, SpecifierRange)) {
2415     Class->setInvalidDecl();
2416     return nullptr;
2417   }
2418 
2419   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2420   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2421   assert(BaseDecl && "Record type has no declaration");
2422   BaseDecl = BaseDecl->getDefinition();
2423   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2424   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2425   assert(CXXBaseDecl && "Base type is not a C++ type");
2426 
2427   // Microsoft docs say:
2428   // "If a base-class has a code_seg attribute, derived classes must have the
2429   // same attribute."
2430   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2431   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2432   if ((DerivedCSA || BaseCSA) &&
2433       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2434     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2435     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2436       << CXXBaseDecl;
2437     return nullptr;
2438   }
2439 
2440   // A class which contains a flexible array member is not suitable for use as a
2441   // base class:
2442   //   - If the layout determines that a base comes before another base,
2443   //     the flexible array member would index into the subsequent base.
2444   //   - If the layout determines that base comes before the derived class,
2445   //     the flexible array member would index into the derived class.
2446   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2447     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2448       << CXXBaseDecl->getDeclName();
2449     return nullptr;
2450   }
2451 
2452   // C++ [class]p3:
2453   //   If a class is marked final and it appears as a base-type-specifier in
2454   //   base-clause, the program is ill-formed.
2455   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2456     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2457       << CXXBaseDecl->getDeclName()
2458       << FA->isSpelledAsSealed();
2459     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2460         << CXXBaseDecl->getDeclName() << FA->getRange();
2461     return nullptr;
2462   }
2463 
2464   if (BaseDecl->isInvalidDecl())
2465     Class->setInvalidDecl();
2466 
2467   // Create the base specifier.
2468   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2469                                         Class->getTagKind() == TTK_Class,
2470                                         Access, TInfo, EllipsisLoc);
2471 }
2472 
2473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2474 /// one entry in the base class list of a class specifier, for
2475 /// example:
2476 ///    class foo : public bar, virtual private baz {
2477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2478 BaseResult
2479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2480                          ParsedAttributes &Attributes,
2481                          bool Virtual, AccessSpecifier Access,
2482                          ParsedType basetype, SourceLocation BaseLoc,
2483                          SourceLocation EllipsisLoc) {
2484   if (!classdecl)
2485     return true;
2486 
2487   AdjustDeclIfTemplate(classdecl);
2488   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2489   if (!Class)
2490     return true;
2491 
2492   // We haven't yet attached the base specifiers.
2493   Class->setIsParsingBaseSpecifiers();
2494 
2495   // We do not support any C++11 attributes on base-specifiers yet.
2496   // Diagnose any attributes we see.
2497   for (const ParsedAttr &AL : Attributes) {
2498     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2499       continue;
2500     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2501                           ? (unsigned)diag::warn_unknown_attribute_ignored
2502                           : (unsigned)diag::err_base_specifier_attribute)
2503         << AL.getName();
2504   }
2505 
2506   TypeSourceInfo *TInfo = nullptr;
2507   GetTypeFromParser(basetype, &TInfo);
2508 
2509   if (EllipsisLoc.isInvalid() &&
2510       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2511                                       UPPC_BaseType))
2512     return true;
2513 
2514   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2515                                                       Virtual, Access, TInfo,
2516                                                       EllipsisLoc))
2517     return BaseSpec;
2518   else
2519     Class->setInvalidDecl();
2520 
2521   return true;
2522 }
2523 
2524 /// Use small set to collect indirect bases.  As this is only used
2525 /// locally, there's no need to abstract the small size parameter.
2526 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2527 
2528 /// Recursively add the bases of Type.  Don't add Type itself.
2529 static void
2530 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2531                   const QualType &Type)
2532 {
2533   // Even though the incoming type is a base, it might not be
2534   // a class -- it could be a template parm, for instance.
2535   if (auto Rec = Type->getAs<RecordType>()) {
2536     auto Decl = Rec->getAsCXXRecordDecl();
2537 
2538     // Iterate over its bases.
2539     for (const auto &BaseSpec : Decl->bases()) {
2540       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2541         .getUnqualifiedType();
2542       if (Set.insert(Base).second)
2543         // If we've not already seen it, recurse.
2544         NoteIndirectBases(Context, Set, Base);
2545     }
2546   }
2547 }
2548 
2549 /// Performs the actual work of attaching the given base class
2550 /// specifiers to a C++ class.
2551 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2552                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2553  if (Bases.empty())
2554     return false;
2555 
2556   // Used to keep track of which base types we have already seen, so
2557   // that we can properly diagnose redundant direct base types. Note
2558   // that the key is always the unqualified canonical type of the base
2559   // class.
2560   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2561 
2562   // Used to track indirect bases so we can see if a direct base is
2563   // ambiguous.
2564   IndirectBaseSet IndirectBaseTypes;
2565 
2566   // Copy non-redundant base specifiers into permanent storage.
2567   unsigned NumGoodBases = 0;
2568   bool Invalid = false;
2569   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2570     QualType NewBaseType
2571       = Context.getCanonicalType(Bases[idx]->getType());
2572     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2573 
2574     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2575     if (KnownBase) {
2576       // C++ [class.mi]p3:
2577       //   A class shall not be specified as a direct base class of a
2578       //   derived class more than once.
2579       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2580           << KnownBase->getType() << Bases[idx]->getSourceRange();
2581 
2582       // Delete the duplicate base class specifier; we're going to
2583       // overwrite its pointer later.
2584       Context.Deallocate(Bases[idx]);
2585 
2586       Invalid = true;
2587     } else {
2588       // Okay, add this new base class.
2589       KnownBase = Bases[idx];
2590       Bases[NumGoodBases++] = Bases[idx];
2591 
2592       // Note this base's direct & indirect bases, if there could be ambiguity.
2593       if (Bases.size() > 1)
2594         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2595 
2596       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2597         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2598         if (Class->isInterface() &&
2599               (!RD->isInterfaceLike() ||
2600                KnownBase->getAccessSpecifier() != AS_public)) {
2601           // The Microsoft extension __interface does not permit bases that
2602           // are not themselves public interfaces.
2603           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2604               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2605               << RD->getSourceRange();
2606           Invalid = true;
2607         }
2608         if (RD->hasAttr<WeakAttr>())
2609           Class->addAttr(WeakAttr::CreateImplicit(Context));
2610       }
2611     }
2612   }
2613 
2614   // Attach the remaining base class specifiers to the derived class.
2615   Class->setBases(Bases.data(), NumGoodBases);
2616 
2617   // Check that the only base classes that are duplicate are virtual.
2618   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2619     // Check whether this direct base is inaccessible due to ambiguity.
2620     QualType BaseType = Bases[idx]->getType();
2621 
2622     // Skip all dependent types in templates being used as base specifiers.
2623     // Checks below assume that the base specifier is a CXXRecord.
2624     if (BaseType->isDependentType())
2625       continue;
2626 
2627     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2628       .getUnqualifiedType();
2629 
2630     if (IndirectBaseTypes.count(CanonicalBase)) {
2631       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2632                          /*DetectVirtual=*/true);
2633       bool found
2634         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2635       assert(found);
2636       (void)found;
2637 
2638       if (Paths.isAmbiguous(CanonicalBase))
2639         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2640             << BaseType << getAmbiguousPathsDisplayString(Paths)
2641             << Bases[idx]->getSourceRange();
2642       else
2643         assert(Bases[idx]->isVirtual());
2644     }
2645 
2646     // Delete the base class specifier, since its data has been copied
2647     // into the CXXRecordDecl.
2648     Context.Deallocate(Bases[idx]);
2649   }
2650 
2651   return Invalid;
2652 }
2653 
2654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2655 /// class, after checking whether there are any duplicate base
2656 /// classes.
2657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2658                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2659   if (!ClassDecl || Bases.empty())
2660     return;
2661 
2662   AdjustDeclIfTemplate(ClassDecl);
2663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2664 }
2665 
2666 /// Determine whether the type \p Derived is a C++ class that is
2667 /// derived from the type \p Base.
2668 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2669   if (!getLangOpts().CPlusPlus)
2670     return false;
2671 
2672   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2673   if (!DerivedRD)
2674     return false;
2675 
2676   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2677   if (!BaseRD)
2678     return false;
2679 
2680   // If either the base or the derived type is invalid, don't try to
2681   // check whether one is derived from the other.
2682   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2683     return false;
2684 
2685   // FIXME: In a modules build, do we need the entire path to be visible for us
2686   // to be able to use the inheritance relationship?
2687   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2688     return false;
2689 
2690   return DerivedRD->isDerivedFrom(BaseRD);
2691 }
2692 
2693 /// Determine whether the type \p Derived is a C++ class that is
2694 /// derived from the type \p Base.
2695 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2696                          CXXBasePaths &Paths) {
2697   if (!getLangOpts().CPlusPlus)
2698     return false;
2699 
2700   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2701   if (!DerivedRD)
2702     return false;
2703 
2704   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2705   if (!BaseRD)
2706     return false;
2707 
2708   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2709     return false;
2710 
2711   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2712 }
2713 
2714 static void BuildBasePathArray(const CXXBasePath &Path,
2715                                CXXCastPath &BasePathArray) {
2716   // We first go backward and check if we have a virtual base.
2717   // FIXME: It would be better if CXXBasePath had the base specifier for
2718   // the nearest virtual base.
2719   unsigned Start = 0;
2720   for (unsigned I = Path.size(); I != 0; --I) {
2721     if (Path[I - 1].Base->isVirtual()) {
2722       Start = I - 1;
2723       break;
2724     }
2725   }
2726 
2727   // Now add all bases.
2728   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2729     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2730 }
2731 
2732 
2733 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2734                               CXXCastPath &BasePathArray) {
2735   assert(BasePathArray.empty() && "Base path array must be empty!");
2736   assert(Paths.isRecordingPaths() && "Must record paths!");
2737   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2738 }
2739 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2740 /// conversion (where Derived and Base are class types) is
2741 /// well-formed, meaning that the conversion is unambiguous (and
2742 /// that all of the base classes are accessible). Returns true
2743 /// and emits a diagnostic if the code is ill-formed, returns false
2744 /// otherwise. Loc is the location where this routine should point to
2745 /// if there is an error, and Range is the source range to highlight
2746 /// if there is an error.
2747 ///
2748 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2749 /// diagnostic for the respective type of error will be suppressed, but the
2750 /// check for ill-formed code will still be performed.
2751 bool
2752 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2753                                    unsigned InaccessibleBaseID,
2754                                    unsigned AmbigiousBaseConvID,
2755                                    SourceLocation Loc, SourceRange Range,
2756                                    DeclarationName Name,
2757                                    CXXCastPath *BasePath,
2758                                    bool IgnoreAccess) {
2759   // First, determine whether the path from Derived to Base is
2760   // ambiguous. This is slightly more expensive than checking whether
2761   // the Derived to Base conversion exists, because here we need to
2762   // explore multiple paths to determine if there is an ambiguity.
2763   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2764                      /*DetectVirtual=*/false);
2765   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2766   if (!DerivationOkay)
2767     return true;
2768 
2769   const CXXBasePath *Path = nullptr;
2770   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2771     Path = &Paths.front();
2772 
2773   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2774   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2775   // user to access such bases.
2776   if (!Path && getLangOpts().MSVCCompat) {
2777     for (const CXXBasePath &PossiblePath : Paths) {
2778       if (PossiblePath.size() == 1) {
2779         Path = &PossiblePath;
2780         if (AmbigiousBaseConvID)
2781           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2782               << Base << Derived << Range;
2783         break;
2784       }
2785     }
2786   }
2787 
2788   if (Path) {
2789     if (!IgnoreAccess) {
2790       // Check that the base class can be accessed.
2791       switch (
2792           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2793       case AR_inaccessible:
2794         return true;
2795       case AR_accessible:
2796       case AR_dependent:
2797       case AR_delayed:
2798         break;
2799       }
2800     }
2801 
2802     // Build a base path if necessary.
2803     if (BasePath)
2804       ::BuildBasePathArray(*Path, *BasePath);
2805     return false;
2806   }
2807 
2808   if (AmbigiousBaseConvID) {
2809     // We know that the derived-to-base conversion is ambiguous, and
2810     // we're going to produce a diagnostic. Perform the derived-to-base
2811     // search just one more time to compute all of the possible paths so
2812     // that we can print them out. This is more expensive than any of
2813     // the previous derived-to-base checks we've done, but at this point
2814     // performance isn't as much of an issue.
2815     Paths.clear();
2816     Paths.setRecordingPaths(true);
2817     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2818     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2819     (void)StillOkay;
2820 
2821     // Build up a textual representation of the ambiguous paths, e.g.,
2822     // D -> B -> A, that will be used to illustrate the ambiguous
2823     // conversions in the diagnostic. We only print one of the paths
2824     // to each base class subobject.
2825     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2826 
2827     Diag(Loc, AmbigiousBaseConvID)
2828     << Derived << Base << PathDisplayStr << Range << Name;
2829   }
2830   return true;
2831 }
2832 
2833 bool
2834 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2835                                    SourceLocation Loc, SourceRange Range,
2836                                    CXXCastPath *BasePath,
2837                                    bool IgnoreAccess) {
2838   return CheckDerivedToBaseConversion(
2839       Derived, Base, diag::err_upcast_to_inaccessible_base,
2840       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2841       BasePath, IgnoreAccess);
2842 }
2843 
2844 
2845 /// Builds a string representing ambiguous paths from a
2846 /// specific derived class to different subobjects of the same base
2847 /// class.
2848 ///
2849 /// This function builds a string that can be used in error messages
2850 /// to show the different paths that one can take through the
2851 /// inheritance hierarchy to go from the derived class to different
2852 /// subobjects of a base class. The result looks something like this:
2853 /// @code
2854 /// struct D -> struct B -> struct A
2855 /// struct D -> struct C -> struct A
2856 /// @endcode
2857 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2858   std::string PathDisplayStr;
2859   std::set<unsigned> DisplayedPaths;
2860   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2861        Path != Paths.end(); ++Path) {
2862     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2863       // We haven't displayed a path to this particular base
2864       // class subobject yet.
2865       PathDisplayStr += "\n    ";
2866       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2867       for (CXXBasePath::const_iterator Element = Path->begin();
2868            Element != Path->end(); ++Element)
2869         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2870     }
2871   }
2872 
2873   return PathDisplayStr;
2874 }
2875 
2876 //===----------------------------------------------------------------------===//
2877 // C++ class member Handling
2878 //===----------------------------------------------------------------------===//
2879 
2880 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2881 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2882                                 SourceLocation ColonLoc,
2883                                 const ParsedAttributesView &Attrs) {
2884   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2885   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2886                                                   ASLoc, ColonLoc);
2887   CurContext->addHiddenDecl(ASDecl);
2888   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2889 }
2890 
2891 /// CheckOverrideControl - Check C++11 override control semantics.
2892 void Sema::CheckOverrideControl(NamedDecl *D) {
2893   if (D->isInvalidDecl())
2894     return;
2895 
2896   // We only care about "override" and "final" declarations.
2897   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2898     return;
2899 
2900   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2901 
2902   // We can't check dependent instance methods.
2903   if (MD && MD->isInstance() &&
2904       (MD->getParent()->hasAnyDependentBases() ||
2905        MD->getType()->isDependentType()))
2906     return;
2907 
2908   if (MD && !MD->isVirtual()) {
2909     // If we have a non-virtual method, check if if hides a virtual method.
2910     // (In that case, it's most likely the method has the wrong type.)
2911     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2912     FindHiddenVirtualMethods(MD, OverloadedMethods);
2913 
2914     if (!OverloadedMethods.empty()) {
2915       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2916         Diag(OA->getLocation(),
2917              diag::override_keyword_hides_virtual_member_function)
2918           << "override" << (OverloadedMethods.size() > 1);
2919       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2920         Diag(FA->getLocation(),
2921              diag::override_keyword_hides_virtual_member_function)
2922           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2923           << (OverloadedMethods.size() > 1);
2924       }
2925       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2926       MD->setInvalidDecl();
2927       return;
2928     }
2929     // Fall through into the general case diagnostic.
2930     // FIXME: We might want to attempt typo correction here.
2931   }
2932 
2933   if (!MD || !MD->isVirtual()) {
2934     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2935       Diag(OA->getLocation(),
2936            diag::override_keyword_only_allowed_on_virtual_member_functions)
2937         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2938       D->dropAttr<OverrideAttr>();
2939     }
2940     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2941       Diag(FA->getLocation(),
2942            diag::override_keyword_only_allowed_on_virtual_member_functions)
2943         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2944         << FixItHint::CreateRemoval(FA->getLocation());
2945       D->dropAttr<FinalAttr>();
2946     }
2947     return;
2948   }
2949 
2950   // C++11 [class.virtual]p5:
2951   //   If a function is marked with the virt-specifier override and
2952   //   does not override a member function of a base class, the program is
2953   //   ill-formed.
2954   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2955   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2956     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2957       << MD->getDeclName();
2958 }
2959 
2960 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2961   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2962     return;
2963   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2964   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2965     return;
2966 
2967   SourceLocation Loc = MD->getLocation();
2968   SourceLocation SpellingLoc = Loc;
2969   if (getSourceManager().isMacroArgExpansion(Loc))
2970     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2971   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2972   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2973       return;
2974 
2975   if (MD->size_overridden_methods() > 0) {
2976     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2977                           ? diag::warn_destructor_marked_not_override_overriding
2978                           : diag::warn_function_marked_not_override_overriding;
2979     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2980     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2981     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2982   }
2983 }
2984 
2985 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2986 /// function overrides a virtual member function marked 'final', according to
2987 /// C++11 [class.virtual]p4.
2988 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2989                                                   const CXXMethodDecl *Old) {
2990   FinalAttr *FA = Old->getAttr<FinalAttr>();
2991   if (!FA)
2992     return false;
2993 
2994   Diag(New->getLocation(), diag::err_final_function_overridden)
2995     << New->getDeclName()
2996     << FA->isSpelledAsSealed();
2997   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2998   return true;
2999 }
3000 
3001 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3002   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3003   // FIXME: Destruction of ObjC lifetime types has side-effects.
3004   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3005     return !RD->isCompleteDefinition() ||
3006            !RD->hasTrivialDefaultConstructor() ||
3007            !RD->hasTrivialDestructor();
3008   return false;
3009 }
3010 
3011 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3012   ParsedAttributesView::const_iterator Itr =
3013       llvm::find_if(list, [](const ParsedAttr &AL) {
3014         return AL.isDeclspecPropertyAttribute();
3015       });
3016   if (Itr != list.end())
3017     return &*Itr;
3018   return nullptr;
3019 }
3020 
3021 // Check if there is a field shadowing.
3022 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3023                                       DeclarationName FieldName,
3024                                       const CXXRecordDecl *RD,
3025                                       bool DeclIsField) {
3026   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3027     return;
3028 
3029   // To record a shadowed field in a base
3030   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3031   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3032                            CXXBasePath &Path) {
3033     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3034     // Record an ambiguous path directly
3035     if (Bases.find(Base) != Bases.end())
3036       return true;
3037     for (const auto Field : Base->lookup(FieldName)) {
3038       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3039           Field->getAccess() != AS_private) {
3040         assert(Field->getAccess() != AS_none);
3041         assert(Bases.find(Base) == Bases.end());
3042         Bases[Base] = Field;
3043         return true;
3044       }
3045     }
3046     return false;
3047   };
3048 
3049   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3050                      /*DetectVirtual=*/true);
3051   if (!RD->lookupInBases(FieldShadowed, Paths))
3052     return;
3053 
3054   for (const auto &P : Paths) {
3055     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3056     auto It = Bases.find(Base);
3057     // Skip duplicated bases
3058     if (It == Bases.end())
3059       continue;
3060     auto BaseField = It->second;
3061     assert(BaseField->getAccess() != AS_private);
3062     if (AS_none !=
3063         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3064       Diag(Loc, diag::warn_shadow_field)
3065         << FieldName << RD << Base << DeclIsField;
3066       Diag(BaseField->getLocation(), diag::note_shadow_field);
3067       Bases.erase(It);
3068     }
3069   }
3070 }
3071 
3072 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3073 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3074 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3075 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3076 /// present (but parsing it has been deferred).
3077 NamedDecl *
3078 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3079                                MultiTemplateParamsArg TemplateParameterLists,
3080                                Expr *BW, const VirtSpecifiers &VS,
3081                                InClassInitStyle InitStyle) {
3082   const DeclSpec &DS = D.getDeclSpec();
3083   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3084   DeclarationName Name = NameInfo.getName();
3085   SourceLocation Loc = NameInfo.getLoc();
3086 
3087   // For anonymous bitfields, the location should point to the type.
3088   if (Loc.isInvalid())
3089     Loc = D.getBeginLoc();
3090 
3091   Expr *BitWidth = static_cast<Expr*>(BW);
3092 
3093   assert(isa<CXXRecordDecl>(CurContext));
3094   assert(!DS.isFriendSpecified());
3095 
3096   bool isFunc = D.isDeclarationOfFunction();
3097   const ParsedAttr *MSPropertyAttr =
3098       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3099 
3100   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3101     // The Microsoft extension __interface only permits public member functions
3102     // and prohibits constructors, destructors, operators, non-public member
3103     // functions, static methods and data members.
3104     unsigned InvalidDecl;
3105     bool ShowDeclName = true;
3106     if (!isFunc &&
3107         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3108       InvalidDecl = 0;
3109     else if (!isFunc)
3110       InvalidDecl = 1;
3111     else if (AS != AS_public)
3112       InvalidDecl = 2;
3113     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3114       InvalidDecl = 3;
3115     else switch (Name.getNameKind()) {
3116       case DeclarationName::CXXConstructorName:
3117         InvalidDecl = 4;
3118         ShowDeclName = false;
3119         break;
3120 
3121       case DeclarationName::CXXDestructorName:
3122         InvalidDecl = 5;
3123         ShowDeclName = false;
3124         break;
3125 
3126       case DeclarationName::CXXOperatorName:
3127       case DeclarationName::CXXConversionFunctionName:
3128         InvalidDecl = 6;
3129         break;
3130 
3131       default:
3132         InvalidDecl = 0;
3133         break;
3134     }
3135 
3136     if (InvalidDecl) {
3137       if (ShowDeclName)
3138         Diag(Loc, diag::err_invalid_member_in_interface)
3139           << (InvalidDecl-1) << Name;
3140       else
3141         Diag(Loc, diag::err_invalid_member_in_interface)
3142           << (InvalidDecl-1) << "";
3143       return nullptr;
3144     }
3145   }
3146 
3147   // C++ 9.2p6: A member shall not be declared to have automatic storage
3148   // duration (auto, register) or with the extern storage-class-specifier.
3149   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3150   // data members and cannot be applied to names declared const or static,
3151   // and cannot be applied to reference members.
3152   switch (DS.getStorageClassSpec()) {
3153   case DeclSpec::SCS_unspecified:
3154   case DeclSpec::SCS_typedef:
3155   case DeclSpec::SCS_static:
3156     break;
3157   case DeclSpec::SCS_mutable:
3158     if (isFunc) {
3159       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3160 
3161       // FIXME: It would be nicer if the keyword was ignored only for this
3162       // declarator. Otherwise we could get follow-up errors.
3163       D.getMutableDeclSpec().ClearStorageClassSpecs();
3164     }
3165     break;
3166   default:
3167     Diag(DS.getStorageClassSpecLoc(),
3168          diag::err_storageclass_invalid_for_member);
3169     D.getMutableDeclSpec().ClearStorageClassSpecs();
3170     break;
3171   }
3172 
3173   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3174                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3175                       !isFunc);
3176 
3177   if (DS.hasConstexprSpecifier() && isInstField) {
3178     SemaDiagnosticBuilder B =
3179         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3180     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3181     if (InitStyle == ICIS_NoInit) {
3182       B << 0 << 0;
3183       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3184         B << FixItHint::CreateRemoval(ConstexprLoc);
3185       else {
3186         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3187         D.getMutableDeclSpec().ClearConstexprSpec();
3188         const char *PrevSpec;
3189         unsigned DiagID;
3190         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3191             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3192         (void)Failed;
3193         assert(!Failed && "Making a constexpr member const shouldn't fail");
3194       }
3195     } else {
3196       B << 1;
3197       const char *PrevSpec;
3198       unsigned DiagID;
3199       if (D.getMutableDeclSpec().SetStorageClassSpec(
3200           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3201           Context.getPrintingPolicy())) {
3202         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3203                "This is the only DeclSpec that should fail to be applied");
3204         B << 1;
3205       } else {
3206         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3207         isInstField = false;
3208       }
3209     }
3210   }
3211 
3212   NamedDecl *Member;
3213   if (isInstField) {
3214     CXXScopeSpec &SS = D.getCXXScopeSpec();
3215 
3216     // Data members must have identifiers for names.
3217     if (!Name.isIdentifier()) {
3218       Diag(Loc, diag::err_bad_variable_name)
3219         << Name;
3220       return nullptr;
3221     }
3222 
3223     IdentifierInfo *II = Name.getAsIdentifierInfo();
3224 
3225     // Member field could not be with "template" keyword.
3226     // So TemplateParameterLists should be empty in this case.
3227     if (TemplateParameterLists.size()) {
3228       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3229       if (TemplateParams->size()) {
3230         // There is no such thing as a member field template.
3231         Diag(D.getIdentifierLoc(), diag::err_template_member)
3232             << II
3233             << SourceRange(TemplateParams->getTemplateLoc(),
3234                 TemplateParams->getRAngleLoc());
3235       } else {
3236         // There is an extraneous 'template<>' for this member.
3237         Diag(TemplateParams->getTemplateLoc(),
3238             diag::err_template_member_noparams)
3239             << II
3240             << SourceRange(TemplateParams->getTemplateLoc(),
3241                 TemplateParams->getRAngleLoc());
3242       }
3243       return nullptr;
3244     }
3245 
3246     if (SS.isSet() && !SS.isInvalid()) {
3247       // The user provided a superfluous scope specifier inside a class
3248       // definition:
3249       //
3250       // class X {
3251       //   int X::member;
3252       // };
3253       if (DeclContext *DC = computeDeclContext(SS, false))
3254         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3255                                      D.getName().getKind() ==
3256                                          UnqualifiedIdKind::IK_TemplateId);
3257       else
3258         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3259           << Name << SS.getRange();
3260 
3261       SS.clear();
3262     }
3263 
3264     if (MSPropertyAttr) {
3265       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3266                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3267       if (!Member)
3268         return nullptr;
3269       isInstField = false;
3270     } else {
3271       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3272                                 BitWidth, InitStyle, AS);
3273       if (!Member)
3274         return nullptr;
3275     }
3276 
3277     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3278   } else {
3279     Member = HandleDeclarator(S, D, TemplateParameterLists);
3280     if (!Member)
3281       return nullptr;
3282 
3283     // Non-instance-fields can't have a bitfield.
3284     if (BitWidth) {
3285       if (Member->isInvalidDecl()) {
3286         // don't emit another diagnostic.
3287       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3288         // C++ 9.6p3: A bit-field shall not be a static member.
3289         // "static member 'A' cannot be a bit-field"
3290         Diag(Loc, diag::err_static_not_bitfield)
3291           << Name << BitWidth->getSourceRange();
3292       } else if (isa<TypedefDecl>(Member)) {
3293         // "typedef member 'x' cannot be a bit-field"
3294         Diag(Loc, diag::err_typedef_not_bitfield)
3295           << Name << BitWidth->getSourceRange();
3296       } else {
3297         // A function typedef ("typedef int f(); f a;").
3298         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3299         Diag(Loc, diag::err_not_integral_type_bitfield)
3300           << Name << cast<ValueDecl>(Member)->getType()
3301           << BitWidth->getSourceRange();
3302       }
3303 
3304       BitWidth = nullptr;
3305       Member->setInvalidDecl();
3306     }
3307 
3308     NamedDecl *NonTemplateMember = Member;
3309     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3310       NonTemplateMember = FunTmpl->getTemplatedDecl();
3311     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3312       NonTemplateMember = VarTmpl->getTemplatedDecl();
3313 
3314     Member->setAccess(AS);
3315 
3316     // If we have declared a member function template or static data member
3317     // template, set the access of the templated declaration as well.
3318     if (NonTemplateMember != Member)
3319       NonTemplateMember->setAccess(AS);
3320 
3321     // C++ [temp.deduct.guide]p3:
3322     //   A deduction guide [...] for a member class template [shall be
3323     //   declared] with the same access [as the template].
3324     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3325       auto *TD = DG->getDeducedTemplate();
3326       // Access specifiers are only meaningful if both the template and the
3327       // deduction guide are from the same scope.
3328       if (AS != TD->getAccess() &&
3329           TD->getDeclContext()->getRedeclContext()->Equals(
3330               DG->getDeclContext()->getRedeclContext())) {
3331         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3332         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3333             << TD->getAccess();
3334         const AccessSpecDecl *LastAccessSpec = nullptr;
3335         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3336           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3337             LastAccessSpec = AccessSpec;
3338         }
3339         assert(LastAccessSpec && "differing access with no access specifier");
3340         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3341             << AS;
3342       }
3343     }
3344   }
3345 
3346   if (VS.isOverrideSpecified())
3347     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3348   if (VS.isFinalSpecified())
3349     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3350                                             VS.isFinalSpelledSealed()));
3351 
3352   if (VS.getLastLocation().isValid()) {
3353     // Update the end location of a method that has a virt-specifiers.
3354     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3355       MD->setRangeEnd(VS.getLastLocation());
3356   }
3357 
3358   CheckOverrideControl(Member);
3359 
3360   assert((Name || isInstField) && "No identifier for non-field ?");
3361 
3362   if (isInstField) {
3363     FieldDecl *FD = cast<FieldDecl>(Member);
3364     FieldCollector->Add(FD);
3365 
3366     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3367       // Remember all explicit private FieldDecls that have a name, no side
3368       // effects and are not part of a dependent type declaration.
3369       if (!FD->isImplicit() && FD->getDeclName() &&
3370           FD->getAccess() == AS_private &&
3371           !FD->hasAttr<UnusedAttr>() &&
3372           !FD->getParent()->isDependentContext() &&
3373           !InitializationHasSideEffects(*FD))
3374         UnusedPrivateFields.insert(FD);
3375     }
3376   }
3377 
3378   return Member;
3379 }
3380 
3381 namespace {
3382   class UninitializedFieldVisitor
3383       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3384     Sema &S;
3385     // List of Decls to generate a warning on.  Also remove Decls that become
3386     // initialized.
3387     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3388     // List of base classes of the record.  Classes are removed after their
3389     // initializers.
3390     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3391     // Vector of decls to be removed from the Decl set prior to visiting the
3392     // nodes.  These Decls may have been initialized in the prior initializer.
3393     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3394     // If non-null, add a note to the warning pointing back to the constructor.
3395     const CXXConstructorDecl *Constructor;
3396     // Variables to hold state when processing an initializer list.  When
3397     // InitList is true, special case initialization of FieldDecls matching
3398     // InitListFieldDecl.
3399     bool InitList;
3400     FieldDecl *InitListFieldDecl;
3401     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3402 
3403   public:
3404     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3405     UninitializedFieldVisitor(Sema &S,
3406                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3407                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3408       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3409         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3410 
3411     // Returns true if the use of ME is not an uninitialized use.
3412     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3413                                          bool CheckReferenceOnly) {
3414       llvm::SmallVector<FieldDecl*, 4> Fields;
3415       bool ReferenceField = false;
3416       while (ME) {
3417         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3418         if (!FD)
3419           return false;
3420         Fields.push_back(FD);
3421         if (FD->getType()->isReferenceType())
3422           ReferenceField = true;
3423         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3424       }
3425 
3426       // Binding a reference to an uninitialized field is not an
3427       // uninitialized use.
3428       if (CheckReferenceOnly && !ReferenceField)
3429         return true;
3430 
3431       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3432       // Discard the first field since it is the field decl that is being
3433       // initialized.
3434       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3435         UsedFieldIndex.push_back((*I)->getFieldIndex());
3436       }
3437 
3438       for (auto UsedIter = UsedFieldIndex.begin(),
3439                 UsedEnd = UsedFieldIndex.end(),
3440                 OrigIter = InitFieldIndex.begin(),
3441                 OrigEnd = InitFieldIndex.end();
3442            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3443         if (*UsedIter < *OrigIter)
3444           return true;
3445         if (*UsedIter > *OrigIter)
3446           break;
3447       }
3448 
3449       return false;
3450     }
3451 
3452     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3453                           bool AddressOf) {
3454       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3455         return;
3456 
3457       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3458       // or union.
3459       MemberExpr *FieldME = ME;
3460 
3461       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3462 
3463       Expr *Base = ME;
3464       while (MemberExpr *SubME =
3465                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3466 
3467         if (isa<VarDecl>(SubME->getMemberDecl()))
3468           return;
3469 
3470         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3471           if (!FD->isAnonymousStructOrUnion())
3472             FieldME = SubME;
3473 
3474         if (!FieldME->getType().isPODType(S.Context))
3475           AllPODFields = false;
3476 
3477         Base = SubME->getBase();
3478       }
3479 
3480       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3481         return;
3482 
3483       if (AddressOf && AllPODFields)
3484         return;
3485 
3486       ValueDecl* FoundVD = FieldME->getMemberDecl();
3487 
3488       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3489         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3490           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3491         }
3492 
3493         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3494           QualType T = BaseCast->getType();
3495           if (T->isPointerType() &&
3496               BaseClasses.count(T->getPointeeType())) {
3497             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3498                 << T->getPointeeType() << FoundVD;
3499           }
3500         }
3501       }
3502 
3503       if (!Decls.count(FoundVD))
3504         return;
3505 
3506       const bool IsReference = FoundVD->getType()->isReferenceType();
3507 
3508       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3509         // Special checking for initializer lists.
3510         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3511           return;
3512         }
3513       } else {
3514         // Prevent double warnings on use of unbounded references.
3515         if (CheckReferenceOnly && !IsReference)
3516           return;
3517       }
3518 
3519       unsigned diag = IsReference
3520           ? diag::warn_reference_field_is_uninit
3521           : diag::warn_field_is_uninit;
3522       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3523       if (Constructor)
3524         S.Diag(Constructor->getLocation(),
3525                diag::note_uninit_in_this_constructor)
3526           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3527 
3528     }
3529 
3530     void HandleValue(Expr *E, bool AddressOf) {
3531       E = E->IgnoreParens();
3532 
3533       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3534         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3535                          AddressOf /*AddressOf*/);
3536         return;
3537       }
3538 
3539       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3540         Visit(CO->getCond());
3541         HandleValue(CO->getTrueExpr(), AddressOf);
3542         HandleValue(CO->getFalseExpr(), AddressOf);
3543         return;
3544       }
3545 
3546       if (BinaryConditionalOperator *BCO =
3547               dyn_cast<BinaryConditionalOperator>(E)) {
3548         Visit(BCO->getCond());
3549         HandleValue(BCO->getFalseExpr(), AddressOf);
3550         return;
3551       }
3552 
3553       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3554         HandleValue(OVE->getSourceExpr(), AddressOf);
3555         return;
3556       }
3557 
3558       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3559         switch (BO->getOpcode()) {
3560         default:
3561           break;
3562         case(BO_PtrMemD):
3563         case(BO_PtrMemI):
3564           HandleValue(BO->getLHS(), AddressOf);
3565           Visit(BO->getRHS());
3566           return;
3567         case(BO_Comma):
3568           Visit(BO->getLHS());
3569           HandleValue(BO->getRHS(), AddressOf);
3570           return;
3571         }
3572       }
3573 
3574       Visit(E);
3575     }
3576 
3577     void CheckInitListExpr(InitListExpr *ILE) {
3578       InitFieldIndex.push_back(0);
3579       for (auto Child : ILE->children()) {
3580         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3581           CheckInitListExpr(SubList);
3582         } else {
3583           Visit(Child);
3584         }
3585         ++InitFieldIndex.back();
3586       }
3587       InitFieldIndex.pop_back();
3588     }
3589 
3590     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3591                           FieldDecl *Field, const Type *BaseClass) {
3592       // Remove Decls that may have been initialized in the previous
3593       // initializer.
3594       for (ValueDecl* VD : DeclsToRemove)
3595         Decls.erase(VD);
3596       DeclsToRemove.clear();
3597 
3598       Constructor = FieldConstructor;
3599       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3600 
3601       if (ILE && Field) {
3602         InitList = true;
3603         InitListFieldDecl = Field;
3604         InitFieldIndex.clear();
3605         CheckInitListExpr(ILE);
3606       } else {
3607         InitList = false;
3608         Visit(E);
3609       }
3610 
3611       if (Field)
3612         Decls.erase(Field);
3613       if (BaseClass)
3614         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3615     }
3616 
3617     void VisitMemberExpr(MemberExpr *ME) {
3618       // All uses of unbounded reference fields will warn.
3619       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3620     }
3621 
3622     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3623       if (E->getCastKind() == CK_LValueToRValue) {
3624         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3625         return;
3626       }
3627 
3628       Inherited::VisitImplicitCastExpr(E);
3629     }
3630 
3631     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3632       if (E->getConstructor()->isCopyConstructor()) {
3633         Expr *ArgExpr = E->getArg(0);
3634         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3635           if (ILE->getNumInits() == 1)
3636             ArgExpr = ILE->getInit(0);
3637         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3638           if (ICE->getCastKind() == CK_NoOp)
3639             ArgExpr = ICE->getSubExpr();
3640         HandleValue(ArgExpr, false /*AddressOf*/);
3641         return;
3642       }
3643       Inherited::VisitCXXConstructExpr(E);
3644     }
3645 
3646     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3647       Expr *Callee = E->getCallee();
3648       if (isa<MemberExpr>(Callee)) {
3649         HandleValue(Callee, false /*AddressOf*/);
3650         for (auto Arg : E->arguments())
3651           Visit(Arg);
3652         return;
3653       }
3654 
3655       Inherited::VisitCXXMemberCallExpr(E);
3656     }
3657 
3658     void VisitCallExpr(CallExpr *E) {
3659       // Treat std::move as a use.
3660       if (E->isCallToStdMove()) {
3661         HandleValue(E->getArg(0), /*AddressOf=*/false);
3662         return;
3663       }
3664 
3665       Inherited::VisitCallExpr(E);
3666     }
3667 
3668     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3669       Expr *Callee = E->getCallee();
3670 
3671       if (isa<UnresolvedLookupExpr>(Callee))
3672         return Inherited::VisitCXXOperatorCallExpr(E);
3673 
3674       Visit(Callee);
3675       for (auto Arg : E->arguments())
3676         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3677     }
3678 
3679     void VisitBinaryOperator(BinaryOperator *E) {
3680       // If a field assignment is detected, remove the field from the
3681       // uninitiailized field set.
3682       if (E->getOpcode() == BO_Assign)
3683         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3684           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3685             if (!FD->getType()->isReferenceType())
3686               DeclsToRemove.push_back(FD);
3687 
3688       if (E->isCompoundAssignmentOp()) {
3689         HandleValue(E->getLHS(), false /*AddressOf*/);
3690         Visit(E->getRHS());
3691         return;
3692       }
3693 
3694       Inherited::VisitBinaryOperator(E);
3695     }
3696 
3697     void VisitUnaryOperator(UnaryOperator *E) {
3698       if (E->isIncrementDecrementOp()) {
3699         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3700         return;
3701       }
3702       if (E->getOpcode() == UO_AddrOf) {
3703         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3704           HandleValue(ME->getBase(), true /*AddressOf*/);
3705           return;
3706         }
3707       }
3708 
3709       Inherited::VisitUnaryOperator(E);
3710     }
3711   };
3712 
3713   // Diagnose value-uses of fields to initialize themselves, e.g.
3714   //   foo(foo)
3715   // where foo is not also a parameter to the constructor.
3716   // Also diagnose across field uninitialized use such as
3717   //   x(y), y(x)
3718   // TODO: implement -Wuninitialized and fold this into that framework.
3719   static void DiagnoseUninitializedFields(
3720       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3721 
3722     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3723                                            Constructor->getLocation())) {
3724       return;
3725     }
3726 
3727     if (Constructor->isInvalidDecl())
3728       return;
3729 
3730     const CXXRecordDecl *RD = Constructor->getParent();
3731 
3732     if (RD->getDescribedClassTemplate())
3733       return;
3734 
3735     // Holds fields that are uninitialized.
3736     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3737 
3738     // At the beginning, all fields are uninitialized.
3739     for (auto *I : RD->decls()) {
3740       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3741         UninitializedFields.insert(FD);
3742       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3743         UninitializedFields.insert(IFD->getAnonField());
3744       }
3745     }
3746 
3747     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3748     for (auto I : RD->bases())
3749       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3750 
3751     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3752       return;
3753 
3754     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3755                                                    UninitializedFields,
3756                                                    UninitializedBaseClasses);
3757 
3758     for (const auto *FieldInit : Constructor->inits()) {
3759       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3760         break;
3761 
3762       Expr *InitExpr = FieldInit->getInit();
3763       if (!InitExpr)
3764         continue;
3765 
3766       if (CXXDefaultInitExpr *Default =
3767               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3768         InitExpr = Default->getExpr();
3769         if (!InitExpr)
3770           continue;
3771         // In class initializers will point to the constructor.
3772         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3773                                               FieldInit->getAnyMember(),
3774                                               FieldInit->getBaseClass());
3775       } else {
3776         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3777                                               FieldInit->getAnyMember(),
3778                                               FieldInit->getBaseClass());
3779       }
3780     }
3781   }
3782 } // namespace
3783 
3784 /// Enter a new C++ default initializer scope. After calling this, the
3785 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3786 /// parsing or instantiating the initializer failed.
3787 void Sema::ActOnStartCXXInClassMemberInitializer() {
3788   // Create a synthetic function scope to represent the call to the constructor
3789   // that notionally surrounds a use of this initializer.
3790   PushFunctionScope();
3791 }
3792 
3793 /// This is invoked after parsing an in-class initializer for a
3794 /// non-static C++ class member, and after instantiating an in-class initializer
3795 /// in a class template. Such actions are deferred until the class is complete.
3796 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3797                                                   SourceLocation InitLoc,
3798                                                   Expr *InitExpr) {
3799   // Pop the notional constructor scope we created earlier.
3800   PopFunctionScopeInfo(nullptr, D);
3801 
3802   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3803   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3804          "must set init style when field is created");
3805 
3806   if (!InitExpr) {
3807     D->setInvalidDecl();
3808     if (FD)
3809       FD->removeInClassInitializer();
3810     return;
3811   }
3812 
3813   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3814     FD->setInvalidDecl();
3815     FD->removeInClassInitializer();
3816     return;
3817   }
3818 
3819   ExprResult Init = InitExpr;
3820   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3821     InitializedEntity Entity =
3822         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3823     InitializationKind Kind =
3824         FD->getInClassInitStyle() == ICIS_ListInit
3825             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3826                                                    InitExpr->getBeginLoc(),
3827                                                    InitExpr->getEndLoc())
3828             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3829     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3830     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3831     if (Init.isInvalid()) {
3832       FD->setInvalidDecl();
3833       return;
3834     }
3835   }
3836 
3837   // C++11 [class.base.init]p7:
3838   //   The initialization of each base and member constitutes a
3839   //   full-expression.
3840   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3841   if (Init.isInvalid()) {
3842     FD->setInvalidDecl();
3843     return;
3844   }
3845 
3846   InitExpr = Init.get();
3847 
3848   FD->setInClassInitializer(InitExpr);
3849 }
3850 
3851 /// Find the direct and/or virtual base specifiers that
3852 /// correspond to the given base type, for use in base initialization
3853 /// within a constructor.
3854 static bool FindBaseInitializer(Sema &SemaRef,
3855                                 CXXRecordDecl *ClassDecl,
3856                                 QualType BaseType,
3857                                 const CXXBaseSpecifier *&DirectBaseSpec,
3858                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3859   // First, check for a direct base class.
3860   DirectBaseSpec = nullptr;
3861   for (const auto &Base : ClassDecl->bases()) {
3862     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3863       // We found a direct base of this type. That's what we're
3864       // initializing.
3865       DirectBaseSpec = &Base;
3866       break;
3867     }
3868   }
3869 
3870   // Check for a virtual base class.
3871   // FIXME: We might be able to short-circuit this if we know in advance that
3872   // there are no virtual bases.
3873   VirtualBaseSpec = nullptr;
3874   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3875     // We haven't found a base yet; search the class hierarchy for a
3876     // virtual base class.
3877     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3878                        /*DetectVirtual=*/false);
3879     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3880                               SemaRef.Context.getTypeDeclType(ClassDecl),
3881                               BaseType, Paths)) {
3882       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3883            Path != Paths.end(); ++Path) {
3884         if (Path->back().Base->isVirtual()) {
3885           VirtualBaseSpec = Path->back().Base;
3886           break;
3887         }
3888       }
3889     }
3890   }
3891 
3892   return DirectBaseSpec || VirtualBaseSpec;
3893 }
3894 
3895 /// Handle a C++ member initializer using braced-init-list syntax.
3896 MemInitResult
3897 Sema::ActOnMemInitializer(Decl *ConstructorD,
3898                           Scope *S,
3899                           CXXScopeSpec &SS,
3900                           IdentifierInfo *MemberOrBase,
3901                           ParsedType TemplateTypeTy,
3902                           const DeclSpec &DS,
3903                           SourceLocation IdLoc,
3904                           Expr *InitList,
3905                           SourceLocation EllipsisLoc) {
3906   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3907                              DS, IdLoc, InitList,
3908                              EllipsisLoc);
3909 }
3910 
3911 /// Handle a C++ member initializer using parentheses syntax.
3912 MemInitResult
3913 Sema::ActOnMemInitializer(Decl *ConstructorD,
3914                           Scope *S,
3915                           CXXScopeSpec &SS,
3916                           IdentifierInfo *MemberOrBase,
3917                           ParsedType TemplateTypeTy,
3918                           const DeclSpec &DS,
3919                           SourceLocation IdLoc,
3920                           SourceLocation LParenLoc,
3921                           ArrayRef<Expr *> Args,
3922                           SourceLocation RParenLoc,
3923                           SourceLocation EllipsisLoc) {
3924   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3925   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3926                              DS, IdLoc, List, EllipsisLoc);
3927 }
3928 
3929 namespace {
3930 
3931 // Callback to only accept typo corrections that can be a valid C++ member
3932 // intializer: either a non-static field member or a base class.
3933 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3934 public:
3935   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3936       : ClassDecl(ClassDecl) {}
3937 
3938   bool ValidateCandidate(const TypoCorrection &candidate) override {
3939     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3940       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3941         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3942       return isa<TypeDecl>(ND);
3943     }
3944     return false;
3945   }
3946 
3947   std::unique_ptr<CorrectionCandidateCallback> clone() override {
3948     return std::make_unique<MemInitializerValidatorCCC>(*this);
3949   }
3950 
3951 private:
3952   CXXRecordDecl *ClassDecl;
3953 };
3954 
3955 }
3956 
3957 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3958                                              CXXScopeSpec &SS,
3959                                              ParsedType TemplateTypeTy,
3960                                              IdentifierInfo *MemberOrBase) {
3961   if (SS.getScopeRep() || TemplateTypeTy)
3962     return nullptr;
3963   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3964   if (Result.empty())
3965     return nullptr;
3966   ValueDecl *Member;
3967   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3968       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3969     return Member;
3970   return nullptr;
3971 }
3972 
3973 /// Handle a C++ member initializer.
3974 MemInitResult
3975 Sema::BuildMemInitializer(Decl *ConstructorD,
3976                           Scope *S,
3977                           CXXScopeSpec &SS,
3978                           IdentifierInfo *MemberOrBase,
3979                           ParsedType TemplateTypeTy,
3980                           const DeclSpec &DS,
3981                           SourceLocation IdLoc,
3982                           Expr *Init,
3983                           SourceLocation EllipsisLoc) {
3984   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3985   if (!Res.isUsable())
3986     return true;
3987   Init = Res.get();
3988 
3989   if (!ConstructorD)
3990     return true;
3991 
3992   AdjustDeclIfTemplate(ConstructorD);
3993 
3994   CXXConstructorDecl *Constructor
3995     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3996   if (!Constructor) {
3997     // The user wrote a constructor initializer on a function that is
3998     // not a C++ constructor. Ignore the error for now, because we may
3999     // have more member initializers coming; we'll diagnose it just
4000     // once in ActOnMemInitializers.
4001     return true;
4002   }
4003 
4004   CXXRecordDecl *ClassDecl = Constructor->getParent();
4005 
4006   // C++ [class.base.init]p2:
4007   //   Names in a mem-initializer-id are looked up in the scope of the
4008   //   constructor's class and, if not found in that scope, are looked
4009   //   up in the scope containing the constructor's definition.
4010   //   [Note: if the constructor's class contains a member with the
4011   //   same name as a direct or virtual base class of the class, a
4012   //   mem-initializer-id naming the member or base class and composed
4013   //   of a single identifier refers to the class member. A
4014   //   mem-initializer-id for the hidden base class may be specified
4015   //   using a qualified name. ]
4016 
4017   // Look for a member, first.
4018   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4019           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4020     if (EllipsisLoc.isValid())
4021       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4022           << MemberOrBase
4023           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4024 
4025     return BuildMemberInitializer(Member, Init, IdLoc);
4026   }
4027   // It didn't name a member, so see if it names a class.
4028   QualType BaseType;
4029   TypeSourceInfo *TInfo = nullptr;
4030 
4031   if (TemplateTypeTy) {
4032     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4033     if (BaseType.isNull())
4034       return true;
4035   } else if (DS.getTypeSpecType() == TST_decltype) {
4036     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4037   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4038     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4039     return true;
4040   } else {
4041     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4042     LookupParsedName(R, S, &SS);
4043 
4044     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4045     if (!TyD) {
4046       if (R.isAmbiguous()) return true;
4047 
4048       // We don't want access-control diagnostics here.
4049       R.suppressDiagnostics();
4050 
4051       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4052         bool NotUnknownSpecialization = false;
4053         DeclContext *DC = computeDeclContext(SS, false);
4054         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4055           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4056 
4057         if (!NotUnknownSpecialization) {
4058           // When the scope specifier can refer to a member of an unknown
4059           // specialization, we take it as a type name.
4060           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4061                                        SS.getWithLocInContext(Context),
4062                                        *MemberOrBase, IdLoc);
4063           if (BaseType.isNull())
4064             return true;
4065 
4066           TInfo = Context.CreateTypeSourceInfo(BaseType);
4067           DependentNameTypeLoc TL =
4068               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4069           if (!TL.isNull()) {
4070             TL.setNameLoc(IdLoc);
4071             TL.setElaboratedKeywordLoc(SourceLocation());
4072             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4073           }
4074 
4075           R.clear();
4076           R.setLookupName(MemberOrBase);
4077         }
4078       }
4079 
4080       // If no results were found, try to correct typos.
4081       TypoCorrection Corr;
4082       MemInitializerValidatorCCC CCC(ClassDecl);
4083       if (R.empty() && BaseType.isNull() &&
4084           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4085                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4086         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4087           // We have found a non-static data member with a similar
4088           // name to what was typed; complain and initialize that
4089           // member.
4090           diagnoseTypo(Corr,
4091                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4092                          << MemberOrBase << true);
4093           return BuildMemberInitializer(Member, Init, IdLoc);
4094         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4095           const CXXBaseSpecifier *DirectBaseSpec;
4096           const CXXBaseSpecifier *VirtualBaseSpec;
4097           if (FindBaseInitializer(*this, ClassDecl,
4098                                   Context.getTypeDeclType(Type),
4099                                   DirectBaseSpec, VirtualBaseSpec)) {
4100             // We have found a direct or virtual base class with a
4101             // similar name to what was typed; complain and initialize
4102             // that base class.
4103             diagnoseTypo(Corr,
4104                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4105                            << MemberOrBase << false,
4106                          PDiag() /*Suppress note, we provide our own.*/);
4107 
4108             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4109                                                               : VirtualBaseSpec;
4110             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4111                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4112 
4113             TyD = Type;
4114           }
4115         }
4116       }
4117 
4118       if (!TyD && BaseType.isNull()) {
4119         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4120           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4121         return true;
4122       }
4123     }
4124 
4125     if (BaseType.isNull()) {
4126       BaseType = Context.getTypeDeclType(TyD);
4127       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4128       if (SS.isSet()) {
4129         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4130                                              BaseType);
4131         TInfo = Context.CreateTypeSourceInfo(BaseType);
4132         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4133         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4134         TL.setElaboratedKeywordLoc(SourceLocation());
4135         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4136       }
4137     }
4138   }
4139 
4140   if (!TInfo)
4141     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4142 
4143   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4144 }
4145 
4146 MemInitResult
4147 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4148                              SourceLocation IdLoc) {
4149   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4150   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4151   assert((DirectMember || IndirectMember) &&
4152          "Member must be a FieldDecl or IndirectFieldDecl");
4153 
4154   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4155     return true;
4156 
4157   if (Member->isInvalidDecl())
4158     return true;
4159 
4160   MultiExprArg Args;
4161   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4162     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4163   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4164     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4165   } else {
4166     // Template instantiation doesn't reconstruct ParenListExprs for us.
4167     Args = Init;
4168   }
4169 
4170   SourceRange InitRange = Init->getSourceRange();
4171 
4172   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4173     // Can't check initialization for a member of dependent type or when
4174     // any of the arguments are type-dependent expressions.
4175     DiscardCleanupsInEvaluationContext();
4176   } else {
4177     bool InitList = false;
4178     if (isa<InitListExpr>(Init)) {
4179       InitList = true;
4180       Args = Init;
4181     }
4182 
4183     // Initialize the member.
4184     InitializedEntity MemberEntity =
4185       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4186                    : InitializedEntity::InitializeMember(IndirectMember,
4187                                                          nullptr);
4188     InitializationKind Kind =
4189         InitList ? InitializationKind::CreateDirectList(
4190                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4191                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4192                                                     InitRange.getEnd());
4193 
4194     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4195     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4196                                             nullptr);
4197     if (MemberInit.isInvalid())
4198       return true;
4199 
4200     // C++11 [class.base.init]p7:
4201     //   The initialization of each base and member constitutes a
4202     //   full-expression.
4203     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4204                                      /*DiscardedValue*/ false);
4205     if (MemberInit.isInvalid())
4206       return true;
4207 
4208     Init = MemberInit.get();
4209   }
4210 
4211   if (DirectMember) {
4212     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4213                                             InitRange.getBegin(), Init,
4214                                             InitRange.getEnd());
4215   } else {
4216     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4217                                             InitRange.getBegin(), Init,
4218                                             InitRange.getEnd());
4219   }
4220 }
4221 
4222 MemInitResult
4223 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4224                                  CXXRecordDecl *ClassDecl) {
4225   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4226   if (!LangOpts.CPlusPlus11)
4227     return Diag(NameLoc, diag::err_delegating_ctor)
4228       << TInfo->getTypeLoc().getLocalSourceRange();
4229   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4230 
4231   bool InitList = true;
4232   MultiExprArg Args = Init;
4233   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4234     InitList = false;
4235     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4236   }
4237 
4238   SourceRange InitRange = Init->getSourceRange();
4239   // Initialize the object.
4240   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4241                                      QualType(ClassDecl->getTypeForDecl(), 0));
4242   InitializationKind Kind =
4243       InitList ? InitializationKind::CreateDirectList(
4244                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4245                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4246                                                   InitRange.getEnd());
4247   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4248   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4249                                               Args, nullptr);
4250   if (DelegationInit.isInvalid())
4251     return true;
4252 
4253   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4254          "Delegating constructor with no target?");
4255 
4256   // C++11 [class.base.init]p7:
4257   //   The initialization of each base and member constitutes a
4258   //   full-expression.
4259   DelegationInit = ActOnFinishFullExpr(
4260       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4261   if (DelegationInit.isInvalid())
4262     return true;
4263 
4264   // If we are in a dependent context, template instantiation will
4265   // perform this type-checking again. Just save the arguments that we
4266   // received in a ParenListExpr.
4267   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4268   // of the information that we have about the base
4269   // initializer. However, deconstructing the ASTs is a dicey process,
4270   // and this approach is far more likely to get the corner cases right.
4271   if (CurContext->isDependentContext())
4272     DelegationInit = Init;
4273 
4274   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4275                                           DelegationInit.getAs<Expr>(),
4276                                           InitRange.getEnd());
4277 }
4278 
4279 MemInitResult
4280 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4281                            Expr *Init, CXXRecordDecl *ClassDecl,
4282                            SourceLocation EllipsisLoc) {
4283   SourceLocation BaseLoc
4284     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4285 
4286   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4287     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4288              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4289 
4290   // C++ [class.base.init]p2:
4291   //   [...] Unless the mem-initializer-id names a nonstatic data
4292   //   member of the constructor's class or a direct or virtual base
4293   //   of that class, the mem-initializer is ill-formed. A
4294   //   mem-initializer-list can initialize a base class using any
4295   //   name that denotes that base class type.
4296   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4297 
4298   SourceRange InitRange = Init->getSourceRange();
4299   if (EllipsisLoc.isValid()) {
4300     // This is a pack expansion.
4301     if (!BaseType->containsUnexpandedParameterPack())  {
4302       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4303         << SourceRange(BaseLoc, InitRange.getEnd());
4304 
4305       EllipsisLoc = SourceLocation();
4306     }
4307   } else {
4308     // Check for any unexpanded parameter packs.
4309     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4310       return true;
4311 
4312     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4313       return true;
4314   }
4315 
4316   // Check for direct and virtual base classes.
4317   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4318   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4319   if (!Dependent) {
4320     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4321                                        BaseType))
4322       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4323 
4324     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4325                         VirtualBaseSpec);
4326 
4327     // C++ [base.class.init]p2:
4328     // Unless the mem-initializer-id names a nonstatic data member of the
4329     // constructor's class or a direct or virtual base of that class, the
4330     // mem-initializer is ill-formed.
4331     if (!DirectBaseSpec && !VirtualBaseSpec) {
4332       // If the class has any dependent bases, then it's possible that
4333       // one of those types will resolve to the same type as
4334       // BaseType. Therefore, just treat this as a dependent base
4335       // class initialization.  FIXME: Should we try to check the
4336       // initialization anyway? It seems odd.
4337       if (ClassDecl->hasAnyDependentBases())
4338         Dependent = true;
4339       else
4340         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4341           << BaseType << Context.getTypeDeclType(ClassDecl)
4342           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4343     }
4344   }
4345 
4346   if (Dependent) {
4347     DiscardCleanupsInEvaluationContext();
4348 
4349     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4350                                             /*IsVirtual=*/false,
4351                                             InitRange.getBegin(), Init,
4352                                             InitRange.getEnd(), EllipsisLoc);
4353   }
4354 
4355   // C++ [base.class.init]p2:
4356   //   If a mem-initializer-id is ambiguous because it designates both
4357   //   a direct non-virtual base class and an inherited virtual base
4358   //   class, the mem-initializer is ill-formed.
4359   if (DirectBaseSpec && VirtualBaseSpec)
4360     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4361       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4362 
4363   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4364   if (!BaseSpec)
4365     BaseSpec = VirtualBaseSpec;
4366 
4367   // Initialize the base.
4368   bool InitList = true;
4369   MultiExprArg Args = Init;
4370   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4371     InitList = false;
4372     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4373   }
4374 
4375   InitializedEntity BaseEntity =
4376     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4377   InitializationKind Kind =
4378       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4379                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4380                                                   InitRange.getEnd());
4381   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4382   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4383   if (BaseInit.isInvalid())
4384     return true;
4385 
4386   // C++11 [class.base.init]p7:
4387   //   The initialization of each base and member constitutes a
4388   //   full-expression.
4389   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4390                                  /*DiscardedValue*/ false);
4391   if (BaseInit.isInvalid())
4392     return true;
4393 
4394   // If we are in a dependent context, template instantiation will
4395   // perform this type-checking again. Just save the arguments that we
4396   // received in a ParenListExpr.
4397   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4398   // of the information that we have about the base
4399   // initializer. However, deconstructing the ASTs is a dicey process,
4400   // and this approach is far more likely to get the corner cases right.
4401   if (CurContext->isDependentContext())
4402     BaseInit = Init;
4403 
4404   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4405                                           BaseSpec->isVirtual(),
4406                                           InitRange.getBegin(),
4407                                           BaseInit.getAs<Expr>(),
4408                                           InitRange.getEnd(), EllipsisLoc);
4409 }
4410 
4411 // Create a static_cast\<T&&>(expr).
4412 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4413   if (T.isNull()) T = E->getType();
4414   QualType TargetType = SemaRef.BuildReferenceType(
4415       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4416   SourceLocation ExprLoc = E->getBeginLoc();
4417   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4418       TargetType, ExprLoc);
4419 
4420   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4421                                    SourceRange(ExprLoc, ExprLoc),
4422                                    E->getSourceRange()).get();
4423 }
4424 
4425 /// ImplicitInitializerKind - How an implicit base or member initializer should
4426 /// initialize its base or member.
4427 enum ImplicitInitializerKind {
4428   IIK_Default,
4429   IIK_Copy,
4430   IIK_Move,
4431   IIK_Inherit
4432 };
4433 
4434 static bool
4435 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4436                              ImplicitInitializerKind ImplicitInitKind,
4437                              CXXBaseSpecifier *BaseSpec,
4438                              bool IsInheritedVirtualBase,
4439                              CXXCtorInitializer *&CXXBaseInit) {
4440   InitializedEntity InitEntity
4441     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4442                                         IsInheritedVirtualBase);
4443 
4444   ExprResult BaseInit;
4445 
4446   switch (ImplicitInitKind) {
4447   case IIK_Inherit:
4448   case IIK_Default: {
4449     InitializationKind InitKind
4450       = InitializationKind::CreateDefault(Constructor->getLocation());
4451     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4452     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4453     break;
4454   }
4455 
4456   case IIK_Move:
4457   case IIK_Copy: {
4458     bool Moving = ImplicitInitKind == IIK_Move;
4459     ParmVarDecl *Param = Constructor->getParamDecl(0);
4460     QualType ParamType = Param->getType().getNonReferenceType();
4461 
4462     Expr *CopyCtorArg =
4463       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4464                           SourceLocation(), Param, false,
4465                           Constructor->getLocation(), ParamType,
4466                           VK_LValue, nullptr);
4467 
4468     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4469 
4470     // Cast to the base class to avoid ambiguities.
4471     QualType ArgTy =
4472       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4473                                        ParamType.getQualifiers());
4474 
4475     if (Moving) {
4476       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4477     }
4478 
4479     CXXCastPath BasePath;
4480     BasePath.push_back(BaseSpec);
4481     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4482                                             CK_UncheckedDerivedToBase,
4483                                             Moving ? VK_XValue : VK_LValue,
4484                                             &BasePath).get();
4485 
4486     InitializationKind InitKind
4487       = InitializationKind::CreateDirect(Constructor->getLocation(),
4488                                          SourceLocation(), SourceLocation());
4489     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4490     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4491     break;
4492   }
4493   }
4494 
4495   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4496   if (BaseInit.isInvalid())
4497     return true;
4498 
4499   CXXBaseInit =
4500     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4501                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4502                                                         SourceLocation()),
4503                                              BaseSpec->isVirtual(),
4504                                              SourceLocation(),
4505                                              BaseInit.getAs<Expr>(),
4506                                              SourceLocation(),
4507                                              SourceLocation());
4508 
4509   return false;
4510 }
4511 
4512 static bool RefersToRValueRef(Expr *MemRef) {
4513   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4514   return Referenced->getType()->isRValueReferenceType();
4515 }
4516 
4517 static bool
4518 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4519                                ImplicitInitializerKind ImplicitInitKind,
4520                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4521                                CXXCtorInitializer *&CXXMemberInit) {
4522   if (Field->isInvalidDecl())
4523     return true;
4524 
4525   SourceLocation Loc = Constructor->getLocation();
4526 
4527   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4528     bool Moving = ImplicitInitKind == IIK_Move;
4529     ParmVarDecl *Param = Constructor->getParamDecl(0);
4530     QualType ParamType = Param->getType().getNonReferenceType();
4531 
4532     // Suppress copying zero-width bitfields.
4533     if (Field->isZeroLengthBitField(SemaRef.Context))
4534       return false;
4535 
4536     Expr *MemberExprBase =
4537       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4538                           SourceLocation(), Param, false,
4539                           Loc, ParamType, VK_LValue, nullptr);
4540 
4541     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4542 
4543     if (Moving) {
4544       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4545     }
4546 
4547     // Build a reference to this field within the parameter.
4548     CXXScopeSpec SS;
4549     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4550                               Sema::LookupMemberName);
4551     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4552                                   : cast<ValueDecl>(Field), AS_public);
4553     MemberLookup.resolveKind();
4554     ExprResult CtorArg
4555       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4556                                          ParamType, Loc,
4557                                          /*IsArrow=*/false,
4558                                          SS,
4559                                          /*TemplateKWLoc=*/SourceLocation(),
4560                                          /*FirstQualifierInScope=*/nullptr,
4561                                          MemberLookup,
4562                                          /*TemplateArgs=*/nullptr,
4563                                          /*S*/nullptr);
4564     if (CtorArg.isInvalid())
4565       return true;
4566 
4567     // C++11 [class.copy]p15:
4568     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4569     //     with static_cast<T&&>(x.m);
4570     if (RefersToRValueRef(CtorArg.get())) {
4571       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4572     }
4573 
4574     InitializedEntity Entity =
4575         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4576                                                        /*Implicit*/ true)
4577                  : InitializedEntity::InitializeMember(Field, nullptr,
4578                                                        /*Implicit*/ true);
4579 
4580     // Direct-initialize to use the copy constructor.
4581     InitializationKind InitKind =
4582       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4583 
4584     Expr *CtorArgE = CtorArg.getAs<Expr>();
4585     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4586     ExprResult MemberInit =
4587         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4588     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4589     if (MemberInit.isInvalid())
4590       return true;
4591 
4592     if (Indirect)
4593       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4594           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4595     else
4596       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4597           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4598     return false;
4599   }
4600 
4601   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4602          "Unhandled implicit init kind!");
4603 
4604   QualType FieldBaseElementType =
4605     SemaRef.Context.getBaseElementType(Field->getType());
4606 
4607   if (FieldBaseElementType->isRecordType()) {
4608     InitializedEntity InitEntity =
4609         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4610                                                        /*Implicit*/ true)
4611                  : InitializedEntity::InitializeMember(Field, nullptr,
4612                                                        /*Implicit*/ true);
4613     InitializationKind InitKind =
4614       InitializationKind::CreateDefault(Loc);
4615 
4616     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4617     ExprResult MemberInit =
4618       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4619 
4620     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4621     if (MemberInit.isInvalid())
4622       return true;
4623 
4624     if (Indirect)
4625       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4626                                                                Indirect, Loc,
4627                                                                Loc,
4628                                                                MemberInit.get(),
4629                                                                Loc);
4630     else
4631       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4632                                                                Field, Loc, Loc,
4633                                                                MemberInit.get(),
4634                                                                Loc);
4635     return false;
4636   }
4637 
4638   if (!Field->getParent()->isUnion()) {
4639     if (FieldBaseElementType->isReferenceType()) {
4640       SemaRef.Diag(Constructor->getLocation(),
4641                    diag::err_uninitialized_member_in_ctor)
4642       << (int)Constructor->isImplicit()
4643       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4644       << 0 << Field->getDeclName();
4645       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4646       return true;
4647     }
4648 
4649     if (FieldBaseElementType.isConstQualified()) {
4650       SemaRef.Diag(Constructor->getLocation(),
4651                    diag::err_uninitialized_member_in_ctor)
4652       << (int)Constructor->isImplicit()
4653       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4654       << 1 << Field->getDeclName();
4655       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4656       return true;
4657     }
4658   }
4659 
4660   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4661     // ARC and Weak:
4662     //   Default-initialize Objective-C pointers to NULL.
4663     CXXMemberInit
4664       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4665                                                  Loc, Loc,
4666                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4667                                                  Loc);
4668     return false;
4669   }
4670 
4671   // Nothing to initialize.
4672   CXXMemberInit = nullptr;
4673   return false;
4674 }
4675 
4676 namespace {
4677 struct BaseAndFieldInfo {
4678   Sema &S;
4679   CXXConstructorDecl *Ctor;
4680   bool AnyErrorsInInits;
4681   ImplicitInitializerKind IIK;
4682   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4683   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4684   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4685 
4686   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4687     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4688     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4689     if (Ctor->getInheritedConstructor())
4690       IIK = IIK_Inherit;
4691     else if (Generated && Ctor->isCopyConstructor())
4692       IIK = IIK_Copy;
4693     else if (Generated && Ctor->isMoveConstructor())
4694       IIK = IIK_Move;
4695     else
4696       IIK = IIK_Default;
4697   }
4698 
4699   bool isImplicitCopyOrMove() const {
4700     switch (IIK) {
4701     case IIK_Copy:
4702     case IIK_Move:
4703       return true;
4704 
4705     case IIK_Default:
4706     case IIK_Inherit:
4707       return false;
4708     }
4709 
4710     llvm_unreachable("Invalid ImplicitInitializerKind!");
4711   }
4712 
4713   bool addFieldInitializer(CXXCtorInitializer *Init) {
4714     AllToInit.push_back(Init);
4715 
4716     // Check whether this initializer makes the field "used".
4717     if (Init->getInit()->HasSideEffects(S.Context))
4718       S.UnusedPrivateFields.remove(Init->getAnyMember());
4719 
4720     return false;
4721   }
4722 
4723   bool isInactiveUnionMember(FieldDecl *Field) {
4724     RecordDecl *Record = Field->getParent();
4725     if (!Record->isUnion())
4726       return false;
4727 
4728     if (FieldDecl *Active =
4729             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4730       return Active != Field->getCanonicalDecl();
4731 
4732     // In an implicit copy or move constructor, ignore any in-class initializer.
4733     if (isImplicitCopyOrMove())
4734       return true;
4735 
4736     // If there's no explicit initialization, the field is active only if it
4737     // has an in-class initializer...
4738     if (Field->hasInClassInitializer())
4739       return false;
4740     // ... or it's an anonymous struct or union whose class has an in-class
4741     // initializer.
4742     if (!Field->isAnonymousStructOrUnion())
4743       return true;
4744     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4745     return !FieldRD->hasInClassInitializer();
4746   }
4747 
4748   /// Determine whether the given field is, or is within, a union member
4749   /// that is inactive (because there was an initializer given for a different
4750   /// member of the union, or because the union was not initialized at all).
4751   bool isWithinInactiveUnionMember(FieldDecl *Field,
4752                                    IndirectFieldDecl *Indirect) {
4753     if (!Indirect)
4754       return isInactiveUnionMember(Field);
4755 
4756     for (auto *C : Indirect->chain()) {
4757       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4758       if (Field && isInactiveUnionMember(Field))
4759         return true;
4760     }
4761     return false;
4762   }
4763 };
4764 }
4765 
4766 /// Determine whether the given type is an incomplete or zero-lenfgth
4767 /// array type.
4768 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4769   if (T->isIncompleteArrayType())
4770     return true;
4771 
4772   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4773     if (!ArrayT->getSize())
4774       return true;
4775 
4776     T = ArrayT->getElementType();
4777   }
4778 
4779   return false;
4780 }
4781 
4782 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4783                                     FieldDecl *Field,
4784                                     IndirectFieldDecl *Indirect = nullptr) {
4785   if (Field->isInvalidDecl())
4786     return false;
4787 
4788   // Overwhelmingly common case: we have a direct initializer for this field.
4789   if (CXXCtorInitializer *Init =
4790           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4791     return Info.addFieldInitializer(Init);
4792 
4793   // C++11 [class.base.init]p8:
4794   //   if the entity is a non-static data member that has a
4795   //   brace-or-equal-initializer and either
4796   //   -- the constructor's class is a union and no other variant member of that
4797   //      union is designated by a mem-initializer-id or
4798   //   -- the constructor's class is not a union, and, if the entity is a member
4799   //      of an anonymous union, no other member of that union is designated by
4800   //      a mem-initializer-id,
4801   //   the entity is initialized as specified in [dcl.init].
4802   //
4803   // We also apply the same rules to handle anonymous structs within anonymous
4804   // unions.
4805   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4806     return false;
4807 
4808   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4809     ExprResult DIE =
4810         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4811     if (DIE.isInvalid())
4812       return true;
4813 
4814     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4815     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4816 
4817     CXXCtorInitializer *Init;
4818     if (Indirect)
4819       Init = new (SemaRef.Context)
4820           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4821                              SourceLocation(), DIE.get(), SourceLocation());
4822     else
4823       Init = new (SemaRef.Context)
4824           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4825                              SourceLocation(), DIE.get(), SourceLocation());
4826     return Info.addFieldInitializer(Init);
4827   }
4828 
4829   // Don't initialize incomplete or zero-length arrays.
4830   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4831     return false;
4832 
4833   // Don't try to build an implicit initializer if there were semantic
4834   // errors in any of the initializers (and therefore we might be
4835   // missing some that the user actually wrote).
4836   if (Info.AnyErrorsInInits)
4837     return false;
4838 
4839   CXXCtorInitializer *Init = nullptr;
4840   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4841                                      Indirect, Init))
4842     return true;
4843 
4844   if (!Init)
4845     return false;
4846 
4847   return Info.addFieldInitializer(Init);
4848 }
4849 
4850 bool
4851 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4852                                CXXCtorInitializer *Initializer) {
4853   assert(Initializer->isDelegatingInitializer());
4854   Constructor->setNumCtorInitializers(1);
4855   CXXCtorInitializer **initializer =
4856     new (Context) CXXCtorInitializer*[1];
4857   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4858   Constructor->setCtorInitializers(initializer);
4859 
4860   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4861     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4862     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4863   }
4864 
4865   DelegatingCtorDecls.push_back(Constructor);
4866 
4867   DiagnoseUninitializedFields(*this, Constructor);
4868 
4869   return false;
4870 }
4871 
4872 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4873                                ArrayRef<CXXCtorInitializer *> Initializers) {
4874   if (Constructor->isDependentContext()) {
4875     // Just store the initializers as written, they will be checked during
4876     // instantiation.
4877     if (!Initializers.empty()) {
4878       Constructor->setNumCtorInitializers(Initializers.size());
4879       CXXCtorInitializer **baseOrMemberInitializers =
4880         new (Context) CXXCtorInitializer*[Initializers.size()];
4881       memcpy(baseOrMemberInitializers, Initializers.data(),
4882              Initializers.size() * sizeof(CXXCtorInitializer*));
4883       Constructor->setCtorInitializers(baseOrMemberInitializers);
4884     }
4885 
4886     // Let template instantiation know whether we had errors.
4887     if (AnyErrors)
4888       Constructor->setInvalidDecl();
4889 
4890     return false;
4891   }
4892 
4893   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4894 
4895   // We need to build the initializer AST according to order of construction
4896   // and not what user specified in the Initializers list.
4897   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4898   if (!ClassDecl)
4899     return true;
4900 
4901   bool HadError = false;
4902 
4903   for (unsigned i = 0; i < Initializers.size(); i++) {
4904     CXXCtorInitializer *Member = Initializers[i];
4905 
4906     if (Member->isBaseInitializer())
4907       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4908     else {
4909       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4910 
4911       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4912         for (auto *C : F->chain()) {
4913           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4914           if (FD && FD->getParent()->isUnion())
4915             Info.ActiveUnionMember.insert(std::make_pair(
4916                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4917         }
4918       } else if (FieldDecl *FD = Member->getMember()) {
4919         if (FD->getParent()->isUnion())
4920           Info.ActiveUnionMember.insert(std::make_pair(
4921               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4922       }
4923     }
4924   }
4925 
4926   // Keep track of the direct virtual bases.
4927   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4928   for (auto &I : ClassDecl->bases()) {
4929     if (I.isVirtual())
4930       DirectVBases.insert(&I);
4931   }
4932 
4933   // Push virtual bases before others.
4934   for (auto &VBase : ClassDecl->vbases()) {
4935     if (CXXCtorInitializer *Value
4936         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4937       // [class.base.init]p7, per DR257:
4938       //   A mem-initializer where the mem-initializer-id names a virtual base
4939       //   class is ignored during execution of a constructor of any class that
4940       //   is not the most derived class.
4941       if (ClassDecl->isAbstract()) {
4942         // FIXME: Provide a fixit to remove the base specifier. This requires
4943         // tracking the location of the associated comma for a base specifier.
4944         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4945           << VBase.getType() << ClassDecl;
4946         DiagnoseAbstractType(ClassDecl);
4947       }
4948 
4949       Info.AllToInit.push_back(Value);
4950     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4951       // [class.base.init]p8, per DR257:
4952       //   If a given [...] base class is not named by a mem-initializer-id
4953       //   [...] and the entity is not a virtual base class of an abstract
4954       //   class, then [...] the entity is default-initialized.
4955       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4956       CXXCtorInitializer *CXXBaseInit;
4957       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4958                                        &VBase, IsInheritedVirtualBase,
4959                                        CXXBaseInit)) {
4960         HadError = true;
4961         continue;
4962       }
4963 
4964       Info.AllToInit.push_back(CXXBaseInit);
4965     }
4966   }
4967 
4968   // Non-virtual bases.
4969   for (auto &Base : ClassDecl->bases()) {
4970     // Virtuals are in the virtual base list and already constructed.
4971     if (Base.isVirtual())
4972       continue;
4973 
4974     if (CXXCtorInitializer *Value
4975           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4976       Info.AllToInit.push_back(Value);
4977     } else if (!AnyErrors) {
4978       CXXCtorInitializer *CXXBaseInit;
4979       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4980                                        &Base, /*IsInheritedVirtualBase=*/false,
4981                                        CXXBaseInit)) {
4982         HadError = true;
4983         continue;
4984       }
4985 
4986       Info.AllToInit.push_back(CXXBaseInit);
4987     }
4988   }
4989 
4990   // Fields.
4991   for (auto *Mem : ClassDecl->decls()) {
4992     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4993       // C++ [class.bit]p2:
4994       //   A declaration for a bit-field that omits the identifier declares an
4995       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4996       //   initialized.
4997       if (F->isUnnamedBitfield())
4998         continue;
4999 
5000       // If we're not generating the implicit copy/move constructor, then we'll
5001       // handle anonymous struct/union fields based on their individual
5002       // indirect fields.
5003       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5004         continue;
5005 
5006       if (CollectFieldInitializer(*this, Info, F))
5007         HadError = true;
5008       continue;
5009     }
5010 
5011     // Beyond this point, we only consider default initialization.
5012     if (Info.isImplicitCopyOrMove())
5013       continue;
5014 
5015     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5016       if (F->getType()->isIncompleteArrayType()) {
5017         assert(ClassDecl->hasFlexibleArrayMember() &&
5018                "Incomplete array type is not valid");
5019         continue;
5020       }
5021 
5022       // Initialize each field of an anonymous struct individually.
5023       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5024         HadError = true;
5025 
5026       continue;
5027     }
5028   }
5029 
5030   unsigned NumInitializers = Info.AllToInit.size();
5031   if (NumInitializers > 0) {
5032     Constructor->setNumCtorInitializers(NumInitializers);
5033     CXXCtorInitializer **baseOrMemberInitializers =
5034       new (Context) CXXCtorInitializer*[NumInitializers];
5035     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5036            NumInitializers * sizeof(CXXCtorInitializer*));
5037     Constructor->setCtorInitializers(baseOrMemberInitializers);
5038 
5039     // Constructors implicitly reference the base and member
5040     // destructors.
5041     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5042                                            Constructor->getParent());
5043   }
5044 
5045   return HadError;
5046 }
5047 
5048 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5049   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5050     const RecordDecl *RD = RT->getDecl();
5051     if (RD->isAnonymousStructOrUnion()) {
5052       for (auto *Field : RD->fields())
5053         PopulateKeysForFields(Field, IdealInits);
5054       return;
5055     }
5056   }
5057   IdealInits.push_back(Field->getCanonicalDecl());
5058 }
5059 
5060 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5061   return Context.getCanonicalType(BaseType).getTypePtr();
5062 }
5063 
5064 static const void *GetKeyForMember(ASTContext &Context,
5065                                    CXXCtorInitializer *Member) {
5066   if (!Member->isAnyMemberInitializer())
5067     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5068 
5069   return Member->getAnyMember()->getCanonicalDecl();
5070 }
5071 
5072 static void DiagnoseBaseOrMemInitializerOrder(
5073     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5074     ArrayRef<CXXCtorInitializer *> Inits) {
5075   if (Constructor->getDeclContext()->isDependentContext())
5076     return;
5077 
5078   // Don't check initializers order unless the warning is enabled at the
5079   // location of at least one initializer.
5080   bool ShouldCheckOrder = false;
5081   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5082     CXXCtorInitializer *Init = Inits[InitIndex];
5083     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5084                                  Init->getSourceLocation())) {
5085       ShouldCheckOrder = true;
5086       break;
5087     }
5088   }
5089   if (!ShouldCheckOrder)
5090     return;
5091 
5092   // Build the list of bases and members in the order that they'll
5093   // actually be initialized.  The explicit initializers should be in
5094   // this same order but may be missing things.
5095   SmallVector<const void*, 32> IdealInitKeys;
5096 
5097   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5098 
5099   // 1. Virtual bases.
5100   for (const auto &VBase : ClassDecl->vbases())
5101     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5102 
5103   // 2. Non-virtual bases.
5104   for (const auto &Base : ClassDecl->bases()) {
5105     if (Base.isVirtual())
5106       continue;
5107     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5108   }
5109 
5110   // 3. Direct fields.
5111   for (auto *Field : ClassDecl->fields()) {
5112     if (Field->isUnnamedBitfield())
5113       continue;
5114 
5115     PopulateKeysForFields(Field, IdealInitKeys);
5116   }
5117 
5118   unsigned NumIdealInits = IdealInitKeys.size();
5119   unsigned IdealIndex = 0;
5120 
5121   CXXCtorInitializer *PrevInit = nullptr;
5122   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5123     CXXCtorInitializer *Init = Inits[InitIndex];
5124     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5125 
5126     // Scan forward to try to find this initializer in the idealized
5127     // initializers list.
5128     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5129       if (InitKey == IdealInitKeys[IdealIndex])
5130         break;
5131 
5132     // If we didn't find this initializer, it must be because we
5133     // scanned past it on a previous iteration.  That can only
5134     // happen if we're out of order;  emit a warning.
5135     if (IdealIndex == NumIdealInits && PrevInit) {
5136       Sema::SemaDiagnosticBuilder D =
5137         SemaRef.Diag(PrevInit->getSourceLocation(),
5138                      diag::warn_initializer_out_of_order);
5139 
5140       if (PrevInit->isAnyMemberInitializer())
5141         D << 0 << PrevInit->getAnyMember()->getDeclName();
5142       else
5143         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5144 
5145       if (Init->isAnyMemberInitializer())
5146         D << 0 << Init->getAnyMember()->getDeclName();
5147       else
5148         D << 1 << Init->getTypeSourceInfo()->getType();
5149 
5150       // Move back to the initializer's location in the ideal list.
5151       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5152         if (InitKey == IdealInitKeys[IdealIndex])
5153           break;
5154 
5155       assert(IdealIndex < NumIdealInits &&
5156              "initializer not found in initializer list");
5157     }
5158 
5159     PrevInit = Init;
5160   }
5161 }
5162 
5163 namespace {
5164 bool CheckRedundantInit(Sema &S,
5165                         CXXCtorInitializer *Init,
5166                         CXXCtorInitializer *&PrevInit) {
5167   if (!PrevInit) {
5168     PrevInit = Init;
5169     return false;
5170   }
5171 
5172   if (FieldDecl *Field = Init->getAnyMember())
5173     S.Diag(Init->getSourceLocation(),
5174            diag::err_multiple_mem_initialization)
5175       << Field->getDeclName()
5176       << Init->getSourceRange();
5177   else {
5178     const Type *BaseClass = Init->getBaseClass();
5179     assert(BaseClass && "neither field nor base");
5180     S.Diag(Init->getSourceLocation(),
5181            diag::err_multiple_base_initialization)
5182       << QualType(BaseClass, 0)
5183       << Init->getSourceRange();
5184   }
5185   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5186     << 0 << PrevInit->getSourceRange();
5187 
5188   return true;
5189 }
5190 
5191 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5192 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5193 
5194 bool CheckRedundantUnionInit(Sema &S,
5195                              CXXCtorInitializer *Init,
5196                              RedundantUnionMap &Unions) {
5197   FieldDecl *Field = Init->getAnyMember();
5198   RecordDecl *Parent = Field->getParent();
5199   NamedDecl *Child = Field;
5200 
5201   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5202     if (Parent->isUnion()) {
5203       UnionEntry &En = Unions[Parent];
5204       if (En.first && En.first != Child) {
5205         S.Diag(Init->getSourceLocation(),
5206                diag::err_multiple_mem_union_initialization)
5207           << Field->getDeclName()
5208           << Init->getSourceRange();
5209         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5210           << 0 << En.second->getSourceRange();
5211         return true;
5212       }
5213       if (!En.first) {
5214         En.first = Child;
5215         En.second = Init;
5216       }
5217       if (!Parent->isAnonymousStructOrUnion())
5218         return false;
5219     }
5220 
5221     Child = Parent;
5222     Parent = cast<RecordDecl>(Parent->getDeclContext());
5223   }
5224 
5225   return false;
5226 }
5227 }
5228 
5229 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5230 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5231                                 SourceLocation ColonLoc,
5232                                 ArrayRef<CXXCtorInitializer*> MemInits,
5233                                 bool AnyErrors) {
5234   if (!ConstructorDecl)
5235     return;
5236 
5237   AdjustDeclIfTemplate(ConstructorDecl);
5238 
5239   CXXConstructorDecl *Constructor
5240     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5241 
5242   if (!Constructor) {
5243     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5244     return;
5245   }
5246 
5247   // Mapping for the duplicate initializers check.
5248   // For member initializers, this is keyed with a FieldDecl*.
5249   // For base initializers, this is keyed with a Type*.
5250   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5251 
5252   // Mapping for the inconsistent anonymous-union initializers check.
5253   RedundantUnionMap MemberUnions;
5254 
5255   bool HadError = false;
5256   for (unsigned i = 0; i < MemInits.size(); i++) {
5257     CXXCtorInitializer *Init = MemInits[i];
5258 
5259     // Set the source order index.
5260     Init->setSourceOrder(i);
5261 
5262     if (Init->isAnyMemberInitializer()) {
5263       const void *Key = GetKeyForMember(Context, Init);
5264       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5265           CheckRedundantUnionInit(*this, Init, MemberUnions))
5266         HadError = true;
5267     } else if (Init->isBaseInitializer()) {
5268       const void *Key = GetKeyForMember(Context, Init);
5269       if (CheckRedundantInit(*this, Init, Members[Key]))
5270         HadError = true;
5271     } else {
5272       assert(Init->isDelegatingInitializer());
5273       // This must be the only initializer
5274       if (MemInits.size() != 1) {
5275         Diag(Init->getSourceLocation(),
5276              diag::err_delegating_initializer_alone)
5277           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5278         // We will treat this as being the only initializer.
5279       }
5280       SetDelegatingInitializer(Constructor, MemInits[i]);
5281       // Return immediately as the initializer is set.
5282       return;
5283     }
5284   }
5285 
5286   if (HadError)
5287     return;
5288 
5289   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5290 
5291   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5292 
5293   DiagnoseUninitializedFields(*this, Constructor);
5294 }
5295 
5296 void
5297 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5298                                              CXXRecordDecl *ClassDecl) {
5299   // Ignore dependent contexts. Also ignore unions, since their members never
5300   // have destructors implicitly called.
5301   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5302     return;
5303 
5304   // FIXME: all the access-control diagnostics are positioned on the
5305   // field/base declaration.  That's probably good; that said, the
5306   // user might reasonably want to know why the destructor is being
5307   // emitted, and we currently don't say.
5308 
5309   // Non-static data members.
5310   for (auto *Field : ClassDecl->fields()) {
5311     if (Field->isInvalidDecl())
5312       continue;
5313 
5314     // Don't destroy incomplete or zero-length arrays.
5315     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5316       continue;
5317 
5318     QualType FieldType = Context.getBaseElementType(Field->getType());
5319 
5320     const RecordType* RT = FieldType->getAs<RecordType>();
5321     if (!RT)
5322       continue;
5323 
5324     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5325     if (FieldClassDecl->isInvalidDecl())
5326       continue;
5327     if (FieldClassDecl->hasIrrelevantDestructor())
5328       continue;
5329     // The destructor for an implicit anonymous union member is never invoked.
5330     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5331       continue;
5332 
5333     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5334     assert(Dtor && "No dtor found for FieldClassDecl!");
5335     CheckDestructorAccess(Field->getLocation(), Dtor,
5336                           PDiag(diag::err_access_dtor_field)
5337                             << Field->getDeclName()
5338                             << FieldType);
5339 
5340     MarkFunctionReferenced(Location, Dtor);
5341     DiagnoseUseOfDecl(Dtor, Location);
5342   }
5343 
5344   // We only potentially invoke the destructors of potentially constructed
5345   // subobjects.
5346   bool VisitVirtualBases = !ClassDecl->isAbstract();
5347 
5348   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5349 
5350   // Bases.
5351   for (const auto &Base : ClassDecl->bases()) {
5352     // Bases are always records in a well-formed non-dependent class.
5353     const RecordType *RT = Base.getType()->getAs<RecordType>();
5354 
5355     // Remember direct virtual bases.
5356     if (Base.isVirtual()) {
5357       if (!VisitVirtualBases)
5358         continue;
5359       DirectVirtualBases.insert(RT);
5360     }
5361 
5362     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5363     // If our base class is invalid, we probably can't get its dtor anyway.
5364     if (BaseClassDecl->isInvalidDecl())
5365       continue;
5366     if (BaseClassDecl->hasIrrelevantDestructor())
5367       continue;
5368 
5369     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5370     assert(Dtor && "No dtor found for BaseClassDecl!");
5371 
5372     // FIXME: caret should be on the start of the class name
5373     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5374                           PDiag(diag::err_access_dtor_base)
5375                               << Base.getType() << Base.getSourceRange(),
5376                           Context.getTypeDeclType(ClassDecl));
5377 
5378     MarkFunctionReferenced(Location, Dtor);
5379     DiagnoseUseOfDecl(Dtor, Location);
5380   }
5381 
5382   if (!VisitVirtualBases)
5383     return;
5384 
5385   // Virtual bases.
5386   for (const auto &VBase : ClassDecl->vbases()) {
5387     // Bases are always records in a well-formed non-dependent class.
5388     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5389 
5390     // Ignore direct virtual bases.
5391     if (DirectVirtualBases.count(RT))
5392       continue;
5393 
5394     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5395     // If our base class is invalid, we probably can't get its dtor anyway.
5396     if (BaseClassDecl->isInvalidDecl())
5397       continue;
5398     if (BaseClassDecl->hasIrrelevantDestructor())
5399       continue;
5400 
5401     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5402     assert(Dtor && "No dtor found for BaseClassDecl!");
5403     if (CheckDestructorAccess(
5404             ClassDecl->getLocation(), Dtor,
5405             PDiag(diag::err_access_dtor_vbase)
5406                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5407             Context.getTypeDeclType(ClassDecl)) ==
5408         AR_accessible) {
5409       CheckDerivedToBaseConversion(
5410           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5411           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5412           SourceRange(), DeclarationName(), nullptr);
5413     }
5414 
5415     MarkFunctionReferenced(Location, Dtor);
5416     DiagnoseUseOfDecl(Dtor, Location);
5417   }
5418 }
5419 
5420 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5421   if (!CDtorDecl)
5422     return;
5423 
5424   if (CXXConstructorDecl *Constructor
5425       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5426     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5427     DiagnoseUninitializedFields(*this, Constructor);
5428   }
5429 }
5430 
5431 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5432   if (!getLangOpts().CPlusPlus)
5433     return false;
5434 
5435   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5436   if (!RD)
5437     return false;
5438 
5439   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5440   // class template specialization here, but doing so breaks a lot of code.
5441 
5442   // We can't answer whether something is abstract until it has a
5443   // definition. If it's currently being defined, we'll walk back
5444   // over all the declarations when we have a full definition.
5445   const CXXRecordDecl *Def = RD->getDefinition();
5446   if (!Def || Def->isBeingDefined())
5447     return false;
5448 
5449   return RD->isAbstract();
5450 }
5451 
5452 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5453                                   TypeDiagnoser &Diagnoser) {
5454   if (!isAbstractType(Loc, T))
5455     return false;
5456 
5457   T = Context.getBaseElementType(T);
5458   Diagnoser.diagnose(*this, Loc, T);
5459   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5460   return true;
5461 }
5462 
5463 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5464   // Check if we've already emitted the list of pure virtual functions
5465   // for this class.
5466   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5467     return;
5468 
5469   // If the diagnostic is suppressed, don't emit the notes. We're only
5470   // going to emit them once, so try to attach them to a diagnostic we're
5471   // actually going to show.
5472   if (Diags.isLastDiagnosticIgnored())
5473     return;
5474 
5475   CXXFinalOverriderMap FinalOverriders;
5476   RD->getFinalOverriders(FinalOverriders);
5477 
5478   // Keep a set of seen pure methods so we won't diagnose the same method
5479   // more than once.
5480   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5481 
5482   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5483                                    MEnd = FinalOverriders.end();
5484        M != MEnd;
5485        ++M) {
5486     for (OverridingMethods::iterator SO = M->second.begin(),
5487                                   SOEnd = M->second.end();
5488          SO != SOEnd; ++SO) {
5489       // C++ [class.abstract]p4:
5490       //   A class is abstract if it contains or inherits at least one
5491       //   pure virtual function for which the final overrider is pure
5492       //   virtual.
5493 
5494       //
5495       if (SO->second.size() != 1)
5496         continue;
5497 
5498       if (!SO->second.front().Method->isPure())
5499         continue;
5500 
5501       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5502         continue;
5503 
5504       Diag(SO->second.front().Method->getLocation(),
5505            diag::note_pure_virtual_function)
5506         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5507     }
5508   }
5509 
5510   if (!PureVirtualClassDiagSet)
5511     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5512   PureVirtualClassDiagSet->insert(RD);
5513 }
5514 
5515 namespace {
5516 struct AbstractUsageInfo {
5517   Sema &S;
5518   CXXRecordDecl *Record;
5519   CanQualType AbstractType;
5520   bool Invalid;
5521 
5522   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5523     : S(S), Record(Record),
5524       AbstractType(S.Context.getCanonicalType(
5525                    S.Context.getTypeDeclType(Record))),
5526       Invalid(false) {}
5527 
5528   void DiagnoseAbstractType() {
5529     if (Invalid) return;
5530     S.DiagnoseAbstractType(Record);
5531     Invalid = true;
5532   }
5533 
5534   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5535 };
5536 
5537 struct CheckAbstractUsage {
5538   AbstractUsageInfo &Info;
5539   const NamedDecl *Ctx;
5540 
5541   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5542     : Info(Info), Ctx(Ctx) {}
5543 
5544   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5545     switch (TL.getTypeLocClass()) {
5546 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5547 #define TYPELOC(CLASS, PARENT) \
5548     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5549 #include "clang/AST/TypeLocNodes.def"
5550     }
5551   }
5552 
5553   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5554     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5555     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5556       if (!TL.getParam(I))
5557         continue;
5558 
5559       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5560       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5561     }
5562   }
5563 
5564   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5565     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5566   }
5567 
5568   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5569     // Visit the type parameters from a permissive context.
5570     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5571       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5572       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5573         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5574           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5575       // TODO: other template argument types?
5576     }
5577   }
5578 
5579   // Visit pointee types from a permissive context.
5580 #define CheckPolymorphic(Type) \
5581   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5582     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5583   }
5584   CheckPolymorphic(PointerTypeLoc)
5585   CheckPolymorphic(ReferenceTypeLoc)
5586   CheckPolymorphic(MemberPointerTypeLoc)
5587   CheckPolymorphic(BlockPointerTypeLoc)
5588   CheckPolymorphic(AtomicTypeLoc)
5589 
5590   /// Handle all the types we haven't given a more specific
5591   /// implementation for above.
5592   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5593     // Every other kind of type that we haven't called out already
5594     // that has an inner type is either (1) sugar or (2) contains that
5595     // inner type in some way as a subobject.
5596     if (TypeLoc Next = TL.getNextTypeLoc())
5597       return Visit(Next, Sel);
5598 
5599     // If there's no inner type and we're in a permissive context,
5600     // don't diagnose.
5601     if (Sel == Sema::AbstractNone) return;
5602 
5603     // Check whether the type matches the abstract type.
5604     QualType T = TL.getType();
5605     if (T->isArrayType()) {
5606       Sel = Sema::AbstractArrayType;
5607       T = Info.S.Context.getBaseElementType(T);
5608     }
5609     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5610     if (CT != Info.AbstractType) return;
5611 
5612     // It matched; do some magic.
5613     if (Sel == Sema::AbstractArrayType) {
5614       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5615         << T << TL.getSourceRange();
5616     } else {
5617       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5618         << Sel << T << TL.getSourceRange();
5619     }
5620     Info.DiagnoseAbstractType();
5621   }
5622 };
5623 
5624 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5625                                   Sema::AbstractDiagSelID Sel) {
5626   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5627 }
5628 
5629 }
5630 
5631 /// Check for invalid uses of an abstract type in a method declaration.
5632 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5633                                     CXXMethodDecl *MD) {
5634   // No need to do the check on definitions, which require that
5635   // the return/param types be complete.
5636   if (MD->doesThisDeclarationHaveABody())
5637     return;
5638 
5639   // For safety's sake, just ignore it if we don't have type source
5640   // information.  This should never happen for non-implicit methods,
5641   // but...
5642   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5643     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5644 }
5645 
5646 /// Check for invalid uses of an abstract type within a class definition.
5647 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5648                                     CXXRecordDecl *RD) {
5649   for (auto *D : RD->decls()) {
5650     if (D->isImplicit()) continue;
5651 
5652     // Methods and method templates.
5653     if (isa<CXXMethodDecl>(D)) {
5654       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5655     } else if (isa<FunctionTemplateDecl>(D)) {
5656       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5657       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5658 
5659     // Fields and static variables.
5660     } else if (isa<FieldDecl>(D)) {
5661       FieldDecl *FD = cast<FieldDecl>(D);
5662       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5663         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5664     } else if (isa<VarDecl>(D)) {
5665       VarDecl *VD = cast<VarDecl>(D);
5666       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5667         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5668 
5669     // Nested classes and class templates.
5670     } else if (isa<CXXRecordDecl>(D)) {
5671       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5672     } else if (isa<ClassTemplateDecl>(D)) {
5673       CheckAbstractClassUsage(Info,
5674                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5675     }
5676   }
5677 }
5678 
5679 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5680   Attr *ClassAttr = getDLLAttr(Class);
5681   if (!ClassAttr)
5682     return;
5683 
5684   assert(ClassAttr->getKind() == attr::DLLExport);
5685 
5686   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5687 
5688   if (TSK == TSK_ExplicitInstantiationDeclaration)
5689     // Don't go any further if this is just an explicit instantiation
5690     // declaration.
5691     return;
5692 
5693   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5694     S.MarkVTableUsed(Class->getLocation(), Class, true);
5695 
5696   for (Decl *Member : Class->decls()) {
5697     // Defined static variables that are members of an exported base
5698     // class must be marked export too.
5699     auto *VD = dyn_cast<VarDecl>(Member);
5700     if (VD && Member->getAttr<DLLExportAttr>() &&
5701         VD->getStorageClass() == SC_Static &&
5702         TSK == TSK_ImplicitInstantiation)
5703       S.MarkVariableReferenced(VD->getLocation(), VD);
5704 
5705     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5706     if (!MD)
5707       continue;
5708 
5709     if (Member->getAttr<DLLExportAttr>()) {
5710       if (MD->isUserProvided()) {
5711         // Instantiate non-default class member functions ...
5712 
5713         // .. except for certain kinds of template specializations.
5714         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5715           continue;
5716 
5717         S.MarkFunctionReferenced(Class->getLocation(), MD);
5718 
5719         // The function will be passed to the consumer when its definition is
5720         // encountered.
5721       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5722                  MD->isCopyAssignmentOperator() ||
5723                  MD->isMoveAssignmentOperator()) {
5724         // Synthesize and instantiate non-trivial implicit methods, explicitly
5725         // defaulted methods, and the copy and move assignment operators. The
5726         // latter are exported even if they are trivial, because the address of
5727         // an operator can be taken and should compare equal across libraries.
5728         DiagnosticErrorTrap Trap(S.Diags);
5729         S.MarkFunctionReferenced(Class->getLocation(), MD);
5730         if (Trap.hasErrorOccurred()) {
5731           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5732               << Class << !S.getLangOpts().CPlusPlus11;
5733           break;
5734         }
5735 
5736         // There is no later point when we will see the definition of this
5737         // function, so pass it to the consumer now.
5738         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5739       }
5740     }
5741   }
5742 }
5743 
5744 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5745                                                         CXXRecordDecl *Class) {
5746   // Only the MS ABI has default constructor closures, so we don't need to do
5747   // this semantic checking anywhere else.
5748   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5749     return;
5750 
5751   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5752   for (Decl *Member : Class->decls()) {
5753     // Look for exported default constructors.
5754     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5755     if (!CD || !CD->isDefaultConstructor())
5756       continue;
5757     auto *Attr = CD->getAttr<DLLExportAttr>();
5758     if (!Attr)
5759       continue;
5760 
5761     // If the class is non-dependent, mark the default arguments as ODR-used so
5762     // that we can properly codegen the constructor closure.
5763     if (!Class->isDependentContext()) {
5764       for (ParmVarDecl *PD : CD->parameters()) {
5765         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5766         S.DiscardCleanupsInEvaluationContext();
5767       }
5768     }
5769 
5770     if (LastExportedDefaultCtor) {
5771       S.Diag(LastExportedDefaultCtor->getLocation(),
5772              diag::err_attribute_dll_ambiguous_default_ctor)
5773           << Class;
5774       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5775           << CD->getDeclName();
5776       return;
5777     }
5778     LastExportedDefaultCtor = CD;
5779   }
5780 }
5781 
5782 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5783   // Mark any compiler-generated routines with the implicit code_seg attribute.
5784   for (auto *Method : Class->methods()) {
5785     if (Method->isUserProvided())
5786       continue;
5787     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5788       Method->addAttr(A);
5789   }
5790 }
5791 
5792 /// Check class-level dllimport/dllexport attribute.
5793 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5794   Attr *ClassAttr = getDLLAttr(Class);
5795 
5796   // MSVC inherits DLL attributes to partial class template specializations.
5797   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5798     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5799       if (Attr *TemplateAttr =
5800               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5801         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5802         A->setInherited(true);
5803         ClassAttr = A;
5804       }
5805     }
5806   }
5807 
5808   if (!ClassAttr)
5809     return;
5810 
5811   if (!Class->isExternallyVisible()) {
5812     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5813         << Class << ClassAttr;
5814     return;
5815   }
5816 
5817   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5818       !ClassAttr->isInherited()) {
5819     // Diagnose dll attributes on members of class with dll attribute.
5820     for (Decl *Member : Class->decls()) {
5821       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5822         continue;
5823       InheritableAttr *MemberAttr = getDLLAttr(Member);
5824       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5825         continue;
5826 
5827       Diag(MemberAttr->getLocation(),
5828              diag::err_attribute_dll_member_of_dll_class)
5829           << MemberAttr << ClassAttr;
5830       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5831       Member->setInvalidDecl();
5832     }
5833   }
5834 
5835   if (Class->getDescribedClassTemplate())
5836     // Don't inherit dll attribute until the template is instantiated.
5837     return;
5838 
5839   // The class is either imported or exported.
5840   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5841 
5842   // Check if this was a dllimport attribute propagated from a derived class to
5843   // a base class template specialization. We don't apply these attributes to
5844   // static data members.
5845   const bool PropagatedImport =
5846       !ClassExported &&
5847       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5848 
5849   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5850 
5851   // Ignore explicit dllexport on explicit class template instantiation
5852   // declarations, except in MinGW mode.
5853   if (ClassExported && !ClassAttr->isInherited() &&
5854       TSK == TSK_ExplicitInstantiationDeclaration &&
5855       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5856     Class->dropAttr<DLLExportAttr>();
5857     return;
5858   }
5859 
5860   // Force declaration of implicit members so they can inherit the attribute.
5861   ForceDeclarationOfImplicitMembers(Class);
5862 
5863   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5864   // seem to be true in practice?
5865 
5866   for (Decl *Member : Class->decls()) {
5867     VarDecl *VD = dyn_cast<VarDecl>(Member);
5868     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5869 
5870     // Only methods and static fields inherit the attributes.
5871     if (!VD && !MD)
5872       continue;
5873 
5874     if (MD) {
5875       // Don't process deleted methods.
5876       if (MD->isDeleted())
5877         continue;
5878 
5879       if (MD->isInlined()) {
5880         // MinGW does not import or export inline methods. But do it for
5881         // template instantiations.
5882         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5883             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5884             TSK != TSK_ExplicitInstantiationDeclaration &&
5885             TSK != TSK_ExplicitInstantiationDefinition)
5886           continue;
5887 
5888         // MSVC versions before 2015 don't export the move assignment operators
5889         // and move constructor, so don't attempt to import/export them if
5890         // we have a definition.
5891         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5892         if ((MD->isMoveAssignmentOperator() ||
5893              (Ctor && Ctor->isMoveConstructor())) &&
5894             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5895           continue;
5896 
5897         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5898         // operator is exported anyway.
5899         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5900             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5901           continue;
5902       }
5903     }
5904 
5905     // Don't apply dllimport attributes to static data members of class template
5906     // instantiations when the attribute is propagated from a derived class.
5907     if (VD && PropagatedImport)
5908       continue;
5909 
5910     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5911       continue;
5912 
5913     if (!getDLLAttr(Member)) {
5914       InheritableAttr *NewAttr = nullptr;
5915 
5916       // Do not export/import inline function when -fno-dllexport-inlines is
5917       // passed. But add attribute for later local static var check.
5918       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5919           TSK != TSK_ExplicitInstantiationDeclaration &&
5920           TSK != TSK_ExplicitInstantiationDefinition) {
5921         if (ClassExported) {
5922           NewAttr = ::new (getASTContext())
5923             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5924                                      getASTContext(),
5925                                      ClassAttr->getSpellingListIndex());
5926         } else {
5927           NewAttr = ::new (getASTContext())
5928             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5929                                      getASTContext(),
5930                                      ClassAttr->getSpellingListIndex());
5931         }
5932       } else {
5933         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5934       }
5935 
5936       NewAttr->setInherited(true);
5937       Member->addAttr(NewAttr);
5938 
5939       if (MD) {
5940         // Propagate DLLAttr to friend re-declarations of MD that have already
5941         // been constructed.
5942         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5943              FD = FD->getPreviousDecl()) {
5944           if (FD->getFriendObjectKind() == Decl::FOK_None)
5945             continue;
5946           assert(!getDLLAttr(FD) &&
5947                  "friend re-decl should not already have a DLLAttr");
5948           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5949           NewAttr->setInherited(true);
5950           FD->addAttr(NewAttr);
5951         }
5952       }
5953     }
5954   }
5955 
5956   if (ClassExported)
5957     DelayedDllExportClasses.push_back(Class);
5958 }
5959 
5960 /// Perform propagation of DLL attributes from a derived class to a
5961 /// templated base class for MS compatibility.
5962 void Sema::propagateDLLAttrToBaseClassTemplate(
5963     CXXRecordDecl *Class, Attr *ClassAttr,
5964     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5965   if (getDLLAttr(
5966           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5967     // If the base class template has a DLL attribute, don't try to change it.
5968     return;
5969   }
5970 
5971   auto TSK = BaseTemplateSpec->getSpecializationKind();
5972   if (!getDLLAttr(BaseTemplateSpec) &&
5973       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5974        TSK == TSK_ImplicitInstantiation)) {
5975     // The template hasn't been instantiated yet (or it has, but only as an
5976     // explicit instantiation declaration or implicit instantiation, which means
5977     // we haven't codegenned any members yet), so propagate the attribute.
5978     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5979     NewAttr->setInherited(true);
5980     BaseTemplateSpec->addAttr(NewAttr);
5981 
5982     // If this was an import, mark that we propagated it from a derived class to
5983     // a base class template specialization.
5984     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5985       ImportAttr->setPropagatedToBaseTemplate();
5986 
5987     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5988     // needs to be run again to work see the new attribute. Otherwise this will
5989     // get run whenever the template is instantiated.
5990     if (TSK != TSK_Undeclared)
5991       checkClassLevelDLLAttribute(BaseTemplateSpec);
5992 
5993     return;
5994   }
5995 
5996   if (getDLLAttr(BaseTemplateSpec)) {
5997     // The template has already been specialized or instantiated with an
5998     // attribute, explicitly or through propagation. We should not try to change
5999     // it.
6000     return;
6001   }
6002 
6003   // The template was previously instantiated or explicitly specialized without
6004   // a dll attribute, It's too late for us to add an attribute, so warn that
6005   // this is unsupported.
6006   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6007       << BaseTemplateSpec->isExplicitSpecialization();
6008   Diag(ClassAttr->getLocation(), diag::note_attribute);
6009   if (BaseTemplateSpec->isExplicitSpecialization()) {
6010     Diag(BaseTemplateSpec->getLocation(),
6011            diag::note_template_class_explicit_specialization_was_here)
6012         << BaseTemplateSpec;
6013   } else {
6014     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6015            diag::note_template_class_instantiation_was_here)
6016         << BaseTemplateSpec;
6017   }
6018 }
6019 
6020 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
6021                                         SourceLocation DefaultLoc) {
6022   switch (S.getSpecialMember(MD)) {
6023   case Sema::CXXDefaultConstructor:
6024     S.DefineImplicitDefaultConstructor(DefaultLoc,
6025                                        cast<CXXConstructorDecl>(MD));
6026     break;
6027   case Sema::CXXCopyConstructor:
6028     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6029     break;
6030   case Sema::CXXCopyAssignment:
6031     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
6032     break;
6033   case Sema::CXXDestructor:
6034     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
6035     break;
6036   case Sema::CXXMoveConstructor:
6037     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6038     break;
6039   case Sema::CXXMoveAssignment:
6040     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
6041     break;
6042   case Sema::CXXInvalid:
6043     llvm_unreachable("Invalid special member.");
6044   }
6045 }
6046 
6047 /// Determine whether a type is permitted to be passed or returned in
6048 /// registers, per C++ [class.temporary]p3.
6049 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6050                                TargetInfo::CallingConvKind CCK) {
6051   if (D->isDependentType() || D->isInvalidDecl())
6052     return false;
6053 
6054   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6055   // The PS4 platform ABI follows the behavior of Clang 3.2.
6056   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6057     return !D->hasNonTrivialDestructorForCall() &&
6058            !D->hasNonTrivialCopyConstructorForCall();
6059 
6060   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6061     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6062     bool DtorIsTrivialForCall = false;
6063 
6064     // If a class has at least one non-deleted, trivial copy constructor, it
6065     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6066     //
6067     // Note: This permits classes with non-trivial copy or move ctors to be
6068     // passed in registers, so long as they *also* have a trivial copy ctor,
6069     // which is non-conforming.
6070     if (D->needsImplicitCopyConstructor()) {
6071       if (!D->defaultedCopyConstructorIsDeleted()) {
6072         if (D->hasTrivialCopyConstructor())
6073           CopyCtorIsTrivial = true;
6074         if (D->hasTrivialCopyConstructorForCall())
6075           CopyCtorIsTrivialForCall = true;
6076       }
6077     } else {
6078       for (const CXXConstructorDecl *CD : D->ctors()) {
6079         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6080           if (CD->isTrivial())
6081             CopyCtorIsTrivial = true;
6082           if (CD->isTrivialForCall())
6083             CopyCtorIsTrivialForCall = true;
6084         }
6085       }
6086     }
6087 
6088     if (D->needsImplicitDestructor()) {
6089       if (!D->defaultedDestructorIsDeleted() &&
6090           D->hasTrivialDestructorForCall())
6091         DtorIsTrivialForCall = true;
6092     } else if (const auto *DD = D->getDestructor()) {
6093       if (!DD->isDeleted() && DD->isTrivialForCall())
6094         DtorIsTrivialForCall = true;
6095     }
6096 
6097     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6098     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6099       return true;
6100 
6101     // If a class has a destructor, we'd really like to pass it indirectly
6102     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6103     // impossible for small types, which it will pass in a single register or
6104     // stack slot. Most objects with dtors are large-ish, so handle that early.
6105     // We can't call out all large objects as being indirect because there are
6106     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6107     // how we pass large POD types.
6108 
6109     // Note: This permits small classes with nontrivial destructors to be
6110     // passed in registers, which is non-conforming.
6111     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6112     uint64_t TypeSize = isAArch64 ? 128 : 64;
6113 
6114     if (CopyCtorIsTrivial &&
6115         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6116       return true;
6117     return false;
6118   }
6119 
6120   // Per C++ [class.temporary]p3, the relevant condition is:
6121   //   each copy constructor, move constructor, and destructor of X is
6122   //   either trivial or deleted, and X has at least one non-deleted copy
6123   //   or move constructor
6124   bool HasNonDeletedCopyOrMove = false;
6125 
6126   if (D->needsImplicitCopyConstructor() &&
6127       !D->defaultedCopyConstructorIsDeleted()) {
6128     if (!D->hasTrivialCopyConstructorForCall())
6129       return false;
6130     HasNonDeletedCopyOrMove = true;
6131   }
6132 
6133   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6134       !D->defaultedMoveConstructorIsDeleted()) {
6135     if (!D->hasTrivialMoveConstructorForCall())
6136       return false;
6137     HasNonDeletedCopyOrMove = true;
6138   }
6139 
6140   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6141       !D->hasTrivialDestructorForCall())
6142     return false;
6143 
6144   for (const CXXMethodDecl *MD : D->methods()) {
6145     if (MD->isDeleted())
6146       continue;
6147 
6148     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6149     if (CD && CD->isCopyOrMoveConstructor())
6150       HasNonDeletedCopyOrMove = true;
6151     else if (!isa<CXXDestructorDecl>(MD))
6152       continue;
6153 
6154     if (!MD->isTrivialForCall())
6155       return false;
6156   }
6157 
6158   return HasNonDeletedCopyOrMove;
6159 }
6160 
6161 /// Perform semantic checks on a class definition that has been
6162 /// completing, introducing implicitly-declared members, checking for
6163 /// abstract types, etc.
6164 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6165   if (!Record)
6166     return;
6167 
6168   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6169     AbstractUsageInfo Info(*this, Record);
6170     CheckAbstractClassUsage(Info, Record);
6171   }
6172 
6173   // If this is not an aggregate type and has no user-declared constructor,
6174   // complain about any non-static data members of reference or const scalar
6175   // type, since they will never get initializers.
6176   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6177       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6178       !Record->isLambda()) {
6179     bool Complained = false;
6180     for (const auto *F : Record->fields()) {
6181       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6182         continue;
6183 
6184       if (F->getType()->isReferenceType() ||
6185           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6186         if (!Complained) {
6187           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6188             << Record->getTagKind() << Record;
6189           Complained = true;
6190         }
6191 
6192         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6193           << F->getType()->isReferenceType()
6194           << F->getDeclName();
6195       }
6196     }
6197   }
6198 
6199   if (Record->getIdentifier()) {
6200     // C++ [class.mem]p13:
6201     //   If T is the name of a class, then each of the following shall have a
6202     //   name different from T:
6203     //     - every member of every anonymous union that is a member of class T.
6204     //
6205     // C++ [class.mem]p14:
6206     //   In addition, if class T has a user-declared constructor (12.1), every
6207     //   non-static data member of class T shall have a name different from T.
6208     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6209     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6210          ++I) {
6211       NamedDecl *D = (*I)->getUnderlyingDecl();
6212       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6213            Record->hasUserDeclaredConstructor()) ||
6214           isa<IndirectFieldDecl>(D)) {
6215         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6216           << D->getDeclName();
6217         break;
6218       }
6219     }
6220   }
6221 
6222   // Warn if the class has virtual methods but non-virtual public destructor.
6223   if (Record->isPolymorphic() && !Record->isDependentType()) {
6224     CXXDestructorDecl *dtor = Record->getDestructor();
6225     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6226         !Record->hasAttr<FinalAttr>())
6227       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6228            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6229   }
6230 
6231   if (Record->isAbstract()) {
6232     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6233       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6234         << FA->isSpelledAsSealed();
6235       DiagnoseAbstractType(Record);
6236     }
6237   }
6238 
6239   // Warn if the class has a final destructor but is not itself marked final.
6240   if (!Record->hasAttr<FinalAttr>()) {
6241     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6242       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6243         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6244             << FA->isSpelledAsSealed()
6245             << FixItHint::CreateInsertion(
6246                    getLocForEndOfToken(Record->getLocation()),
6247                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6248         Diag(Record->getLocation(),
6249              diag::note_final_dtor_non_final_class_silence)
6250             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6251       }
6252     }
6253   }
6254 
6255   // See if trivial_abi has to be dropped.
6256   if (Record->hasAttr<TrivialABIAttr>())
6257     checkIllFormedTrivialABIStruct(*Record);
6258 
6259   // Set HasTrivialSpecialMemberForCall if the record has attribute
6260   // "trivial_abi".
6261   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6262 
6263   if (HasTrivialABI)
6264     Record->setHasTrivialSpecialMemberForCall();
6265 
6266   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6267     // Check whether the explicitly-defaulted special members are valid.
6268     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6269       CheckExplicitlyDefaultedSpecialMember(M);
6270 
6271     // For an explicitly defaulted or deleted special member, we defer
6272     // determining triviality until the class is complete. That time is now!
6273     CXXSpecialMember CSM = getSpecialMember(M);
6274     if (!M->isImplicit() && !M->isUserProvided()) {
6275       if (CSM != CXXInvalid) {
6276         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6277         // Inform the class that we've finished declaring this member.
6278         Record->finishedDefaultedOrDeletedMember(M);
6279         M->setTrivialForCall(
6280             HasTrivialABI ||
6281             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6282         Record->setTrivialForCallFlags(M);
6283       }
6284     }
6285 
6286     // Set triviality for the purpose of calls if this is a user-provided
6287     // copy/move constructor or destructor.
6288     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6289          CSM == CXXDestructor) && M->isUserProvided()) {
6290       M->setTrivialForCall(HasTrivialABI);
6291       Record->setTrivialForCallFlags(M);
6292     }
6293 
6294     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6295         M->hasAttr<DLLExportAttr>()) {
6296       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6297           M->isTrivial() &&
6298           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6299            CSM == CXXDestructor))
6300         M->dropAttr<DLLExportAttr>();
6301 
6302       if (M->hasAttr<DLLExportAttr>()) {
6303         // Define after any fields with in-class initializers have been parsed.
6304         DelayedDllExportMemberFunctions.push_back(M);
6305       }
6306     }
6307   };
6308 
6309   bool HasMethodWithOverrideControl = false,
6310        HasOverridingMethodWithoutOverrideControl = false;
6311   if (!Record->isDependentType()) {
6312     // Check the destructor before any other member function. We need to
6313     // determine whether it's trivial in order to determine whether the claas
6314     // type is a literal type, which is a prerequisite for determining whether
6315     // other special member functions are valid and whether they're implicitly
6316     // 'constexpr'.
6317     if (CXXDestructorDecl *Dtor = Record->getDestructor())
6318       CompleteMemberFunction(Dtor);
6319 
6320     for (auto *M : Record->methods()) {
6321       // See if a method overloads virtual methods in a base
6322       // class without overriding any.
6323       if (!M->isStatic())
6324         DiagnoseHiddenVirtualMethods(M);
6325       if (M->hasAttr<OverrideAttr>())
6326         HasMethodWithOverrideControl = true;
6327       else if (M->size_overridden_methods() > 0)
6328         HasOverridingMethodWithoutOverrideControl = true;
6329 
6330       if (!isa<CXXDestructorDecl>(M))
6331         CompleteMemberFunction(M);
6332     }
6333   }
6334 
6335   if (HasMethodWithOverrideControl &&
6336       HasOverridingMethodWithoutOverrideControl) {
6337     // At least one method has the 'override' control declared.
6338     // Diagnose all other overridden methods which do not have 'override' specified on them.
6339     for (auto *M : Record->methods())
6340       DiagnoseAbsenceOfOverrideControl(M);
6341   }
6342 
6343   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6344   // whether this class uses any C++ features that are implemented
6345   // completely differently in MSVC, and if so, emit a diagnostic.
6346   // That diagnostic defaults to an error, but we allow projects to
6347   // map it down to a warning (or ignore it).  It's a fairly common
6348   // practice among users of the ms_struct pragma to mass-annotate
6349   // headers, sweeping up a bunch of types that the project doesn't
6350   // really rely on MSVC-compatible layout for.  We must therefore
6351   // support "ms_struct except for C++ stuff" as a secondary ABI.
6352   if (Record->isMsStruct(Context) &&
6353       (Record->isPolymorphic() || Record->getNumBases())) {
6354     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6355   }
6356 
6357   checkClassLevelDLLAttribute(Record);
6358   checkClassLevelCodeSegAttribute(Record);
6359 
6360   bool ClangABICompat4 =
6361       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6362   TargetInfo::CallingConvKind CCK =
6363       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6364   bool CanPass = canPassInRegisters(*this, Record, CCK);
6365 
6366   // Do not change ArgPassingRestrictions if it has already been set to
6367   // APK_CanNeverPassInRegs.
6368   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6369     Record->setArgPassingRestrictions(CanPass
6370                                           ? RecordDecl::APK_CanPassInRegs
6371                                           : RecordDecl::APK_CannotPassInRegs);
6372 
6373   // If canPassInRegisters returns true despite the record having a non-trivial
6374   // destructor, the record is destructed in the callee. This happens only when
6375   // the record or one of its subobjects has a field annotated with trivial_abi
6376   // or a field qualified with ObjC __strong/__weak.
6377   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6378     Record->setParamDestroyedInCallee(true);
6379   else if (Record->hasNonTrivialDestructor())
6380     Record->setParamDestroyedInCallee(CanPass);
6381 
6382   if (getLangOpts().ForceEmitVTables) {
6383     // If we want to emit all the vtables, we need to mark it as used.  This
6384     // is especially required for cases like vtable assumption loads.
6385     MarkVTableUsed(Record->getInnerLocStart(), Record);
6386   }
6387 }
6388 
6389 /// Look up the special member function that would be called by a special
6390 /// member function for a subobject of class type.
6391 ///
6392 /// \param Class The class type of the subobject.
6393 /// \param CSM The kind of special member function.
6394 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6395 /// \param ConstRHS True if this is a copy operation with a const object
6396 ///        on its RHS, that is, if the argument to the outer special member
6397 ///        function is 'const' and this is not a field marked 'mutable'.
6398 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6399     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6400     unsigned FieldQuals, bool ConstRHS) {
6401   unsigned LHSQuals = 0;
6402   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6403     LHSQuals = FieldQuals;
6404 
6405   unsigned RHSQuals = FieldQuals;
6406   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6407     RHSQuals = 0;
6408   else if (ConstRHS)
6409     RHSQuals |= Qualifiers::Const;
6410 
6411   return S.LookupSpecialMember(Class, CSM,
6412                                RHSQuals & Qualifiers::Const,
6413                                RHSQuals & Qualifiers::Volatile,
6414                                false,
6415                                LHSQuals & Qualifiers::Const,
6416                                LHSQuals & Qualifiers::Volatile);
6417 }
6418 
6419 class Sema::InheritedConstructorInfo {
6420   Sema &S;
6421   SourceLocation UseLoc;
6422 
6423   /// A mapping from the base classes through which the constructor was
6424   /// inherited to the using shadow declaration in that base class (or a null
6425   /// pointer if the constructor was declared in that base class).
6426   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6427       InheritedFromBases;
6428 
6429 public:
6430   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6431                            ConstructorUsingShadowDecl *Shadow)
6432       : S(S), UseLoc(UseLoc) {
6433     bool DiagnosedMultipleConstructedBases = false;
6434     CXXRecordDecl *ConstructedBase = nullptr;
6435     UsingDecl *ConstructedBaseUsing = nullptr;
6436 
6437     // Find the set of such base class subobjects and check that there's a
6438     // unique constructed subobject.
6439     for (auto *D : Shadow->redecls()) {
6440       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6441       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6442       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6443 
6444       InheritedFromBases.insert(
6445           std::make_pair(DNominatedBase->getCanonicalDecl(),
6446                          DShadow->getNominatedBaseClassShadowDecl()));
6447       if (DShadow->constructsVirtualBase())
6448         InheritedFromBases.insert(
6449             std::make_pair(DConstructedBase->getCanonicalDecl(),
6450                            DShadow->getConstructedBaseClassShadowDecl()));
6451       else
6452         assert(DNominatedBase == DConstructedBase);
6453 
6454       // [class.inhctor.init]p2:
6455       //   If the constructor was inherited from multiple base class subobjects
6456       //   of type B, the program is ill-formed.
6457       if (!ConstructedBase) {
6458         ConstructedBase = DConstructedBase;
6459         ConstructedBaseUsing = D->getUsingDecl();
6460       } else if (ConstructedBase != DConstructedBase &&
6461                  !Shadow->isInvalidDecl()) {
6462         if (!DiagnosedMultipleConstructedBases) {
6463           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6464               << Shadow->getTargetDecl();
6465           S.Diag(ConstructedBaseUsing->getLocation(),
6466                diag::note_ambiguous_inherited_constructor_using)
6467               << ConstructedBase;
6468           DiagnosedMultipleConstructedBases = true;
6469         }
6470         S.Diag(D->getUsingDecl()->getLocation(),
6471                diag::note_ambiguous_inherited_constructor_using)
6472             << DConstructedBase;
6473       }
6474     }
6475 
6476     if (DiagnosedMultipleConstructedBases)
6477       Shadow->setInvalidDecl();
6478   }
6479 
6480   /// Find the constructor to use for inherited construction of a base class,
6481   /// and whether that base class constructor inherits the constructor from a
6482   /// virtual base class (in which case it won't actually invoke it).
6483   std::pair<CXXConstructorDecl *, bool>
6484   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6485     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6486     if (It == InheritedFromBases.end())
6487       return std::make_pair(nullptr, false);
6488 
6489     // This is an intermediary class.
6490     if (It->second)
6491       return std::make_pair(
6492           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6493           It->second->constructsVirtualBase());
6494 
6495     // This is the base class from which the constructor was inherited.
6496     return std::make_pair(Ctor, false);
6497   }
6498 };
6499 
6500 /// Is the special member function which would be selected to perform the
6501 /// specified operation on the specified class type a constexpr constructor?
6502 static bool
6503 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6504                          Sema::CXXSpecialMember CSM, unsigned Quals,
6505                          bool ConstRHS,
6506                          CXXConstructorDecl *InheritedCtor = nullptr,
6507                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6508   // If we're inheriting a constructor, see if we need to call it for this base
6509   // class.
6510   if (InheritedCtor) {
6511     assert(CSM == Sema::CXXDefaultConstructor);
6512     auto BaseCtor =
6513         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6514     if (BaseCtor)
6515       return BaseCtor->isConstexpr();
6516   }
6517 
6518   if (CSM == Sema::CXXDefaultConstructor)
6519     return ClassDecl->hasConstexprDefaultConstructor();
6520 
6521   Sema::SpecialMemberOverloadResult SMOR =
6522       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6523   if (!SMOR.getMethod())
6524     // A constructor we wouldn't select can't be "involved in initializing"
6525     // anything.
6526     return true;
6527   return SMOR.getMethod()->isConstexpr();
6528 }
6529 
6530 /// Determine whether the specified special member function would be constexpr
6531 /// if it were implicitly defined.
6532 static bool defaultedSpecialMemberIsConstexpr(
6533     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6534     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6535     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6536   if (!S.getLangOpts().CPlusPlus11)
6537     return false;
6538 
6539   // C++11 [dcl.constexpr]p4:
6540   // In the definition of a constexpr constructor [...]
6541   bool Ctor = true;
6542   switch (CSM) {
6543   case Sema::CXXDefaultConstructor:
6544     if (Inherited)
6545       break;
6546     // Since default constructor lookup is essentially trivial (and cannot
6547     // involve, for instance, template instantiation), we compute whether a
6548     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6549     //
6550     // This is important for performance; we need to know whether the default
6551     // constructor is constexpr to determine whether the type is a literal type.
6552     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6553 
6554   case Sema::CXXCopyConstructor:
6555   case Sema::CXXMoveConstructor:
6556     // For copy or move constructors, we need to perform overload resolution.
6557     break;
6558 
6559   case Sema::CXXCopyAssignment:
6560   case Sema::CXXMoveAssignment:
6561     if (!S.getLangOpts().CPlusPlus14)
6562       return false;
6563     // In C++1y, we need to perform overload resolution.
6564     Ctor = false;
6565     break;
6566 
6567   case Sema::CXXDestructor:
6568   case Sema::CXXInvalid:
6569     return false;
6570   }
6571 
6572   //   -- if the class is a non-empty union, or for each non-empty anonymous
6573   //      union member of a non-union class, exactly one non-static data member
6574   //      shall be initialized; [DR1359]
6575   //
6576   // If we squint, this is guaranteed, since exactly one non-static data member
6577   // will be initialized (if the constructor isn't deleted), we just don't know
6578   // which one.
6579   if (Ctor && ClassDecl->isUnion())
6580     return CSM == Sema::CXXDefaultConstructor
6581                ? ClassDecl->hasInClassInitializer() ||
6582                      !ClassDecl->hasVariantMembers()
6583                : true;
6584 
6585   //   -- the class shall not have any virtual base classes;
6586   if (Ctor && ClassDecl->getNumVBases())
6587     return false;
6588 
6589   // C++1y [class.copy]p26:
6590   //   -- [the class] is a literal type, and
6591   if (!Ctor && !ClassDecl->isLiteral())
6592     return false;
6593 
6594   //   -- every constructor involved in initializing [...] base class
6595   //      sub-objects shall be a constexpr constructor;
6596   //   -- the assignment operator selected to copy/move each direct base
6597   //      class is a constexpr function, and
6598   for (const auto &B : ClassDecl->bases()) {
6599     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6600     if (!BaseType) continue;
6601 
6602     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6603     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6604                                   InheritedCtor, Inherited))
6605       return false;
6606   }
6607 
6608   //   -- every constructor involved in initializing non-static data members
6609   //      [...] shall be a constexpr constructor;
6610   //   -- every non-static data member and base class sub-object shall be
6611   //      initialized
6612   //   -- for each non-static data member of X that is of class type (or array
6613   //      thereof), the assignment operator selected to copy/move that member is
6614   //      a constexpr function
6615   for (const auto *F : ClassDecl->fields()) {
6616     if (F->isInvalidDecl())
6617       continue;
6618     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6619       continue;
6620     QualType BaseType = S.Context.getBaseElementType(F->getType());
6621     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6622       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6623       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6624                                     BaseType.getCVRQualifiers(),
6625                                     ConstArg && !F->isMutable()))
6626         return false;
6627     } else if (CSM == Sema::CXXDefaultConstructor) {
6628       return false;
6629     }
6630   }
6631 
6632   // All OK, it's constexpr!
6633   return true;
6634 }
6635 
6636 static Sema::ImplicitExceptionSpecification
6637 ComputeDefaultedSpecialMemberExceptionSpec(
6638     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6639     Sema::InheritedConstructorInfo *ICI);
6640 
6641 static Sema::ImplicitExceptionSpecification
6642 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6643   auto CSM = S.getSpecialMember(MD);
6644   if (CSM != Sema::CXXInvalid)
6645     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6646 
6647   auto *CD = cast<CXXConstructorDecl>(MD);
6648   assert(CD->getInheritedConstructor() &&
6649          "only special members have implicit exception specs");
6650   Sema::InheritedConstructorInfo ICI(
6651       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6652   return ComputeDefaultedSpecialMemberExceptionSpec(
6653       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6654 }
6655 
6656 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6657                                                             CXXMethodDecl *MD) {
6658   FunctionProtoType::ExtProtoInfo EPI;
6659 
6660   // Build an exception specification pointing back at this member.
6661   EPI.ExceptionSpec.Type = EST_Unevaluated;
6662   EPI.ExceptionSpec.SourceDecl = MD;
6663 
6664   // Set the calling convention to the default for C++ instance methods.
6665   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6666       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6667                                             /*IsCXXMethod=*/true));
6668   return EPI;
6669 }
6670 
6671 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6672   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6673   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6674     return;
6675 
6676   // Evaluate the exception specification.
6677   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6678   auto ESI = IES.getExceptionSpec();
6679 
6680   // Update the type of the special member to use it.
6681   UpdateExceptionSpec(MD, ESI);
6682 
6683   // A user-provided destructor can be defined outside the class. When that
6684   // happens, be sure to update the exception specification on both
6685   // declarations.
6686   const FunctionProtoType *CanonicalFPT =
6687     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6688   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6689     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6690 }
6691 
6692 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6693   CXXRecordDecl *RD = MD->getParent();
6694   CXXSpecialMember CSM = getSpecialMember(MD);
6695 
6696   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6697          "not an explicitly-defaulted special member");
6698 
6699   // Whether this was the first-declared instance of the constructor.
6700   // This affects whether we implicitly add an exception spec and constexpr.
6701   bool First = MD == MD->getCanonicalDecl();
6702 
6703   bool HadError = false;
6704 
6705   // C++11 [dcl.fct.def.default]p1:
6706   //   A function that is explicitly defaulted shall
6707   //     -- be a special member function (checked elsewhere),
6708   //     -- have the same type (except for ref-qualifiers, and except that a
6709   //        copy operation can take a non-const reference) as an implicit
6710   //        declaration, and
6711   //     -- not have default arguments.
6712   // C++2a changes the second bullet to instead delete the function if it's
6713   // defaulted on its first declaration, unless it's "an assignment operator,
6714   // and its return type differs or its parameter type is not a reference".
6715   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6716   bool ShouldDeleteForTypeMismatch = false;
6717   unsigned ExpectedParams = 1;
6718   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6719     ExpectedParams = 0;
6720   if (MD->getNumParams() != ExpectedParams) {
6721     // This checks for default arguments: a copy or move constructor with a
6722     // default argument is classified as a default constructor, and assignment
6723     // operations and destructors can't have default arguments.
6724     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6725       << CSM << MD->getSourceRange();
6726     HadError = true;
6727   } else if (MD->isVariadic()) {
6728     if (DeleteOnTypeMismatch)
6729       ShouldDeleteForTypeMismatch = true;
6730     else {
6731       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6732         << CSM << MD->getSourceRange();
6733       HadError = true;
6734     }
6735   }
6736 
6737   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6738 
6739   bool CanHaveConstParam = false;
6740   if (CSM == CXXCopyConstructor)
6741     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6742   else if (CSM == CXXCopyAssignment)
6743     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6744 
6745   QualType ReturnType = Context.VoidTy;
6746   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6747     // Check for return type matching.
6748     ReturnType = Type->getReturnType();
6749 
6750     QualType DeclType = Context.getTypeDeclType(RD);
6751     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6752     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6753 
6754     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6755       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6756         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6757       HadError = true;
6758     }
6759 
6760     // A defaulted special member cannot have cv-qualifiers.
6761     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6762       if (DeleteOnTypeMismatch)
6763         ShouldDeleteForTypeMismatch = true;
6764       else {
6765         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6766           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6767         HadError = true;
6768       }
6769     }
6770   }
6771 
6772   // Check for parameter type matching.
6773   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6774   bool HasConstParam = false;
6775   if (ExpectedParams && ArgType->isReferenceType()) {
6776     // Argument must be reference to possibly-const T.
6777     QualType ReferentType = ArgType->getPointeeType();
6778     HasConstParam = ReferentType.isConstQualified();
6779 
6780     if (ReferentType.isVolatileQualified()) {
6781       if (DeleteOnTypeMismatch)
6782         ShouldDeleteForTypeMismatch = true;
6783       else {
6784         Diag(MD->getLocation(),
6785              diag::err_defaulted_special_member_volatile_param) << CSM;
6786         HadError = true;
6787       }
6788     }
6789 
6790     if (HasConstParam && !CanHaveConstParam) {
6791       if (DeleteOnTypeMismatch)
6792         ShouldDeleteForTypeMismatch = true;
6793       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6794         Diag(MD->getLocation(),
6795              diag::err_defaulted_special_member_copy_const_param)
6796           << (CSM == CXXCopyAssignment);
6797         // FIXME: Explain why this special member can't be const.
6798         HadError = true;
6799       } else {
6800         Diag(MD->getLocation(),
6801              diag::err_defaulted_special_member_move_const_param)
6802           << (CSM == CXXMoveAssignment);
6803         HadError = true;
6804       }
6805     }
6806   } else if (ExpectedParams) {
6807     // A copy assignment operator can take its argument by value, but a
6808     // defaulted one cannot.
6809     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6810     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6811     HadError = true;
6812   }
6813 
6814   // C++11 [dcl.fct.def.default]p2:
6815   //   An explicitly-defaulted function may be declared constexpr only if it
6816   //   would have been implicitly declared as constexpr,
6817   // Do not apply this rule to members of class templates, since core issue 1358
6818   // makes such functions always instantiate to constexpr functions. For
6819   // functions which cannot be constexpr (for non-constructors in C++11 and for
6820   // destructors in C++1y), this is checked elsewhere.
6821   //
6822   // FIXME: This should not apply if the member is deleted.
6823   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6824                                                      HasConstParam);
6825   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6826                                  : isa<CXXConstructorDecl>(MD)) &&
6827       MD->isConstexpr() && !Constexpr &&
6828       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6829     Diag(MD->getBeginLoc(), MD->isConsteval()
6830                                 ? diag::err_incorrect_defaulted_consteval
6831                                 : diag::err_incorrect_defaulted_constexpr)
6832         << CSM;
6833     // FIXME: Explain why the special member can't be constexpr.
6834     HadError = true;
6835   }
6836 
6837   if (First) {
6838     // C++2a [dcl.fct.def.default]p3:
6839     //   If a function is explicitly defaulted on its first declaration, it is
6840     //   implicitly considered to be constexpr if the implicit declaration
6841     //   would be.
6842     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6843 
6844     if (!Type->hasExceptionSpec()) {
6845       // C++2a [except.spec]p3:
6846       //   If a declaration of a function does not have a noexcept-specifier
6847       //   [and] is defaulted on its first declaration, [...] the exception
6848       //   specification is as specified below
6849       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6850       EPI.ExceptionSpec.Type = EST_Unevaluated;
6851       EPI.ExceptionSpec.SourceDecl = MD;
6852       MD->setType(Context.getFunctionType(ReturnType,
6853                                           llvm::makeArrayRef(&ArgType,
6854                                                              ExpectedParams),
6855                                           EPI));
6856     }
6857   }
6858 
6859   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6860     if (First) {
6861       SetDeclDeleted(MD, MD->getLocation());
6862       if (!inTemplateInstantiation() && !HadError) {
6863         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6864         if (ShouldDeleteForTypeMismatch) {
6865           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6866         } else {
6867           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6868         }
6869       }
6870       if (ShouldDeleteForTypeMismatch && !HadError) {
6871         Diag(MD->getLocation(),
6872              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6873       }
6874     } else {
6875       // C++11 [dcl.fct.def.default]p4:
6876       //   [For a] user-provided explicitly-defaulted function [...] if such a
6877       //   function is implicitly defined as deleted, the program is ill-formed.
6878       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6879       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6880       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6881       HadError = true;
6882     }
6883   }
6884 
6885   if (HadError)
6886     MD->setInvalidDecl();
6887 }
6888 
6889 void Sema::CheckDelayedMemberExceptionSpecs() {
6890   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6891   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6892 
6893   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6894   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6895 
6896   // Perform any deferred checking of exception specifications for virtual
6897   // destructors.
6898   for (auto &Check : Overriding)
6899     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6900 
6901   // Perform any deferred checking of exception specifications for befriended
6902   // special members.
6903   for (auto &Check : Equivalent)
6904     CheckEquivalentExceptionSpec(Check.second, Check.first);
6905 }
6906 
6907 namespace {
6908 /// CRTP base class for visiting operations performed by a special member
6909 /// function (or inherited constructor).
6910 template<typename Derived>
6911 struct SpecialMemberVisitor {
6912   Sema &S;
6913   CXXMethodDecl *MD;
6914   Sema::CXXSpecialMember CSM;
6915   Sema::InheritedConstructorInfo *ICI;
6916 
6917   // Properties of the special member, computed for convenience.
6918   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6919 
6920   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6921                        Sema::InheritedConstructorInfo *ICI)
6922       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6923     switch (CSM) {
6924     case Sema::CXXDefaultConstructor:
6925     case Sema::CXXCopyConstructor:
6926     case Sema::CXXMoveConstructor:
6927       IsConstructor = true;
6928       break;
6929     case Sema::CXXCopyAssignment:
6930     case Sema::CXXMoveAssignment:
6931       IsAssignment = true;
6932       break;
6933     case Sema::CXXDestructor:
6934       break;
6935     case Sema::CXXInvalid:
6936       llvm_unreachable("invalid special member kind");
6937     }
6938 
6939     if (MD->getNumParams()) {
6940       if (const ReferenceType *RT =
6941               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6942         ConstArg = RT->getPointeeType().isConstQualified();
6943     }
6944   }
6945 
6946   Derived &getDerived() { return static_cast<Derived&>(*this); }
6947 
6948   /// Is this a "move" special member?
6949   bool isMove() const {
6950     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6951   }
6952 
6953   /// Look up the corresponding special member in the given class.
6954   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6955                                              unsigned Quals, bool IsMutable) {
6956     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6957                                        ConstArg && !IsMutable);
6958   }
6959 
6960   /// Look up the constructor for the specified base class to see if it's
6961   /// overridden due to this being an inherited constructor.
6962   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6963     if (!ICI)
6964       return {};
6965     assert(CSM == Sema::CXXDefaultConstructor);
6966     auto *BaseCtor =
6967       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6968     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6969       return MD;
6970     return {};
6971   }
6972 
6973   /// A base or member subobject.
6974   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6975 
6976   /// Get the location to use for a subobject in diagnostics.
6977   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6978     // FIXME: For an indirect virtual base, the direct base leading to
6979     // the indirect virtual base would be a more useful choice.
6980     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6981       return B->getBaseTypeLoc();
6982     else
6983       return Subobj.get<FieldDecl*>()->getLocation();
6984   }
6985 
6986   enum BasesToVisit {
6987     /// Visit all non-virtual (direct) bases.
6988     VisitNonVirtualBases,
6989     /// Visit all direct bases, virtual or not.
6990     VisitDirectBases,
6991     /// Visit all non-virtual bases, and all virtual bases if the class
6992     /// is not abstract.
6993     VisitPotentiallyConstructedBases,
6994     /// Visit all direct or virtual bases.
6995     VisitAllBases
6996   };
6997 
6998   // Visit the bases and members of the class.
6999   bool visit(BasesToVisit Bases) {
7000     CXXRecordDecl *RD = MD->getParent();
7001 
7002     if (Bases == VisitPotentiallyConstructedBases)
7003       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
7004 
7005     for (auto &B : RD->bases())
7006       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
7007           getDerived().visitBase(&B))
7008         return true;
7009 
7010     if (Bases == VisitAllBases)
7011       for (auto &B : RD->vbases())
7012         if (getDerived().visitBase(&B))
7013           return true;
7014 
7015     for (auto *F : RD->fields())
7016       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
7017           getDerived().visitField(F))
7018         return true;
7019 
7020     return false;
7021   }
7022 };
7023 }
7024 
7025 namespace {
7026 struct SpecialMemberDeletionInfo
7027     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
7028   bool Diagnose;
7029 
7030   SourceLocation Loc;
7031 
7032   bool AllFieldsAreConst;
7033 
7034   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
7035                             Sema::CXXSpecialMember CSM,
7036                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
7037       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
7038         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
7039 
7040   bool inUnion() const { return MD->getParent()->isUnion(); }
7041 
7042   Sema::CXXSpecialMember getEffectiveCSM() {
7043     return ICI ? Sema::CXXInvalid : CSM;
7044   }
7045 
7046   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
7047 
7048   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
7049   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
7050 
7051   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
7052   bool shouldDeleteForField(FieldDecl *FD);
7053   bool shouldDeleteForAllConstMembers();
7054 
7055   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
7056                                      unsigned Quals);
7057   bool shouldDeleteForSubobjectCall(Subobject Subobj,
7058                                     Sema::SpecialMemberOverloadResult SMOR,
7059                                     bool IsDtorCallInCtor);
7060 
7061   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
7062 };
7063 }
7064 
7065 /// Is the given special member inaccessible when used on the given
7066 /// sub-object.
7067 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
7068                                              CXXMethodDecl *target) {
7069   /// If we're operating on a base class, the object type is the
7070   /// type of this special member.
7071   QualType objectTy;
7072   AccessSpecifier access = target->getAccess();
7073   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
7074     objectTy = S.Context.getTypeDeclType(MD->getParent());
7075     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
7076 
7077   // If we're operating on a field, the object type is the type of the field.
7078   } else {
7079     objectTy = S.Context.getTypeDeclType(target->getParent());
7080   }
7081 
7082   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
7083 }
7084 
7085 /// Check whether we should delete a special member due to the implicit
7086 /// definition containing a call to a special member of a subobject.
7087 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
7088     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
7089     bool IsDtorCallInCtor) {
7090   CXXMethodDecl *Decl = SMOR.getMethod();
7091   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7092 
7093   int DiagKind = -1;
7094 
7095   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
7096     DiagKind = !Decl ? 0 : 1;
7097   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7098     DiagKind = 2;
7099   else if (!isAccessible(Subobj, Decl))
7100     DiagKind = 3;
7101   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
7102            !Decl->isTrivial()) {
7103     // A member of a union must have a trivial corresponding special member.
7104     // As a weird special case, a destructor call from a union's constructor
7105     // must be accessible and non-deleted, but need not be trivial. Such a
7106     // destructor is never actually called, but is semantically checked as
7107     // if it were.
7108     DiagKind = 4;
7109   }
7110 
7111   if (DiagKind == -1)
7112     return false;
7113 
7114   if (Diagnose) {
7115     if (Field) {
7116       S.Diag(Field->getLocation(),
7117              diag::note_deleted_special_member_class_subobject)
7118         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
7119         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
7120     } else {
7121       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
7122       S.Diag(Base->getBeginLoc(),
7123              diag::note_deleted_special_member_class_subobject)
7124           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7125           << Base->getType() << DiagKind << IsDtorCallInCtor
7126           << /*IsObjCPtr*/false;
7127     }
7128 
7129     if (DiagKind == 1)
7130       S.NoteDeletedFunction(Decl);
7131     // FIXME: Explain inaccessibility if DiagKind == 3.
7132   }
7133 
7134   return true;
7135 }
7136 
7137 /// Check whether we should delete a special member function due to having a
7138 /// direct or virtual base class or non-static data member of class type M.
7139 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7140     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7141   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7142   bool IsMutable = Field && Field->isMutable();
7143 
7144   // C++11 [class.ctor]p5:
7145   // -- any direct or virtual base class, or non-static data member with no
7146   //    brace-or-equal-initializer, has class type M (or array thereof) and
7147   //    either M has no default constructor or overload resolution as applied
7148   //    to M's default constructor results in an ambiguity or in a function
7149   //    that is deleted or inaccessible
7150   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7151   // -- a direct or virtual base class B that cannot be copied/moved because
7152   //    overload resolution, as applied to B's corresponding special member,
7153   //    results in an ambiguity or a function that is deleted or inaccessible
7154   //    from the defaulted special member
7155   // C++11 [class.dtor]p5:
7156   // -- any direct or virtual base class [...] has a type with a destructor
7157   //    that is deleted or inaccessible
7158   if (!(CSM == Sema::CXXDefaultConstructor &&
7159         Field && Field->hasInClassInitializer()) &&
7160       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7161                                    false))
7162     return true;
7163 
7164   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7165   // -- any direct or virtual base class or non-static data member has a
7166   //    type with a destructor that is deleted or inaccessible
7167   if (IsConstructor) {
7168     Sema::SpecialMemberOverloadResult SMOR =
7169         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7170                               false, false, false, false, false);
7171     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7172       return true;
7173   }
7174 
7175   return false;
7176 }
7177 
7178 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7179     FieldDecl *FD, QualType FieldType) {
7180   // The defaulted special functions are defined as deleted if this is a variant
7181   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7182   // type under ARC.
7183   if (!FieldType.hasNonTrivialObjCLifetime())
7184     return false;
7185 
7186   // Don't make the defaulted default constructor defined as deleted if the
7187   // member has an in-class initializer.
7188   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7189     return false;
7190 
7191   if (Diagnose) {
7192     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7193     S.Diag(FD->getLocation(),
7194            diag::note_deleted_special_member_class_subobject)
7195         << getEffectiveCSM() << ParentClass << /*IsField*/true
7196         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7197   }
7198 
7199   return true;
7200 }
7201 
7202 /// Check whether we should delete a special member function due to the class
7203 /// having a particular direct or virtual base class.
7204 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7205   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7206   // If program is correct, BaseClass cannot be null, but if it is, the error
7207   // must be reported elsewhere.
7208   if (!BaseClass)
7209     return false;
7210   // If we have an inheriting constructor, check whether we're calling an
7211   // inherited constructor instead of a default constructor.
7212   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7213   if (auto *BaseCtor = SMOR.getMethod()) {
7214     // Note that we do not check access along this path; other than that,
7215     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7216     // FIXME: Check that the base has a usable destructor! Sink this into
7217     // shouldDeleteForClassSubobject.
7218     if (BaseCtor->isDeleted() && Diagnose) {
7219       S.Diag(Base->getBeginLoc(),
7220              diag::note_deleted_special_member_class_subobject)
7221           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7222           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7223           << /*IsObjCPtr*/false;
7224       S.NoteDeletedFunction(BaseCtor);
7225     }
7226     return BaseCtor->isDeleted();
7227   }
7228   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7229 }
7230 
7231 /// Check whether we should delete a special member function due to the class
7232 /// having a particular non-static data member.
7233 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7234   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7235   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7236 
7237   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7238     return true;
7239 
7240   if (CSM == Sema::CXXDefaultConstructor) {
7241     // For a default constructor, all references must be initialized in-class
7242     // and, if a union, it must have a non-const member.
7243     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7244       if (Diagnose)
7245         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7246           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7247       return true;
7248     }
7249     // C++11 [class.ctor]p5: any non-variant non-static data member of
7250     // const-qualified type (or array thereof) with no
7251     // brace-or-equal-initializer does not have a user-provided default
7252     // constructor.
7253     if (!inUnion() && FieldType.isConstQualified() &&
7254         !FD->hasInClassInitializer() &&
7255         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7256       if (Diagnose)
7257         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7258           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7259       return true;
7260     }
7261 
7262     if (inUnion() && !FieldType.isConstQualified())
7263       AllFieldsAreConst = false;
7264   } else if (CSM == Sema::CXXCopyConstructor) {
7265     // For a copy constructor, data members must not be of rvalue reference
7266     // type.
7267     if (FieldType->isRValueReferenceType()) {
7268       if (Diagnose)
7269         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7270           << MD->getParent() << FD << FieldType;
7271       return true;
7272     }
7273   } else if (IsAssignment) {
7274     // For an assignment operator, data members must not be of reference type.
7275     if (FieldType->isReferenceType()) {
7276       if (Diagnose)
7277         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7278           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7279       return true;
7280     }
7281     if (!FieldRecord && FieldType.isConstQualified()) {
7282       // C++11 [class.copy]p23:
7283       // -- a non-static data member of const non-class type (or array thereof)
7284       if (Diagnose)
7285         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7286           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7287       return true;
7288     }
7289   }
7290 
7291   if (FieldRecord) {
7292     // Some additional restrictions exist on the variant members.
7293     if (!inUnion() && FieldRecord->isUnion() &&
7294         FieldRecord->isAnonymousStructOrUnion()) {
7295       bool AllVariantFieldsAreConst = true;
7296 
7297       // FIXME: Handle anonymous unions declared within anonymous unions.
7298       for (auto *UI : FieldRecord->fields()) {
7299         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7300 
7301         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7302           return true;
7303 
7304         if (!UnionFieldType.isConstQualified())
7305           AllVariantFieldsAreConst = false;
7306 
7307         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7308         if (UnionFieldRecord &&
7309             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7310                                           UnionFieldType.getCVRQualifiers()))
7311           return true;
7312       }
7313 
7314       // At least one member in each anonymous union must be non-const
7315       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7316           !FieldRecord->field_empty()) {
7317         if (Diagnose)
7318           S.Diag(FieldRecord->getLocation(),
7319                  diag::note_deleted_default_ctor_all_const)
7320             << !!ICI << MD->getParent() << /*anonymous union*/1;
7321         return true;
7322       }
7323 
7324       // Don't check the implicit member of the anonymous union type.
7325       // This is technically non-conformant, but sanity demands it.
7326       return false;
7327     }
7328 
7329     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7330                                       FieldType.getCVRQualifiers()))
7331       return true;
7332   }
7333 
7334   return false;
7335 }
7336 
7337 /// C++11 [class.ctor] p5:
7338 ///   A defaulted default constructor for a class X is defined as deleted if
7339 /// X is a union and all of its variant members are of const-qualified type.
7340 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7341   // This is a silly definition, because it gives an empty union a deleted
7342   // default constructor. Don't do that.
7343   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7344     bool AnyFields = false;
7345     for (auto *F : MD->getParent()->fields())
7346       if ((AnyFields = !F->isUnnamedBitfield()))
7347         break;
7348     if (!AnyFields)
7349       return false;
7350     if (Diagnose)
7351       S.Diag(MD->getParent()->getLocation(),
7352              diag::note_deleted_default_ctor_all_const)
7353         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7354     return true;
7355   }
7356   return false;
7357 }
7358 
7359 /// Determine whether a defaulted special member function should be defined as
7360 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7361 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7362 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7363                                      InheritedConstructorInfo *ICI,
7364                                      bool Diagnose) {
7365   if (MD->isInvalidDecl())
7366     return false;
7367   CXXRecordDecl *RD = MD->getParent();
7368   assert(!RD->isDependentType() && "do deletion after instantiation");
7369   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7370     return false;
7371 
7372   // C++11 [expr.lambda.prim]p19:
7373   //   The closure type associated with a lambda-expression has a
7374   //   deleted (8.4.3) default constructor and a deleted copy
7375   //   assignment operator.
7376   // C++2a adds back these operators if the lambda has no lambda-capture.
7377   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7378       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7379     if (Diagnose)
7380       Diag(RD->getLocation(), diag::note_lambda_decl);
7381     return true;
7382   }
7383 
7384   // For an anonymous struct or union, the copy and assignment special members
7385   // will never be used, so skip the check. For an anonymous union declared at
7386   // namespace scope, the constructor and destructor are used.
7387   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7388       RD->isAnonymousStructOrUnion())
7389     return false;
7390 
7391   // C++11 [class.copy]p7, p18:
7392   //   If the class definition declares a move constructor or move assignment
7393   //   operator, an implicitly declared copy constructor or copy assignment
7394   //   operator is defined as deleted.
7395   if (MD->isImplicit() &&
7396       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7397     CXXMethodDecl *UserDeclaredMove = nullptr;
7398 
7399     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7400     // deletion of the corresponding copy operation, not both copy operations.
7401     // MSVC 2015 has adopted the standards conforming behavior.
7402     bool DeletesOnlyMatchingCopy =
7403         getLangOpts().MSVCCompat &&
7404         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7405 
7406     if (RD->hasUserDeclaredMoveConstructor() &&
7407         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7408       if (!Diagnose) return true;
7409 
7410       // Find any user-declared move constructor.
7411       for (auto *I : RD->ctors()) {
7412         if (I->isMoveConstructor()) {
7413           UserDeclaredMove = I;
7414           break;
7415         }
7416       }
7417       assert(UserDeclaredMove);
7418     } else if (RD->hasUserDeclaredMoveAssignment() &&
7419                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7420       if (!Diagnose) return true;
7421 
7422       // Find any user-declared move assignment operator.
7423       for (auto *I : RD->methods()) {
7424         if (I->isMoveAssignmentOperator()) {
7425           UserDeclaredMove = I;
7426           break;
7427         }
7428       }
7429       assert(UserDeclaredMove);
7430     }
7431 
7432     if (UserDeclaredMove) {
7433       Diag(UserDeclaredMove->getLocation(),
7434            diag::note_deleted_copy_user_declared_move)
7435         << (CSM == CXXCopyAssignment) << RD
7436         << UserDeclaredMove->isMoveAssignmentOperator();
7437       return true;
7438     }
7439   }
7440 
7441   // Do access control from the special member function
7442   ContextRAII MethodContext(*this, MD);
7443 
7444   // C++11 [class.dtor]p5:
7445   // -- for a virtual destructor, lookup of the non-array deallocation function
7446   //    results in an ambiguity or in a function that is deleted or inaccessible
7447   if (CSM == CXXDestructor && MD->isVirtual()) {
7448     FunctionDecl *OperatorDelete = nullptr;
7449     DeclarationName Name =
7450       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7451     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7452                                  OperatorDelete, /*Diagnose*/false)) {
7453       if (Diagnose)
7454         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7455       return true;
7456     }
7457   }
7458 
7459   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7460 
7461   // Per DR1611, do not consider virtual bases of constructors of abstract
7462   // classes, since we are not going to construct them.
7463   // Per DR1658, do not consider virtual bases of destructors of abstract
7464   // classes either.
7465   // Per DR2180, for assignment operators we only assign (and thus only
7466   // consider) direct bases.
7467   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7468                                  : SMI.VisitPotentiallyConstructedBases))
7469     return true;
7470 
7471   if (SMI.shouldDeleteForAllConstMembers())
7472     return true;
7473 
7474   if (getLangOpts().CUDA) {
7475     // We should delete the special member in CUDA mode if target inference
7476     // failed.
7477     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7478     // is treated as certain special member, which may not reflect what special
7479     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7480     // expects CSM to match MD, therefore recalculate CSM.
7481     assert(ICI || CSM == getSpecialMember(MD));
7482     auto RealCSM = CSM;
7483     if (ICI)
7484       RealCSM = getSpecialMember(MD);
7485 
7486     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7487                                                    SMI.ConstArg, Diagnose);
7488   }
7489 
7490   return false;
7491 }
7492 
7493 /// Perform lookup for a special member of the specified kind, and determine
7494 /// whether it is trivial. If the triviality can be determined without the
7495 /// lookup, skip it. This is intended for use when determining whether a
7496 /// special member of a containing object is trivial, and thus does not ever
7497 /// perform overload resolution for default constructors.
7498 ///
7499 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7500 /// member that was most likely to be intended to be trivial, if any.
7501 ///
7502 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7503 /// determine whether the special member is trivial.
7504 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7505                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7506                                      bool ConstRHS,
7507                                      Sema::TrivialABIHandling TAH,
7508                                      CXXMethodDecl **Selected) {
7509   if (Selected)
7510     *Selected = nullptr;
7511 
7512   switch (CSM) {
7513   case Sema::CXXInvalid:
7514     llvm_unreachable("not a special member");
7515 
7516   case Sema::CXXDefaultConstructor:
7517     // C++11 [class.ctor]p5:
7518     //   A default constructor is trivial if:
7519     //    - all the [direct subobjects] have trivial default constructors
7520     //
7521     // Note, no overload resolution is performed in this case.
7522     if (RD->hasTrivialDefaultConstructor())
7523       return true;
7524 
7525     if (Selected) {
7526       // If there's a default constructor which could have been trivial, dig it
7527       // out. Otherwise, if there's any user-provided default constructor, point
7528       // to that as an example of why there's not a trivial one.
7529       CXXConstructorDecl *DefCtor = nullptr;
7530       if (RD->needsImplicitDefaultConstructor())
7531         S.DeclareImplicitDefaultConstructor(RD);
7532       for (auto *CI : RD->ctors()) {
7533         if (!CI->isDefaultConstructor())
7534           continue;
7535         DefCtor = CI;
7536         if (!DefCtor->isUserProvided())
7537           break;
7538       }
7539 
7540       *Selected = DefCtor;
7541     }
7542 
7543     return false;
7544 
7545   case Sema::CXXDestructor:
7546     // C++11 [class.dtor]p5:
7547     //   A destructor is trivial if:
7548     //    - all the direct [subobjects] have trivial destructors
7549     if (RD->hasTrivialDestructor() ||
7550         (TAH == Sema::TAH_ConsiderTrivialABI &&
7551          RD->hasTrivialDestructorForCall()))
7552       return true;
7553 
7554     if (Selected) {
7555       if (RD->needsImplicitDestructor())
7556         S.DeclareImplicitDestructor(RD);
7557       *Selected = RD->getDestructor();
7558     }
7559 
7560     return false;
7561 
7562   case Sema::CXXCopyConstructor:
7563     // C++11 [class.copy]p12:
7564     //   A copy constructor is trivial if:
7565     //    - the constructor selected to copy each direct [subobject] is trivial
7566     if (RD->hasTrivialCopyConstructor() ||
7567         (TAH == Sema::TAH_ConsiderTrivialABI &&
7568          RD->hasTrivialCopyConstructorForCall())) {
7569       if (Quals == Qualifiers::Const)
7570         // We must either select the trivial copy constructor or reach an
7571         // ambiguity; no need to actually perform overload resolution.
7572         return true;
7573     } else if (!Selected) {
7574       return false;
7575     }
7576     // In C++98, we are not supposed to perform overload resolution here, but we
7577     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7578     // cases like B as having a non-trivial copy constructor:
7579     //   struct A { template<typename T> A(T&); };
7580     //   struct B { mutable A a; };
7581     goto NeedOverloadResolution;
7582 
7583   case Sema::CXXCopyAssignment:
7584     // C++11 [class.copy]p25:
7585     //   A copy assignment operator is trivial if:
7586     //    - the assignment operator selected to copy each direct [subobject] is
7587     //      trivial
7588     if (RD->hasTrivialCopyAssignment()) {
7589       if (Quals == Qualifiers::Const)
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.
7596     goto NeedOverloadResolution;
7597 
7598   case Sema::CXXMoveConstructor:
7599   case Sema::CXXMoveAssignment:
7600   NeedOverloadResolution:
7601     Sema::SpecialMemberOverloadResult SMOR =
7602         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7603 
7604     // The standard doesn't describe how to behave if the lookup is ambiguous.
7605     // We treat it as not making the member non-trivial, just like the standard
7606     // mandates for the default constructor. This should rarely matter, because
7607     // the member will also be deleted.
7608     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7609       return true;
7610 
7611     if (!SMOR.getMethod()) {
7612       assert(SMOR.getKind() ==
7613              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7614       return false;
7615     }
7616 
7617     // We deliberately don't check if we found a deleted special member. We're
7618     // not supposed to!
7619     if (Selected)
7620       *Selected = SMOR.getMethod();
7621 
7622     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7623         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7624       return SMOR.getMethod()->isTrivialForCall();
7625     return SMOR.getMethod()->isTrivial();
7626   }
7627 
7628   llvm_unreachable("unknown special method kind");
7629 }
7630 
7631 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7632   for (auto *CI : RD->ctors())
7633     if (!CI->isImplicit())
7634       return CI;
7635 
7636   // Look for constructor templates.
7637   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7638   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7639     if (CXXConstructorDecl *CD =
7640           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7641       return CD;
7642   }
7643 
7644   return nullptr;
7645 }
7646 
7647 /// The kind of subobject we are checking for triviality. The values of this
7648 /// enumeration are used in diagnostics.
7649 enum TrivialSubobjectKind {
7650   /// The subobject is a base class.
7651   TSK_BaseClass,
7652   /// The subobject is a non-static data member.
7653   TSK_Field,
7654   /// The object is actually the complete object.
7655   TSK_CompleteObject
7656 };
7657 
7658 /// Check whether the special member selected for a given type would be trivial.
7659 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7660                                       QualType SubType, bool ConstRHS,
7661                                       Sema::CXXSpecialMember CSM,
7662                                       TrivialSubobjectKind Kind,
7663                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7664   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7665   if (!SubRD)
7666     return true;
7667 
7668   CXXMethodDecl *Selected;
7669   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7670                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7671     return true;
7672 
7673   if (Diagnose) {
7674     if (ConstRHS)
7675       SubType.addConst();
7676 
7677     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7678       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7679         << Kind << SubType.getUnqualifiedType();
7680       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7681         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7682     } else if (!Selected)
7683       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7684         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7685     else if (Selected->isUserProvided()) {
7686       if (Kind == TSK_CompleteObject)
7687         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7688           << Kind << SubType.getUnqualifiedType() << CSM;
7689       else {
7690         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7691           << Kind << SubType.getUnqualifiedType() << CSM;
7692         S.Diag(Selected->getLocation(), diag::note_declared_at);
7693       }
7694     } else {
7695       if (Kind != TSK_CompleteObject)
7696         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7697           << Kind << SubType.getUnqualifiedType() << CSM;
7698 
7699       // Explain why the defaulted or deleted special member isn't trivial.
7700       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7701                                Diagnose);
7702     }
7703   }
7704 
7705   return false;
7706 }
7707 
7708 /// Check whether the members of a class type allow a special member to be
7709 /// trivial.
7710 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7711                                      Sema::CXXSpecialMember CSM,
7712                                      bool ConstArg,
7713                                      Sema::TrivialABIHandling TAH,
7714                                      bool Diagnose) {
7715   for (const auto *FI : RD->fields()) {
7716     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7717       continue;
7718 
7719     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7720 
7721     // Pretend anonymous struct or union members are members of this class.
7722     if (FI->isAnonymousStructOrUnion()) {
7723       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7724                                     CSM, ConstArg, TAH, Diagnose))
7725         return false;
7726       continue;
7727     }
7728 
7729     // C++11 [class.ctor]p5:
7730     //   A default constructor is trivial if [...]
7731     //    -- no non-static data member of its class has a
7732     //       brace-or-equal-initializer
7733     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7734       if (Diagnose)
7735         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7736       return false;
7737     }
7738 
7739     // Objective C ARC 4.3.5:
7740     //   [...] nontrivally ownership-qualified types are [...] not trivially
7741     //   default constructible, copy constructible, move constructible, copy
7742     //   assignable, move assignable, or destructible [...]
7743     if (FieldType.hasNonTrivialObjCLifetime()) {
7744       if (Diagnose)
7745         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7746           << RD << FieldType.getObjCLifetime();
7747       return false;
7748     }
7749 
7750     bool ConstRHS = ConstArg && !FI->isMutable();
7751     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7752                                    CSM, TSK_Field, TAH, Diagnose))
7753       return false;
7754   }
7755 
7756   return true;
7757 }
7758 
7759 /// Diagnose why the specified class does not have a trivial special member of
7760 /// the given kind.
7761 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7762   QualType Ty = Context.getRecordType(RD);
7763 
7764   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7765   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7766                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7767                             /*Diagnose*/true);
7768 }
7769 
7770 /// Determine whether a defaulted or deleted special member function is trivial,
7771 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7772 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7773 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7774                                   TrivialABIHandling TAH, bool Diagnose) {
7775   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7776 
7777   CXXRecordDecl *RD = MD->getParent();
7778 
7779   bool ConstArg = false;
7780 
7781   // C++11 [class.copy]p12, p25: [DR1593]
7782   //   A [special member] is trivial if [...] its parameter-type-list is
7783   //   equivalent to the parameter-type-list of an implicit declaration [...]
7784   switch (CSM) {
7785   case CXXDefaultConstructor:
7786   case CXXDestructor:
7787     // Trivial default constructors and destructors cannot have parameters.
7788     break;
7789 
7790   case CXXCopyConstructor:
7791   case CXXCopyAssignment: {
7792     // Trivial copy operations always have const, non-volatile parameter types.
7793     ConstArg = true;
7794     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7795     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7796     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7797       if (Diagnose)
7798         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7799           << Param0->getSourceRange() << Param0->getType()
7800           << Context.getLValueReferenceType(
7801                Context.getRecordType(RD).withConst());
7802       return false;
7803     }
7804     break;
7805   }
7806 
7807   case CXXMoveConstructor:
7808   case CXXMoveAssignment: {
7809     // Trivial move operations always have non-cv-qualified parameters.
7810     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7811     const RValueReferenceType *RT =
7812       Param0->getType()->getAs<RValueReferenceType>();
7813     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7814       if (Diagnose)
7815         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7816           << Param0->getSourceRange() << Param0->getType()
7817           << Context.getRValueReferenceType(Context.getRecordType(RD));
7818       return false;
7819     }
7820     break;
7821   }
7822 
7823   case CXXInvalid:
7824     llvm_unreachable("not a special member");
7825   }
7826 
7827   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7828     if (Diagnose)
7829       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7830            diag::note_nontrivial_default_arg)
7831         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7832     return false;
7833   }
7834   if (MD->isVariadic()) {
7835     if (Diagnose)
7836       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7837     return false;
7838   }
7839 
7840   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7841   //   A copy/move [constructor or assignment operator] is trivial if
7842   //    -- the [member] selected to copy/move each direct base class subobject
7843   //       is trivial
7844   //
7845   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7846   //   A [default constructor or destructor] is trivial if
7847   //    -- all the direct base classes have trivial [default constructors or
7848   //       destructors]
7849   for (const auto &BI : RD->bases())
7850     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7851                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7852       return false;
7853 
7854   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7855   //   A copy/move [constructor or assignment operator] for a class X is
7856   //   trivial if
7857   //    -- for each non-static data member of X that is of class type (or array
7858   //       thereof), the constructor selected to copy/move that member is
7859   //       trivial
7860   //
7861   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7862   //   A [default constructor or destructor] is trivial if
7863   //    -- for all of the non-static data members of its class that are of class
7864   //       type (or array thereof), each such class has a trivial [default
7865   //       constructor or destructor]
7866   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7867     return false;
7868 
7869   // C++11 [class.dtor]p5:
7870   //   A destructor is trivial if [...]
7871   //    -- the destructor is not virtual
7872   if (CSM == CXXDestructor && MD->isVirtual()) {
7873     if (Diagnose)
7874       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7875     return false;
7876   }
7877 
7878   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7879   //   A [special member] for class X is trivial if [...]
7880   //    -- class X has no virtual functions and no virtual base classes
7881   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7882     if (!Diagnose)
7883       return false;
7884 
7885     if (RD->getNumVBases()) {
7886       // Check for virtual bases. We already know that the corresponding
7887       // member in all bases is trivial, so vbases must all be direct.
7888       CXXBaseSpecifier &BS = *RD->vbases_begin();
7889       assert(BS.isVirtual());
7890       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7891       return false;
7892     }
7893 
7894     // Must have a virtual method.
7895     for (const auto *MI : RD->methods()) {
7896       if (MI->isVirtual()) {
7897         SourceLocation MLoc = MI->getBeginLoc();
7898         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7899         return false;
7900       }
7901     }
7902 
7903     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7904   }
7905 
7906   // Looks like it's trivial!
7907   return true;
7908 }
7909 
7910 namespace {
7911 struct FindHiddenVirtualMethod {
7912   Sema *S;
7913   CXXMethodDecl *Method;
7914   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7915   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7916 
7917 private:
7918   /// Check whether any most overridden method from MD in Methods
7919   static bool CheckMostOverridenMethods(
7920       const CXXMethodDecl *MD,
7921       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7922     if (MD->size_overridden_methods() == 0)
7923       return Methods.count(MD->getCanonicalDecl());
7924     for (const CXXMethodDecl *O : MD->overridden_methods())
7925       if (CheckMostOverridenMethods(O, Methods))
7926         return true;
7927     return false;
7928   }
7929 
7930 public:
7931   /// Member lookup function that determines whether a given C++
7932   /// method overloads virtual methods in a base class without overriding any,
7933   /// to be used with CXXRecordDecl::lookupInBases().
7934   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7935     RecordDecl *BaseRecord =
7936         Specifier->getType()->getAs<RecordType>()->getDecl();
7937 
7938     DeclarationName Name = Method->getDeclName();
7939     assert(Name.getNameKind() == DeclarationName::Identifier);
7940 
7941     bool foundSameNameMethod = false;
7942     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7943     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7944          Path.Decls = Path.Decls.slice(1)) {
7945       NamedDecl *D = Path.Decls.front();
7946       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7947         MD = MD->getCanonicalDecl();
7948         foundSameNameMethod = true;
7949         // Interested only in hidden virtual methods.
7950         if (!MD->isVirtual())
7951           continue;
7952         // If the method we are checking overrides a method from its base
7953         // don't warn about the other overloaded methods. Clang deviates from
7954         // GCC by only diagnosing overloads of inherited virtual functions that
7955         // do not override any other virtual functions in the base. GCC's
7956         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7957         // function from a base class. These cases may be better served by a
7958         // warning (not specific to virtual functions) on call sites when the
7959         // call would select a different function from the base class, were it
7960         // visible.
7961         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7962         if (!S->IsOverload(Method, MD, false))
7963           return true;
7964         // Collect the overload only if its hidden.
7965         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7966           overloadedMethods.push_back(MD);
7967       }
7968     }
7969 
7970     if (foundSameNameMethod)
7971       OverloadedMethods.append(overloadedMethods.begin(),
7972                                overloadedMethods.end());
7973     return foundSameNameMethod;
7974   }
7975 };
7976 } // end anonymous namespace
7977 
7978 /// Add the most overriden methods from MD to Methods
7979 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7980                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7981   if (MD->size_overridden_methods() == 0)
7982     Methods.insert(MD->getCanonicalDecl());
7983   else
7984     for (const CXXMethodDecl *O : MD->overridden_methods())
7985       AddMostOverridenMethods(O, Methods);
7986 }
7987 
7988 /// Check if a method overloads virtual methods in a base class without
7989 /// overriding any.
7990 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7991                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7992   if (!MD->getDeclName().isIdentifier())
7993     return;
7994 
7995   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7996                      /*bool RecordPaths=*/false,
7997                      /*bool DetectVirtual=*/false);
7998   FindHiddenVirtualMethod FHVM;
7999   FHVM.Method = MD;
8000   FHVM.S = this;
8001 
8002   // Keep the base methods that were overridden or introduced in the subclass
8003   // by 'using' in a set. A base method not in this set is hidden.
8004   CXXRecordDecl *DC = MD->getParent();
8005   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
8006   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
8007     NamedDecl *ND = *I;
8008     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
8009       ND = shad->getTargetDecl();
8010     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
8011       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
8012   }
8013 
8014   if (DC->lookupInBases(FHVM, Paths))
8015     OverloadedMethods = FHVM.OverloadedMethods;
8016 }
8017 
8018 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
8019                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8020   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
8021     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
8022     PartialDiagnostic PD = PDiag(
8023          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
8024     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
8025     Diag(overloadedMD->getLocation(), PD);
8026   }
8027 }
8028 
8029 /// Diagnose methods which overload virtual methods in a base class
8030 /// without overriding any.
8031 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
8032   if (MD->isInvalidDecl())
8033     return;
8034 
8035   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
8036     return;
8037 
8038   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
8039   FindHiddenVirtualMethods(MD, OverloadedMethods);
8040   if (!OverloadedMethods.empty()) {
8041     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
8042       << MD << (OverloadedMethods.size() > 1);
8043 
8044     NoteHiddenVirtualMethods(MD, OverloadedMethods);
8045   }
8046 }
8047 
8048 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
8049   auto PrintDiagAndRemoveAttr = [&]() {
8050     // No diagnostics if this is a template instantiation.
8051     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
8052       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
8053            diag::ext_cannot_use_trivial_abi) << &RD;
8054     RD.dropAttr<TrivialABIAttr>();
8055   };
8056 
8057   // Ill-formed if the struct has virtual functions.
8058   if (RD.isPolymorphic()) {
8059     PrintDiagAndRemoveAttr();
8060     return;
8061   }
8062 
8063   for (const auto &B : RD.bases()) {
8064     // Ill-formed if the base class is non-trivial for the purpose of calls or a
8065     // virtual base.
8066     if ((!B.getType()->isDependentType() &&
8067          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
8068         B.isVirtual()) {
8069       PrintDiagAndRemoveAttr();
8070       return;
8071     }
8072   }
8073 
8074   for (const auto *FD : RD.fields()) {
8075     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
8076     // non-trivial for the purpose of calls.
8077     QualType FT = FD->getType();
8078     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
8079       PrintDiagAndRemoveAttr();
8080       return;
8081     }
8082 
8083     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
8084       if (!RT->isDependentType() &&
8085           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
8086         PrintDiagAndRemoveAttr();
8087         return;
8088       }
8089   }
8090 }
8091 
8092 void Sema::ActOnFinishCXXMemberSpecification(
8093     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
8094     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
8095   if (!TagDecl)
8096     return;
8097 
8098   AdjustDeclIfTemplate(TagDecl);
8099 
8100   for (const ParsedAttr &AL : AttrList) {
8101     if (AL.getKind() != ParsedAttr::AT_Visibility)
8102       continue;
8103     AL.setInvalid();
8104     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
8105         << AL.getName();
8106   }
8107 
8108   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
8109               // strict aliasing violation!
8110               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
8111               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
8112 
8113   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
8114 }
8115 
8116 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
8117 /// special functions, such as the default constructor, copy
8118 /// constructor, or destructor, to the given C++ class (C++
8119 /// [special]p1).  This routine can only be executed just before the
8120 /// definition of the class is complete.
8121 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
8122   if (ClassDecl->needsImplicitDefaultConstructor()) {
8123     ++getASTContext().NumImplicitDefaultConstructors;
8124 
8125     if (ClassDecl->hasInheritedConstructor())
8126       DeclareImplicitDefaultConstructor(ClassDecl);
8127   }
8128 
8129   if (ClassDecl->needsImplicitCopyConstructor()) {
8130     ++getASTContext().NumImplicitCopyConstructors;
8131 
8132     // If the properties or semantics of the copy constructor couldn't be
8133     // determined while the class was being declared, force a declaration
8134     // of it now.
8135     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
8136         ClassDecl->hasInheritedConstructor())
8137       DeclareImplicitCopyConstructor(ClassDecl);
8138     // For the MS ABI we need to know whether the copy ctor is deleted. A
8139     // prerequisite for deleting the implicit copy ctor is that the class has a
8140     // move ctor or move assignment that is either user-declared or whose
8141     // semantics are inherited from a subobject. FIXME: We should provide a more
8142     // direct way for CodeGen to ask whether the constructor was deleted.
8143     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8144              (ClassDecl->hasUserDeclaredMoveConstructor() ||
8145               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8146               ClassDecl->hasUserDeclaredMoveAssignment() ||
8147               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8148       DeclareImplicitCopyConstructor(ClassDecl);
8149   }
8150 
8151   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8152     ++getASTContext().NumImplicitMoveConstructors;
8153 
8154     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8155         ClassDecl->hasInheritedConstructor())
8156       DeclareImplicitMoveConstructor(ClassDecl);
8157   }
8158 
8159   if (ClassDecl->needsImplicitCopyAssignment()) {
8160     ++getASTContext().NumImplicitCopyAssignmentOperators;
8161 
8162     // If we have a dynamic class, then the copy assignment operator may be
8163     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8164     // it shows up in the right place in the vtable and that we diagnose
8165     // problems with the implicit exception specification.
8166     if (ClassDecl->isDynamicClass() ||
8167         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8168         ClassDecl->hasInheritedAssignment())
8169       DeclareImplicitCopyAssignment(ClassDecl);
8170   }
8171 
8172   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8173     ++getASTContext().NumImplicitMoveAssignmentOperators;
8174 
8175     // Likewise for the move assignment operator.
8176     if (ClassDecl->isDynamicClass() ||
8177         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8178         ClassDecl->hasInheritedAssignment())
8179       DeclareImplicitMoveAssignment(ClassDecl);
8180   }
8181 
8182   if (ClassDecl->needsImplicitDestructor()) {
8183     ++getASTContext().NumImplicitDestructors;
8184 
8185     // If we have a dynamic class, then the destructor may be virtual, so we
8186     // have to declare the destructor immediately. This ensures that, e.g., it
8187     // shows up in the right place in the vtable and that we diagnose problems
8188     // with the implicit exception specification.
8189     if (ClassDecl->isDynamicClass() ||
8190         ClassDecl->needsOverloadResolutionForDestructor())
8191       DeclareImplicitDestructor(ClassDecl);
8192   }
8193 }
8194 
8195 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8196   if (!D)
8197     return 0;
8198 
8199   // The order of template parameters is not important here. All names
8200   // get added to the same scope.
8201   SmallVector<TemplateParameterList *, 4> ParameterLists;
8202 
8203   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8204     D = TD->getTemplatedDecl();
8205 
8206   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8207     ParameterLists.push_back(PSD->getTemplateParameters());
8208 
8209   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8210     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8211       ParameterLists.push_back(DD->getTemplateParameterList(i));
8212 
8213     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8214       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8215         ParameterLists.push_back(FTD->getTemplateParameters());
8216     }
8217   }
8218 
8219   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8220     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8221       ParameterLists.push_back(TD->getTemplateParameterList(i));
8222 
8223     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8224       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8225         ParameterLists.push_back(CTD->getTemplateParameters());
8226     }
8227   }
8228 
8229   unsigned Count = 0;
8230   for (TemplateParameterList *Params : ParameterLists) {
8231     if (Params->size() > 0)
8232       // Ignore explicit specializations; they don't contribute to the template
8233       // depth.
8234       ++Count;
8235     for (NamedDecl *Param : *Params) {
8236       if (Param->getDeclName()) {
8237         S->AddDecl(Param);
8238         IdResolver.AddDecl(Param);
8239       }
8240     }
8241   }
8242 
8243   return Count;
8244 }
8245 
8246 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8247   if (!RecordD) return;
8248   AdjustDeclIfTemplate(RecordD);
8249   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8250   PushDeclContext(S, Record);
8251 }
8252 
8253 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8254   if (!RecordD) return;
8255   PopDeclContext();
8256 }
8257 
8258 /// This is used to implement the constant expression evaluation part of the
8259 /// attribute enable_if extension. There is nothing in standard C++ which would
8260 /// require reentering parameters.
8261 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8262   if (!Param)
8263     return;
8264 
8265   S->AddDecl(Param);
8266   if (Param->getDeclName())
8267     IdResolver.AddDecl(Param);
8268 }
8269 
8270 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8271 /// parsing a top-level (non-nested) C++ class, and we are now
8272 /// parsing those parts of the given Method declaration that could
8273 /// not be parsed earlier (C++ [class.mem]p2), such as default
8274 /// arguments. This action should enter the scope of the given
8275 /// Method declaration as if we had just parsed the qualified method
8276 /// name. However, it should not bring the parameters into scope;
8277 /// that will be performed by ActOnDelayedCXXMethodParameter.
8278 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8279 }
8280 
8281 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8282 /// C++ method declaration. We're (re-)introducing the given
8283 /// function parameter into scope for use in parsing later parts of
8284 /// the method declaration. For example, we could see an
8285 /// ActOnParamDefaultArgument event for this parameter.
8286 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8287   if (!ParamD)
8288     return;
8289 
8290   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8291 
8292   // If this parameter has an unparsed default argument, clear it out
8293   // to make way for the parsed default argument.
8294   if (Param->hasUnparsedDefaultArg())
8295     Param->setDefaultArg(nullptr);
8296 
8297   S->AddDecl(Param);
8298   if (Param->getDeclName())
8299     IdResolver.AddDecl(Param);
8300 }
8301 
8302 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8303 /// processing the delayed method declaration for Method. The method
8304 /// declaration is now considered finished. There may be a separate
8305 /// ActOnStartOfFunctionDef action later (not necessarily
8306 /// immediately!) for this method, if it was also defined inside the
8307 /// class body.
8308 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8309   if (!MethodD)
8310     return;
8311 
8312   AdjustDeclIfTemplate(MethodD);
8313 
8314   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8315 
8316   // Now that we have our default arguments, check the constructor
8317   // again. It could produce additional diagnostics or affect whether
8318   // the class has implicitly-declared destructors, among other
8319   // things.
8320   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8321     CheckConstructor(Constructor);
8322 
8323   // Check the default arguments, which we may have added.
8324   if (!Method->isInvalidDecl())
8325     CheckCXXDefaultArguments(Method);
8326 }
8327 
8328 // Emit the given diagnostic for each non-address-space qualifier.
8329 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8330 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8331   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8332   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8333     bool DiagOccured = false;
8334     FTI.MethodQualifiers->forEachQualifier(
8335         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8336                                    SourceLocation SL) {
8337           // This diagnostic should be emitted on any qualifier except an addr
8338           // space qualifier. However, forEachQualifier currently doesn't visit
8339           // addr space qualifiers, so there's no way to write this condition
8340           // right now; we just diagnose on everything.
8341           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8342           DiagOccured = true;
8343         });
8344     if (DiagOccured)
8345       D.setInvalidType();
8346   }
8347 }
8348 
8349 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8350 /// the well-formedness of the constructor declarator @p D with type @p
8351 /// R. If there are any errors in the declarator, this routine will
8352 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8353 /// will be updated to reflect a well-formed type for the constructor and
8354 /// returned.
8355 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8356                                           StorageClass &SC) {
8357   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8358 
8359   // C++ [class.ctor]p3:
8360   //   A constructor shall not be virtual (10.3) or static (9.4). A
8361   //   constructor can be invoked for a const, volatile or const
8362   //   volatile object. A constructor shall not be declared const,
8363   //   volatile, or const volatile (9.3.2).
8364   if (isVirtual) {
8365     if (!D.isInvalidType())
8366       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8367         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8368         << SourceRange(D.getIdentifierLoc());
8369     D.setInvalidType();
8370   }
8371   if (SC == SC_Static) {
8372     if (!D.isInvalidType())
8373       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8374         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8375         << SourceRange(D.getIdentifierLoc());
8376     D.setInvalidType();
8377     SC = SC_None;
8378   }
8379 
8380   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8381     diagnoseIgnoredQualifiers(
8382         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8383         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8384         D.getDeclSpec().getRestrictSpecLoc(),
8385         D.getDeclSpec().getAtomicSpecLoc());
8386     D.setInvalidType();
8387   }
8388 
8389   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8390 
8391   // C++0x [class.ctor]p4:
8392   //   A constructor shall not be declared with a ref-qualifier.
8393   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8394   if (FTI.hasRefQualifier()) {
8395     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8396       << FTI.RefQualifierIsLValueRef
8397       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8398     D.setInvalidType();
8399   }
8400 
8401   // Rebuild the function type "R" without any type qualifiers (in
8402   // case any of the errors above fired) and with "void" as the
8403   // return type, since constructors don't have return types.
8404   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8405   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8406     return R;
8407 
8408   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8409   EPI.TypeQuals = Qualifiers();
8410   EPI.RefQualifier = RQ_None;
8411 
8412   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8413 }
8414 
8415 /// CheckConstructor - Checks a fully-formed constructor for
8416 /// well-formedness, issuing any diagnostics required. Returns true if
8417 /// the constructor declarator is invalid.
8418 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8419   CXXRecordDecl *ClassDecl
8420     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8421   if (!ClassDecl)
8422     return Constructor->setInvalidDecl();
8423 
8424   // C++ [class.copy]p3:
8425   //   A declaration of a constructor for a class X is ill-formed if
8426   //   its first parameter is of type (optionally cv-qualified) X and
8427   //   either there are no other parameters or else all other
8428   //   parameters have default arguments.
8429   if (!Constructor->isInvalidDecl() &&
8430       ((Constructor->getNumParams() == 1) ||
8431        (Constructor->getNumParams() > 1 &&
8432         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8433       Constructor->getTemplateSpecializationKind()
8434                                               != TSK_ImplicitInstantiation) {
8435     QualType ParamType = Constructor->getParamDecl(0)->getType();
8436     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8437     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8438       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8439       const char *ConstRef
8440         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8441                                                         : " const &";
8442       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8443         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8444 
8445       // FIXME: Rather that making the constructor invalid, we should endeavor
8446       // to fix the type.
8447       Constructor->setInvalidDecl();
8448     }
8449   }
8450 }
8451 
8452 /// CheckDestructor - Checks a fully-formed destructor definition for
8453 /// well-formedness, issuing any diagnostics required.  Returns true
8454 /// on error.
8455 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8456   CXXRecordDecl *RD = Destructor->getParent();
8457 
8458   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8459     SourceLocation Loc;
8460 
8461     if (!Destructor->isImplicit())
8462       Loc = Destructor->getLocation();
8463     else
8464       Loc = RD->getLocation();
8465 
8466     // If we have a virtual destructor, look up the deallocation function
8467     if (FunctionDecl *OperatorDelete =
8468             FindDeallocationFunctionForDestructor(Loc, RD)) {
8469       Expr *ThisArg = nullptr;
8470 
8471       // If the notional 'delete this' expression requires a non-trivial
8472       // conversion from 'this' to the type of a destroying operator delete's
8473       // first parameter, perform that conversion now.
8474       if (OperatorDelete->isDestroyingOperatorDelete()) {
8475         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8476         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8477           // C++ [class.dtor]p13:
8478           //   ... as if for the expression 'delete this' appearing in a
8479           //   non-virtual destructor of the destructor's class.
8480           ContextRAII SwitchContext(*this, Destructor);
8481           ExprResult This =
8482               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8483           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8484           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8485           if (This.isInvalid()) {
8486             // FIXME: Register this as a context note so that it comes out
8487             // in the right order.
8488             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8489             return true;
8490           }
8491           ThisArg = This.get();
8492         }
8493       }
8494 
8495       DiagnoseUseOfDecl(OperatorDelete, Loc);
8496       MarkFunctionReferenced(Loc, OperatorDelete);
8497       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8498     }
8499   }
8500 
8501   return false;
8502 }
8503 
8504 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8505 /// the well-formednes of the destructor declarator @p D with type @p
8506 /// R. If there are any errors in the declarator, this routine will
8507 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8508 /// will be updated to reflect a well-formed type for the destructor and
8509 /// returned.
8510 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8511                                          StorageClass& SC) {
8512   // C++ [class.dtor]p1:
8513   //   [...] A typedef-name that names a class is a class-name
8514   //   (7.1.3); however, a typedef-name that names a class shall not
8515   //   be used as the identifier in the declarator for a destructor
8516   //   declaration.
8517   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8518   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8519     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8520       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8521   else if (const TemplateSpecializationType *TST =
8522              DeclaratorType->getAs<TemplateSpecializationType>())
8523     if (TST->isTypeAlias())
8524       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8525         << DeclaratorType << 1;
8526 
8527   // C++ [class.dtor]p2:
8528   //   A destructor is used to destroy objects of its class type. A
8529   //   destructor takes no parameters, and no return type can be
8530   //   specified for it (not even void). The address of a destructor
8531   //   shall not be taken. A destructor shall not be static. A
8532   //   destructor can be invoked for a const, volatile or const
8533   //   volatile object. A destructor shall not be declared const,
8534   //   volatile or const volatile (9.3.2).
8535   if (SC == SC_Static) {
8536     if (!D.isInvalidType())
8537       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8538         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8539         << SourceRange(D.getIdentifierLoc())
8540         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8541 
8542     SC = SC_None;
8543   }
8544   if (!D.isInvalidType()) {
8545     // Destructors don't have return types, but the parser will
8546     // happily parse something like:
8547     //
8548     //   class X {
8549     //     float ~X();
8550     //   };
8551     //
8552     // The return type will be eliminated later.
8553     if (D.getDeclSpec().hasTypeSpecifier())
8554       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8555         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8556         << SourceRange(D.getIdentifierLoc());
8557     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8558       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8559                                 SourceLocation(),
8560                                 D.getDeclSpec().getConstSpecLoc(),
8561                                 D.getDeclSpec().getVolatileSpecLoc(),
8562                                 D.getDeclSpec().getRestrictSpecLoc(),
8563                                 D.getDeclSpec().getAtomicSpecLoc());
8564       D.setInvalidType();
8565     }
8566   }
8567 
8568   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8569 
8570   // C++0x [class.dtor]p2:
8571   //   A destructor shall not be declared with a ref-qualifier.
8572   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8573   if (FTI.hasRefQualifier()) {
8574     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8575       << FTI.RefQualifierIsLValueRef
8576       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8577     D.setInvalidType();
8578   }
8579 
8580   // Make sure we don't have any parameters.
8581   if (FTIHasNonVoidParameters(FTI)) {
8582     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8583 
8584     // Delete the parameters.
8585     FTI.freeParams();
8586     D.setInvalidType();
8587   }
8588 
8589   // Make sure the destructor isn't variadic.
8590   if (FTI.isVariadic) {
8591     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8592     D.setInvalidType();
8593   }
8594 
8595   // Rebuild the function type "R" without any type qualifiers or
8596   // parameters (in case any of the errors above fired) and with
8597   // "void" as the return type, since destructors don't have return
8598   // types.
8599   if (!D.isInvalidType())
8600     return R;
8601 
8602   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8603   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8604   EPI.Variadic = false;
8605   EPI.TypeQuals = Qualifiers();
8606   EPI.RefQualifier = RQ_None;
8607   return Context.getFunctionType(Context.VoidTy, None, EPI);
8608 }
8609 
8610 static void extendLeft(SourceRange &R, SourceRange Before) {
8611   if (Before.isInvalid())
8612     return;
8613   R.setBegin(Before.getBegin());
8614   if (R.getEnd().isInvalid())
8615     R.setEnd(Before.getEnd());
8616 }
8617 
8618 static void extendRight(SourceRange &R, SourceRange After) {
8619   if (After.isInvalid())
8620     return;
8621   if (R.getBegin().isInvalid())
8622     R.setBegin(After.getBegin());
8623   R.setEnd(After.getEnd());
8624 }
8625 
8626 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8627 /// well-formednes of the conversion function declarator @p D with
8628 /// type @p R. If there are any errors in the declarator, this routine
8629 /// will emit diagnostics and return true. Otherwise, it will return
8630 /// false. Either way, the type @p R will be updated to reflect a
8631 /// well-formed type for the conversion operator.
8632 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8633                                      StorageClass& SC) {
8634   // C++ [class.conv.fct]p1:
8635   //   Neither parameter types nor return type can be specified. The
8636   //   type of a conversion function (8.3.5) is "function taking no
8637   //   parameter returning conversion-type-id."
8638   if (SC == SC_Static) {
8639     if (!D.isInvalidType())
8640       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8641         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8642         << D.getName().getSourceRange();
8643     D.setInvalidType();
8644     SC = SC_None;
8645   }
8646 
8647   TypeSourceInfo *ConvTSI = nullptr;
8648   QualType ConvType =
8649       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8650 
8651   const DeclSpec &DS = D.getDeclSpec();
8652   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8653     // Conversion functions don't have return types, but the parser will
8654     // happily parse something like:
8655     //
8656     //   class X {
8657     //     float operator bool();
8658     //   };
8659     //
8660     // The return type will be changed later anyway.
8661     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8662       << SourceRange(DS.getTypeSpecTypeLoc())
8663       << SourceRange(D.getIdentifierLoc());
8664     D.setInvalidType();
8665   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8666     // It's also plausible that the user writes type qualifiers in the wrong
8667     // place, such as:
8668     //   struct S { const operator int(); };
8669     // FIXME: we could provide a fixit to move the qualifiers onto the
8670     // conversion type.
8671     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8672         << SourceRange(D.getIdentifierLoc()) << 0;
8673     D.setInvalidType();
8674   }
8675 
8676   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8677 
8678   // Make sure we don't have any parameters.
8679   if (Proto->getNumParams() > 0) {
8680     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8681 
8682     // Delete the parameters.
8683     D.getFunctionTypeInfo().freeParams();
8684     D.setInvalidType();
8685   } else if (Proto->isVariadic()) {
8686     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8687     D.setInvalidType();
8688   }
8689 
8690   // Diagnose "&operator bool()" and other such nonsense.  This
8691   // is actually a gcc extension which we don't support.
8692   if (Proto->getReturnType() != ConvType) {
8693     bool NeedsTypedef = false;
8694     SourceRange Before, After;
8695 
8696     // Walk the chunks and extract information on them for our diagnostic.
8697     bool PastFunctionChunk = false;
8698     for (auto &Chunk : D.type_objects()) {
8699       switch (Chunk.Kind) {
8700       case DeclaratorChunk::Function:
8701         if (!PastFunctionChunk) {
8702           if (Chunk.Fun.HasTrailingReturnType) {
8703             TypeSourceInfo *TRT = nullptr;
8704             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8705             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8706           }
8707           PastFunctionChunk = true;
8708           break;
8709         }
8710         LLVM_FALLTHROUGH;
8711       case DeclaratorChunk::Array:
8712         NeedsTypedef = true;
8713         extendRight(After, Chunk.getSourceRange());
8714         break;
8715 
8716       case DeclaratorChunk::Pointer:
8717       case DeclaratorChunk::BlockPointer:
8718       case DeclaratorChunk::Reference:
8719       case DeclaratorChunk::MemberPointer:
8720       case DeclaratorChunk::Pipe:
8721         extendLeft(Before, Chunk.getSourceRange());
8722         break;
8723 
8724       case DeclaratorChunk::Paren:
8725         extendLeft(Before, Chunk.Loc);
8726         extendRight(After, Chunk.EndLoc);
8727         break;
8728       }
8729     }
8730 
8731     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8732                          After.isValid()  ? After.getBegin() :
8733                                             D.getIdentifierLoc();
8734     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8735     DB << Before << After;
8736 
8737     if (!NeedsTypedef) {
8738       DB << /*don't need a typedef*/0;
8739 
8740       // If we can provide a correct fix-it hint, do so.
8741       if (After.isInvalid() && ConvTSI) {
8742         SourceLocation InsertLoc =
8743             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8744         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8745            << FixItHint::CreateInsertionFromRange(
8746                   InsertLoc, CharSourceRange::getTokenRange(Before))
8747            << FixItHint::CreateRemoval(Before);
8748       }
8749     } else if (!Proto->getReturnType()->isDependentType()) {
8750       DB << /*typedef*/1 << Proto->getReturnType();
8751     } else if (getLangOpts().CPlusPlus11) {
8752       DB << /*alias template*/2 << Proto->getReturnType();
8753     } else {
8754       DB << /*might not be fixable*/3;
8755     }
8756 
8757     // Recover by incorporating the other type chunks into the result type.
8758     // Note, this does *not* change the name of the function. This is compatible
8759     // with the GCC extension:
8760     //   struct S { &operator int(); } s;
8761     //   int &r = s.operator int(); // ok in GCC
8762     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8763     ConvType = Proto->getReturnType();
8764   }
8765 
8766   // C++ [class.conv.fct]p4:
8767   //   The conversion-type-id shall not represent a function type nor
8768   //   an array type.
8769   if (ConvType->isArrayType()) {
8770     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8771     ConvType = Context.getPointerType(ConvType);
8772     D.setInvalidType();
8773   } else if (ConvType->isFunctionType()) {
8774     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8775     ConvType = Context.getPointerType(ConvType);
8776     D.setInvalidType();
8777   }
8778 
8779   // Rebuild the function type "R" without any parameters (in case any
8780   // of the errors above fired) and with the conversion type as the
8781   // return type.
8782   if (D.isInvalidType())
8783     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8784 
8785   // C++0x explicit conversion operators.
8786   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8787     Diag(DS.getExplicitSpecLoc(),
8788          getLangOpts().CPlusPlus11
8789              ? diag::warn_cxx98_compat_explicit_conversion_functions
8790              : diag::ext_explicit_conversion_functions)
8791         << SourceRange(DS.getExplicitSpecRange());
8792 }
8793 
8794 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8795 /// the declaration of the given C++ conversion function. This routine
8796 /// is responsible for recording the conversion function in the C++
8797 /// class, if possible.
8798 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8799   assert(Conversion && "Expected to receive a conversion function declaration");
8800 
8801   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8802 
8803   // Make sure we aren't redeclaring the conversion function.
8804   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8805 
8806   // C++ [class.conv.fct]p1:
8807   //   [...] A conversion function is never used to convert a
8808   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8809   //   same object type (or a reference to it), to a (possibly
8810   //   cv-qualified) base class of that type (or a reference to it),
8811   //   or to (possibly cv-qualified) void.
8812   // FIXME: Suppress this warning if the conversion function ends up being a
8813   // virtual function that overrides a virtual function in a base class.
8814   QualType ClassType
8815     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8816   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8817     ConvType = ConvTypeRef->getPointeeType();
8818   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8819       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8820     /* Suppress diagnostics for instantiations. */;
8821   else if (ConvType->isRecordType()) {
8822     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8823     if (ConvType == ClassType)
8824       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8825         << ClassType;
8826     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8827       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8828         <<  ClassType << ConvType;
8829   } else if (ConvType->isVoidType()) {
8830     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8831       << ClassType << ConvType;
8832   }
8833 
8834   if (FunctionTemplateDecl *ConversionTemplate
8835                                 = Conversion->getDescribedFunctionTemplate())
8836     return ConversionTemplate;
8837 
8838   return Conversion;
8839 }
8840 
8841 namespace {
8842 /// Utility class to accumulate and print a diagnostic listing the invalid
8843 /// specifier(s) on a declaration.
8844 struct BadSpecifierDiagnoser {
8845   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8846       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8847   ~BadSpecifierDiagnoser() {
8848     Diagnostic << Specifiers;
8849   }
8850 
8851   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8852     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8853   }
8854   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8855     return check(SpecLoc,
8856                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8857   }
8858   void check(SourceLocation SpecLoc, const char *Spec) {
8859     if (SpecLoc.isInvalid()) return;
8860     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8861     if (!Specifiers.empty()) Specifiers += " ";
8862     Specifiers += Spec;
8863   }
8864 
8865   Sema &S;
8866   Sema::SemaDiagnosticBuilder Diagnostic;
8867   std::string Specifiers;
8868 };
8869 }
8870 
8871 /// Check the validity of a declarator that we parsed for a deduction-guide.
8872 /// These aren't actually declarators in the grammar, so we need to check that
8873 /// the user didn't specify any pieces that are not part of the deduction-guide
8874 /// grammar.
8875 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8876                                          StorageClass &SC) {
8877   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8878   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8879   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8880 
8881   // C++ [temp.deduct.guide]p3:
8882   //   A deduction-gide shall be declared in the same scope as the
8883   //   corresponding class template.
8884   if (!CurContext->getRedeclContext()->Equals(
8885           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8886     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8887       << GuidedTemplateDecl;
8888     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8889   }
8890 
8891   auto &DS = D.getMutableDeclSpec();
8892   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8893   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8894       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8895       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8896     BadSpecifierDiagnoser Diagnoser(
8897         *this, D.getIdentifierLoc(),
8898         diag::err_deduction_guide_invalid_specifier);
8899 
8900     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8901     DS.ClearStorageClassSpecs();
8902     SC = SC_None;
8903 
8904     // 'explicit' is permitted.
8905     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8906     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8907     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8908     DS.ClearConstexprSpec();
8909 
8910     Diagnoser.check(DS.getConstSpecLoc(), "const");
8911     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8912     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8913     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8914     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8915     DS.ClearTypeQualifiers();
8916 
8917     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8918     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8919     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8920     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8921     DS.ClearTypeSpecType();
8922   }
8923 
8924   if (D.isInvalidType())
8925     return;
8926 
8927   // Check the declarator is simple enough.
8928   bool FoundFunction = false;
8929   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8930     if (Chunk.Kind == DeclaratorChunk::Paren)
8931       continue;
8932     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8933       Diag(D.getDeclSpec().getBeginLoc(),
8934            diag::err_deduction_guide_with_complex_decl)
8935           << D.getSourceRange();
8936       break;
8937     }
8938     if (!Chunk.Fun.hasTrailingReturnType()) {
8939       Diag(D.getName().getBeginLoc(),
8940            diag::err_deduction_guide_no_trailing_return_type);
8941       break;
8942     }
8943 
8944     // Check that the return type is written as a specialization of
8945     // the template specified as the deduction-guide's name.
8946     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8947     TypeSourceInfo *TSI = nullptr;
8948     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8949     assert(TSI && "deduction guide has valid type but invalid return type?");
8950     bool AcceptableReturnType = false;
8951     bool MightInstantiateToSpecialization = false;
8952     if (auto RetTST =
8953             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8954       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8955       bool TemplateMatches =
8956           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8957       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8958         AcceptableReturnType = true;
8959       else {
8960         // This could still instantiate to the right type, unless we know it
8961         // names the wrong class template.
8962         auto *TD = SpecifiedName.getAsTemplateDecl();
8963         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8964                                              !TemplateMatches);
8965       }
8966     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8967       MightInstantiateToSpecialization = true;
8968     }
8969 
8970     if (!AcceptableReturnType) {
8971       Diag(TSI->getTypeLoc().getBeginLoc(),
8972            diag::err_deduction_guide_bad_trailing_return_type)
8973           << GuidedTemplate << TSI->getType()
8974           << MightInstantiateToSpecialization
8975           << TSI->getTypeLoc().getSourceRange();
8976     }
8977 
8978     // Keep going to check that we don't have any inner declarator pieces (we
8979     // could still have a function returning a pointer to a function).
8980     FoundFunction = true;
8981   }
8982 
8983   if (D.isFunctionDefinition())
8984     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8985 }
8986 
8987 //===----------------------------------------------------------------------===//
8988 // Namespace Handling
8989 //===----------------------------------------------------------------------===//
8990 
8991 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8992 /// reopened.
8993 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8994                                             SourceLocation Loc,
8995                                             IdentifierInfo *II, bool *IsInline,
8996                                             NamespaceDecl *PrevNS) {
8997   assert(*IsInline != PrevNS->isInline());
8998 
8999   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
9000   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
9001   // inline namespaces, with the intention of bringing names into namespace std.
9002   //
9003   // We support this just well enough to get that case working; this is not
9004   // sufficient to support reopening namespaces as inline in general.
9005   if (*IsInline && II && II->getName().startswith("__atomic") &&
9006       S.getSourceManager().isInSystemHeader(Loc)) {
9007     // Mark all prior declarations of the namespace as inline.
9008     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
9009          NS = NS->getPreviousDecl())
9010       NS->setInline(*IsInline);
9011     // Patch up the lookup table for the containing namespace. This isn't really
9012     // correct, but it's good enough for this particular case.
9013     for (auto *I : PrevNS->decls())
9014       if (auto *ND = dyn_cast<NamedDecl>(I))
9015         PrevNS->getParent()->makeDeclVisibleInContext(ND);
9016     return;
9017   }
9018 
9019   if (PrevNS->isInline())
9020     // The user probably just forgot the 'inline', so suggest that it
9021     // be added back.
9022     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
9023       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
9024   else
9025     S.Diag(Loc, diag::err_inline_namespace_mismatch);
9026 
9027   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
9028   *IsInline = PrevNS->isInline();
9029 }
9030 
9031 /// ActOnStartNamespaceDef - This is called at the start of a namespace
9032 /// definition.
9033 Decl *Sema::ActOnStartNamespaceDef(
9034     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
9035     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
9036     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
9037   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
9038   // For anonymous namespace, take the location of the left brace.
9039   SourceLocation Loc = II ? IdentLoc : LBrace;
9040   bool IsInline = InlineLoc.isValid();
9041   bool IsInvalid = false;
9042   bool IsStd = false;
9043   bool AddToKnown = false;
9044   Scope *DeclRegionScope = NamespcScope->getParent();
9045 
9046   NamespaceDecl *PrevNS = nullptr;
9047   if (II) {
9048     // C++ [namespace.def]p2:
9049     //   The identifier in an original-namespace-definition shall not
9050     //   have been previously defined in the declarative region in
9051     //   which the original-namespace-definition appears. The
9052     //   identifier in an original-namespace-definition is the name of
9053     //   the namespace. Subsequently in that declarative region, it is
9054     //   treated as an original-namespace-name.
9055     //
9056     // Since namespace names are unique in their scope, and we don't
9057     // look through using directives, just look for any ordinary names
9058     // as if by qualified name lookup.
9059     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
9060                    ForExternalRedeclaration);
9061     LookupQualifiedName(R, CurContext->getRedeclContext());
9062     NamedDecl *PrevDecl =
9063         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
9064     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
9065 
9066     if (PrevNS) {
9067       // This is an extended namespace definition.
9068       if (IsInline != PrevNS->isInline())
9069         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
9070                                         &IsInline, PrevNS);
9071     } else if (PrevDecl) {
9072       // This is an invalid name redefinition.
9073       Diag(Loc, diag::err_redefinition_different_kind)
9074         << II;
9075       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9076       IsInvalid = true;
9077       // Continue on to push Namespc as current DeclContext and return it.
9078     } else if (II->isStr("std") &&
9079                CurContext->getRedeclContext()->isTranslationUnit()) {
9080       // This is the first "real" definition of the namespace "std", so update
9081       // our cache of the "std" namespace to point at this definition.
9082       PrevNS = getStdNamespace();
9083       IsStd = true;
9084       AddToKnown = !IsInline;
9085     } else {
9086       // We've seen this namespace for the first time.
9087       AddToKnown = !IsInline;
9088     }
9089   } else {
9090     // Anonymous namespaces.
9091 
9092     // Determine whether the parent already has an anonymous namespace.
9093     DeclContext *Parent = CurContext->getRedeclContext();
9094     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9095       PrevNS = TU->getAnonymousNamespace();
9096     } else {
9097       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
9098       PrevNS = ND->getAnonymousNamespace();
9099     }
9100 
9101     if (PrevNS && IsInline != PrevNS->isInline())
9102       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
9103                                       &IsInline, PrevNS);
9104   }
9105 
9106   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
9107                                                  StartLoc, Loc, II, PrevNS);
9108   if (IsInvalid)
9109     Namespc->setInvalidDecl();
9110 
9111   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
9112   AddPragmaAttributes(DeclRegionScope, Namespc);
9113 
9114   // FIXME: Should we be merging attributes?
9115   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
9116     PushNamespaceVisibilityAttr(Attr, Loc);
9117 
9118   if (IsStd)
9119     StdNamespace = Namespc;
9120   if (AddToKnown)
9121     KnownNamespaces[Namespc] = false;
9122 
9123   if (II) {
9124     PushOnScopeChains(Namespc, DeclRegionScope);
9125   } else {
9126     // Link the anonymous namespace into its parent.
9127     DeclContext *Parent = CurContext->getRedeclContext();
9128     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9129       TU->setAnonymousNamespace(Namespc);
9130     } else {
9131       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
9132     }
9133 
9134     CurContext->addDecl(Namespc);
9135 
9136     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
9137     //   behaves as if it were replaced by
9138     //     namespace unique { /* empty body */ }
9139     //     using namespace unique;
9140     //     namespace unique { namespace-body }
9141     //   where all occurrences of 'unique' in a translation unit are
9142     //   replaced by the same identifier and this identifier differs
9143     //   from all other identifiers in the entire program.
9144 
9145     // We just create the namespace with an empty name and then add an
9146     // implicit using declaration, just like the standard suggests.
9147     //
9148     // CodeGen enforces the "universally unique" aspect by giving all
9149     // declarations semantically contained within an anonymous
9150     // namespace internal linkage.
9151 
9152     if (!PrevNS) {
9153       UD = UsingDirectiveDecl::Create(Context, Parent,
9154                                       /* 'using' */ LBrace,
9155                                       /* 'namespace' */ SourceLocation(),
9156                                       /* qualifier */ NestedNameSpecifierLoc(),
9157                                       /* identifier */ SourceLocation(),
9158                                       Namespc,
9159                                       /* Ancestor */ Parent);
9160       UD->setImplicit();
9161       Parent->addDecl(UD);
9162     }
9163   }
9164 
9165   ActOnDocumentableDecl(Namespc);
9166 
9167   // Although we could have an invalid decl (i.e. the namespace name is a
9168   // redefinition), push it as current DeclContext and try to continue parsing.
9169   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9170   // for the namespace has the declarations that showed up in that particular
9171   // namespace definition.
9172   PushDeclContext(NamespcScope, Namespc);
9173   return Namespc;
9174 }
9175 
9176 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9177 /// is a namespace alias, returns the namespace it points to.
9178 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9179   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9180     return AD->getNamespace();
9181   return dyn_cast_or_null<NamespaceDecl>(D);
9182 }
9183 
9184 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9185 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9186 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9187   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9188   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9189   Namespc->setRBraceLoc(RBrace);
9190   PopDeclContext();
9191   if (Namespc->hasAttr<VisibilityAttr>())
9192     PopPragmaVisibility(true, RBrace);
9193   // If this namespace contains an export-declaration, export it now.
9194   if (DeferredExportedNamespaces.erase(Namespc))
9195     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9196 }
9197 
9198 CXXRecordDecl *Sema::getStdBadAlloc() const {
9199   return cast_or_null<CXXRecordDecl>(
9200                                   StdBadAlloc.get(Context.getExternalSource()));
9201 }
9202 
9203 EnumDecl *Sema::getStdAlignValT() const {
9204   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9205 }
9206 
9207 NamespaceDecl *Sema::getStdNamespace() const {
9208   return cast_or_null<NamespaceDecl>(
9209                                  StdNamespace.get(Context.getExternalSource()));
9210 }
9211 
9212 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9213   if (!StdExperimentalNamespaceCache) {
9214     if (auto Std = getStdNamespace()) {
9215       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9216                           SourceLocation(), LookupNamespaceName);
9217       if (!LookupQualifiedName(Result, Std) ||
9218           !(StdExperimentalNamespaceCache =
9219                 Result.getAsSingle<NamespaceDecl>()))
9220         Result.suppressDiagnostics();
9221     }
9222   }
9223   return StdExperimentalNamespaceCache;
9224 }
9225 
9226 namespace {
9227 
9228 enum UnsupportedSTLSelect {
9229   USS_InvalidMember,
9230   USS_MissingMember,
9231   USS_NonTrivial,
9232   USS_Other
9233 };
9234 
9235 struct InvalidSTLDiagnoser {
9236   Sema &S;
9237   SourceLocation Loc;
9238   QualType TyForDiags;
9239 
9240   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9241                       const VarDecl *VD = nullptr) {
9242     {
9243       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9244                << TyForDiags << ((int)Sel);
9245       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9246         assert(!Name.empty());
9247         D << Name;
9248       }
9249     }
9250     if (Sel == USS_InvalidMember) {
9251       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9252           << VD << VD->getSourceRange();
9253     }
9254     return QualType();
9255   }
9256 };
9257 } // namespace
9258 
9259 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9260                                            SourceLocation Loc) {
9261   assert(getLangOpts().CPlusPlus &&
9262          "Looking for comparison category type outside of C++.");
9263 
9264   // Check if we've already successfully checked the comparison category type
9265   // before. If so, skip checking it again.
9266   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9267   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9268     return Info->getType();
9269 
9270   // If lookup failed
9271   if (!Info) {
9272     std::string NameForDiags = "std::";
9273     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9274     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9275         << NameForDiags;
9276     return QualType();
9277   }
9278 
9279   assert(Info->Kind == Kind);
9280   assert(Info->Record);
9281 
9282   // Update the Record decl in case we encountered a forward declaration on our
9283   // first pass. FIXME: This is a bit of a hack.
9284   if (Info->Record->hasDefinition())
9285     Info->Record = Info->Record->getDefinition();
9286 
9287   // Use an elaborated type for diagnostics which has a name containing the
9288   // prepended 'std' namespace but not any inline namespace names.
9289   QualType TyForDiags = [&]() {
9290     auto *NNS =
9291         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9292     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9293   }();
9294 
9295   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9296     return QualType();
9297 
9298   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9299 
9300   if (!Info->Record->isTriviallyCopyable())
9301     return UnsupportedSTLError(USS_NonTrivial);
9302 
9303   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9304     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9305     // Tolerate empty base classes.
9306     if (Base->isEmpty())
9307       continue;
9308     // Reject STL implementations which have at least one non-empty base.
9309     return UnsupportedSTLError();
9310   }
9311 
9312   // Check that the STL has implemented the types using a single integer field.
9313   // This expectation allows better codegen for builtin operators. We require:
9314   //   (1) The class has exactly one field.
9315   //   (2) The field is an integral or enumeration type.
9316   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9317   if (std::distance(FIt, FEnd) != 1 ||
9318       !FIt->getType()->isIntegralOrEnumerationType()) {
9319     return UnsupportedSTLError();
9320   }
9321 
9322   // Build each of the require values and store them in Info.
9323   for (ComparisonCategoryResult CCR :
9324        ComparisonCategories::getPossibleResultsForType(Kind)) {
9325     StringRef MemName = ComparisonCategories::getResultString(CCR);
9326     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9327 
9328     if (!ValInfo)
9329       return UnsupportedSTLError(USS_MissingMember, MemName);
9330 
9331     VarDecl *VD = ValInfo->VD;
9332     assert(VD && "should not be null!");
9333 
9334     // Attempt to diagnose reasons why the STL definition of this type
9335     // might be foobar, including it failing to be a constant expression.
9336     // TODO Handle more ways the lookup or result can be invalid.
9337     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9338         !VD->checkInitIsICE())
9339       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9340 
9341     // Attempt to evaluate the var decl as a constant expression and extract
9342     // the value of its first field as a ICE. If this fails, the STL
9343     // implementation is not supported.
9344     if (!ValInfo->hasValidIntValue())
9345       return UnsupportedSTLError();
9346 
9347     MarkVariableReferenced(Loc, VD);
9348   }
9349 
9350   // We've successfully built the required types and expressions. Update
9351   // the cache and return the newly cached value.
9352   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9353   return Info->getType();
9354 }
9355 
9356 /// Retrieve the special "std" namespace, which may require us to
9357 /// implicitly define the namespace.
9358 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9359   if (!StdNamespace) {
9360     // The "std" namespace has not yet been defined, so build one implicitly.
9361     StdNamespace = NamespaceDecl::Create(Context,
9362                                          Context.getTranslationUnitDecl(),
9363                                          /*Inline=*/false,
9364                                          SourceLocation(), SourceLocation(),
9365                                          &PP.getIdentifierTable().get("std"),
9366                                          /*PrevDecl=*/nullptr);
9367     getStdNamespace()->setImplicit(true);
9368   }
9369 
9370   return getStdNamespace();
9371 }
9372 
9373 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9374   assert(getLangOpts().CPlusPlus &&
9375          "Looking for std::initializer_list outside of C++.");
9376 
9377   // We're looking for implicit instantiations of
9378   // template <typename E> class std::initializer_list.
9379 
9380   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9381     return false;
9382 
9383   ClassTemplateDecl *Template = nullptr;
9384   const TemplateArgument *Arguments = nullptr;
9385 
9386   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9387 
9388     ClassTemplateSpecializationDecl *Specialization =
9389         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9390     if (!Specialization)
9391       return false;
9392 
9393     Template = Specialization->getSpecializedTemplate();
9394     Arguments = Specialization->getTemplateArgs().data();
9395   } else if (const TemplateSpecializationType *TST =
9396                  Ty->getAs<TemplateSpecializationType>()) {
9397     Template = dyn_cast_or_null<ClassTemplateDecl>(
9398         TST->getTemplateName().getAsTemplateDecl());
9399     Arguments = TST->getArgs();
9400   }
9401   if (!Template)
9402     return false;
9403 
9404   if (!StdInitializerList) {
9405     // Haven't recognized std::initializer_list yet, maybe this is it.
9406     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9407     if (TemplateClass->getIdentifier() !=
9408             &PP.getIdentifierTable().get("initializer_list") ||
9409         !getStdNamespace()->InEnclosingNamespaceSetOf(
9410             TemplateClass->getDeclContext()))
9411       return false;
9412     // This is a template called std::initializer_list, but is it the right
9413     // template?
9414     TemplateParameterList *Params = Template->getTemplateParameters();
9415     if (Params->getMinRequiredArguments() != 1)
9416       return false;
9417     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9418       return false;
9419 
9420     // It's the right template.
9421     StdInitializerList = Template;
9422   }
9423 
9424   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9425     return false;
9426 
9427   // This is an instance of std::initializer_list. Find the argument type.
9428   if (Element)
9429     *Element = Arguments[0].getAsType();
9430   return true;
9431 }
9432 
9433 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9434   NamespaceDecl *Std = S.getStdNamespace();
9435   if (!Std) {
9436     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9437     return nullptr;
9438   }
9439 
9440   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9441                       Loc, Sema::LookupOrdinaryName);
9442   if (!S.LookupQualifiedName(Result, Std)) {
9443     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9444     return nullptr;
9445   }
9446   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9447   if (!Template) {
9448     Result.suppressDiagnostics();
9449     // We found something weird. Complain about the first thing we found.
9450     NamedDecl *Found = *Result.begin();
9451     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9452     return nullptr;
9453   }
9454 
9455   // We found some template called std::initializer_list. Now verify that it's
9456   // correct.
9457   TemplateParameterList *Params = Template->getTemplateParameters();
9458   if (Params->getMinRequiredArguments() != 1 ||
9459       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9460     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9461     return nullptr;
9462   }
9463 
9464   return Template;
9465 }
9466 
9467 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9468   if (!StdInitializerList) {
9469     StdInitializerList = LookupStdInitializerList(*this, Loc);
9470     if (!StdInitializerList)
9471       return QualType();
9472   }
9473 
9474   TemplateArgumentListInfo Args(Loc, Loc);
9475   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9476                                        Context.getTrivialTypeSourceInfo(Element,
9477                                                                         Loc)));
9478   return Context.getCanonicalType(
9479       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9480 }
9481 
9482 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9483   // C++ [dcl.init.list]p2:
9484   //   A constructor is an initializer-list constructor if its first parameter
9485   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9486   //   std::initializer_list<E> for some type E, and either there are no other
9487   //   parameters or else all other parameters have default arguments.
9488   if (Ctor->getNumParams() < 1 ||
9489       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9490     return false;
9491 
9492   QualType ArgType = Ctor->getParamDecl(0)->getType();
9493   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9494     ArgType = RT->getPointeeType().getUnqualifiedType();
9495 
9496   return isStdInitializerList(ArgType, nullptr);
9497 }
9498 
9499 /// Determine whether a using statement is in a context where it will be
9500 /// apply in all contexts.
9501 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9502   switch (CurContext->getDeclKind()) {
9503     case Decl::TranslationUnit:
9504       return true;
9505     case Decl::LinkageSpec:
9506       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9507     default:
9508       return false;
9509   }
9510 }
9511 
9512 namespace {
9513 
9514 // Callback to only accept typo corrections that are namespaces.
9515 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9516 public:
9517   bool ValidateCandidate(const TypoCorrection &candidate) override {
9518     if (NamedDecl *ND = candidate.getCorrectionDecl())
9519       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9520     return false;
9521   }
9522 
9523   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9524     return std::make_unique<NamespaceValidatorCCC>(*this);
9525   }
9526 };
9527 
9528 }
9529 
9530 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9531                                        CXXScopeSpec &SS,
9532                                        SourceLocation IdentLoc,
9533                                        IdentifierInfo *Ident) {
9534   R.clear();
9535   NamespaceValidatorCCC CCC{};
9536   if (TypoCorrection Corrected =
9537           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9538                         Sema::CTK_ErrorRecovery)) {
9539     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9540       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9541       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9542                               Ident->getName().equals(CorrectedStr);
9543       S.diagnoseTypo(Corrected,
9544                      S.PDiag(diag::err_using_directive_member_suggest)
9545                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9546                      S.PDiag(diag::note_namespace_defined_here));
9547     } else {
9548       S.diagnoseTypo(Corrected,
9549                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9550                      S.PDiag(diag::note_namespace_defined_here));
9551     }
9552     R.addDecl(Corrected.getFoundDecl());
9553     return true;
9554   }
9555   return false;
9556 }
9557 
9558 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9559                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9560                                 SourceLocation IdentLoc,
9561                                 IdentifierInfo *NamespcName,
9562                                 const ParsedAttributesView &AttrList) {
9563   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9564   assert(NamespcName && "Invalid NamespcName.");
9565   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9566 
9567   // This can only happen along a recovery path.
9568   while (S->isTemplateParamScope())
9569     S = S->getParent();
9570   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9571 
9572   UsingDirectiveDecl *UDir = nullptr;
9573   NestedNameSpecifier *Qualifier = nullptr;
9574   if (SS.isSet())
9575     Qualifier = SS.getScopeRep();
9576 
9577   // Lookup namespace name.
9578   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9579   LookupParsedName(R, S, &SS);
9580   if (R.isAmbiguous())
9581     return nullptr;
9582 
9583   if (R.empty()) {
9584     R.clear();
9585     // Allow "using namespace std;" or "using namespace ::std;" even if
9586     // "std" hasn't been defined yet, for GCC compatibility.
9587     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9588         NamespcName->isStr("std")) {
9589       Diag(IdentLoc, diag::ext_using_undefined_std);
9590       R.addDecl(getOrCreateStdNamespace());
9591       R.resolveKind();
9592     }
9593     // Otherwise, attempt typo correction.
9594     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9595   }
9596 
9597   if (!R.empty()) {
9598     NamedDecl *Named = R.getRepresentativeDecl();
9599     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9600     assert(NS && "expected namespace decl");
9601 
9602     // The use of a nested name specifier may trigger deprecation warnings.
9603     DiagnoseUseOfDecl(Named, IdentLoc);
9604 
9605     // C++ [namespace.udir]p1:
9606     //   A using-directive specifies that the names in the nominated
9607     //   namespace can be used in the scope in which the
9608     //   using-directive appears after the using-directive. During
9609     //   unqualified name lookup (3.4.1), the names appear as if they
9610     //   were declared in the nearest enclosing namespace which
9611     //   contains both the using-directive and the nominated
9612     //   namespace. [Note: in this context, "contains" means "contains
9613     //   directly or indirectly". ]
9614 
9615     // Find enclosing context containing both using-directive and
9616     // nominated namespace.
9617     DeclContext *CommonAncestor = NS;
9618     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9619       CommonAncestor = CommonAncestor->getParent();
9620 
9621     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9622                                       SS.getWithLocInContext(Context),
9623                                       IdentLoc, Named, CommonAncestor);
9624 
9625     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9626         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9627       Diag(IdentLoc, diag::warn_using_directive_in_header);
9628     }
9629 
9630     PushUsingDirective(S, UDir);
9631   } else {
9632     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9633   }
9634 
9635   if (UDir)
9636     ProcessDeclAttributeList(S, UDir, AttrList);
9637 
9638   return UDir;
9639 }
9640 
9641 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9642   // If the scope has an associated entity and the using directive is at
9643   // namespace or translation unit scope, add the UsingDirectiveDecl into
9644   // its lookup structure so qualified name lookup can find it.
9645   DeclContext *Ctx = S->getEntity();
9646   if (Ctx && !Ctx->isFunctionOrMethod())
9647     Ctx->addDecl(UDir);
9648   else
9649     // Otherwise, it is at block scope. The using-directives will affect lookup
9650     // only to the end of the scope.
9651     S->PushUsingDirective(UDir);
9652 }
9653 
9654 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9655                                   SourceLocation UsingLoc,
9656                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9657                                   UnqualifiedId &Name,
9658                                   SourceLocation EllipsisLoc,
9659                                   const ParsedAttributesView &AttrList) {
9660   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9661 
9662   if (SS.isEmpty()) {
9663     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9664     return nullptr;
9665   }
9666 
9667   switch (Name.getKind()) {
9668   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9669   case UnqualifiedIdKind::IK_Identifier:
9670   case UnqualifiedIdKind::IK_OperatorFunctionId:
9671   case UnqualifiedIdKind::IK_LiteralOperatorId:
9672   case UnqualifiedIdKind::IK_ConversionFunctionId:
9673     break;
9674 
9675   case UnqualifiedIdKind::IK_ConstructorName:
9676   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9677     // C++11 inheriting constructors.
9678     Diag(Name.getBeginLoc(),
9679          getLangOpts().CPlusPlus11
9680              ? diag::warn_cxx98_compat_using_decl_constructor
9681              : diag::err_using_decl_constructor)
9682         << SS.getRange();
9683 
9684     if (getLangOpts().CPlusPlus11) break;
9685 
9686     return nullptr;
9687 
9688   case UnqualifiedIdKind::IK_DestructorName:
9689     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9690     return nullptr;
9691 
9692   case UnqualifiedIdKind::IK_TemplateId:
9693     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9694         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9695     return nullptr;
9696 
9697   case UnqualifiedIdKind::IK_DeductionGuideName:
9698     llvm_unreachable("cannot parse qualified deduction guide name");
9699   }
9700 
9701   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9702   DeclarationName TargetName = TargetNameInfo.getName();
9703   if (!TargetName)
9704     return nullptr;
9705 
9706   // Warn about access declarations.
9707   if (UsingLoc.isInvalid()) {
9708     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9709                                  ? diag::err_access_decl
9710                                  : diag::warn_access_decl_deprecated)
9711         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9712   }
9713 
9714   if (EllipsisLoc.isInvalid()) {
9715     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9716         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9717       return nullptr;
9718   } else {
9719     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9720         !TargetNameInfo.containsUnexpandedParameterPack()) {
9721       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9722         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9723       EllipsisLoc = SourceLocation();
9724     }
9725   }
9726 
9727   NamedDecl *UD =
9728       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9729                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9730                             /*IsInstantiation*/false);
9731   if (UD)
9732     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9733 
9734   return UD;
9735 }
9736 
9737 /// Determine whether a using declaration considers the given
9738 /// declarations as "equivalent", e.g., if they are redeclarations of
9739 /// the same entity or are both typedefs of the same type.
9740 static bool
9741 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9742   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9743     return true;
9744 
9745   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9746     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9747       return Context.hasSameType(TD1->getUnderlyingType(),
9748                                  TD2->getUnderlyingType());
9749 
9750   return false;
9751 }
9752 
9753 
9754 /// Determines whether to create a using shadow decl for a particular
9755 /// decl, given the set of decls existing prior to this using lookup.
9756 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9757                                 const LookupResult &Previous,
9758                                 UsingShadowDecl *&PrevShadow) {
9759   // Diagnose finding a decl which is not from a base class of the
9760   // current class.  We do this now because there are cases where this
9761   // function will silently decide not to build a shadow decl, which
9762   // will pre-empt further diagnostics.
9763   //
9764   // We don't need to do this in C++11 because we do the check once on
9765   // the qualifier.
9766   //
9767   // FIXME: diagnose the following if we care enough:
9768   //   struct A { int foo; };
9769   //   struct B : A { using A::foo; };
9770   //   template <class T> struct C : A {};
9771   //   template <class T> struct D : C<T> { using B::foo; } // <---
9772   // This is invalid (during instantiation) in C++03 because B::foo
9773   // resolves to the using decl in B, which is not a base class of D<T>.
9774   // We can't diagnose it immediately because C<T> is an unknown
9775   // specialization.  The UsingShadowDecl in D<T> then points directly
9776   // to A::foo, which will look well-formed when we instantiate.
9777   // The right solution is to not collapse the shadow-decl chain.
9778   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9779     DeclContext *OrigDC = Orig->getDeclContext();
9780 
9781     // Handle enums and anonymous structs.
9782     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9783     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9784     while (OrigRec->isAnonymousStructOrUnion())
9785       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9786 
9787     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9788       if (OrigDC == CurContext) {
9789         Diag(Using->getLocation(),
9790              diag::err_using_decl_nested_name_specifier_is_current_class)
9791           << Using->getQualifierLoc().getSourceRange();
9792         Diag(Orig->getLocation(), diag::note_using_decl_target);
9793         Using->setInvalidDecl();
9794         return true;
9795       }
9796 
9797       Diag(Using->getQualifierLoc().getBeginLoc(),
9798            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9799         << Using->getQualifier()
9800         << cast<CXXRecordDecl>(CurContext)
9801         << Using->getQualifierLoc().getSourceRange();
9802       Diag(Orig->getLocation(), diag::note_using_decl_target);
9803       Using->setInvalidDecl();
9804       return true;
9805     }
9806   }
9807 
9808   if (Previous.empty()) return false;
9809 
9810   NamedDecl *Target = Orig;
9811   if (isa<UsingShadowDecl>(Target))
9812     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9813 
9814   // If the target happens to be one of the previous declarations, we
9815   // don't have a conflict.
9816   //
9817   // FIXME: but we might be increasing its access, in which case we
9818   // should redeclare it.
9819   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9820   bool FoundEquivalentDecl = false;
9821   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9822          I != E; ++I) {
9823     NamedDecl *D = (*I)->getUnderlyingDecl();
9824     // We can have UsingDecls in our Previous results because we use the same
9825     // LookupResult for checking whether the UsingDecl itself is a valid
9826     // redeclaration.
9827     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9828       continue;
9829 
9830     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9831       // C++ [class.mem]p19:
9832       //   If T is the name of a class, then [every named member other than
9833       //   a non-static data member] shall have a name different from T
9834       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9835           !isa<IndirectFieldDecl>(Target) &&
9836           !isa<UnresolvedUsingValueDecl>(Target) &&
9837           DiagnoseClassNameShadow(
9838               CurContext,
9839               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9840         return true;
9841     }
9842 
9843     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9844       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9845         PrevShadow = Shadow;
9846       FoundEquivalentDecl = true;
9847     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9848       // We don't conflict with an existing using shadow decl of an equivalent
9849       // declaration, but we're not a redeclaration of it.
9850       FoundEquivalentDecl = true;
9851     }
9852 
9853     if (isVisible(D))
9854       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9855   }
9856 
9857   if (FoundEquivalentDecl)
9858     return false;
9859 
9860   if (FunctionDecl *FD = Target->getAsFunction()) {
9861     NamedDecl *OldDecl = nullptr;
9862     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9863                           /*IsForUsingDecl*/ true)) {
9864     case Ovl_Overload:
9865       return false;
9866 
9867     case Ovl_NonFunction:
9868       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9869       break;
9870 
9871     // We found a decl with the exact signature.
9872     case Ovl_Match:
9873       // If we're in a record, we want to hide the target, so we
9874       // return true (without a diagnostic) to tell the caller not to
9875       // build a shadow decl.
9876       if (CurContext->isRecord())
9877         return true;
9878 
9879       // If we're not in a record, this is an error.
9880       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9881       break;
9882     }
9883 
9884     Diag(Target->getLocation(), diag::note_using_decl_target);
9885     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9886     Using->setInvalidDecl();
9887     return true;
9888   }
9889 
9890   // Target is not a function.
9891 
9892   if (isa<TagDecl>(Target)) {
9893     // No conflict between a tag and a non-tag.
9894     if (!Tag) return false;
9895 
9896     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9897     Diag(Target->getLocation(), diag::note_using_decl_target);
9898     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9899     Using->setInvalidDecl();
9900     return true;
9901   }
9902 
9903   // No conflict between a tag and a non-tag.
9904   if (!NonTag) return false;
9905 
9906   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9907   Diag(Target->getLocation(), diag::note_using_decl_target);
9908   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9909   Using->setInvalidDecl();
9910   return true;
9911 }
9912 
9913 /// Determine whether a direct base class is a virtual base class.
9914 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9915   if (!Derived->getNumVBases())
9916     return false;
9917   for (auto &B : Derived->bases())
9918     if (B.getType()->getAsCXXRecordDecl() == Base)
9919       return B.isVirtual();
9920   llvm_unreachable("not a direct base class");
9921 }
9922 
9923 /// Builds a shadow declaration corresponding to a 'using' declaration.
9924 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9925                                             UsingDecl *UD,
9926                                             NamedDecl *Orig,
9927                                             UsingShadowDecl *PrevDecl) {
9928   // If we resolved to another shadow declaration, just coalesce them.
9929   NamedDecl *Target = Orig;
9930   if (isa<UsingShadowDecl>(Target)) {
9931     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9932     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9933   }
9934 
9935   NamedDecl *NonTemplateTarget = Target;
9936   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9937     NonTemplateTarget = TargetTD->getTemplatedDecl();
9938 
9939   UsingShadowDecl *Shadow;
9940   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
9941     bool IsVirtualBase =
9942         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9943                             UD->getQualifier()->getAsRecordDecl());
9944     Shadow = ConstructorUsingShadowDecl::Create(
9945         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9946   } else {
9947     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9948                                      Target);
9949   }
9950   UD->addShadowDecl(Shadow);
9951 
9952   Shadow->setAccess(UD->getAccess());
9953   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9954     Shadow->setInvalidDecl();
9955 
9956   Shadow->setPreviousDecl(PrevDecl);
9957 
9958   if (S)
9959     PushOnScopeChains(Shadow, S);
9960   else
9961     CurContext->addDecl(Shadow);
9962 
9963 
9964   return Shadow;
9965 }
9966 
9967 /// Hides a using shadow declaration.  This is required by the current
9968 /// using-decl implementation when a resolvable using declaration in a
9969 /// class is followed by a declaration which would hide or override
9970 /// one or more of the using decl's targets; for example:
9971 ///
9972 ///   struct Base { void foo(int); };
9973 ///   struct Derived : Base {
9974 ///     using Base::foo;
9975 ///     void foo(int);
9976 ///   };
9977 ///
9978 /// The governing language is C++03 [namespace.udecl]p12:
9979 ///
9980 ///   When a using-declaration brings names from a base class into a
9981 ///   derived class scope, member functions in the derived class
9982 ///   override and/or hide member functions with the same name and
9983 ///   parameter types in a base class (rather than conflicting).
9984 ///
9985 /// There are two ways to implement this:
9986 ///   (1) optimistically create shadow decls when they're not hidden
9987 ///       by existing declarations, or
9988 ///   (2) don't create any shadow decls (or at least don't make them
9989 ///       visible) until we've fully parsed/instantiated the class.
9990 /// The problem with (1) is that we might have to retroactively remove
9991 /// a shadow decl, which requires several O(n) operations because the
9992 /// decl structures are (very reasonably) not designed for removal.
9993 /// (2) avoids this but is very fiddly and phase-dependent.
9994 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9995   if (Shadow->getDeclName().getNameKind() ==
9996         DeclarationName::CXXConversionFunctionName)
9997     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9998 
9999   // Remove it from the DeclContext...
10000   Shadow->getDeclContext()->removeDecl(Shadow);
10001 
10002   // ...and the scope, if applicable...
10003   if (S) {
10004     S->RemoveDecl(Shadow);
10005     IdResolver.RemoveDecl(Shadow);
10006   }
10007 
10008   // ...and the using decl.
10009   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
10010 
10011   // TODO: complain somehow if Shadow was used.  It shouldn't
10012   // be possible for this to happen, because...?
10013 }
10014 
10015 /// Find the base specifier for a base class with the given type.
10016 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
10017                                                 QualType DesiredBase,
10018                                                 bool &AnyDependentBases) {
10019   // Check whether the named type is a direct base class.
10020   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
10021     .getUnqualifiedType();
10022   for (auto &Base : Derived->bases()) {
10023     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
10024     if (CanonicalDesiredBase == BaseType)
10025       return &Base;
10026     if (BaseType->isDependentType())
10027       AnyDependentBases = true;
10028   }
10029   return nullptr;
10030 }
10031 
10032 namespace {
10033 class UsingValidatorCCC final : public CorrectionCandidateCallback {
10034 public:
10035   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
10036                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
10037       : HasTypenameKeyword(HasTypenameKeyword),
10038         IsInstantiation(IsInstantiation), OldNNS(NNS),
10039         RequireMemberOf(RequireMemberOf) {}
10040 
10041   bool ValidateCandidate(const TypoCorrection &Candidate) override {
10042     NamedDecl *ND = Candidate.getCorrectionDecl();
10043 
10044     // Keywords are not valid here.
10045     if (!ND || isa<NamespaceDecl>(ND))
10046       return false;
10047 
10048     // Completely unqualified names are invalid for a 'using' declaration.
10049     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
10050       return false;
10051 
10052     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
10053     // reject.
10054 
10055     if (RequireMemberOf) {
10056       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10057       if (FoundRecord && FoundRecord->isInjectedClassName()) {
10058         // No-one ever wants a using-declaration to name an injected-class-name
10059         // of a base class, unless they're declaring an inheriting constructor.
10060         ASTContext &Ctx = ND->getASTContext();
10061         if (!Ctx.getLangOpts().CPlusPlus11)
10062           return false;
10063         QualType FoundType = Ctx.getRecordType(FoundRecord);
10064 
10065         // Check that the injected-class-name is named as a member of its own
10066         // type; we don't want to suggest 'using Derived::Base;', since that
10067         // means something else.
10068         NestedNameSpecifier *Specifier =
10069             Candidate.WillReplaceSpecifier()
10070                 ? Candidate.getCorrectionSpecifier()
10071                 : OldNNS;
10072         if (!Specifier->getAsType() ||
10073             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
10074           return false;
10075 
10076         // Check that this inheriting constructor declaration actually names a
10077         // direct base class of the current class.
10078         bool AnyDependentBases = false;
10079         if (!findDirectBaseWithType(RequireMemberOf,
10080                                     Ctx.getRecordType(FoundRecord),
10081                                     AnyDependentBases) &&
10082             !AnyDependentBases)
10083           return false;
10084       } else {
10085         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
10086         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
10087           return false;
10088 
10089         // FIXME: Check that the base class member is accessible?
10090       }
10091     } else {
10092       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10093       if (FoundRecord && FoundRecord->isInjectedClassName())
10094         return false;
10095     }
10096 
10097     if (isa<TypeDecl>(ND))
10098       return HasTypenameKeyword || !IsInstantiation;
10099 
10100     return !HasTypenameKeyword;
10101   }
10102 
10103   std::unique_ptr<CorrectionCandidateCallback> clone() override {
10104     return std::make_unique<UsingValidatorCCC>(*this);
10105   }
10106 
10107 private:
10108   bool HasTypenameKeyword;
10109   bool IsInstantiation;
10110   NestedNameSpecifier *OldNNS;
10111   CXXRecordDecl *RequireMemberOf;
10112 };
10113 } // end anonymous namespace
10114 
10115 /// Builds a using declaration.
10116 ///
10117 /// \param IsInstantiation - Whether this call arises from an
10118 ///   instantiation of an unresolved using declaration.  We treat
10119 ///   the lookup differently for these declarations.
10120 NamedDecl *Sema::BuildUsingDeclaration(
10121     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
10122     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
10123     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
10124     const ParsedAttributesView &AttrList, bool IsInstantiation) {
10125   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
10126   SourceLocation IdentLoc = NameInfo.getLoc();
10127   assert(IdentLoc.isValid() && "Invalid TargetName location.");
10128 
10129   // FIXME: We ignore attributes for now.
10130 
10131   // For an inheriting constructor declaration, the name of the using
10132   // declaration is the name of a constructor in this class, not in the
10133   // base class.
10134   DeclarationNameInfo UsingName = NameInfo;
10135   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
10136     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
10137       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10138           Context.getCanonicalType(Context.getRecordType(RD))));
10139 
10140   // Do the redeclaration lookup in the current scope.
10141   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10142                         ForVisibleRedeclaration);
10143   Previous.setHideTags(false);
10144   if (S) {
10145     LookupName(Previous, S);
10146 
10147     // It is really dumb that we have to do this.
10148     LookupResult::Filter F = Previous.makeFilter();
10149     while (F.hasNext()) {
10150       NamedDecl *D = F.next();
10151       if (!isDeclInScope(D, CurContext, S))
10152         F.erase();
10153       // If we found a local extern declaration that's not ordinarily visible,
10154       // and this declaration is being added to a non-block scope, ignore it.
10155       // We're only checking for scope conflicts here, not also for violations
10156       // of the linkage rules.
10157       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10158                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10159         F.erase();
10160     }
10161     F.done();
10162   } else {
10163     assert(IsInstantiation && "no scope in non-instantiation");
10164     if (CurContext->isRecord())
10165       LookupQualifiedName(Previous, CurContext);
10166     else {
10167       // No redeclaration check is needed here; in non-member contexts we
10168       // diagnosed all possible conflicts with other using-declarations when
10169       // building the template:
10170       //
10171       // For a dependent non-type using declaration, the only valid case is
10172       // if we instantiate to a single enumerator. We check for conflicts
10173       // between shadow declarations we introduce, and we check in the template
10174       // definition for conflicts between a non-type using declaration and any
10175       // other declaration, which together covers all cases.
10176       //
10177       // A dependent typename using declaration will never successfully
10178       // instantiate, since it will always name a class member, so we reject
10179       // that in the template definition.
10180     }
10181   }
10182 
10183   // Check for invalid redeclarations.
10184   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10185                                   SS, IdentLoc, Previous))
10186     return nullptr;
10187 
10188   // Check for bad qualifiers.
10189   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10190                               IdentLoc))
10191     return nullptr;
10192 
10193   DeclContext *LookupContext = computeDeclContext(SS);
10194   NamedDecl *D;
10195   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10196   if (!LookupContext || EllipsisLoc.isValid()) {
10197     if (HasTypenameKeyword) {
10198       // FIXME: not all declaration name kinds are legal here
10199       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10200                                               UsingLoc, TypenameLoc,
10201                                               QualifierLoc,
10202                                               IdentLoc, NameInfo.getName(),
10203                                               EllipsisLoc);
10204     } else {
10205       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10206                                            QualifierLoc, NameInfo, EllipsisLoc);
10207     }
10208     D->setAccess(AS);
10209     CurContext->addDecl(D);
10210     return D;
10211   }
10212 
10213   auto Build = [&](bool Invalid) {
10214     UsingDecl *UD =
10215         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10216                           UsingName, HasTypenameKeyword);
10217     UD->setAccess(AS);
10218     CurContext->addDecl(UD);
10219     UD->setInvalidDecl(Invalid);
10220     return UD;
10221   };
10222   auto BuildInvalid = [&]{ return Build(true); };
10223   auto BuildValid = [&]{ return Build(false); };
10224 
10225   if (RequireCompleteDeclContext(SS, LookupContext))
10226     return BuildInvalid();
10227 
10228   // Look up the target name.
10229   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10230 
10231   // Unlike most lookups, we don't always want to hide tag
10232   // declarations: tag names are visible through the using declaration
10233   // even if hidden by ordinary names, *except* in a dependent context
10234   // where it's important for the sanity of two-phase lookup.
10235   if (!IsInstantiation)
10236     R.setHideTags(false);
10237 
10238   // For the purposes of this lookup, we have a base object type
10239   // equal to that of the current context.
10240   if (CurContext->isRecord()) {
10241     R.setBaseObjectType(
10242                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10243   }
10244 
10245   LookupQualifiedName(R, LookupContext);
10246 
10247   // Try to correct typos if possible. If constructor name lookup finds no
10248   // results, that means the named class has no explicit constructors, and we
10249   // suppressed declaring implicit ones (probably because it's dependent or
10250   // invalid).
10251   if (R.empty() &&
10252       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10253     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10254     // it will believe that glibc provides a ::gets in cases where it does not,
10255     // and will try to pull it into namespace std with a using-declaration.
10256     // Just ignore the using-declaration in that case.
10257     auto *II = NameInfo.getName().getAsIdentifierInfo();
10258     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10259         CurContext->isStdNamespace() &&
10260         isa<TranslationUnitDecl>(LookupContext) &&
10261         getSourceManager().isInSystemHeader(UsingLoc))
10262       return nullptr;
10263     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10264                           dyn_cast<CXXRecordDecl>(CurContext));
10265     if (TypoCorrection Corrected =
10266             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10267                         CTK_ErrorRecovery)) {
10268       // We reject candidates where DroppedSpecifier == true, hence the
10269       // literal '0' below.
10270       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10271                                 << NameInfo.getName() << LookupContext << 0
10272                                 << SS.getRange());
10273 
10274       // If we picked a correction with no attached Decl we can't do anything
10275       // useful with it, bail out.
10276       NamedDecl *ND = Corrected.getCorrectionDecl();
10277       if (!ND)
10278         return BuildInvalid();
10279 
10280       // If we corrected to an inheriting constructor, handle it as one.
10281       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10282       if (RD && RD->isInjectedClassName()) {
10283         // The parent of the injected class name is the class itself.
10284         RD = cast<CXXRecordDecl>(RD->getParent());
10285 
10286         // Fix up the information we'll use to build the using declaration.
10287         if (Corrected.WillReplaceSpecifier()) {
10288           NestedNameSpecifierLocBuilder Builder;
10289           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10290                               QualifierLoc.getSourceRange());
10291           QualifierLoc = Builder.getWithLocInContext(Context);
10292         }
10293 
10294         // In this case, the name we introduce is the name of a derived class
10295         // constructor.
10296         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10297         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10298             Context.getCanonicalType(Context.getRecordType(CurClass))));
10299         UsingName.setNamedTypeInfo(nullptr);
10300         for (auto *Ctor : LookupConstructors(RD))
10301           R.addDecl(Ctor);
10302         R.resolveKind();
10303       } else {
10304         // FIXME: Pick up all the declarations if we found an overloaded
10305         // function.
10306         UsingName.setName(ND->getDeclName());
10307         R.addDecl(ND);
10308       }
10309     } else {
10310       Diag(IdentLoc, diag::err_no_member)
10311         << NameInfo.getName() << LookupContext << SS.getRange();
10312       return BuildInvalid();
10313     }
10314   }
10315 
10316   if (R.isAmbiguous())
10317     return BuildInvalid();
10318 
10319   if (HasTypenameKeyword) {
10320     // If we asked for a typename and got a non-type decl, error out.
10321     if (!R.getAsSingle<TypeDecl>()) {
10322       Diag(IdentLoc, diag::err_using_typename_non_type);
10323       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10324         Diag((*I)->getUnderlyingDecl()->getLocation(),
10325              diag::note_using_decl_target);
10326       return BuildInvalid();
10327     }
10328   } else {
10329     // If we asked for a non-typename and we got a type, error out,
10330     // but only if this is an instantiation of an unresolved using
10331     // decl.  Otherwise just silently find the type name.
10332     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10333       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10334       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10335       return BuildInvalid();
10336     }
10337   }
10338 
10339   // C++14 [namespace.udecl]p6:
10340   // A using-declaration shall not name a namespace.
10341   if (R.getAsSingle<NamespaceDecl>()) {
10342     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10343       << SS.getRange();
10344     return BuildInvalid();
10345   }
10346 
10347   // C++14 [namespace.udecl]p7:
10348   // A using-declaration shall not name a scoped enumerator.
10349   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10350     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10351       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10352         << SS.getRange();
10353       return BuildInvalid();
10354     }
10355   }
10356 
10357   UsingDecl *UD = BuildValid();
10358 
10359   // Some additional rules apply to inheriting constructors.
10360   if (UsingName.getName().getNameKind() ==
10361         DeclarationName::CXXConstructorName) {
10362     // Suppress access diagnostics; the access check is instead performed at the
10363     // point of use for an inheriting constructor.
10364     R.suppressDiagnostics();
10365     if (CheckInheritingConstructorUsingDecl(UD))
10366       return UD;
10367   }
10368 
10369   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10370     UsingShadowDecl *PrevDecl = nullptr;
10371     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10372       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10373   }
10374 
10375   return UD;
10376 }
10377 
10378 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10379                                     ArrayRef<NamedDecl *> Expansions) {
10380   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10381          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10382          isa<UsingPackDecl>(InstantiatedFrom));
10383 
10384   auto *UPD =
10385       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10386   UPD->setAccess(InstantiatedFrom->getAccess());
10387   CurContext->addDecl(UPD);
10388   return UPD;
10389 }
10390 
10391 /// Additional checks for a using declaration referring to a constructor name.
10392 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10393   assert(!UD->hasTypename() && "expecting a constructor name");
10394 
10395   const Type *SourceType = UD->getQualifier()->getAsType();
10396   assert(SourceType &&
10397          "Using decl naming constructor doesn't have type in scope spec.");
10398   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10399 
10400   // Check whether the named type is a direct base class.
10401   bool AnyDependentBases = false;
10402   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10403                                       AnyDependentBases);
10404   if (!Base && !AnyDependentBases) {
10405     Diag(UD->getUsingLoc(),
10406          diag::err_using_decl_constructor_not_in_direct_base)
10407       << UD->getNameInfo().getSourceRange()
10408       << QualType(SourceType, 0) << TargetClass;
10409     UD->setInvalidDecl();
10410     return true;
10411   }
10412 
10413   if (Base)
10414     Base->setInheritConstructors();
10415 
10416   return false;
10417 }
10418 
10419 /// Checks that the given using declaration is not an invalid
10420 /// redeclaration.  Note that this is checking only for the using decl
10421 /// itself, not for any ill-formedness among the UsingShadowDecls.
10422 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10423                                        bool HasTypenameKeyword,
10424                                        const CXXScopeSpec &SS,
10425                                        SourceLocation NameLoc,
10426                                        const LookupResult &Prev) {
10427   NestedNameSpecifier *Qual = SS.getScopeRep();
10428 
10429   // C++03 [namespace.udecl]p8:
10430   // C++0x [namespace.udecl]p10:
10431   //   A using-declaration is a declaration and can therefore be used
10432   //   repeatedly where (and only where) multiple declarations are
10433   //   allowed.
10434   //
10435   // That's in non-member contexts.
10436   if (!CurContext->getRedeclContext()->isRecord()) {
10437     // A dependent qualifier outside a class can only ever resolve to an
10438     // enumeration type. Therefore it conflicts with any other non-type
10439     // declaration in the same scope.
10440     // FIXME: How should we check for dependent type-type conflicts at block
10441     // scope?
10442     if (Qual->isDependent() && !HasTypenameKeyword) {
10443       for (auto *D : Prev) {
10444         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10445           bool OldCouldBeEnumerator =
10446               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10447           Diag(NameLoc,
10448                OldCouldBeEnumerator ? diag::err_redefinition
10449                                     : diag::err_redefinition_different_kind)
10450               << Prev.getLookupName();
10451           Diag(D->getLocation(), diag::note_previous_definition);
10452           return true;
10453         }
10454       }
10455     }
10456     return false;
10457   }
10458 
10459   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10460     NamedDecl *D = *I;
10461 
10462     bool DTypename;
10463     NestedNameSpecifier *DQual;
10464     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10465       DTypename = UD->hasTypename();
10466       DQual = UD->getQualifier();
10467     } else if (UnresolvedUsingValueDecl *UD
10468                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10469       DTypename = false;
10470       DQual = UD->getQualifier();
10471     } else if (UnresolvedUsingTypenameDecl *UD
10472                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10473       DTypename = true;
10474       DQual = UD->getQualifier();
10475     } else continue;
10476 
10477     // using decls differ if one says 'typename' and the other doesn't.
10478     // FIXME: non-dependent using decls?
10479     if (HasTypenameKeyword != DTypename) continue;
10480 
10481     // using decls differ if they name different scopes (but note that
10482     // template instantiation can cause this check to trigger when it
10483     // didn't before instantiation).
10484     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10485         Context.getCanonicalNestedNameSpecifier(DQual))
10486       continue;
10487 
10488     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10489     Diag(D->getLocation(), diag::note_using_decl) << 1;
10490     return true;
10491   }
10492 
10493   return false;
10494 }
10495 
10496 
10497 /// Checks that the given nested-name qualifier used in a using decl
10498 /// in the current context is appropriately related to the current
10499 /// scope.  If an error is found, diagnoses it and returns true.
10500 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10501                                    bool HasTypename,
10502                                    const CXXScopeSpec &SS,
10503                                    const DeclarationNameInfo &NameInfo,
10504                                    SourceLocation NameLoc) {
10505   DeclContext *NamedContext = computeDeclContext(SS);
10506 
10507   if (!CurContext->isRecord()) {
10508     // C++03 [namespace.udecl]p3:
10509     // C++0x [namespace.udecl]p8:
10510     //   A using-declaration for a class member shall be a member-declaration.
10511 
10512     // If we weren't able to compute a valid scope, it might validly be a
10513     // dependent class scope or a dependent enumeration unscoped scope. If
10514     // we have a 'typename' keyword, the scope must resolve to a class type.
10515     if ((HasTypename && !NamedContext) ||
10516         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10517       auto *RD = NamedContext
10518                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10519                      : nullptr;
10520       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10521         RD = nullptr;
10522 
10523       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10524         << SS.getRange();
10525 
10526       // If we have a complete, non-dependent source type, try to suggest a
10527       // way to get the same effect.
10528       if (!RD)
10529         return true;
10530 
10531       // Find what this using-declaration was referring to.
10532       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10533       R.setHideTags(false);
10534       R.suppressDiagnostics();
10535       LookupQualifiedName(R, RD);
10536 
10537       if (R.getAsSingle<TypeDecl>()) {
10538         if (getLangOpts().CPlusPlus11) {
10539           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10540           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10541             << 0 // alias declaration
10542             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10543                                           NameInfo.getName().getAsString() +
10544                                               " = ");
10545         } else {
10546           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10547           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10548           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10549             << 1 // typedef declaration
10550             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10551             << FixItHint::CreateInsertion(
10552                    InsertLoc, " " + NameInfo.getName().getAsString());
10553         }
10554       } else if (R.getAsSingle<VarDecl>()) {
10555         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10556         // repeating the type of the static data member here.
10557         FixItHint FixIt;
10558         if (getLangOpts().CPlusPlus11) {
10559           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10560           FixIt = FixItHint::CreateReplacement(
10561               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10562         }
10563 
10564         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10565           << 2 // reference declaration
10566           << FixIt;
10567       } else if (R.getAsSingle<EnumConstantDecl>()) {
10568         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10569         // repeating the type of the enumeration here, and we can't do so if
10570         // the type is anonymous.
10571         FixItHint FixIt;
10572         if (getLangOpts().CPlusPlus11) {
10573           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10574           FixIt = FixItHint::CreateReplacement(
10575               UsingLoc,
10576               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10577         }
10578 
10579         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10580           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10581           << FixIt;
10582       }
10583       return true;
10584     }
10585 
10586     // Otherwise, this might be valid.
10587     return false;
10588   }
10589 
10590   // The current scope is a record.
10591 
10592   // If the named context is dependent, we can't decide much.
10593   if (!NamedContext) {
10594     // FIXME: in C++0x, we can diagnose if we can prove that the
10595     // nested-name-specifier does not refer to a base class, which is
10596     // still possible in some cases.
10597 
10598     // Otherwise we have to conservatively report that things might be
10599     // okay.
10600     return false;
10601   }
10602 
10603   if (!NamedContext->isRecord()) {
10604     // Ideally this would point at the last name in the specifier,
10605     // but we don't have that level of source info.
10606     Diag(SS.getRange().getBegin(),
10607          diag::err_using_decl_nested_name_specifier_is_not_class)
10608       << SS.getScopeRep() << SS.getRange();
10609     return true;
10610   }
10611 
10612   if (!NamedContext->isDependentContext() &&
10613       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10614     return true;
10615 
10616   if (getLangOpts().CPlusPlus11) {
10617     // C++11 [namespace.udecl]p3:
10618     //   In a using-declaration used as a member-declaration, the
10619     //   nested-name-specifier shall name a base class of the class
10620     //   being defined.
10621 
10622     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10623                                  cast<CXXRecordDecl>(NamedContext))) {
10624       if (CurContext == NamedContext) {
10625         Diag(NameLoc,
10626              diag::err_using_decl_nested_name_specifier_is_current_class)
10627           << SS.getRange();
10628         return true;
10629       }
10630 
10631       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10632         Diag(SS.getRange().getBegin(),
10633              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10634           << SS.getScopeRep()
10635           << cast<CXXRecordDecl>(CurContext)
10636           << SS.getRange();
10637       }
10638       return true;
10639     }
10640 
10641     return false;
10642   }
10643 
10644   // C++03 [namespace.udecl]p4:
10645   //   A using-declaration used as a member-declaration shall refer
10646   //   to a member of a base class of the class being defined [etc.].
10647 
10648   // Salient point: SS doesn't have to name a base class as long as
10649   // lookup only finds members from base classes.  Therefore we can
10650   // diagnose here only if we can prove that that can't happen,
10651   // i.e. if the class hierarchies provably don't intersect.
10652 
10653   // TODO: it would be nice if "definitely valid" results were cached
10654   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10655   // need to be repeated.
10656 
10657   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10658   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10659     Bases.insert(Base);
10660     return true;
10661   };
10662 
10663   // Collect all bases. Return false if we find a dependent base.
10664   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10665     return false;
10666 
10667   // Returns true if the base is dependent or is one of the accumulated base
10668   // classes.
10669   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10670     return !Bases.count(Base);
10671   };
10672 
10673   // Return false if the class has a dependent base or if it or one
10674   // of its bases is present in the base set of the current context.
10675   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10676       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10677     return false;
10678 
10679   Diag(SS.getRange().getBegin(),
10680        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10681     << SS.getScopeRep()
10682     << cast<CXXRecordDecl>(CurContext)
10683     << SS.getRange();
10684 
10685   return true;
10686 }
10687 
10688 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10689                                   MultiTemplateParamsArg TemplateParamLists,
10690                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10691                                   const ParsedAttributesView &AttrList,
10692                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10693   // Skip up to the relevant declaration scope.
10694   while (S->isTemplateParamScope())
10695     S = S->getParent();
10696   assert((S->getFlags() & Scope::DeclScope) &&
10697          "got alias-declaration outside of declaration scope");
10698 
10699   if (Type.isInvalid())
10700     return nullptr;
10701 
10702   bool Invalid = false;
10703   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10704   TypeSourceInfo *TInfo = nullptr;
10705   GetTypeFromParser(Type.get(), &TInfo);
10706 
10707   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10708     return nullptr;
10709 
10710   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10711                                       UPPC_DeclarationType)) {
10712     Invalid = true;
10713     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10714                                              TInfo->getTypeLoc().getBeginLoc());
10715   }
10716 
10717   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10718                         TemplateParamLists.size()
10719                             ? forRedeclarationInCurContext()
10720                             : ForVisibleRedeclaration);
10721   LookupName(Previous, S);
10722 
10723   // Warn about shadowing the name of a template parameter.
10724   if (Previous.isSingleResult() &&
10725       Previous.getFoundDecl()->isTemplateParameter()) {
10726     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10727     Previous.clear();
10728   }
10729 
10730   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10731          "name in alias declaration must be an identifier");
10732   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10733                                                Name.StartLocation,
10734                                                Name.Identifier, TInfo);
10735 
10736   NewTD->setAccess(AS);
10737 
10738   if (Invalid)
10739     NewTD->setInvalidDecl();
10740 
10741   ProcessDeclAttributeList(S, NewTD, AttrList);
10742   AddPragmaAttributes(S, NewTD);
10743 
10744   CheckTypedefForVariablyModifiedType(S, NewTD);
10745   Invalid |= NewTD->isInvalidDecl();
10746 
10747   bool Redeclaration = false;
10748 
10749   NamedDecl *NewND;
10750   if (TemplateParamLists.size()) {
10751     TypeAliasTemplateDecl *OldDecl = nullptr;
10752     TemplateParameterList *OldTemplateParams = nullptr;
10753 
10754     if (TemplateParamLists.size() != 1) {
10755       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10756         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10757          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10758     }
10759     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10760 
10761     // Check that we can declare a template here.
10762     if (CheckTemplateDeclScope(S, TemplateParams))
10763       return nullptr;
10764 
10765     // Only consider previous declarations in the same scope.
10766     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10767                          /*ExplicitInstantiationOrSpecialization*/false);
10768     if (!Previous.empty()) {
10769       Redeclaration = true;
10770 
10771       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10772       if (!OldDecl && !Invalid) {
10773         Diag(UsingLoc, diag::err_redefinition_different_kind)
10774           << Name.Identifier;
10775 
10776         NamedDecl *OldD = Previous.getRepresentativeDecl();
10777         if (OldD->getLocation().isValid())
10778           Diag(OldD->getLocation(), diag::note_previous_definition);
10779 
10780         Invalid = true;
10781       }
10782 
10783       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10784         if (TemplateParameterListsAreEqual(TemplateParams,
10785                                            OldDecl->getTemplateParameters(),
10786                                            /*Complain=*/true,
10787                                            TPL_TemplateMatch))
10788           OldTemplateParams =
10789               OldDecl->getMostRecentDecl()->getTemplateParameters();
10790         else
10791           Invalid = true;
10792 
10793         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10794         if (!Invalid &&
10795             !Context.hasSameType(OldTD->getUnderlyingType(),
10796                                  NewTD->getUnderlyingType())) {
10797           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10798           // but we can't reasonably accept it.
10799           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10800             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10801           if (OldTD->getLocation().isValid())
10802             Diag(OldTD->getLocation(), diag::note_previous_definition);
10803           Invalid = true;
10804         }
10805       }
10806     }
10807 
10808     // Merge any previous default template arguments into our parameters,
10809     // and check the parameter list.
10810     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10811                                    TPC_TypeAliasTemplate))
10812       return nullptr;
10813 
10814     TypeAliasTemplateDecl *NewDecl =
10815       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10816                                     Name.Identifier, TemplateParams,
10817                                     NewTD);
10818     NewTD->setDescribedAliasTemplate(NewDecl);
10819 
10820     NewDecl->setAccess(AS);
10821 
10822     if (Invalid)
10823       NewDecl->setInvalidDecl();
10824     else if (OldDecl) {
10825       NewDecl->setPreviousDecl(OldDecl);
10826       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10827     }
10828 
10829     NewND = NewDecl;
10830   } else {
10831     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10832       setTagNameForLinkagePurposes(TD, NewTD);
10833       handleTagNumbering(TD, S);
10834     }
10835     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10836     NewND = NewTD;
10837   }
10838 
10839   PushOnScopeChains(NewND, S);
10840   ActOnDocumentableDecl(NewND);
10841   return NewND;
10842 }
10843 
10844 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10845                                    SourceLocation AliasLoc,
10846                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10847                                    SourceLocation IdentLoc,
10848                                    IdentifierInfo *Ident) {
10849 
10850   // Lookup the namespace name.
10851   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10852   LookupParsedName(R, S, &SS);
10853 
10854   if (R.isAmbiguous())
10855     return nullptr;
10856 
10857   if (R.empty()) {
10858     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10859       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10860       return nullptr;
10861     }
10862   }
10863   assert(!R.isAmbiguous() && !R.empty());
10864   NamedDecl *ND = R.getRepresentativeDecl();
10865 
10866   // Check if we have a previous declaration with the same name.
10867   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10868                      ForVisibleRedeclaration);
10869   LookupName(PrevR, S);
10870 
10871   // Check we're not shadowing a template parameter.
10872   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10873     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10874     PrevR.clear();
10875   }
10876 
10877   // Filter out any other lookup result from an enclosing scope.
10878   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10879                        /*AllowInlineNamespace*/false);
10880 
10881   // Find the previous declaration and check that we can redeclare it.
10882   NamespaceAliasDecl *Prev = nullptr;
10883   if (PrevR.isSingleResult()) {
10884     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10885     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10886       // We already have an alias with the same name that points to the same
10887       // namespace; check that it matches.
10888       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10889         Prev = AD;
10890       } else if (isVisible(PrevDecl)) {
10891         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10892           << Alias;
10893         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10894           << AD->getNamespace();
10895         return nullptr;
10896       }
10897     } else if (isVisible(PrevDecl)) {
10898       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10899                             ? diag::err_redefinition
10900                             : diag::err_redefinition_different_kind;
10901       Diag(AliasLoc, DiagID) << Alias;
10902       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10903       return nullptr;
10904     }
10905   }
10906 
10907   // The use of a nested name specifier may trigger deprecation warnings.
10908   DiagnoseUseOfDecl(ND, IdentLoc);
10909 
10910   NamespaceAliasDecl *AliasDecl =
10911     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10912                                Alias, SS.getWithLocInContext(Context),
10913                                IdentLoc, ND);
10914   if (Prev)
10915     AliasDecl->setPreviousDecl(Prev);
10916 
10917   PushOnScopeChains(AliasDecl, S);
10918   return AliasDecl;
10919 }
10920 
10921 namespace {
10922 struct SpecialMemberExceptionSpecInfo
10923     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10924   SourceLocation Loc;
10925   Sema::ImplicitExceptionSpecification ExceptSpec;
10926 
10927   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10928                                  Sema::CXXSpecialMember CSM,
10929                                  Sema::InheritedConstructorInfo *ICI,
10930                                  SourceLocation Loc)
10931       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10932 
10933   bool visitBase(CXXBaseSpecifier *Base);
10934   bool visitField(FieldDecl *FD);
10935 
10936   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10937                            unsigned Quals);
10938 
10939   void visitSubobjectCall(Subobject Subobj,
10940                           Sema::SpecialMemberOverloadResult SMOR);
10941 };
10942 }
10943 
10944 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10945   auto *RT = Base->getType()->getAs<RecordType>();
10946   if (!RT)
10947     return false;
10948 
10949   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10950   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10951   if (auto *BaseCtor = SMOR.getMethod()) {
10952     visitSubobjectCall(Base, BaseCtor);
10953     return false;
10954   }
10955 
10956   visitClassSubobject(BaseClass, Base, 0);
10957   return false;
10958 }
10959 
10960 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10961   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10962     Expr *E = FD->getInClassInitializer();
10963     if (!E)
10964       // FIXME: It's a little wasteful to build and throw away a
10965       // CXXDefaultInitExpr here.
10966       // FIXME: We should have a single context note pointing at Loc, and
10967       // this location should be MD->getLocation() instead, since that's
10968       // the location where we actually use the default init expression.
10969       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10970     if (E)
10971       ExceptSpec.CalledExpr(E);
10972   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10973                             ->getAs<RecordType>()) {
10974     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10975                         FD->getType().getCVRQualifiers());
10976   }
10977   return false;
10978 }
10979 
10980 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10981                                                          Subobject Subobj,
10982                                                          unsigned Quals) {
10983   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10984   bool IsMutable = Field && Field->isMutable();
10985   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10986 }
10987 
10988 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10989     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10990   // Note, if lookup fails, it doesn't matter what exception specification we
10991   // choose because the special member will be deleted.
10992   if (CXXMethodDecl *MD = SMOR.getMethod())
10993     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10994 }
10995 
10996 namespace {
10997 /// RAII object to register a special member as being currently declared.
10998 struct ComputingExceptionSpec {
10999   Sema &S;
11000 
11001   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
11002       : S(S) {
11003     Sema::CodeSynthesisContext Ctx;
11004     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
11005     Ctx.PointOfInstantiation = Loc;
11006     Ctx.Entity = MD;
11007     S.pushCodeSynthesisContext(Ctx);
11008   }
11009   ~ComputingExceptionSpec() {
11010     S.popCodeSynthesisContext();
11011   }
11012 };
11013 }
11014 
11015 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
11016   llvm::APSInt Result;
11017   ExprResult Converted = CheckConvertedConstantExpression(
11018       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
11019   ExplicitSpec.setExpr(Converted.get());
11020   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
11021     ExplicitSpec.setKind(Result.getBoolValue()
11022                              ? ExplicitSpecKind::ResolvedTrue
11023                              : ExplicitSpecKind::ResolvedFalse);
11024     return true;
11025   }
11026   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
11027   return false;
11028 }
11029 
11030 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
11031   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
11032   if (!ExplicitExpr->isTypeDependent())
11033     tryResolveExplicitSpecifier(ES);
11034   return ES;
11035 }
11036 
11037 static Sema::ImplicitExceptionSpecification
11038 ComputeDefaultedSpecialMemberExceptionSpec(
11039     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
11040     Sema::InheritedConstructorInfo *ICI) {
11041   ComputingExceptionSpec CES(S, MD, Loc);
11042 
11043   CXXRecordDecl *ClassDecl = MD->getParent();
11044 
11045   // C++ [except.spec]p14:
11046   //   An implicitly declared special member function (Clause 12) shall have an
11047   //   exception-specification. [...]
11048   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
11049   if (ClassDecl->isInvalidDecl())
11050     return Info.ExceptSpec;
11051 
11052   // FIXME: If this diagnostic fires, we're probably missing a check for
11053   // attempting to resolve an exception specification before it's known
11054   // at a higher level.
11055   if (S.RequireCompleteType(MD->getLocation(),
11056                             S.Context.getRecordType(ClassDecl),
11057                             diag::err_exception_spec_incomplete_type))
11058     return Info.ExceptSpec;
11059 
11060   // C++1z [except.spec]p7:
11061   //   [Look for exceptions thrown by] a constructor selected [...] to
11062   //   initialize a potentially constructed subobject,
11063   // C++1z [except.spec]p8:
11064   //   The exception specification for an implicitly-declared destructor, or a
11065   //   destructor without a noexcept-specifier, is potentially-throwing if and
11066   //   only if any of the destructors for any of its potentially constructed
11067   //   subojects is potentially throwing.
11068   // FIXME: We respect the first rule but ignore the "potentially constructed"
11069   // in the second rule to resolve a core issue (no number yet) that would have
11070   // us reject:
11071   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
11072   //   struct B : A {};
11073   //   struct C : B { void f(); };
11074   // ... due to giving B::~B() a non-throwing exception specification.
11075   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
11076                                 : Info.VisitAllBases);
11077 
11078   return Info.ExceptSpec;
11079 }
11080 
11081 namespace {
11082 /// RAII object to register a special member as being currently declared.
11083 struct DeclaringSpecialMember {
11084   Sema &S;
11085   Sema::SpecialMemberDecl D;
11086   Sema::ContextRAII SavedContext;
11087   bool WasAlreadyBeingDeclared;
11088 
11089   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
11090       : S(S), D(RD, CSM), SavedContext(S, RD) {
11091     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
11092     if (WasAlreadyBeingDeclared)
11093       // This almost never happens, but if it does, ensure that our cache
11094       // doesn't contain a stale result.
11095       S.SpecialMemberCache.clear();
11096     else {
11097       // Register a note to be produced if we encounter an error while
11098       // declaring the special member.
11099       Sema::CodeSynthesisContext Ctx;
11100       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
11101       // FIXME: We don't have a location to use here. Using the class's
11102       // location maintains the fiction that we declare all special members
11103       // with the class, but (1) it's not clear that lying about that helps our
11104       // users understand what's going on, and (2) there may be outer contexts
11105       // on the stack (some of which are relevant) and printing them exposes
11106       // our lies.
11107       Ctx.PointOfInstantiation = RD->getLocation();
11108       Ctx.Entity = RD;
11109       Ctx.SpecialMember = CSM;
11110       S.pushCodeSynthesisContext(Ctx);
11111     }
11112   }
11113   ~DeclaringSpecialMember() {
11114     if (!WasAlreadyBeingDeclared) {
11115       S.SpecialMembersBeingDeclared.erase(D);
11116       S.popCodeSynthesisContext();
11117     }
11118   }
11119 
11120   /// Are we already trying to declare this special member?
11121   bool isAlreadyBeingDeclared() const {
11122     return WasAlreadyBeingDeclared;
11123   }
11124 };
11125 }
11126 
11127 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
11128   // Look up any existing declarations, but don't trigger declaration of all
11129   // implicit special members with this name.
11130   DeclarationName Name = FD->getDeclName();
11131   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
11132                  ForExternalRedeclaration);
11133   for (auto *D : FD->getParent()->lookup(Name))
11134     if (auto *Acceptable = R.getAcceptableDecl(D))
11135       R.addDecl(Acceptable);
11136   R.resolveKind();
11137   R.suppressDiagnostics();
11138 
11139   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11140 }
11141 
11142 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11143                                           QualType ResultTy,
11144                                           ArrayRef<QualType> Args) {
11145   // Build an exception specification pointing back at this constructor.
11146   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11147 
11148   if (getLangOpts().OpenCLCPlusPlus) {
11149     // OpenCL: Implicitly defaulted special member are of the generic address
11150     // space.
11151     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11152   }
11153 
11154   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11155   SpecialMem->setType(QT);
11156 }
11157 
11158 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11159                                                      CXXRecordDecl *ClassDecl) {
11160   // C++ [class.ctor]p5:
11161   //   A default constructor for a class X is a constructor of class X
11162   //   that can be called without an argument. If there is no
11163   //   user-declared constructor for class X, a default constructor is
11164   //   implicitly declared. An implicitly-declared default constructor
11165   //   is an inline public member of its class.
11166   assert(ClassDecl->needsImplicitDefaultConstructor() &&
11167          "Should not build implicit default constructor!");
11168 
11169   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11170   if (DSM.isAlreadyBeingDeclared())
11171     return nullptr;
11172 
11173   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11174                                                      CXXDefaultConstructor,
11175                                                      false);
11176 
11177   // Create the actual constructor declaration.
11178   CanQualType ClassType
11179     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11180   SourceLocation ClassLoc = ClassDecl->getLocation();
11181   DeclarationName Name
11182     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11183   DeclarationNameInfo NameInfo(Name, ClassLoc);
11184   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11185       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11186       /*TInfo=*/nullptr, ExplicitSpecifier(),
11187       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11188       Constexpr ? CSK_constexpr : CSK_unspecified);
11189   DefaultCon->setAccess(AS_public);
11190   DefaultCon->setDefaulted();
11191 
11192   if (getLangOpts().CUDA) {
11193     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11194                                             DefaultCon,
11195                                             /* ConstRHS */ false,
11196                                             /* Diagnose */ false);
11197   }
11198 
11199   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11200 
11201   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11202   // constructors is easy to compute.
11203   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11204 
11205   // Note that we have declared this constructor.
11206   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11207 
11208   Scope *S = getScopeForContext(ClassDecl);
11209   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11210 
11211   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11212     SetDeclDeleted(DefaultCon, ClassLoc);
11213 
11214   if (S)
11215     PushOnScopeChains(DefaultCon, S, false);
11216   ClassDecl->addDecl(DefaultCon);
11217 
11218   return DefaultCon;
11219 }
11220 
11221 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11222                                             CXXConstructorDecl *Constructor) {
11223   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11224           !Constructor->doesThisDeclarationHaveABody() &&
11225           !Constructor->isDeleted()) &&
11226     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11227   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11228     return;
11229 
11230   CXXRecordDecl *ClassDecl = Constructor->getParent();
11231   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11232 
11233   SynthesizedFunctionScope Scope(*this, Constructor);
11234 
11235   // The exception specification is needed because we are defining the
11236   // function.
11237   ResolveExceptionSpec(CurrentLocation,
11238                        Constructor->getType()->castAs<FunctionProtoType>());
11239   MarkVTableUsed(CurrentLocation, ClassDecl);
11240 
11241   // Add a context note for diagnostics produced after this point.
11242   Scope.addContextNote(CurrentLocation);
11243 
11244   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11245     Constructor->setInvalidDecl();
11246     return;
11247   }
11248 
11249   SourceLocation Loc = Constructor->getEndLoc().isValid()
11250                            ? Constructor->getEndLoc()
11251                            : Constructor->getLocation();
11252   Constructor->setBody(new (Context) CompoundStmt(Loc));
11253   Constructor->markUsed(Context);
11254 
11255   if (ASTMutationListener *L = getASTMutationListener()) {
11256     L->CompletedImplicitDefinition(Constructor);
11257   }
11258 
11259   DiagnoseUninitializedFields(*this, Constructor);
11260 }
11261 
11262 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11263   // Perform any delayed checks on exception specifications.
11264   CheckDelayedMemberExceptionSpecs();
11265 }
11266 
11267 /// Find or create the fake constructor we synthesize to model constructing an
11268 /// object of a derived class via a constructor of a base class.
11269 CXXConstructorDecl *
11270 Sema::findInheritingConstructor(SourceLocation Loc,
11271                                 CXXConstructorDecl *BaseCtor,
11272                                 ConstructorUsingShadowDecl *Shadow) {
11273   CXXRecordDecl *Derived = Shadow->getParent();
11274   SourceLocation UsingLoc = Shadow->getLocation();
11275 
11276   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11277   // For now we use the name of the base class constructor as a member of the
11278   // derived class to indicate a (fake) inherited constructor name.
11279   DeclarationName Name = BaseCtor->getDeclName();
11280 
11281   // Check to see if we already have a fake constructor for this inherited
11282   // constructor call.
11283   for (NamedDecl *Ctor : Derived->lookup(Name))
11284     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11285                                ->getInheritedConstructor()
11286                                .getConstructor(),
11287                            BaseCtor))
11288       return cast<CXXConstructorDecl>(Ctor);
11289 
11290   DeclarationNameInfo NameInfo(Name, UsingLoc);
11291   TypeSourceInfo *TInfo =
11292       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11293   FunctionProtoTypeLoc ProtoLoc =
11294       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11295 
11296   // Check the inherited constructor is valid and find the list of base classes
11297   // from which it was inherited.
11298   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11299 
11300   bool Constexpr =
11301       BaseCtor->isConstexpr() &&
11302       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11303                                         false, BaseCtor, &ICI);
11304 
11305   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11306       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11307       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11308       /*isImplicitlyDeclared=*/true,
11309       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11310       InheritedConstructor(Shadow, BaseCtor));
11311   if (Shadow->isInvalidDecl())
11312     DerivedCtor->setInvalidDecl();
11313 
11314   // Build an unevaluated exception specification for this fake constructor.
11315   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11316   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11317   EPI.ExceptionSpec.Type = EST_Unevaluated;
11318   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11319   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11320                                                FPT->getParamTypes(), EPI));
11321 
11322   // Build the parameter declarations.
11323   SmallVector<ParmVarDecl *, 16> ParamDecls;
11324   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11325     TypeSourceInfo *TInfo =
11326         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11327     ParmVarDecl *PD = ParmVarDecl::Create(
11328         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11329         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11330     PD->setScopeInfo(0, I);
11331     PD->setImplicit();
11332     // Ensure attributes are propagated onto parameters (this matters for
11333     // format, pass_object_size, ...).
11334     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11335     ParamDecls.push_back(PD);
11336     ProtoLoc.setParam(I, PD);
11337   }
11338 
11339   // Set up the new constructor.
11340   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11341   DerivedCtor->setAccess(BaseCtor->getAccess());
11342   DerivedCtor->setParams(ParamDecls);
11343   Derived->addDecl(DerivedCtor);
11344 
11345   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11346     SetDeclDeleted(DerivedCtor, UsingLoc);
11347 
11348   return DerivedCtor;
11349 }
11350 
11351 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11352   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11353                                Ctor->getInheritedConstructor().getShadowDecl());
11354   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11355                             /*Diagnose*/true);
11356 }
11357 
11358 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11359                                        CXXConstructorDecl *Constructor) {
11360   CXXRecordDecl *ClassDecl = Constructor->getParent();
11361   assert(Constructor->getInheritedConstructor() &&
11362          !Constructor->doesThisDeclarationHaveABody() &&
11363          !Constructor->isDeleted());
11364   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11365     return;
11366 
11367   // Initializations are performed "as if by a defaulted default constructor",
11368   // so enter the appropriate scope.
11369   SynthesizedFunctionScope Scope(*this, Constructor);
11370 
11371   // The exception specification is needed because we are defining the
11372   // function.
11373   ResolveExceptionSpec(CurrentLocation,
11374                        Constructor->getType()->castAs<FunctionProtoType>());
11375   MarkVTableUsed(CurrentLocation, ClassDecl);
11376 
11377   // Add a context note for diagnostics produced after this point.
11378   Scope.addContextNote(CurrentLocation);
11379 
11380   ConstructorUsingShadowDecl *Shadow =
11381       Constructor->getInheritedConstructor().getShadowDecl();
11382   CXXConstructorDecl *InheritedCtor =
11383       Constructor->getInheritedConstructor().getConstructor();
11384 
11385   // [class.inhctor.init]p1:
11386   //   initialization proceeds as if a defaulted default constructor is used to
11387   //   initialize the D object and each base class subobject from which the
11388   //   constructor was inherited
11389 
11390   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11391   CXXRecordDecl *RD = Shadow->getParent();
11392   SourceLocation InitLoc = Shadow->getLocation();
11393 
11394   // Build explicit initializers for all base classes from which the
11395   // constructor was inherited.
11396   SmallVector<CXXCtorInitializer*, 8> Inits;
11397   for (bool VBase : {false, true}) {
11398     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11399       if (B.isVirtual() != VBase)
11400         continue;
11401 
11402       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11403       if (!BaseRD)
11404         continue;
11405 
11406       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11407       if (!BaseCtor.first)
11408         continue;
11409 
11410       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11411       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11412           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11413 
11414       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11415       Inits.push_back(new (Context) CXXCtorInitializer(
11416           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11417           SourceLocation()));
11418     }
11419   }
11420 
11421   // We now proceed as if for a defaulted default constructor, with the relevant
11422   // initializers replaced.
11423 
11424   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11425     Constructor->setInvalidDecl();
11426     return;
11427   }
11428 
11429   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11430   Constructor->markUsed(Context);
11431 
11432   if (ASTMutationListener *L = getASTMutationListener()) {
11433     L->CompletedImplicitDefinition(Constructor);
11434   }
11435 
11436   DiagnoseUninitializedFields(*this, Constructor);
11437 }
11438 
11439 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11440   // C++ [class.dtor]p2:
11441   //   If a class has no user-declared destructor, a destructor is
11442   //   declared implicitly. An implicitly-declared destructor is an
11443   //   inline public member of its class.
11444   assert(ClassDecl->needsImplicitDestructor());
11445 
11446   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11447   if (DSM.isAlreadyBeingDeclared())
11448     return nullptr;
11449 
11450   // Create the actual destructor declaration.
11451   CanQualType ClassType
11452     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11453   SourceLocation ClassLoc = ClassDecl->getLocation();
11454   DeclarationName Name
11455     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11456   DeclarationNameInfo NameInfo(Name, ClassLoc);
11457   CXXDestructorDecl *Destructor
11458       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11459                                   QualType(), nullptr, /*isInline=*/true,
11460                                   /*isImplicitlyDeclared=*/true);
11461   Destructor->setAccess(AS_public);
11462   Destructor->setDefaulted();
11463 
11464   if (getLangOpts().CUDA) {
11465     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11466                                             Destructor,
11467                                             /* ConstRHS */ false,
11468                                             /* Diagnose */ false);
11469   }
11470 
11471   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11472 
11473   // We don't need to use SpecialMemberIsTrivial here; triviality for
11474   // destructors is easy to compute.
11475   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11476   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11477                                 ClassDecl->hasTrivialDestructorForCall());
11478 
11479   // Note that we have declared this destructor.
11480   ++getASTContext().NumImplicitDestructorsDeclared;
11481 
11482   Scope *S = getScopeForContext(ClassDecl);
11483   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11484 
11485   // We can't check whether an implicit destructor is deleted before we complete
11486   // the definition of the class, because its validity depends on the alignment
11487   // of the class. We'll check this from ActOnFields once the class is complete.
11488   if (ClassDecl->isCompleteDefinition() &&
11489       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11490     SetDeclDeleted(Destructor, ClassLoc);
11491 
11492   // Introduce this destructor into its scope.
11493   if (S)
11494     PushOnScopeChains(Destructor, S, false);
11495   ClassDecl->addDecl(Destructor);
11496 
11497   return Destructor;
11498 }
11499 
11500 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11501                                     CXXDestructorDecl *Destructor) {
11502   assert((Destructor->isDefaulted() &&
11503           !Destructor->doesThisDeclarationHaveABody() &&
11504           !Destructor->isDeleted()) &&
11505          "DefineImplicitDestructor - call it for implicit default dtor");
11506   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11507     return;
11508 
11509   CXXRecordDecl *ClassDecl = Destructor->getParent();
11510   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11511 
11512   SynthesizedFunctionScope Scope(*this, Destructor);
11513 
11514   // The exception specification is needed because we are defining the
11515   // function.
11516   ResolveExceptionSpec(CurrentLocation,
11517                        Destructor->getType()->castAs<FunctionProtoType>());
11518   MarkVTableUsed(CurrentLocation, ClassDecl);
11519 
11520   // Add a context note for diagnostics produced after this point.
11521   Scope.addContextNote(CurrentLocation);
11522 
11523   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11524                                          Destructor->getParent());
11525 
11526   if (CheckDestructor(Destructor)) {
11527     Destructor->setInvalidDecl();
11528     return;
11529   }
11530 
11531   SourceLocation Loc = Destructor->getEndLoc().isValid()
11532                            ? Destructor->getEndLoc()
11533                            : Destructor->getLocation();
11534   Destructor->setBody(new (Context) CompoundStmt(Loc));
11535   Destructor->markUsed(Context);
11536 
11537   if (ASTMutationListener *L = getASTMutationListener()) {
11538     L->CompletedImplicitDefinition(Destructor);
11539   }
11540 }
11541 
11542 /// Perform any semantic analysis which needs to be delayed until all
11543 /// pending class member declarations have been parsed.
11544 void Sema::ActOnFinishCXXMemberDecls() {
11545   // If the context is an invalid C++ class, just suppress these checks.
11546   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11547     if (Record->isInvalidDecl()) {
11548       DelayedOverridingExceptionSpecChecks.clear();
11549       DelayedEquivalentExceptionSpecChecks.clear();
11550       return;
11551     }
11552     checkForMultipleExportedDefaultConstructors(*this, Record);
11553   }
11554 }
11555 
11556 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11557   referenceDLLExportedClassMethods();
11558 
11559   if (!DelayedDllExportMemberFunctions.empty()) {
11560     SmallVector<CXXMethodDecl*, 4> WorkList;
11561     std::swap(DelayedDllExportMemberFunctions, WorkList);
11562     for (CXXMethodDecl *M : WorkList) {
11563       DefineImplicitSpecialMember(*this, M, M->getLocation());
11564 
11565       // Pass the method to the consumer to get emitted. This is not necessary
11566       // for explicit instantiation definitions, as they will get emitted
11567       // anyway.
11568       if (M->getParent()->getTemplateSpecializationKind() !=
11569           TSK_ExplicitInstantiationDefinition)
11570         ActOnFinishInlineFunctionDef(M);
11571     }
11572   }
11573 }
11574 
11575 void Sema::referenceDLLExportedClassMethods() {
11576   if (!DelayedDllExportClasses.empty()) {
11577     // Calling ReferenceDllExportedMembers might cause the current function to
11578     // be called again, so use a local copy of DelayedDllExportClasses.
11579     SmallVector<CXXRecordDecl *, 4> WorkList;
11580     std::swap(DelayedDllExportClasses, WorkList);
11581     for (CXXRecordDecl *Class : WorkList)
11582       ReferenceDllExportedMembers(*this, Class);
11583   }
11584 }
11585 
11586 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11587   assert(getLangOpts().CPlusPlus11 &&
11588          "adjusting dtor exception specs was introduced in c++11");
11589 
11590   if (Destructor->isDependentContext())
11591     return;
11592 
11593   // C++11 [class.dtor]p3:
11594   //   A declaration of a destructor that does not have an exception-
11595   //   specification is implicitly considered to have the same exception-
11596   //   specification as an implicit declaration.
11597   const FunctionProtoType *DtorType = Destructor->getType()->
11598                                         getAs<FunctionProtoType>();
11599   if (DtorType->hasExceptionSpec())
11600     return;
11601 
11602   // Replace the destructor's type, building off the existing one. Fortunately,
11603   // the only thing of interest in the destructor type is its extended info.
11604   // The return and arguments are fixed.
11605   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11606   EPI.ExceptionSpec.Type = EST_Unevaluated;
11607   EPI.ExceptionSpec.SourceDecl = Destructor;
11608   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11609 
11610   // FIXME: If the destructor has a body that could throw, and the newly created
11611   // spec doesn't allow exceptions, we should emit a warning, because this
11612   // change in behavior can break conforming C++03 programs at runtime.
11613   // However, we don't have a body or an exception specification yet, so it
11614   // needs to be done somewhere else.
11615 }
11616 
11617 namespace {
11618 /// An abstract base class for all helper classes used in building the
11619 //  copy/move operators. These classes serve as factory functions and help us
11620 //  avoid using the same Expr* in the AST twice.
11621 class ExprBuilder {
11622   ExprBuilder(const ExprBuilder&) = delete;
11623   ExprBuilder &operator=(const ExprBuilder&) = delete;
11624 
11625 protected:
11626   static Expr *assertNotNull(Expr *E) {
11627     assert(E && "Expression construction must not fail.");
11628     return E;
11629   }
11630 
11631 public:
11632   ExprBuilder() {}
11633   virtual ~ExprBuilder() {}
11634 
11635   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11636 };
11637 
11638 class RefBuilder: public ExprBuilder {
11639   VarDecl *Var;
11640   QualType VarType;
11641 
11642 public:
11643   Expr *build(Sema &S, SourceLocation Loc) const override {
11644     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11645   }
11646 
11647   RefBuilder(VarDecl *Var, QualType VarType)
11648       : Var(Var), VarType(VarType) {}
11649 };
11650 
11651 class ThisBuilder: public ExprBuilder {
11652 public:
11653   Expr *build(Sema &S, SourceLocation Loc) const override {
11654     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11655   }
11656 };
11657 
11658 class CastBuilder: public ExprBuilder {
11659   const ExprBuilder &Builder;
11660   QualType Type;
11661   ExprValueKind Kind;
11662   const CXXCastPath &Path;
11663 
11664 public:
11665   Expr *build(Sema &S, SourceLocation Loc) const override {
11666     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11667                                              CK_UncheckedDerivedToBase, Kind,
11668                                              &Path).get());
11669   }
11670 
11671   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11672               const CXXCastPath &Path)
11673       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11674 };
11675 
11676 class DerefBuilder: public ExprBuilder {
11677   const ExprBuilder &Builder;
11678 
11679 public:
11680   Expr *build(Sema &S, SourceLocation Loc) const override {
11681     return assertNotNull(
11682         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11683   }
11684 
11685   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11686 };
11687 
11688 class MemberBuilder: public ExprBuilder {
11689   const ExprBuilder &Builder;
11690   QualType Type;
11691   CXXScopeSpec SS;
11692   bool IsArrow;
11693   LookupResult &MemberLookup;
11694 
11695 public:
11696   Expr *build(Sema &S, SourceLocation Loc) const override {
11697     return assertNotNull(S.BuildMemberReferenceExpr(
11698         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11699         nullptr, MemberLookup, nullptr, nullptr).get());
11700   }
11701 
11702   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11703                 LookupResult &MemberLookup)
11704       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11705         MemberLookup(MemberLookup) {}
11706 };
11707 
11708 class MoveCastBuilder: public ExprBuilder {
11709   const ExprBuilder &Builder;
11710 
11711 public:
11712   Expr *build(Sema &S, SourceLocation Loc) const override {
11713     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11714   }
11715 
11716   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11717 };
11718 
11719 class LvalueConvBuilder: public ExprBuilder {
11720   const ExprBuilder &Builder;
11721 
11722 public:
11723   Expr *build(Sema &S, SourceLocation Loc) const override {
11724     return assertNotNull(
11725         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11726   }
11727 
11728   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11729 };
11730 
11731 class SubscriptBuilder: public ExprBuilder {
11732   const ExprBuilder &Base;
11733   const ExprBuilder &Index;
11734 
11735 public:
11736   Expr *build(Sema &S, SourceLocation Loc) const override {
11737     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11738         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11739   }
11740 
11741   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11742       : Base(Base), Index(Index) {}
11743 };
11744 
11745 } // end anonymous namespace
11746 
11747 /// When generating a defaulted copy or move assignment operator, if a field
11748 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11749 /// do so. This optimization only applies for arrays of scalars, and for arrays
11750 /// of class type where the selected copy/move-assignment operator is trivial.
11751 static StmtResult
11752 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11753                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11754   // Compute the size of the memory buffer to be copied.
11755   QualType SizeType = S.Context.getSizeType();
11756   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11757                    S.Context.getTypeSizeInChars(T).getQuantity());
11758 
11759   // Take the address of the field references for "from" and "to". We
11760   // directly construct UnaryOperators here because semantic analysis
11761   // does not permit us to take the address of an xvalue.
11762   Expr *From = FromB.build(S, Loc);
11763   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11764                          S.Context.getPointerType(From->getType()),
11765                          VK_RValue, OK_Ordinary, Loc, false);
11766   Expr *To = ToB.build(S, Loc);
11767   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11768                        S.Context.getPointerType(To->getType()),
11769                        VK_RValue, OK_Ordinary, Loc, false);
11770 
11771   const Type *E = T->getBaseElementTypeUnsafe();
11772   bool NeedsCollectableMemCpy =
11773     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11774 
11775   // Create a reference to the __builtin_objc_memmove_collectable function
11776   StringRef MemCpyName = NeedsCollectableMemCpy ?
11777     "__builtin_objc_memmove_collectable" :
11778     "__builtin_memcpy";
11779   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11780                  Sema::LookupOrdinaryName);
11781   S.LookupName(R, S.TUScope, true);
11782 
11783   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11784   if (!MemCpy)
11785     // Something went horribly wrong earlier, and we will have complained
11786     // about it.
11787     return StmtError();
11788 
11789   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11790                                             VK_RValue, Loc, nullptr);
11791   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11792 
11793   Expr *CallArgs[] = {
11794     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11795   };
11796   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11797                                     Loc, CallArgs, Loc);
11798 
11799   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11800   return Call.getAs<Stmt>();
11801 }
11802 
11803 /// Builds a statement that copies/moves the given entity from \p From to
11804 /// \c To.
11805 ///
11806 /// This routine is used to copy/move the members of a class with an
11807 /// implicitly-declared copy/move assignment operator. When the entities being
11808 /// copied are arrays, this routine builds for loops to copy them.
11809 ///
11810 /// \param S The Sema object used for type-checking.
11811 ///
11812 /// \param Loc The location where the implicit copy/move is being generated.
11813 ///
11814 /// \param T The type of the expressions being copied/moved. Both expressions
11815 /// must have this type.
11816 ///
11817 /// \param To The expression we are copying/moving to.
11818 ///
11819 /// \param From The expression we are copying/moving from.
11820 ///
11821 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11822 /// Otherwise, it's a non-static member subobject.
11823 ///
11824 /// \param Copying Whether we're copying or moving.
11825 ///
11826 /// \param Depth Internal parameter recording the depth of the recursion.
11827 ///
11828 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11829 /// if a memcpy should be used instead.
11830 static StmtResult
11831 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11832                                  const ExprBuilder &To, const ExprBuilder &From,
11833                                  bool CopyingBaseSubobject, bool Copying,
11834                                  unsigned Depth = 0) {
11835   // C++11 [class.copy]p28:
11836   //   Each subobject is assigned in the manner appropriate to its type:
11837   //
11838   //     - if the subobject is of class type, as if by a call to operator= with
11839   //       the subobject as the object expression and the corresponding
11840   //       subobject of x as a single function argument (as if by explicit
11841   //       qualification; that is, ignoring any possible virtual overriding
11842   //       functions in more derived classes);
11843   //
11844   // C++03 [class.copy]p13:
11845   //     - if the subobject is of class type, the copy assignment operator for
11846   //       the class is used (as if by explicit qualification; that is,
11847   //       ignoring any possible virtual overriding functions in more derived
11848   //       classes);
11849   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11850     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11851 
11852     // Look for operator=.
11853     DeclarationName Name
11854       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11855     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11856     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11857 
11858     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11859     // operator.
11860     if (!S.getLangOpts().CPlusPlus11) {
11861       LookupResult::Filter F = OpLookup.makeFilter();
11862       while (F.hasNext()) {
11863         NamedDecl *D = F.next();
11864         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11865           if (Method->isCopyAssignmentOperator() ||
11866               (!Copying && Method->isMoveAssignmentOperator()))
11867             continue;
11868 
11869         F.erase();
11870       }
11871       F.done();
11872     }
11873 
11874     // Suppress the protected check (C++ [class.protected]) for each of the
11875     // assignment operators we found. This strange dance is required when
11876     // we're assigning via a base classes's copy-assignment operator. To
11877     // ensure that we're getting the right base class subobject (without
11878     // ambiguities), we need to cast "this" to that subobject type; to
11879     // ensure that we don't go through the virtual call mechanism, we need
11880     // to qualify the operator= name with the base class (see below). However,
11881     // this means that if the base class has a protected copy assignment
11882     // operator, the protected member access check will fail. So, we
11883     // rewrite "protected" access to "public" access in this case, since we
11884     // know by construction that we're calling from a derived class.
11885     if (CopyingBaseSubobject) {
11886       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11887            L != LEnd; ++L) {
11888         if (L.getAccess() == AS_protected)
11889           L.setAccess(AS_public);
11890       }
11891     }
11892 
11893     // Create the nested-name-specifier that will be used to qualify the
11894     // reference to operator=; this is required to suppress the virtual
11895     // call mechanism.
11896     CXXScopeSpec SS;
11897     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11898     SS.MakeTrivial(S.Context,
11899                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11900                                                CanonicalT),
11901                    Loc);
11902 
11903     // Create the reference to operator=.
11904     ExprResult OpEqualRef
11905       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11906                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11907                                    /*FirstQualifierInScope=*/nullptr,
11908                                    OpLookup,
11909                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11910                                    /*SuppressQualifierCheck=*/true);
11911     if (OpEqualRef.isInvalid())
11912       return StmtError();
11913 
11914     // Build the call to the assignment operator.
11915 
11916     Expr *FromInst = From.build(S, Loc);
11917     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11918                                                   OpEqualRef.getAs<Expr>(),
11919                                                   Loc, FromInst, Loc);
11920     if (Call.isInvalid())
11921       return StmtError();
11922 
11923     // If we built a call to a trivial 'operator=' while copying an array,
11924     // bail out. We'll replace the whole shebang with a memcpy.
11925     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11926     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11927       return StmtResult((Stmt*)nullptr);
11928 
11929     // Convert to an expression-statement, and clean up any produced
11930     // temporaries.
11931     return S.ActOnExprStmt(Call);
11932   }
11933 
11934   //     - if the subobject is of scalar type, the built-in assignment
11935   //       operator is used.
11936   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11937   if (!ArrayTy) {
11938     ExprResult Assignment = S.CreateBuiltinBinOp(
11939         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11940     if (Assignment.isInvalid())
11941       return StmtError();
11942     return S.ActOnExprStmt(Assignment);
11943   }
11944 
11945   //     - if the subobject is an array, each element is assigned, in the
11946   //       manner appropriate to the element type;
11947 
11948   // Construct a loop over the array bounds, e.g.,
11949   //
11950   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11951   //
11952   // that will copy each of the array elements.
11953   QualType SizeType = S.Context.getSizeType();
11954 
11955   // Create the iteration variable.
11956   IdentifierInfo *IterationVarName = nullptr;
11957   {
11958     SmallString<8> Str;
11959     llvm::raw_svector_ostream OS(Str);
11960     OS << "__i" << Depth;
11961     IterationVarName = &S.Context.Idents.get(OS.str());
11962   }
11963   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11964                                           IterationVarName, SizeType,
11965                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11966                                           SC_None);
11967 
11968   // Initialize the iteration variable to zero.
11969   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11970   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11971 
11972   // Creates a reference to the iteration variable.
11973   RefBuilder IterationVarRef(IterationVar, SizeType);
11974   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11975 
11976   // Create the DeclStmt that holds the iteration variable.
11977   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11978 
11979   // Subscript the "from" and "to" expressions with the iteration variable.
11980   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11981   MoveCastBuilder FromIndexMove(FromIndexCopy);
11982   const ExprBuilder *FromIndex;
11983   if (Copying)
11984     FromIndex = &FromIndexCopy;
11985   else
11986     FromIndex = &FromIndexMove;
11987 
11988   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11989 
11990   // Build the copy/move for an individual element of the array.
11991   StmtResult Copy =
11992     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11993                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11994                                      Copying, Depth + 1);
11995   // Bail out if copying fails or if we determined that we should use memcpy.
11996   if (Copy.isInvalid() || !Copy.get())
11997     return Copy;
11998 
11999   // Create the comparison against the array bound.
12000   llvm::APInt Upper
12001     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
12002   Expr *Comparison
12003     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
12004                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
12005                                      BO_NE, S.Context.BoolTy,
12006                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
12007 
12008   // Create the pre-increment of the iteration variable. We can determine
12009   // whether the increment will overflow based on the value of the array
12010   // bound.
12011   Expr *Increment = new (S.Context)
12012       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
12013                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
12014 
12015   // Construct the loop that copies all elements of this array.
12016   return S.ActOnForStmt(
12017       Loc, Loc, InitStmt,
12018       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
12019       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
12020 }
12021 
12022 static StmtResult
12023 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
12024                       const ExprBuilder &To, const ExprBuilder &From,
12025                       bool CopyingBaseSubobject, bool Copying) {
12026   // Maybe we should use a memcpy?
12027   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
12028       T.isTriviallyCopyableType(S.Context))
12029     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12030 
12031   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
12032                                                      CopyingBaseSubobject,
12033                                                      Copying, 0));
12034 
12035   // If we ended up picking a trivial assignment operator for an array of a
12036   // non-trivially-copyable class type, just emit a memcpy.
12037   if (!Result.isInvalid() && !Result.get())
12038     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12039 
12040   return Result;
12041 }
12042 
12043 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
12044   // Note: The following rules are largely analoguous to the copy
12045   // constructor rules. Note that virtual bases are not taken into account
12046   // for determining the argument type of the operator. Note also that
12047   // operators taking an object instead of a reference are allowed.
12048   assert(ClassDecl->needsImplicitCopyAssignment());
12049 
12050   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
12051   if (DSM.isAlreadyBeingDeclared())
12052     return nullptr;
12053 
12054   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12055   if (Context.getLangOpts().OpenCLCPlusPlus)
12056     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12057   QualType RetType = Context.getLValueReferenceType(ArgType);
12058   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
12059   if (Const)
12060     ArgType = ArgType.withConst();
12061 
12062   ArgType = Context.getLValueReferenceType(ArgType);
12063 
12064   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12065                                                      CXXCopyAssignment,
12066                                                      Const);
12067 
12068   //   An implicitly-declared copy assignment operator is an inline public
12069   //   member of its class.
12070   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12071   SourceLocation ClassLoc = ClassDecl->getLocation();
12072   DeclarationNameInfo NameInfo(Name, ClassLoc);
12073   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
12074       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12075       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12076       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12077       SourceLocation());
12078   CopyAssignment->setAccess(AS_public);
12079   CopyAssignment->setDefaulted();
12080   CopyAssignment->setImplicit();
12081 
12082   if (getLangOpts().CUDA) {
12083     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
12084                                             CopyAssignment,
12085                                             /* ConstRHS */ Const,
12086                                             /* Diagnose */ false);
12087   }
12088 
12089   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
12090 
12091   // Add the parameter to the operator.
12092   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
12093                                                ClassLoc, ClassLoc,
12094                                                /*Id=*/nullptr, ArgType,
12095                                                /*TInfo=*/nullptr, SC_None,
12096                                                nullptr);
12097   CopyAssignment->setParams(FromParam);
12098 
12099   CopyAssignment->setTrivial(
12100     ClassDecl->needsOverloadResolutionForCopyAssignment()
12101       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
12102       : ClassDecl->hasTrivialCopyAssignment());
12103 
12104   // Note that we have added this copy-assignment operator.
12105   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
12106 
12107   Scope *S = getScopeForContext(ClassDecl);
12108   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
12109 
12110   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
12111     SetDeclDeleted(CopyAssignment, ClassLoc);
12112 
12113   if (S)
12114     PushOnScopeChains(CopyAssignment, S, false);
12115   ClassDecl->addDecl(CopyAssignment);
12116 
12117   return CopyAssignment;
12118 }
12119 
12120 /// Diagnose an implicit copy operation for a class which is odr-used, but
12121 /// which is deprecated because the class has a user-declared copy constructor,
12122 /// copy assignment operator, or destructor.
12123 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
12124   assert(CopyOp->isImplicit());
12125 
12126   CXXRecordDecl *RD = CopyOp->getParent();
12127   CXXMethodDecl *UserDeclaredOperation = nullptr;
12128 
12129   // In Microsoft mode, assignment operations don't affect constructors and
12130   // vice versa.
12131   if (RD->hasUserDeclaredDestructor()) {
12132     UserDeclaredOperation = RD->getDestructor();
12133   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
12134              RD->hasUserDeclaredCopyConstructor() &&
12135              !S.getLangOpts().MSVCCompat) {
12136     // Find any user-declared copy constructor.
12137     for (auto *I : RD->ctors()) {
12138       if (I->isCopyConstructor()) {
12139         UserDeclaredOperation = I;
12140         break;
12141       }
12142     }
12143     assert(UserDeclaredOperation);
12144   } else if (isa<CXXConstructorDecl>(CopyOp) &&
12145              RD->hasUserDeclaredCopyAssignment() &&
12146              !S.getLangOpts().MSVCCompat) {
12147     // Find any user-declared move assignment operator.
12148     for (auto *I : RD->methods()) {
12149       if (I->isCopyAssignmentOperator()) {
12150         UserDeclaredOperation = I;
12151         break;
12152       }
12153     }
12154     assert(UserDeclaredOperation);
12155   }
12156 
12157   if (UserDeclaredOperation) {
12158     S.Diag(UserDeclaredOperation->getLocation(),
12159          diag::warn_deprecated_copy_operation)
12160       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12161       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12162   }
12163 }
12164 
12165 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12166                                         CXXMethodDecl *CopyAssignOperator) {
12167   assert((CopyAssignOperator->isDefaulted() &&
12168           CopyAssignOperator->isOverloadedOperator() &&
12169           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12170           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12171           !CopyAssignOperator->isDeleted()) &&
12172          "DefineImplicitCopyAssignment called for wrong function");
12173   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12174     return;
12175 
12176   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12177   if (ClassDecl->isInvalidDecl()) {
12178     CopyAssignOperator->setInvalidDecl();
12179     return;
12180   }
12181 
12182   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12183 
12184   // The exception specification is needed because we are defining the
12185   // function.
12186   ResolveExceptionSpec(CurrentLocation,
12187                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12188 
12189   // Add a context note for diagnostics produced after this point.
12190   Scope.addContextNote(CurrentLocation);
12191 
12192   // C++11 [class.copy]p18:
12193   //   The [definition of an implicitly declared copy assignment operator] is
12194   //   deprecated if the class has a user-declared copy constructor or a
12195   //   user-declared destructor.
12196   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12197     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12198 
12199   // C++0x [class.copy]p30:
12200   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12201   //   for a non-union class X performs memberwise copy assignment of its
12202   //   subobjects. The direct base classes of X are assigned first, in the
12203   //   order of their declaration in the base-specifier-list, and then the
12204   //   immediate non-static data members of X are assigned, in the order in
12205   //   which they were declared in the class definition.
12206 
12207   // The statements that form the synthesized function body.
12208   SmallVector<Stmt*, 8> Statements;
12209 
12210   // The parameter for the "other" object, which we are copying from.
12211   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12212   Qualifiers OtherQuals = Other->getType().getQualifiers();
12213   QualType OtherRefType = Other->getType();
12214   if (const LValueReferenceType *OtherRef
12215                                 = OtherRefType->getAs<LValueReferenceType>()) {
12216     OtherRefType = OtherRef->getPointeeType();
12217     OtherQuals = OtherRefType.getQualifiers();
12218   }
12219 
12220   // Our location for everything implicitly-generated.
12221   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12222                            ? CopyAssignOperator->getEndLoc()
12223                            : CopyAssignOperator->getLocation();
12224 
12225   // Builds a DeclRefExpr for the "other" object.
12226   RefBuilder OtherRef(Other, OtherRefType);
12227 
12228   // Builds the "this" pointer.
12229   ThisBuilder This;
12230 
12231   // Assign base classes.
12232   bool Invalid = false;
12233   for (auto &Base : ClassDecl->bases()) {
12234     // Form the assignment:
12235     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12236     QualType BaseType = Base.getType().getUnqualifiedType();
12237     if (!BaseType->isRecordType()) {
12238       Invalid = true;
12239       continue;
12240     }
12241 
12242     CXXCastPath BasePath;
12243     BasePath.push_back(&Base);
12244 
12245     // Construct the "from" expression, which is an implicit cast to the
12246     // appropriately-qualified base type.
12247     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12248                      VK_LValue, BasePath);
12249 
12250     // Dereference "this".
12251     DerefBuilder DerefThis(This);
12252     CastBuilder To(DerefThis,
12253                    Context.getQualifiedType(
12254                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12255                    VK_LValue, BasePath);
12256 
12257     // Build the copy.
12258     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12259                                             To, From,
12260                                             /*CopyingBaseSubobject=*/true,
12261                                             /*Copying=*/true);
12262     if (Copy.isInvalid()) {
12263       CopyAssignOperator->setInvalidDecl();
12264       return;
12265     }
12266 
12267     // Success! Record the copy.
12268     Statements.push_back(Copy.getAs<Expr>());
12269   }
12270 
12271   // Assign non-static members.
12272   for (auto *Field : ClassDecl->fields()) {
12273     // FIXME: We should form some kind of AST representation for the implied
12274     // memcpy in a union copy operation.
12275     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12276       continue;
12277 
12278     if (Field->isInvalidDecl()) {
12279       Invalid = true;
12280       continue;
12281     }
12282 
12283     // Check for members of reference type; we can't copy those.
12284     if (Field->getType()->isReferenceType()) {
12285       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12286         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12287       Diag(Field->getLocation(), diag::note_declared_at);
12288       Invalid = true;
12289       continue;
12290     }
12291 
12292     // Check for members of const-qualified, non-class type.
12293     QualType BaseType = Context.getBaseElementType(Field->getType());
12294     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12295       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12296         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12297       Diag(Field->getLocation(), diag::note_declared_at);
12298       Invalid = true;
12299       continue;
12300     }
12301 
12302     // Suppress assigning zero-width bitfields.
12303     if (Field->isZeroLengthBitField(Context))
12304       continue;
12305 
12306     QualType FieldType = Field->getType().getNonReferenceType();
12307     if (FieldType->isIncompleteArrayType()) {
12308       assert(ClassDecl->hasFlexibleArrayMember() &&
12309              "Incomplete array type is not valid");
12310       continue;
12311     }
12312 
12313     // Build references to the field in the object we're copying from and to.
12314     CXXScopeSpec SS; // Intentionally empty
12315     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12316                               LookupMemberName);
12317     MemberLookup.addDecl(Field);
12318     MemberLookup.resolveKind();
12319 
12320     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12321 
12322     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12323 
12324     // Build the copy of this field.
12325     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12326                                             To, From,
12327                                             /*CopyingBaseSubobject=*/false,
12328                                             /*Copying=*/true);
12329     if (Copy.isInvalid()) {
12330       CopyAssignOperator->setInvalidDecl();
12331       return;
12332     }
12333 
12334     // Success! Record the copy.
12335     Statements.push_back(Copy.getAs<Stmt>());
12336   }
12337 
12338   if (!Invalid) {
12339     // Add a "return *this;"
12340     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12341 
12342     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12343     if (Return.isInvalid())
12344       Invalid = true;
12345     else
12346       Statements.push_back(Return.getAs<Stmt>());
12347   }
12348 
12349   if (Invalid) {
12350     CopyAssignOperator->setInvalidDecl();
12351     return;
12352   }
12353 
12354   StmtResult Body;
12355   {
12356     CompoundScopeRAII CompoundScope(*this);
12357     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12358                              /*isStmtExpr=*/false);
12359     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12360   }
12361   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12362   CopyAssignOperator->markUsed(Context);
12363 
12364   if (ASTMutationListener *L = getASTMutationListener()) {
12365     L->CompletedImplicitDefinition(CopyAssignOperator);
12366   }
12367 }
12368 
12369 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12370   assert(ClassDecl->needsImplicitMoveAssignment());
12371 
12372   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12373   if (DSM.isAlreadyBeingDeclared())
12374     return nullptr;
12375 
12376   // Note: The following rules are largely analoguous to the move
12377   // constructor rules.
12378 
12379   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12380   if (Context.getLangOpts().OpenCLCPlusPlus)
12381     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12382   QualType RetType = Context.getLValueReferenceType(ArgType);
12383   ArgType = Context.getRValueReferenceType(ArgType);
12384 
12385   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12386                                                      CXXMoveAssignment,
12387                                                      false);
12388 
12389   //   An implicitly-declared move assignment operator is an inline public
12390   //   member of its class.
12391   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12392   SourceLocation ClassLoc = ClassDecl->getLocation();
12393   DeclarationNameInfo NameInfo(Name, ClassLoc);
12394   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12395       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12396       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12397       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12398       SourceLocation());
12399   MoveAssignment->setAccess(AS_public);
12400   MoveAssignment->setDefaulted();
12401   MoveAssignment->setImplicit();
12402 
12403   if (getLangOpts().CUDA) {
12404     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12405                                             MoveAssignment,
12406                                             /* ConstRHS */ false,
12407                                             /* Diagnose */ false);
12408   }
12409 
12410   // Build an exception specification pointing back at this member.
12411   FunctionProtoType::ExtProtoInfo EPI =
12412       getImplicitMethodEPI(*this, MoveAssignment);
12413   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12414 
12415   // Add the parameter to the operator.
12416   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12417                                                ClassLoc, ClassLoc,
12418                                                /*Id=*/nullptr, ArgType,
12419                                                /*TInfo=*/nullptr, SC_None,
12420                                                nullptr);
12421   MoveAssignment->setParams(FromParam);
12422 
12423   MoveAssignment->setTrivial(
12424     ClassDecl->needsOverloadResolutionForMoveAssignment()
12425       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12426       : ClassDecl->hasTrivialMoveAssignment());
12427 
12428   // Note that we have added this copy-assignment operator.
12429   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12430 
12431   Scope *S = getScopeForContext(ClassDecl);
12432   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12433 
12434   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12435     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12436     SetDeclDeleted(MoveAssignment, ClassLoc);
12437   }
12438 
12439   if (S)
12440     PushOnScopeChains(MoveAssignment, S, false);
12441   ClassDecl->addDecl(MoveAssignment);
12442 
12443   return MoveAssignment;
12444 }
12445 
12446 /// Check if we're implicitly defining a move assignment operator for a class
12447 /// with virtual bases. Such a move assignment might move-assign the virtual
12448 /// base multiple times.
12449 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12450                                                SourceLocation CurrentLocation) {
12451   assert(!Class->isDependentContext() && "should not define dependent move");
12452 
12453   // Only a virtual base could get implicitly move-assigned multiple times.
12454   // Only a non-trivial move assignment can observe this. We only want to
12455   // diagnose if we implicitly define an assignment operator that assigns
12456   // two base classes, both of which move-assign the same virtual base.
12457   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12458       Class->getNumBases() < 2)
12459     return;
12460 
12461   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12462   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12463   VBaseMap VBases;
12464 
12465   for (auto &BI : Class->bases()) {
12466     Worklist.push_back(&BI);
12467     while (!Worklist.empty()) {
12468       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12469       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12470 
12471       // If the base has no non-trivial move assignment operators,
12472       // we don't care about moves from it.
12473       if (!Base->hasNonTrivialMoveAssignment())
12474         continue;
12475 
12476       // If there's nothing virtual here, skip it.
12477       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12478         continue;
12479 
12480       // If we're not actually going to call a move assignment for this base,
12481       // or the selected move assignment is trivial, skip it.
12482       Sema::SpecialMemberOverloadResult SMOR =
12483         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12484                               /*ConstArg*/false, /*VolatileArg*/false,
12485                               /*RValueThis*/true, /*ConstThis*/false,
12486                               /*VolatileThis*/false);
12487       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12488           !SMOR.getMethod()->isMoveAssignmentOperator())
12489         continue;
12490 
12491       if (BaseSpec->isVirtual()) {
12492         // We're going to move-assign this virtual base, and its move
12493         // assignment operator is not trivial. If this can happen for
12494         // multiple distinct direct bases of Class, diagnose it. (If it
12495         // only happens in one base, we'll diagnose it when synthesizing
12496         // that base class's move assignment operator.)
12497         CXXBaseSpecifier *&Existing =
12498             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12499                 .first->second;
12500         if (Existing && Existing != &BI) {
12501           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12502             << Class << Base;
12503           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12504               << (Base->getCanonicalDecl() ==
12505                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12506               << Base << Existing->getType() << Existing->getSourceRange();
12507           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12508               << (Base->getCanonicalDecl() ==
12509                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12510               << Base << BI.getType() << BaseSpec->getSourceRange();
12511 
12512           // Only diagnose each vbase once.
12513           Existing = nullptr;
12514         }
12515       } else {
12516         // Only walk over bases that have defaulted move assignment operators.
12517         // We assume that any user-provided move assignment operator handles
12518         // the multiple-moves-of-vbase case itself somehow.
12519         if (!SMOR.getMethod()->isDefaulted())
12520           continue;
12521 
12522         // We're going to move the base classes of Base. Add them to the list.
12523         for (auto &BI : Base->bases())
12524           Worklist.push_back(&BI);
12525       }
12526     }
12527   }
12528 }
12529 
12530 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12531                                         CXXMethodDecl *MoveAssignOperator) {
12532   assert((MoveAssignOperator->isDefaulted() &&
12533           MoveAssignOperator->isOverloadedOperator() &&
12534           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12535           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12536           !MoveAssignOperator->isDeleted()) &&
12537          "DefineImplicitMoveAssignment called for wrong function");
12538   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12539     return;
12540 
12541   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12542   if (ClassDecl->isInvalidDecl()) {
12543     MoveAssignOperator->setInvalidDecl();
12544     return;
12545   }
12546 
12547   // C++0x [class.copy]p28:
12548   //   The implicitly-defined or move assignment operator for a non-union class
12549   //   X performs memberwise move assignment of its subobjects. The direct base
12550   //   classes of X are assigned first, in the order of their declaration in the
12551   //   base-specifier-list, and then the immediate non-static data members of X
12552   //   are assigned, in the order in which they were declared in the class
12553   //   definition.
12554 
12555   // Issue a warning if our implicit move assignment operator will move
12556   // from a virtual base more than once.
12557   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12558 
12559   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12560 
12561   // The exception specification is needed because we are defining the
12562   // function.
12563   ResolveExceptionSpec(CurrentLocation,
12564                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12565 
12566   // Add a context note for diagnostics produced after this point.
12567   Scope.addContextNote(CurrentLocation);
12568 
12569   // The statements that form the synthesized function body.
12570   SmallVector<Stmt*, 8> Statements;
12571 
12572   // The parameter for the "other" object, which we are move from.
12573   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12574   QualType OtherRefType = Other->getType()->
12575       getAs<RValueReferenceType>()->getPointeeType();
12576 
12577   // Our location for everything implicitly-generated.
12578   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12579                            ? MoveAssignOperator->getEndLoc()
12580                            : MoveAssignOperator->getLocation();
12581 
12582   // Builds a reference to the "other" object.
12583   RefBuilder OtherRef(Other, OtherRefType);
12584   // Cast to rvalue.
12585   MoveCastBuilder MoveOther(OtherRef);
12586 
12587   // Builds the "this" pointer.
12588   ThisBuilder This;
12589 
12590   // Assign base classes.
12591   bool Invalid = false;
12592   for (auto &Base : ClassDecl->bases()) {
12593     // C++11 [class.copy]p28:
12594     //   It is unspecified whether subobjects representing virtual base classes
12595     //   are assigned more than once by the implicitly-defined copy assignment
12596     //   operator.
12597     // FIXME: Do not assign to a vbase that will be assigned by some other base
12598     // class. For a move-assignment, this can result in the vbase being moved
12599     // multiple times.
12600 
12601     // Form the assignment:
12602     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12603     QualType BaseType = Base.getType().getUnqualifiedType();
12604     if (!BaseType->isRecordType()) {
12605       Invalid = true;
12606       continue;
12607     }
12608 
12609     CXXCastPath BasePath;
12610     BasePath.push_back(&Base);
12611 
12612     // Construct the "from" expression, which is an implicit cast to the
12613     // appropriately-qualified base type.
12614     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12615 
12616     // Dereference "this".
12617     DerefBuilder DerefThis(This);
12618 
12619     // Implicitly cast "this" to the appropriately-qualified base type.
12620     CastBuilder To(DerefThis,
12621                    Context.getQualifiedType(
12622                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12623                    VK_LValue, BasePath);
12624 
12625     // Build the move.
12626     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12627                                             To, From,
12628                                             /*CopyingBaseSubobject=*/true,
12629                                             /*Copying=*/false);
12630     if (Move.isInvalid()) {
12631       MoveAssignOperator->setInvalidDecl();
12632       return;
12633     }
12634 
12635     // Success! Record the move.
12636     Statements.push_back(Move.getAs<Expr>());
12637   }
12638 
12639   // Assign non-static members.
12640   for (auto *Field : ClassDecl->fields()) {
12641     // FIXME: We should form some kind of AST representation for the implied
12642     // memcpy in a union copy operation.
12643     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12644       continue;
12645 
12646     if (Field->isInvalidDecl()) {
12647       Invalid = true;
12648       continue;
12649     }
12650 
12651     // Check for members of reference type; we can't move those.
12652     if (Field->getType()->isReferenceType()) {
12653       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12654         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12655       Diag(Field->getLocation(), diag::note_declared_at);
12656       Invalid = true;
12657       continue;
12658     }
12659 
12660     // Check for members of const-qualified, non-class type.
12661     QualType BaseType = Context.getBaseElementType(Field->getType());
12662     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12663       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12664         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12665       Diag(Field->getLocation(), diag::note_declared_at);
12666       Invalid = true;
12667       continue;
12668     }
12669 
12670     // Suppress assigning zero-width bitfields.
12671     if (Field->isZeroLengthBitField(Context))
12672       continue;
12673 
12674     QualType FieldType = Field->getType().getNonReferenceType();
12675     if (FieldType->isIncompleteArrayType()) {
12676       assert(ClassDecl->hasFlexibleArrayMember() &&
12677              "Incomplete array type is not valid");
12678       continue;
12679     }
12680 
12681     // Build references to the field in the object we're copying from and to.
12682     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12683                               LookupMemberName);
12684     MemberLookup.addDecl(Field);
12685     MemberLookup.resolveKind();
12686     MemberBuilder From(MoveOther, OtherRefType,
12687                        /*IsArrow=*/false, MemberLookup);
12688     MemberBuilder To(This, getCurrentThisType(),
12689                      /*IsArrow=*/true, MemberLookup);
12690 
12691     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12692         "Member reference with rvalue base must be rvalue except for reference "
12693         "members, which aren't allowed for move assignment.");
12694 
12695     // Build the move of this field.
12696     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12697                                             To, From,
12698                                             /*CopyingBaseSubobject=*/false,
12699                                             /*Copying=*/false);
12700     if (Move.isInvalid()) {
12701       MoveAssignOperator->setInvalidDecl();
12702       return;
12703     }
12704 
12705     // Success! Record the copy.
12706     Statements.push_back(Move.getAs<Stmt>());
12707   }
12708 
12709   if (!Invalid) {
12710     // Add a "return *this;"
12711     ExprResult ThisObj =
12712         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12713 
12714     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12715     if (Return.isInvalid())
12716       Invalid = true;
12717     else
12718       Statements.push_back(Return.getAs<Stmt>());
12719   }
12720 
12721   if (Invalid) {
12722     MoveAssignOperator->setInvalidDecl();
12723     return;
12724   }
12725 
12726   StmtResult Body;
12727   {
12728     CompoundScopeRAII CompoundScope(*this);
12729     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12730                              /*isStmtExpr=*/false);
12731     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12732   }
12733   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12734   MoveAssignOperator->markUsed(Context);
12735 
12736   if (ASTMutationListener *L = getASTMutationListener()) {
12737     L->CompletedImplicitDefinition(MoveAssignOperator);
12738   }
12739 }
12740 
12741 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12742                                                     CXXRecordDecl *ClassDecl) {
12743   // C++ [class.copy]p4:
12744   //   If the class definition does not explicitly declare a copy
12745   //   constructor, one is declared implicitly.
12746   assert(ClassDecl->needsImplicitCopyConstructor());
12747 
12748   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12749   if (DSM.isAlreadyBeingDeclared())
12750     return nullptr;
12751 
12752   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12753   QualType ArgType = ClassType;
12754   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12755   if (Const)
12756     ArgType = ArgType.withConst();
12757 
12758   if (Context.getLangOpts().OpenCLCPlusPlus)
12759     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12760 
12761   ArgType = Context.getLValueReferenceType(ArgType);
12762 
12763   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12764                                                      CXXCopyConstructor,
12765                                                      Const);
12766 
12767   DeclarationName Name
12768     = Context.DeclarationNames.getCXXConstructorName(
12769                                            Context.getCanonicalType(ClassType));
12770   SourceLocation ClassLoc = ClassDecl->getLocation();
12771   DeclarationNameInfo NameInfo(Name, ClassLoc);
12772 
12773   //   An implicitly-declared copy constructor is an inline public
12774   //   member of its class.
12775   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12776       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12777       ExplicitSpecifier(),
12778       /*isInline=*/true,
12779       /*isImplicitlyDeclared=*/true,
12780       Constexpr ? CSK_constexpr : CSK_unspecified);
12781   CopyConstructor->setAccess(AS_public);
12782   CopyConstructor->setDefaulted();
12783 
12784   if (getLangOpts().CUDA) {
12785     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12786                                             CopyConstructor,
12787                                             /* ConstRHS */ Const,
12788                                             /* Diagnose */ false);
12789   }
12790 
12791   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12792 
12793   // Add the parameter to the constructor.
12794   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12795                                                ClassLoc, ClassLoc,
12796                                                /*IdentifierInfo=*/nullptr,
12797                                                ArgType, /*TInfo=*/nullptr,
12798                                                SC_None, nullptr);
12799   CopyConstructor->setParams(FromParam);
12800 
12801   CopyConstructor->setTrivial(
12802       ClassDecl->needsOverloadResolutionForCopyConstructor()
12803           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12804           : ClassDecl->hasTrivialCopyConstructor());
12805 
12806   CopyConstructor->setTrivialForCall(
12807       ClassDecl->hasAttr<TrivialABIAttr>() ||
12808       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12809            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12810              TAH_ConsiderTrivialABI)
12811            : ClassDecl->hasTrivialCopyConstructorForCall()));
12812 
12813   // Note that we have declared this constructor.
12814   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12815 
12816   Scope *S = getScopeForContext(ClassDecl);
12817   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12818 
12819   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12820     ClassDecl->setImplicitCopyConstructorIsDeleted();
12821     SetDeclDeleted(CopyConstructor, ClassLoc);
12822   }
12823 
12824   if (S)
12825     PushOnScopeChains(CopyConstructor, S, false);
12826   ClassDecl->addDecl(CopyConstructor);
12827 
12828   return CopyConstructor;
12829 }
12830 
12831 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12832                                          CXXConstructorDecl *CopyConstructor) {
12833   assert((CopyConstructor->isDefaulted() &&
12834           CopyConstructor->isCopyConstructor() &&
12835           !CopyConstructor->doesThisDeclarationHaveABody() &&
12836           !CopyConstructor->isDeleted()) &&
12837          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12838   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12839     return;
12840 
12841   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12842   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12843 
12844   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12845 
12846   // The exception specification is needed because we are defining the
12847   // function.
12848   ResolveExceptionSpec(CurrentLocation,
12849                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12850   MarkVTableUsed(CurrentLocation, ClassDecl);
12851 
12852   // Add a context note for diagnostics produced after this point.
12853   Scope.addContextNote(CurrentLocation);
12854 
12855   // C++11 [class.copy]p7:
12856   //   The [definition of an implicitly declared copy constructor] is
12857   //   deprecated if the class has a user-declared copy assignment operator
12858   //   or a user-declared destructor.
12859   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12860     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12861 
12862   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12863     CopyConstructor->setInvalidDecl();
12864   }  else {
12865     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12866                              ? CopyConstructor->getEndLoc()
12867                              : CopyConstructor->getLocation();
12868     Sema::CompoundScopeRAII CompoundScope(*this);
12869     CopyConstructor->setBody(
12870         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12871     CopyConstructor->markUsed(Context);
12872   }
12873 
12874   if (ASTMutationListener *L = getASTMutationListener()) {
12875     L->CompletedImplicitDefinition(CopyConstructor);
12876   }
12877 }
12878 
12879 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12880                                                     CXXRecordDecl *ClassDecl) {
12881   assert(ClassDecl->needsImplicitMoveConstructor());
12882 
12883   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12884   if (DSM.isAlreadyBeingDeclared())
12885     return nullptr;
12886 
12887   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12888 
12889   QualType ArgType = ClassType;
12890   if (Context.getLangOpts().OpenCLCPlusPlus)
12891     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12892   ArgType = Context.getRValueReferenceType(ArgType);
12893 
12894   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12895                                                      CXXMoveConstructor,
12896                                                      false);
12897 
12898   DeclarationName Name
12899     = Context.DeclarationNames.getCXXConstructorName(
12900                                            Context.getCanonicalType(ClassType));
12901   SourceLocation ClassLoc = ClassDecl->getLocation();
12902   DeclarationNameInfo NameInfo(Name, ClassLoc);
12903 
12904   // C++11 [class.copy]p11:
12905   //   An implicitly-declared copy/move constructor is an inline public
12906   //   member of its class.
12907   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12908       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12909       ExplicitSpecifier(),
12910       /*isInline=*/true,
12911       /*isImplicitlyDeclared=*/true,
12912       Constexpr ? CSK_constexpr : CSK_unspecified);
12913   MoveConstructor->setAccess(AS_public);
12914   MoveConstructor->setDefaulted();
12915 
12916   if (getLangOpts().CUDA) {
12917     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12918                                             MoveConstructor,
12919                                             /* ConstRHS */ false,
12920                                             /* Diagnose */ false);
12921   }
12922 
12923   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12924 
12925   // Add the parameter to the constructor.
12926   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12927                                                ClassLoc, ClassLoc,
12928                                                /*IdentifierInfo=*/nullptr,
12929                                                ArgType, /*TInfo=*/nullptr,
12930                                                SC_None, nullptr);
12931   MoveConstructor->setParams(FromParam);
12932 
12933   MoveConstructor->setTrivial(
12934       ClassDecl->needsOverloadResolutionForMoveConstructor()
12935           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12936           : ClassDecl->hasTrivialMoveConstructor());
12937 
12938   MoveConstructor->setTrivialForCall(
12939       ClassDecl->hasAttr<TrivialABIAttr>() ||
12940       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12941            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12942                                     TAH_ConsiderTrivialABI)
12943            : ClassDecl->hasTrivialMoveConstructorForCall()));
12944 
12945   // Note that we have declared this constructor.
12946   ++getASTContext().NumImplicitMoveConstructorsDeclared;
12947 
12948   Scope *S = getScopeForContext(ClassDecl);
12949   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12950 
12951   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12952     ClassDecl->setImplicitMoveConstructorIsDeleted();
12953     SetDeclDeleted(MoveConstructor, ClassLoc);
12954   }
12955 
12956   if (S)
12957     PushOnScopeChains(MoveConstructor, S, false);
12958   ClassDecl->addDecl(MoveConstructor);
12959 
12960   return MoveConstructor;
12961 }
12962 
12963 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12964                                          CXXConstructorDecl *MoveConstructor) {
12965   assert((MoveConstructor->isDefaulted() &&
12966           MoveConstructor->isMoveConstructor() &&
12967           !MoveConstructor->doesThisDeclarationHaveABody() &&
12968           !MoveConstructor->isDeleted()) &&
12969          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12970   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12971     return;
12972 
12973   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12974   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12975 
12976   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12977 
12978   // The exception specification is needed because we are defining the
12979   // function.
12980   ResolveExceptionSpec(CurrentLocation,
12981                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12982   MarkVTableUsed(CurrentLocation, ClassDecl);
12983 
12984   // Add a context note for diagnostics produced after this point.
12985   Scope.addContextNote(CurrentLocation);
12986 
12987   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12988     MoveConstructor->setInvalidDecl();
12989   } else {
12990     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12991                              ? MoveConstructor->getEndLoc()
12992                              : MoveConstructor->getLocation();
12993     Sema::CompoundScopeRAII CompoundScope(*this);
12994     MoveConstructor->setBody(ActOnCompoundStmt(
12995         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12996     MoveConstructor->markUsed(Context);
12997   }
12998 
12999   if (ASTMutationListener *L = getASTMutationListener()) {
13000     L->CompletedImplicitDefinition(MoveConstructor);
13001   }
13002 }
13003 
13004 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
13005   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
13006 }
13007 
13008 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
13009                             SourceLocation CurrentLocation,
13010                             CXXConversionDecl *Conv) {
13011   SynthesizedFunctionScope Scope(*this, Conv);
13012   assert(!Conv->getReturnType()->isUndeducedType());
13013 
13014   CXXRecordDecl *Lambda = Conv->getParent();
13015   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
13016   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
13017 
13018   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
13019     CallOp = InstantiateFunctionDeclaration(
13020         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13021     if (!CallOp)
13022       return;
13023 
13024     Invoker = InstantiateFunctionDeclaration(
13025         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13026     if (!Invoker)
13027       return;
13028   }
13029 
13030   if (CallOp->isInvalidDecl())
13031     return;
13032 
13033   // Mark the call operator referenced (and add to pending instantiations
13034   // if necessary).
13035   // For both the conversion and static-invoker template specializations
13036   // we construct their body's in this function, so no need to add them
13037   // to the PendingInstantiations.
13038   MarkFunctionReferenced(CurrentLocation, CallOp);
13039 
13040   // Fill in the __invoke function with a dummy implementation. IR generation
13041   // will fill in the actual details. Update its type in case it contained
13042   // an 'auto'.
13043   Invoker->markUsed(Context);
13044   Invoker->setReferenced();
13045   Invoker->setType(Conv->getReturnType()->getPointeeType());
13046   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
13047 
13048   // Construct the body of the conversion function { return __invoke; }.
13049   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
13050                                        VK_LValue, Conv->getLocation());
13051   assert(FunctionRef && "Can't refer to __invoke function?");
13052   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
13053   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
13054                                      Conv->getLocation()));
13055   Conv->markUsed(Context);
13056   Conv->setReferenced();
13057 
13058   if (ASTMutationListener *L = getASTMutationListener()) {
13059     L->CompletedImplicitDefinition(Conv);
13060     L->CompletedImplicitDefinition(Invoker);
13061   }
13062 }
13063 
13064 
13065 
13066 void Sema::DefineImplicitLambdaToBlockPointerConversion(
13067        SourceLocation CurrentLocation,
13068        CXXConversionDecl *Conv)
13069 {
13070   assert(!Conv->getParent()->isGenericLambda());
13071 
13072   SynthesizedFunctionScope Scope(*this, Conv);
13073 
13074   // Copy-initialize the lambda object as needed to capture it.
13075   Expr *This = ActOnCXXThis(CurrentLocation).get();
13076   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
13077 
13078   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
13079                                                         Conv->getLocation(),
13080                                                         Conv, DerefThis);
13081 
13082   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
13083   // behavior.  Note that only the general conversion function does this
13084   // (since it's unusable otherwise); in the case where we inline the
13085   // block literal, it has block literal lifetime semantics.
13086   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
13087     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
13088                                           CK_CopyAndAutoreleaseBlockObject,
13089                                           BuildBlock.get(), nullptr, VK_RValue);
13090 
13091   if (BuildBlock.isInvalid()) {
13092     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13093     Conv->setInvalidDecl();
13094     return;
13095   }
13096 
13097   // Create the return statement that returns the block from the conversion
13098   // function.
13099   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
13100   if (Return.isInvalid()) {
13101     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13102     Conv->setInvalidDecl();
13103     return;
13104   }
13105 
13106   // Set the body of the conversion function.
13107   Stmt *ReturnS = Return.get();
13108   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
13109                                      Conv->getLocation()));
13110   Conv->markUsed(Context);
13111 
13112   // We're done; notify the mutation listener, if any.
13113   if (ASTMutationListener *L = getASTMutationListener()) {
13114     L->CompletedImplicitDefinition(Conv);
13115   }
13116 }
13117 
13118 /// Determine whether the given list arguments contains exactly one
13119 /// "real" (non-default) argument.
13120 static bool hasOneRealArgument(MultiExprArg Args) {
13121   switch (Args.size()) {
13122   case 0:
13123     return false;
13124 
13125   default:
13126     if (!Args[1]->isDefaultArgument())
13127       return false;
13128 
13129     LLVM_FALLTHROUGH;
13130   case 1:
13131     return !Args[0]->isDefaultArgument();
13132   }
13133 
13134   return false;
13135 }
13136 
13137 ExprResult
13138 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13139                             NamedDecl *FoundDecl,
13140                             CXXConstructorDecl *Constructor,
13141                             MultiExprArg ExprArgs,
13142                             bool HadMultipleCandidates,
13143                             bool IsListInitialization,
13144                             bool IsStdInitListInitialization,
13145                             bool RequiresZeroInit,
13146                             unsigned ConstructKind,
13147                             SourceRange ParenRange) {
13148   bool Elidable = false;
13149 
13150   // C++0x [class.copy]p34:
13151   //   When certain criteria are met, an implementation is allowed to
13152   //   omit the copy/move construction of a class object, even if the
13153   //   copy/move constructor and/or destructor for the object have
13154   //   side effects. [...]
13155   //     - when a temporary class object that has not been bound to a
13156   //       reference (12.2) would be copied/moved to a class object
13157   //       with the same cv-unqualified type, the copy/move operation
13158   //       can be omitted by constructing the temporary object
13159   //       directly into the target of the omitted copy/move
13160   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13161       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13162     Expr *SubExpr = ExprArgs[0];
13163     Elidable = SubExpr->isTemporaryObject(
13164         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13165   }
13166 
13167   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13168                                FoundDecl, Constructor,
13169                                Elidable, ExprArgs, HadMultipleCandidates,
13170                                IsListInitialization,
13171                                IsStdInitListInitialization, RequiresZeroInit,
13172                                ConstructKind, ParenRange);
13173 }
13174 
13175 ExprResult
13176 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13177                             NamedDecl *FoundDecl,
13178                             CXXConstructorDecl *Constructor,
13179                             bool Elidable,
13180                             MultiExprArg ExprArgs,
13181                             bool HadMultipleCandidates,
13182                             bool IsListInitialization,
13183                             bool IsStdInitListInitialization,
13184                             bool RequiresZeroInit,
13185                             unsigned ConstructKind,
13186                             SourceRange ParenRange) {
13187   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13188     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13189     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13190       return ExprError();
13191   }
13192 
13193   return BuildCXXConstructExpr(
13194       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13195       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13196       RequiresZeroInit, ConstructKind, ParenRange);
13197 }
13198 
13199 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13200 /// including handling of its default argument expressions.
13201 ExprResult
13202 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13203                             CXXConstructorDecl *Constructor,
13204                             bool Elidable,
13205                             MultiExprArg ExprArgs,
13206                             bool HadMultipleCandidates,
13207                             bool IsListInitialization,
13208                             bool IsStdInitListInitialization,
13209                             bool RequiresZeroInit,
13210                             unsigned ConstructKind,
13211                             SourceRange ParenRange) {
13212   assert(declaresSameEntity(
13213              Constructor->getParent(),
13214              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13215          "given constructor for wrong type");
13216   MarkFunctionReferenced(ConstructLoc, Constructor);
13217   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13218     return ExprError();
13219 
13220   return CXXConstructExpr::Create(
13221       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13222       ExprArgs, HadMultipleCandidates, IsListInitialization,
13223       IsStdInitListInitialization, RequiresZeroInit,
13224       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13225       ParenRange);
13226 }
13227 
13228 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13229   assert(Field->hasInClassInitializer());
13230 
13231   // If we already have the in-class initializer nothing needs to be done.
13232   if (Field->getInClassInitializer())
13233     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13234 
13235   // If we might have already tried and failed to instantiate, don't try again.
13236   if (Field->isInvalidDecl())
13237     return ExprError();
13238 
13239   // Maybe we haven't instantiated the in-class initializer. Go check the
13240   // pattern FieldDecl to see if it has one.
13241   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13242 
13243   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13244     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13245     DeclContext::lookup_result Lookup =
13246         ClassPattern->lookup(Field->getDeclName());
13247 
13248     // Lookup can return at most two results: the pattern for the field, or the
13249     // injected class name of the parent record. No other member can have the
13250     // same name as the field.
13251     // In modules mode, lookup can return multiple results (coming from
13252     // different modules).
13253     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13254            "more than two lookup results for field name");
13255     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13256     if (!Pattern) {
13257       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13258              "cannot have other non-field member with same name");
13259       for (auto L : Lookup)
13260         if (isa<FieldDecl>(L)) {
13261           Pattern = cast<FieldDecl>(L);
13262           break;
13263         }
13264       assert(Pattern && "We must have set the Pattern!");
13265     }
13266 
13267     if (!Pattern->hasInClassInitializer() ||
13268         InstantiateInClassInitializer(Loc, Field, Pattern,
13269                                       getTemplateInstantiationArgs(Field))) {
13270       // Don't diagnose this again.
13271       Field->setInvalidDecl();
13272       return ExprError();
13273     }
13274     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13275   }
13276 
13277   // DR1351:
13278   //   If the brace-or-equal-initializer of a non-static data member
13279   //   invokes a defaulted default constructor of its class or of an
13280   //   enclosing class in a potentially evaluated subexpression, the
13281   //   program is ill-formed.
13282   //
13283   // This resolution is unworkable: the exception specification of the
13284   // default constructor can be needed in an unevaluated context, in
13285   // particular, in the operand of a noexcept-expression, and we can be
13286   // unable to compute an exception specification for an enclosed class.
13287   //
13288   // Any attempt to resolve the exception specification of a defaulted default
13289   // constructor before the initializer is lexically complete will ultimately
13290   // come here at which point we can diagnose it.
13291   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13292   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13293       << OutermostClass << Field;
13294   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13295   // Recover by marking the field invalid, unless we're in a SFINAE context.
13296   if (!isSFINAEContext())
13297     Field->setInvalidDecl();
13298   return ExprError();
13299 }
13300 
13301 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13302   if (VD->isInvalidDecl()) return;
13303 
13304   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13305   if (ClassDecl->isInvalidDecl()) return;
13306   if (ClassDecl->hasIrrelevantDestructor()) return;
13307   if (ClassDecl->isDependentContext()) return;
13308 
13309   if (VD->isNoDestroy(getASTContext()))
13310     return;
13311 
13312   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13313 
13314   // If this is an array, we'll require the destructor during initialization, so
13315   // we can skip over this. We still want to emit exit-time destructor warnings
13316   // though.
13317   if (!VD->getType()->isArrayType()) {
13318     MarkFunctionReferenced(VD->getLocation(), Destructor);
13319     CheckDestructorAccess(VD->getLocation(), Destructor,
13320                           PDiag(diag::err_access_dtor_var)
13321                               << VD->getDeclName() << VD->getType());
13322     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13323   }
13324 
13325   if (Destructor->isTrivial()) return;
13326   if (!VD->hasGlobalStorage()) return;
13327 
13328   // Emit warning for non-trivial dtor in global scope (a real global,
13329   // class-static, function-static).
13330   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13331 
13332   // TODO: this should be re-enabled for static locals by !CXAAtExit
13333   if (!VD->isStaticLocal())
13334     Diag(VD->getLocation(), diag::warn_global_destructor);
13335 }
13336 
13337 /// Given a constructor and the set of arguments provided for the
13338 /// constructor, convert the arguments and add any required default arguments
13339 /// to form a proper call to this constructor.
13340 ///
13341 /// \returns true if an error occurred, false otherwise.
13342 bool
13343 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13344                               MultiExprArg ArgsPtr,
13345                               SourceLocation Loc,
13346                               SmallVectorImpl<Expr*> &ConvertedArgs,
13347                               bool AllowExplicit,
13348                               bool IsListInitialization) {
13349   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13350   unsigned NumArgs = ArgsPtr.size();
13351   Expr **Args = ArgsPtr.data();
13352 
13353   const FunctionProtoType *Proto
13354     = Constructor->getType()->getAs<FunctionProtoType>();
13355   assert(Proto && "Constructor without a prototype?");
13356   unsigned NumParams = Proto->getNumParams();
13357 
13358   // If too few arguments are available, we'll fill in the rest with defaults.
13359   if (NumArgs < NumParams)
13360     ConvertedArgs.reserve(NumParams);
13361   else
13362     ConvertedArgs.reserve(NumArgs);
13363 
13364   VariadicCallType CallType =
13365     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13366   SmallVector<Expr *, 8> AllArgs;
13367   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13368                                         Proto, 0,
13369                                         llvm::makeArrayRef(Args, NumArgs),
13370                                         AllArgs,
13371                                         CallType, AllowExplicit,
13372                                         IsListInitialization);
13373   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13374 
13375   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13376 
13377   CheckConstructorCall(Constructor,
13378                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13379                        Proto, Loc);
13380 
13381   return Invalid;
13382 }
13383 
13384 static inline bool
13385 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13386                                        const FunctionDecl *FnDecl) {
13387   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13388   if (isa<NamespaceDecl>(DC)) {
13389     return SemaRef.Diag(FnDecl->getLocation(),
13390                         diag::err_operator_new_delete_declared_in_namespace)
13391       << FnDecl->getDeclName();
13392   }
13393 
13394   if (isa<TranslationUnitDecl>(DC) &&
13395       FnDecl->getStorageClass() == SC_Static) {
13396     return SemaRef.Diag(FnDecl->getLocation(),
13397                         diag::err_operator_new_delete_declared_static)
13398       << FnDecl->getDeclName();
13399   }
13400 
13401   return false;
13402 }
13403 
13404 static QualType
13405 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13406   QualType QTy = PtrTy->getPointeeType();
13407   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13408   return SemaRef.Context.getPointerType(QTy);
13409 }
13410 
13411 static inline bool
13412 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13413                             CanQualType ExpectedResultType,
13414                             CanQualType ExpectedFirstParamType,
13415                             unsigned DependentParamTypeDiag,
13416                             unsigned InvalidParamTypeDiag) {
13417   QualType ResultType =
13418       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13419 
13420   // Check that the result type is not dependent.
13421   if (ResultType->isDependentType())
13422     return SemaRef.Diag(FnDecl->getLocation(),
13423                         diag::err_operator_new_delete_dependent_result_type)
13424     << FnDecl->getDeclName() << ExpectedResultType;
13425 
13426   // The operator is valid on any address space for OpenCL.
13427   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13428     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13429       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13430     }
13431   }
13432 
13433   // Check that the result type is what we expect.
13434   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13435     return SemaRef.Diag(FnDecl->getLocation(),
13436                         diag::err_operator_new_delete_invalid_result_type)
13437     << FnDecl->getDeclName() << ExpectedResultType;
13438 
13439   // A function template must have at least 2 parameters.
13440   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13441     return SemaRef.Diag(FnDecl->getLocation(),
13442                       diag::err_operator_new_delete_template_too_few_parameters)
13443         << FnDecl->getDeclName();
13444 
13445   // The function decl must have at least 1 parameter.
13446   if (FnDecl->getNumParams() == 0)
13447     return SemaRef.Diag(FnDecl->getLocation(),
13448                         diag::err_operator_new_delete_too_few_parameters)
13449       << FnDecl->getDeclName();
13450 
13451   // Check the first parameter type is not dependent.
13452   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13453   if (FirstParamType->isDependentType())
13454     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13455       << FnDecl->getDeclName() << ExpectedFirstParamType;
13456 
13457   // Check that the first parameter type is what we expect.
13458   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13459     // The operator is valid on any address space for OpenCL.
13460     if (auto *PtrTy =
13461             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13462       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13463     }
13464   }
13465   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13466       ExpectedFirstParamType)
13467     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13468     << FnDecl->getDeclName() << ExpectedFirstParamType;
13469 
13470   return false;
13471 }
13472 
13473 static bool
13474 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13475   // C++ [basic.stc.dynamic.allocation]p1:
13476   //   A program is ill-formed if an allocation function is declared in a
13477   //   namespace scope other than global scope or declared static in global
13478   //   scope.
13479   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13480     return true;
13481 
13482   CanQualType SizeTy =
13483     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13484 
13485   // C++ [basic.stc.dynamic.allocation]p1:
13486   //  The return type shall be void*. The first parameter shall have type
13487   //  std::size_t.
13488   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13489                                   SizeTy,
13490                                   diag::err_operator_new_dependent_param_type,
13491                                   diag::err_operator_new_param_type))
13492     return true;
13493 
13494   // C++ [basic.stc.dynamic.allocation]p1:
13495   //  The first parameter shall not have an associated default argument.
13496   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13497     return SemaRef.Diag(FnDecl->getLocation(),
13498                         diag::err_operator_new_default_arg)
13499       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13500 
13501   return false;
13502 }
13503 
13504 static bool
13505 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13506   // C++ [basic.stc.dynamic.deallocation]p1:
13507   //   A program is ill-formed if deallocation functions are declared in a
13508   //   namespace scope other than global scope or declared static in global
13509   //   scope.
13510   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13511     return true;
13512 
13513   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13514 
13515   // C++ P0722:
13516   //   Within a class C, the first parameter of a destroying operator delete
13517   //   shall be of type C *. The first parameter of any other deallocation
13518   //   function shall be of type void *.
13519   CanQualType ExpectedFirstParamType =
13520       MD && MD->isDestroyingOperatorDelete()
13521           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13522                 SemaRef.Context.getRecordType(MD->getParent())))
13523           : SemaRef.Context.VoidPtrTy;
13524 
13525   // C++ [basic.stc.dynamic.deallocation]p2:
13526   //   Each deallocation function shall return void
13527   if (CheckOperatorNewDeleteTypes(
13528           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13529           diag::err_operator_delete_dependent_param_type,
13530           diag::err_operator_delete_param_type))
13531     return true;
13532 
13533   // C++ P0722:
13534   //   A destroying operator delete shall be a usual deallocation function.
13535   if (MD && !MD->getParent()->isDependentContext() &&
13536       MD->isDestroyingOperatorDelete() &&
13537       !SemaRef.isUsualDeallocationFunction(MD)) {
13538     SemaRef.Diag(MD->getLocation(),
13539                  diag::err_destroying_operator_delete_not_usual);
13540     return true;
13541   }
13542 
13543   return false;
13544 }
13545 
13546 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13547 /// of this overloaded operator is well-formed. If so, returns false;
13548 /// otherwise, emits appropriate diagnostics and returns true.
13549 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13550   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13551          "Expected an overloaded operator declaration");
13552 
13553   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13554 
13555   // C++ [over.oper]p5:
13556   //   The allocation and deallocation functions, operator new,
13557   //   operator new[], operator delete and operator delete[], are
13558   //   described completely in 3.7.3. The attributes and restrictions
13559   //   found in the rest of this subclause do not apply to them unless
13560   //   explicitly stated in 3.7.3.
13561   if (Op == OO_Delete || Op == OO_Array_Delete)
13562     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13563 
13564   if (Op == OO_New || Op == OO_Array_New)
13565     return CheckOperatorNewDeclaration(*this, FnDecl);
13566 
13567   // C++ [over.oper]p6:
13568   //   An operator function shall either be a non-static member
13569   //   function or be a non-member function and have at least one
13570   //   parameter whose type is a class, a reference to a class, an
13571   //   enumeration, or a reference to an enumeration.
13572   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13573     if (MethodDecl->isStatic())
13574       return Diag(FnDecl->getLocation(),
13575                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13576   } else {
13577     bool ClassOrEnumParam = false;
13578     for (auto Param : FnDecl->parameters()) {
13579       QualType ParamType = Param->getType().getNonReferenceType();
13580       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13581           ParamType->isEnumeralType()) {
13582         ClassOrEnumParam = true;
13583         break;
13584       }
13585     }
13586 
13587     if (!ClassOrEnumParam)
13588       return Diag(FnDecl->getLocation(),
13589                   diag::err_operator_overload_needs_class_or_enum)
13590         << FnDecl->getDeclName();
13591   }
13592 
13593   // C++ [over.oper]p8:
13594   //   An operator function cannot have default arguments (8.3.6),
13595   //   except where explicitly stated below.
13596   //
13597   // Only the function-call operator allows default arguments
13598   // (C++ [over.call]p1).
13599   if (Op != OO_Call) {
13600     for (auto Param : FnDecl->parameters()) {
13601       if (Param->hasDefaultArg())
13602         return Diag(Param->getLocation(),
13603                     diag::err_operator_overload_default_arg)
13604           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13605     }
13606   }
13607 
13608   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13609     { false, false, false }
13610 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13611     , { Unary, Binary, MemberOnly }
13612 #include "clang/Basic/OperatorKinds.def"
13613   };
13614 
13615   bool CanBeUnaryOperator = OperatorUses[Op][0];
13616   bool CanBeBinaryOperator = OperatorUses[Op][1];
13617   bool MustBeMemberOperator = OperatorUses[Op][2];
13618 
13619   // C++ [over.oper]p8:
13620   //   [...] Operator functions cannot have more or fewer parameters
13621   //   than the number required for the corresponding operator, as
13622   //   described in the rest of this subclause.
13623   unsigned NumParams = FnDecl->getNumParams()
13624                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13625   if (Op != OO_Call &&
13626       ((NumParams == 1 && !CanBeUnaryOperator) ||
13627        (NumParams == 2 && !CanBeBinaryOperator) ||
13628        (NumParams < 1) || (NumParams > 2))) {
13629     // We have the wrong number of parameters.
13630     unsigned ErrorKind;
13631     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13632       ErrorKind = 2;  // 2 -> unary or binary.
13633     } else if (CanBeUnaryOperator) {
13634       ErrorKind = 0;  // 0 -> unary
13635     } else {
13636       assert(CanBeBinaryOperator &&
13637              "All non-call overloaded operators are unary or binary!");
13638       ErrorKind = 1;  // 1 -> binary
13639     }
13640 
13641     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13642       << FnDecl->getDeclName() << NumParams << ErrorKind;
13643   }
13644 
13645   // Overloaded operators other than operator() cannot be variadic.
13646   if (Op != OO_Call &&
13647       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13648     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13649       << FnDecl->getDeclName();
13650   }
13651 
13652   // Some operators must be non-static member functions.
13653   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13654     return Diag(FnDecl->getLocation(),
13655                 diag::err_operator_overload_must_be_member)
13656       << FnDecl->getDeclName();
13657   }
13658 
13659   // C++ [over.inc]p1:
13660   //   The user-defined function called operator++ implements the
13661   //   prefix and postfix ++ operator. If this function is a member
13662   //   function with no parameters, or a non-member function with one
13663   //   parameter of class or enumeration type, it defines the prefix
13664   //   increment operator ++ for objects of that type. If the function
13665   //   is a member function with one parameter (which shall be of type
13666   //   int) or a non-member function with two parameters (the second
13667   //   of which shall be of type int), it defines the postfix
13668   //   increment operator ++ for objects of that type.
13669   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13670     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13671     QualType ParamType = LastParam->getType();
13672 
13673     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13674         !ParamType->isDependentType())
13675       return Diag(LastParam->getLocation(),
13676                   diag::err_operator_overload_post_incdec_must_be_int)
13677         << LastParam->getType() << (Op == OO_MinusMinus);
13678   }
13679 
13680   return false;
13681 }
13682 
13683 static bool
13684 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13685                                           FunctionTemplateDecl *TpDecl) {
13686   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13687 
13688   // Must have one or two template parameters.
13689   if (TemplateParams->size() == 1) {
13690     NonTypeTemplateParmDecl *PmDecl =
13691         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13692 
13693     // The template parameter must be a char parameter pack.
13694     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13695         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13696       return false;
13697 
13698   } else if (TemplateParams->size() == 2) {
13699     TemplateTypeParmDecl *PmType =
13700         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13701     NonTypeTemplateParmDecl *PmArgs =
13702         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13703 
13704     // The second template parameter must be a parameter pack with the
13705     // first template parameter as its type.
13706     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13707         PmArgs->isTemplateParameterPack()) {
13708       const TemplateTypeParmType *TArgs =
13709           PmArgs->getType()->getAs<TemplateTypeParmType>();
13710       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13711           TArgs->getIndex() == PmType->getIndex()) {
13712         if (!SemaRef.inTemplateInstantiation())
13713           SemaRef.Diag(TpDecl->getLocation(),
13714                        diag::ext_string_literal_operator_template);
13715         return false;
13716       }
13717     }
13718   }
13719 
13720   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13721                diag::err_literal_operator_template)
13722       << TpDecl->getTemplateParameters()->getSourceRange();
13723   return true;
13724 }
13725 
13726 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13727 /// of this literal operator function is well-formed. If so, returns
13728 /// false; otherwise, emits appropriate diagnostics and returns true.
13729 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13730   if (isa<CXXMethodDecl>(FnDecl)) {
13731     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13732       << FnDecl->getDeclName();
13733     return true;
13734   }
13735 
13736   if (FnDecl->isExternC()) {
13737     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13738     if (const LinkageSpecDecl *LSD =
13739             FnDecl->getDeclContext()->getExternCContext())
13740       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13741     return true;
13742   }
13743 
13744   // This might be the definition of a literal operator template.
13745   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13746 
13747   // This might be a specialization of a literal operator template.
13748   if (!TpDecl)
13749     TpDecl = FnDecl->getPrimaryTemplate();
13750 
13751   // template <char...> type operator "" name() and
13752   // template <class T, T...> type operator "" name() are the only valid
13753   // template signatures, and the only valid signatures with no parameters.
13754   if (TpDecl) {
13755     if (FnDecl->param_size() != 0) {
13756       Diag(FnDecl->getLocation(),
13757            diag::err_literal_operator_template_with_params);
13758       return true;
13759     }
13760 
13761     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13762       return true;
13763 
13764   } else if (FnDecl->param_size() == 1) {
13765     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13766 
13767     QualType ParamType = Param->getType().getUnqualifiedType();
13768 
13769     // Only unsigned long long int, long double, any character type, and const
13770     // char * are allowed as the only parameters.
13771     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13772         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13773         Context.hasSameType(ParamType, Context.CharTy) ||
13774         Context.hasSameType(ParamType, Context.WideCharTy) ||
13775         Context.hasSameType(ParamType, Context.Char8Ty) ||
13776         Context.hasSameType(ParamType, Context.Char16Ty) ||
13777         Context.hasSameType(ParamType, Context.Char32Ty)) {
13778     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13779       QualType InnerType = Ptr->getPointeeType();
13780 
13781       // Pointer parameter must be a const char *.
13782       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13783                                 Context.CharTy) &&
13784             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13785         Diag(Param->getSourceRange().getBegin(),
13786              diag::err_literal_operator_param)
13787             << ParamType << "'const char *'" << Param->getSourceRange();
13788         return true;
13789       }
13790 
13791     } else if (ParamType->isRealFloatingType()) {
13792       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13793           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13794       return true;
13795 
13796     } else if (ParamType->isIntegerType()) {
13797       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13798           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13799       return true;
13800 
13801     } else {
13802       Diag(Param->getSourceRange().getBegin(),
13803            diag::err_literal_operator_invalid_param)
13804           << ParamType << Param->getSourceRange();
13805       return true;
13806     }
13807 
13808   } else if (FnDecl->param_size() == 2) {
13809     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13810 
13811     // First, verify that the first parameter is correct.
13812 
13813     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13814 
13815     // Two parameter function must have a pointer to const as a
13816     // first parameter; let's strip those qualifiers.
13817     const PointerType *PT = FirstParamType->getAs<PointerType>();
13818 
13819     if (!PT) {
13820       Diag((*Param)->getSourceRange().getBegin(),
13821            diag::err_literal_operator_param)
13822           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13823       return true;
13824     }
13825 
13826     QualType PointeeType = PT->getPointeeType();
13827     // First parameter must be const
13828     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13829       Diag((*Param)->getSourceRange().getBegin(),
13830            diag::err_literal_operator_param)
13831           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13832       return true;
13833     }
13834 
13835     QualType InnerType = PointeeType.getUnqualifiedType();
13836     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13837     // const char32_t* are allowed as the first parameter to a two-parameter
13838     // function
13839     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13840           Context.hasSameType(InnerType, Context.WideCharTy) ||
13841           Context.hasSameType(InnerType, Context.Char8Ty) ||
13842           Context.hasSameType(InnerType, Context.Char16Ty) ||
13843           Context.hasSameType(InnerType, Context.Char32Ty))) {
13844       Diag((*Param)->getSourceRange().getBegin(),
13845            diag::err_literal_operator_param)
13846           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13847       return true;
13848     }
13849 
13850     // Move on to the second and final parameter.
13851     ++Param;
13852 
13853     // The second parameter must be a std::size_t.
13854     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13855     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13856       Diag((*Param)->getSourceRange().getBegin(),
13857            diag::err_literal_operator_param)
13858           << SecondParamType << Context.getSizeType()
13859           << (*Param)->getSourceRange();
13860       return true;
13861     }
13862   } else {
13863     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13864     return true;
13865   }
13866 
13867   // Parameters are good.
13868 
13869   // A parameter-declaration-clause containing a default argument is not
13870   // equivalent to any of the permitted forms.
13871   for (auto Param : FnDecl->parameters()) {
13872     if (Param->hasDefaultArg()) {
13873       Diag(Param->getDefaultArgRange().getBegin(),
13874            diag::err_literal_operator_default_argument)
13875         << Param->getDefaultArgRange();
13876       break;
13877     }
13878   }
13879 
13880   StringRef LiteralName
13881     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13882   if (LiteralName[0] != '_' &&
13883       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13884     // C++11 [usrlit.suffix]p1:
13885     //   Literal suffix identifiers that do not start with an underscore
13886     //   are reserved for future standardization.
13887     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13888       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13889   }
13890 
13891   return false;
13892 }
13893 
13894 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13895 /// linkage specification, including the language and (if present)
13896 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13897 /// language string literal. LBraceLoc, if valid, provides the location of
13898 /// the '{' brace. Otherwise, this linkage specification does not
13899 /// have any braces.
13900 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13901                                            Expr *LangStr,
13902                                            SourceLocation LBraceLoc) {
13903   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13904   if (!Lit->isAscii()) {
13905     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13906       << LangStr->getSourceRange();
13907     return nullptr;
13908   }
13909 
13910   StringRef Lang = Lit->getString();
13911   LinkageSpecDecl::LanguageIDs Language;
13912   if (Lang == "C")
13913     Language = LinkageSpecDecl::lang_c;
13914   else if (Lang == "C++")
13915     Language = LinkageSpecDecl::lang_cxx;
13916   else {
13917     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13918       << LangStr->getSourceRange();
13919     return nullptr;
13920   }
13921 
13922   // FIXME: Add all the various semantics of linkage specifications
13923 
13924   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13925                                                LangStr->getExprLoc(), Language,
13926                                                LBraceLoc.isValid());
13927   CurContext->addDecl(D);
13928   PushDeclContext(S, D);
13929   return D;
13930 }
13931 
13932 /// ActOnFinishLinkageSpecification - Complete the definition of
13933 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13934 /// valid, it's the position of the closing '}' brace in a linkage
13935 /// specification that uses braces.
13936 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13937                                             Decl *LinkageSpec,
13938                                             SourceLocation RBraceLoc) {
13939   if (RBraceLoc.isValid()) {
13940     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13941     LSDecl->setRBraceLoc(RBraceLoc);
13942   }
13943   PopDeclContext();
13944   return LinkageSpec;
13945 }
13946 
13947 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13948                                   const ParsedAttributesView &AttrList,
13949                                   SourceLocation SemiLoc) {
13950   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13951   // Attribute declarations appertain to empty declaration so we handle
13952   // them here.
13953   ProcessDeclAttributeList(S, ED, AttrList);
13954 
13955   CurContext->addDecl(ED);
13956   return ED;
13957 }
13958 
13959 /// Perform semantic analysis for the variable declaration that
13960 /// occurs within a C++ catch clause, returning the newly-created
13961 /// variable.
13962 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13963                                          TypeSourceInfo *TInfo,
13964                                          SourceLocation StartLoc,
13965                                          SourceLocation Loc,
13966                                          IdentifierInfo *Name) {
13967   bool Invalid = false;
13968   QualType ExDeclType = TInfo->getType();
13969 
13970   // Arrays and functions decay.
13971   if (ExDeclType->isArrayType())
13972     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13973   else if (ExDeclType->isFunctionType())
13974     ExDeclType = Context.getPointerType(ExDeclType);
13975 
13976   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13977   // The exception-declaration shall not denote a pointer or reference to an
13978   // incomplete type, other than [cv] void*.
13979   // N2844 forbids rvalue references.
13980   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13981     Diag(Loc, diag::err_catch_rvalue_ref);
13982     Invalid = true;
13983   }
13984 
13985   if (ExDeclType->isVariablyModifiedType()) {
13986     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13987     Invalid = true;
13988   }
13989 
13990   QualType BaseType = ExDeclType;
13991   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13992   unsigned DK = diag::err_catch_incomplete;
13993   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13994     BaseType = Ptr->getPointeeType();
13995     Mode = 1;
13996     DK = diag::err_catch_incomplete_ptr;
13997   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13998     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13999     BaseType = Ref->getPointeeType();
14000     Mode = 2;
14001     DK = diag::err_catch_incomplete_ref;
14002   }
14003   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
14004       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
14005     Invalid = true;
14006 
14007   if (!Invalid && !ExDeclType->isDependentType() &&
14008       RequireNonAbstractType(Loc, ExDeclType,
14009                              diag::err_abstract_type_in_decl,
14010                              AbstractVariableType))
14011     Invalid = true;
14012 
14013   // Only the non-fragile NeXT runtime currently supports C++ catches
14014   // of ObjC types, and no runtime supports catching ObjC types by value.
14015   if (!Invalid && getLangOpts().ObjC) {
14016     QualType T = ExDeclType;
14017     if (const ReferenceType *RT = T->getAs<ReferenceType>())
14018       T = RT->getPointeeType();
14019 
14020     if (T->isObjCObjectType()) {
14021       Diag(Loc, diag::err_objc_object_catch);
14022       Invalid = true;
14023     } else if (T->isObjCObjectPointerType()) {
14024       // FIXME: should this be a test for macosx-fragile specifically?
14025       if (getLangOpts().ObjCRuntime.isFragile())
14026         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
14027     }
14028   }
14029 
14030   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
14031                                     ExDeclType, TInfo, SC_None);
14032   ExDecl->setExceptionVariable(true);
14033 
14034   // In ARC, infer 'retaining' for variables of retainable type.
14035   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
14036     Invalid = true;
14037 
14038   if (!Invalid && !ExDeclType->isDependentType()) {
14039     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
14040       // Insulate this from anything else we might currently be parsing.
14041       EnterExpressionEvaluationContext scope(
14042           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14043 
14044       // C++ [except.handle]p16:
14045       //   The object declared in an exception-declaration or, if the
14046       //   exception-declaration does not specify a name, a temporary (12.2) is
14047       //   copy-initialized (8.5) from the exception object. [...]
14048       //   The object is destroyed when the handler exits, after the destruction
14049       //   of any automatic objects initialized within the handler.
14050       //
14051       // We just pretend to initialize the object with itself, then make sure
14052       // it can be destroyed later.
14053       QualType initType = Context.getExceptionObjectType(ExDeclType);
14054 
14055       InitializedEntity entity =
14056         InitializedEntity::InitializeVariable(ExDecl);
14057       InitializationKind initKind =
14058         InitializationKind::CreateCopy(Loc, SourceLocation());
14059 
14060       Expr *opaqueValue =
14061         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
14062       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
14063       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
14064       if (result.isInvalid())
14065         Invalid = true;
14066       else {
14067         // If the constructor used was non-trivial, set this as the
14068         // "initializer".
14069         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
14070         if (!construct->getConstructor()->isTrivial()) {
14071           Expr *init = MaybeCreateExprWithCleanups(construct);
14072           ExDecl->setInit(init);
14073         }
14074 
14075         // And make sure it's destructable.
14076         FinalizeVarWithDestructor(ExDecl, recordType);
14077       }
14078     }
14079   }
14080 
14081   if (Invalid)
14082     ExDecl->setInvalidDecl();
14083 
14084   return ExDecl;
14085 }
14086 
14087 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
14088 /// handler.
14089 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
14090   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14091   bool Invalid = D.isInvalidType();
14092 
14093   // Check for unexpanded parameter packs.
14094   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14095                                       UPPC_ExceptionType)) {
14096     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
14097                                              D.getIdentifierLoc());
14098     Invalid = true;
14099   }
14100 
14101   IdentifierInfo *II = D.getIdentifier();
14102   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
14103                                              LookupOrdinaryName,
14104                                              ForVisibleRedeclaration)) {
14105     // The scope should be freshly made just for us. There is just no way
14106     // it contains any previous declaration, except for function parameters in
14107     // a function-try-block's catch statement.
14108     assert(!S->isDeclScope(PrevDecl));
14109     if (isDeclInScope(PrevDecl, CurContext, S)) {
14110       Diag(D.getIdentifierLoc(), diag::err_redefinition)
14111         << D.getIdentifier();
14112       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14113       Invalid = true;
14114     } else if (PrevDecl->isTemplateParameter())
14115       // Maybe we will complain about the shadowed template parameter.
14116       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14117   }
14118 
14119   if (D.getCXXScopeSpec().isSet() && !Invalid) {
14120     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
14121       << D.getCXXScopeSpec().getRange();
14122     Invalid = true;
14123   }
14124 
14125   VarDecl *ExDecl = BuildExceptionDeclaration(
14126       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
14127   if (Invalid)
14128     ExDecl->setInvalidDecl();
14129 
14130   // Add the exception declaration into this scope.
14131   if (II)
14132     PushOnScopeChains(ExDecl, S);
14133   else
14134     CurContext->addDecl(ExDecl);
14135 
14136   ProcessDeclAttributes(S, ExDecl, D);
14137   return ExDecl;
14138 }
14139 
14140 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14141                                          Expr *AssertExpr,
14142                                          Expr *AssertMessageExpr,
14143                                          SourceLocation RParenLoc) {
14144   StringLiteral *AssertMessage =
14145       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14146 
14147   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14148     return nullptr;
14149 
14150   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14151                                       AssertMessage, RParenLoc, false);
14152 }
14153 
14154 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14155                                          Expr *AssertExpr,
14156                                          StringLiteral *AssertMessage,
14157                                          SourceLocation RParenLoc,
14158                                          bool Failed) {
14159   assert(AssertExpr != nullptr && "Expected non-null condition");
14160   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14161       !Failed) {
14162     // In a static_assert-declaration, the constant-expression shall be a
14163     // constant expression that can be contextually converted to bool.
14164     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14165     if (Converted.isInvalid())
14166       Failed = true;
14167 
14168     llvm::APSInt Cond;
14169     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14170           diag::err_static_assert_expression_is_not_constant,
14171           /*AllowFold=*/false).isInvalid())
14172       Failed = true;
14173 
14174     if (!Failed && !Cond) {
14175       SmallString<256> MsgBuffer;
14176       llvm::raw_svector_ostream Msg(MsgBuffer);
14177       if (AssertMessage)
14178         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14179 
14180       Expr *InnerCond = nullptr;
14181       std::string InnerCondDescription;
14182       std::tie(InnerCond, InnerCondDescription) =
14183         findFailedBooleanCondition(Converted.get());
14184       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14185                     && !isa<IntegerLiteral>(InnerCond)) {
14186         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14187           << InnerCondDescription << !AssertMessage
14188           << Msg.str() << InnerCond->getSourceRange();
14189       } else {
14190         Diag(StaticAssertLoc, diag::err_static_assert_failed)
14191           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14192       }
14193       Failed = true;
14194     }
14195   }
14196 
14197   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14198                                                   /*DiscardedValue*/false,
14199                                                   /*IsConstexpr*/true);
14200   if (FullAssertExpr.isInvalid())
14201     Failed = true;
14202   else
14203     AssertExpr = FullAssertExpr.get();
14204 
14205   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14206                                         AssertExpr, AssertMessage, RParenLoc,
14207                                         Failed);
14208 
14209   CurContext->addDecl(Decl);
14210   return Decl;
14211 }
14212 
14213 /// Perform semantic analysis of the given friend type declaration.
14214 ///
14215 /// \returns A friend declaration that.
14216 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14217                                       SourceLocation FriendLoc,
14218                                       TypeSourceInfo *TSInfo) {
14219   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14220 
14221   QualType T = TSInfo->getType();
14222   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14223 
14224   // C++03 [class.friend]p2:
14225   //   An elaborated-type-specifier shall be used in a friend declaration
14226   //   for a class.*
14227   //
14228   //   * The class-key of the elaborated-type-specifier is required.
14229   if (!CodeSynthesisContexts.empty()) {
14230     // Do not complain about the form of friend template types during any kind
14231     // of code synthesis. For template instantiation, we will have complained
14232     // when the template was defined.
14233   } else {
14234     if (!T->isElaboratedTypeSpecifier()) {
14235       // If we evaluated the type to a record type, suggest putting
14236       // a tag in front.
14237       if (const RecordType *RT = T->getAs<RecordType>()) {
14238         RecordDecl *RD = RT->getDecl();
14239 
14240         SmallString<16> InsertionText(" ");
14241         InsertionText += RD->getKindName();
14242 
14243         Diag(TypeRange.getBegin(),
14244              getLangOpts().CPlusPlus11 ?
14245                diag::warn_cxx98_compat_unelaborated_friend_type :
14246                diag::ext_unelaborated_friend_type)
14247           << (unsigned) RD->getTagKind()
14248           << T
14249           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14250                                         InsertionText);
14251       } else {
14252         Diag(FriendLoc,
14253              getLangOpts().CPlusPlus11 ?
14254                diag::warn_cxx98_compat_nonclass_type_friend :
14255                diag::ext_nonclass_type_friend)
14256           << T
14257           << TypeRange;
14258       }
14259     } else if (T->getAs<EnumType>()) {
14260       Diag(FriendLoc,
14261            getLangOpts().CPlusPlus11 ?
14262              diag::warn_cxx98_compat_enum_friend :
14263              diag::ext_enum_friend)
14264         << T
14265         << TypeRange;
14266     }
14267 
14268     // C++11 [class.friend]p3:
14269     //   A friend declaration that does not declare a function shall have one
14270     //   of the following forms:
14271     //     friend elaborated-type-specifier ;
14272     //     friend simple-type-specifier ;
14273     //     friend typename-specifier ;
14274     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14275       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14276   }
14277 
14278   //   If the type specifier in a friend declaration designates a (possibly
14279   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14280   //   the friend declaration is ignored.
14281   return FriendDecl::Create(Context, CurContext,
14282                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14283                             FriendLoc);
14284 }
14285 
14286 /// Handle a friend tag declaration where the scope specifier was
14287 /// templated.
14288 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14289                                     unsigned TagSpec, SourceLocation TagLoc,
14290                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14291                                     SourceLocation NameLoc,
14292                                     const ParsedAttributesView &Attr,
14293                                     MultiTemplateParamsArg TempParamLists) {
14294   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14295 
14296   bool IsMemberSpecialization = false;
14297   bool Invalid = false;
14298 
14299   if (TemplateParameterList *TemplateParams =
14300           MatchTemplateParametersToScopeSpecifier(
14301               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14302               IsMemberSpecialization, Invalid)) {
14303     if (TemplateParams->size() > 0) {
14304       // This is a declaration of a class template.
14305       if (Invalid)
14306         return nullptr;
14307 
14308       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14309                                 NameLoc, Attr, TemplateParams, AS_public,
14310                                 /*ModulePrivateLoc=*/SourceLocation(),
14311                                 FriendLoc, TempParamLists.size() - 1,
14312                                 TempParamLists.data()).get();
14313     } else {
14314       // The "template<>" header is extraneous.
14315       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14316         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14317       IsMemberSpecialization = true;
14318     }
14319   }
14320 
14321   if (Invalid) return nullptr;
14322 
14323   bool isAllExplicitSpecializations = true;
14324   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14325     if (TempParamLists[I]->size()) {
14326       isAllExplicitSpecializations = false;
14327       break;
14328     }
14329   }
14330 
14331   // FIXME: don't ignore attributes.
14332 
14333   // If it's explicit specializations all the way down, just forget
14334   // about the template header and build an appropriate non-templated
14335   // friend.  TODO: for source fidelity, remember the headers.
14336   if (isAllExplicitSpecializations) {
14337     if (SS.isEmpty()) {
14338       bool Owned = false;
14339       bool IsDependent = false;
14340       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14341                       Attr, AS_public,
14342                       /*ModulePrivateLoc=*/SourceLocation(),
14343                       MultiTemplateParamsArg(), Owned, IsDependent,
14344                       /*ScopedEnumKWLoc=*/SourceLocation(),
14345                       /*ScopedEnumUsesClassTag=*/false,
14346                       /*UnderlyingType=*/TypeResult(),
14347                       /*IsTypeSpecifier=*/false,
14348                       /*IsTemplateParamOrArg=*/false);
14349     }
14350 
14351     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14352     ElaboratedTypeKeyword Keyword
14353       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14354     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14355                                    *Name, NameLoc);
14356     if (T.isNull())
14357       return nullptr;
14358 
14359     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14360     if (isa<DependentNameType>(T)) {
14361       DependentNameTypeLoc TL =
14362           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14363       TL.setElaboratedKeywordLoc(TagLoc);
14364       TL.setQualifierLoc(QualifierLoc);
14365       TL.setNameLoc(NameLoc);
14366     } else {
14367       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14368       TL.setElaboratedKeywordLoc(TagLoc);
14369       TL.setQualifierLoc(QualifierLoc);
14370       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14371     }
14372 
14373     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14374                                             TSI, FriendLoc, TempParamLists);
14375     Friend->setAccess(AS_public);
14376     CurContext->addDecl(Friend);
14377     return Friend;
14378   }
14379 
14380   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14381 
14382 
14383 
14384   // Handle the case of a templated-scope friend class.  e.g.
14385   //   template <class T> class A<T>::B;
14386   // FIXME: we don't support these right now.
14387   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14388     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14389   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14390   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14391   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14392   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14393   TL.setElaboratedKeywordLoc(TagLoc);
14394   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14395   TL.setNameLoc(NameLoc);
14396 
14397   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14398                                           TSI, FriendLoc, TempParamLists);
14399   Friend->setAccess(AS_public);
14400   Friend->setUnsupportedFriend(true);
14401   CurContext->addDecl(Friend);
14402   return Friend;
14403 }
14404 
14405 /// Handle a friend type declaration.  This works in tandem with
14406 /// ActOnTag.
14407 ///
14408 /// Notes on friend class templates:
14409 ///
14410 /// We generally treat friend class declarations as if they were
14411 /// declaring a class.  So, for example, the elaborated type specifier
14412 /// in a friend declaration is required to obey the restrictions of a
14413 /// class-head (i.e. no typedefs in the scope chain), template
14414 /// parameters are required to match up with simple template-ids, &c.
14415 /// However, unlike when declaring a template specialization, it's
14416 /// okay to refer to a template specialization without an empty
14417 /// template parameter declaration, e.g.
14418 ///   friend class A<T>::B<unsigned>;
14419 /// We permit this as a special case; if there are any template
14420 /// parameters present at all, require proper matching, i.e.
14421 ///   template <> template \<class T> friend class A<int>::B;
14422 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14423                                 MultiTemplateParamsArg TempParams) {
14424   SourceLocation Loc = DS.getBeginLoc();
14425 
14426   assert(DS.isFriendSpecified());
14427   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14428 
14429   // C++ [class.friend]p3:
14430   // A friend declaration that does not declare a function shall have one of
14431   // the following forms:
14432   //     friend elaborated-type-specifier ;
14433   //     friend simple-type-specifier ;
14434   //     friend typename-specifier ;
14435   //
14436   // Any declaration with a type qualifier does not have that form. (It's
14437   // legal to specify a qualified type as a friend, you just can't write the
14438   // keywords.)
14439   if (DS.getTypeQualifiers()) {
14440     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14441       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14442     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14443       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14444     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14445       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14446     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14447       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14448     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14449       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14450   }
14451 
14452   // Try to convert the decl specifier to a type.  This works for
14453   // friend templates because ActOnTag never produces a ClassTemplateDecl
14454   // for a TUK_Friend.
14455   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14456   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14457   QualType T = TSI->getType();
14458   if (TheDeclarator.isInvalidType())
14459     return nullptr;
14460 
14461   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14462     return nullptr;
14463 
14464   // This is definitely an error in C++98.  It's probably meant to
14465   // be forbidden in C++0x, too, but the specification is just
14466   // poorly written.
14467   //
14468   // The problem is with declarations like the following:
14469   //   template <T> friend A<T>::foo;
14470   // where deciding whether a class C is a friend or not now hinges
14471   // on whether there exists an instantiation of A that causes
14472   // 'foo' to equal C.  There are restrictions on class-heads
14473   // (which we declare (by fiat) elaborated friend declarations to
14474   // be) that makes this tractable.
14475   //
14476   // FIXME: handle "template <> friend class A<T>;", which
14477   // is possibly well-formed?  Who even knows?
14478   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14479     Diag(Loc, diag::err_tagless_friend_type_template)
14480       << DS.getSourceRange();
14481     return nullptr;
14482   }
14483 
14484   // C++98 [class.friend]p1: A friend of a class is a function
14485   //   or class that is not a member of the class . . .
14486   // This is fixed in DR77, which just barely didn't make the C++03
14487   // deadline.  It's also a very silly restriction that seriously
14488   // affects inner classes and which nobody else seems to implement;
14489   // thus we never diagnose it, not even in -pedantic.
14490   //
14491   // But note that we could warn about it: it's always useless to
14492   // friend one of your own members (it's not, however, worthless to
14493   // friend a member of an arbitrary specialization of your template).
14494 
14495   Decl *D;
14496   if (!TempParams.empty())
14497     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14498                                    TempParams,
14499                                    TSI,
14500                                    DS.getFriendSpecLoc());
14501   else
14502     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14503 
14504   if (!D)
14505     return nullptr;
14506 
14507   D->setAccess(AS_public);
14508   CurContext->addDecl(D);
14509 
14510   return D;
14511 }
14512 
14513 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14514                                         MultiTemplateParamsArg TemplateParams) {
14515   const DeclSpec &DS = D.getDeclSpec();
14516 
14517   assert(DS.isFriendSpecified());
14518   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14519 
14520   SourceLocation Loc = D.getIdentifierLoc();
14521   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14522 
14523   // C++ [class.friend]p1
14524   //   A friend of a class is a function or class....
14525   // Note that this sees through typedefs, which is intended.
14526   // It *doesn't* see through dependent types, which is correct
14527   // according to [temp.arg.type]p3:
14528   //   If a declaration acquires a function type through a
14529   //   type dependent on a template-parameter and this causes
14530   //   a declaration that does not use the syntactic form of a
14531   //   function declarator to have a function type, the program
14532   //   is ill-formed.
14533   if (!TInfo->getType()->isFunctionType()) {
14534     Diag(Loc, diag::err_unexpected_friend);
14535 
14536     // It might be worthwhile to try to recover by creating an
14537     // appropriate declaration.
14538     return nullptr;
14539   }
14540 
14541   // C++ [namespace.memdef]p3
14542   //  - If a friend declaration in a non-local class first declares a
14543   //    class or function, the friend class or function is a member
14544   //    of the innermost enclosing namespace.
14545   //  - The name of the friend is not found by simple name lookup
14546   //    until a matching declaration is provided in that namespace
14547   //    scope (either before or after the class declaration granting
14548   //    friendship).
14549   //  - If a friend function is called, its name may be found by the
14550   //    name lookup that considers functions from namespaces and
14551   //    classes associated with the types of the function arguments.
14552   //  - When looking for a prior declaration of a class or a function
14553   //    declared as a friend, scopes outside the innermost enclosing
14554   //    namespace scope are not considered.
14555 
14556   CXXScopeSpec &SS = D.getCXXScopeSpec();
14557   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14558   assert(NameInfo.getName());
14559 
14560   // Check for unexpanded parameter packs.
14561   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14562       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14563       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14564     return nullptr;
14565 
14566   // The context we found the declaration in, or in which we should
14567   // create the declaration.
14568   DeclContext *DC;
14569   Scope *DCScope = S;
14570   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14571                         ForExternalRedeclaration);
14572 
14573   // There are five cases here.
14574   //   - There's no scope specifier and we're in a local class. Only look
14575   //     for functions declared in the immediately-enclosing block scope.
14576   // We recover from invalid scope qualifiers as if they just weren't there.
14577   FunctionDecl *FunctionContainingLocalClass = nullptr;
14578   if ((SS.isInvalid() || !SS.isSet()) &&
14579       (FunctionContainingLocalClass =
14580            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14581     // C++11 [class.friend]p11:
14582     //   If a friend declaration appears in a local class and the name
14583     //   specified is an unqualified name, a prior declaration is
14584     //   looked up without considering scopes that are outside the
14585     //   innermost enclosing non-class scope. For a friend function
14586     //   declaration, if there is no prior declaration, the program is
14587     //   ill-formed.
14588 
14589     // Find the innermost enclosing non-class scope. This is the block
14590     // scope containing the local class definition (or for a nested class,
14591     // the outer local class).
14592     DCScope = S->getFnParent();
14593 
14594     // Look up the function name in the scope.
14595     Previous.clear(LookupLocalFriendName);
14596     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14597 
14598     if (!Previous.empty()) {
14599       // All possible previous declarations must have the same context:
14600       // either they were declared at block scope or they are members of
14601       // one of the enclosing local classes.
14602       DC = Previous.getRepresentativeDecl()->getDeclContext();
14603     } else {
14604       // This is ill-formed, but provide the context that we would have
14605       // declared the function in, if we were permitted to, for error recovery.
14606       DC = FunctionContainingLocalClass;
14607     }
14608     adjustContextForLocalExternDecl(DC);
14609 
14610     // C++ [class.friend]p6:
14611     //   A function can be defined in a friend declaration of a class if and
14612     //   only if the class is a non-local class (9.8), the function name is
14613     //   unqualified, and the function has namespace scope.
14614     if (D.isFunctionDefinition()) {
14615       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14616     }
14617 
14618   //   - There's no scope specifier, in which case we just go to the
14619   //     appropriate scope and look for a function or function template
14620   //     there as appropriate.
14621   } else if (SS.isInvalid() || !SS.isSet()) {
14622     // C++11 [namespace.memdef]p3:
14623     //   If the name in a friend declaration is neither qualified nor
14624     //   a template-id and the declaration is a function or an
14625     //   elaborated-type-specifier, the lookup to determine whether
14626     //   the entity has been previously declared shall not consider
14627     //   any scopes outside the innermost enclosing namespace.
14628     bool isTemplateId =
14629         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14630 
14631     // Find the appropriate context according to the above.
14632     DC = CurContext;
14633 
14634     // Skip class contexts.  If someone can cite chapter and verse
14635     // for this behavior, that would be nice --- it's what GCC and
14636     // EDG do, and it seems like a reasonable intent, but the spec
14637     // really only says that checks for unqualified existing
14638     // declarations should stop at the nearest enclosing namespace,
14639     // not that they should only consider the nearest enclosing
14640     // namespace.
14641     while (DC->isRecord())
14642       DC = DC->getParent();
14643 
14644     DeclContext *LookupDC = DC;
14645     while (LookupDC->isTransparentContext())
14646       LookupDC = LookupDC->getParent();
14647 
14648     while (true) {
14649       LookupQualifiedName(Previous, LookupDC);
14650 
14651       if (!Previous.empty()) {
14652         DC = LookupDC;
14653         break;
14654       }
14655 
14656       if (isTemplateId) {
14657         if (isa<TranslationUnitDecl>(LookupDC)) break;
14658       } else {
14659         if (LookupDC->isFileContext()) break;
14660       }
14661       LookupDC = LookupDC->getParent();
14662     }
14663 
14664     DCScope = getScopeForDeclContext(S, DC);
14665 
14666   //   - There's a non-dependent scope specifier, in which case we
14667   //     compute it and do a previous lookup there for a function
14668   //     or function template.
14669   } else if (!SS.getScopeRep()->isDependent()) {
14670     DC = computeDeclContext(SS);
14671     if (!DC) return nullptr;
14672 
14673     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14674 
14675     LookupQualifiedName(Previous, DC);
14676 
14677     // C++ [class.friend]p1: A friend of a class is a function or
14678     //   class that is not a member of the class . . .
14679     if (DC->Equals(CurContext))
14680       Diag(DS.getFriendSpecLoc(),
14681            getLangOpts().CPlusPlus11 ?
14682              diag::warn_cxx98_compat_friend_is_member :
14683              diag::err_friend_is_member);
14684 
14685     if (D.isFunctionDefinition()) {
14686       // C++ [class.friend]p6:
14687       //   A function can be defined in a friend declaration of a class if and
14688       //   only if the class is a non-local class (9.8), the function name is
14689       //   unqualified, and the function has namespace scope.
14690       //
14691       // FIXME: We should only do this if the scope specifier names the
14692       // innermost enclosing namespace; otherwise the fixit changes the
14693       // meaning of the code.
14694       SemaDiagnosticBuilder DB
14695         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14696 
14697       DB << SS.getScopeRep();
14698       if (DC->isFileContext())
14699         DB << FixItHint::CreateRemoval(SS.getRange());
14700       SS.clear();
14701     }
14702 
14703   //   - There's a scope specifier that does not match any template
14704   //     parameter lists, in which case we use some arbitrary context,
14705   //     create a method or method template, and wait for instantiation.
14706   //   - There's a scope specifier that does match some template
14707   //     parameter lists, which we don't handle right now.
14708   } else {
14709     if (D.isFunctionDefinition()) {
14710       // C++ [class.friend]p6:
14711       //   A function can be defined in a friend declaration of a class if and
14712       //   only if the class is a non-local class (9.8), the function name is
14713       //   unqualified, and the function has namespace scope.
14714       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14715         << SS.getScopeRep();
14716     }
14717 
14718     DC = CurContext;
14719     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14720   }
14721 
14722   if (!DC->isRecord()) {
14723     int DiagArg = -1;
14724     switch (D.getName().getKind()) {
14725     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14726     case UnqualifiedIdKind::IK_ConstructorName:
14727       DiagArg = 0;
14728       break;
14729     case UnqualifiedIdKind::IK_DestructorName:
14730       DiagArg = 1;
14731       break;
14732     case UnqualifiedIdKind::IK_ConversionFunctionId:
14733       DiagArg = 2;
14734       break;
14735     case UnqualifiedIdKind::IK_DeductionGuideName:
14736       DiagArg = 3;
14737       break;
14738     case UnqualifiedIdKind::IK_Identifier:
14739     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14740     case UnqualifiedIdKind::IK_LiteralOperatorId:
14741     case UnqualifiedIdKind::IK_OperatorFunctionId:
14742     case UnqualifiedIdKind::IK_TemplateId:
14743       break;
14744     }
14745     // This implies that it has to be an operator or function.
14746     if (DiagArg >= 0) {
14747       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14748       return nullptr;
14749     }
14750   }
14751 
14752   // FIXME: This is an egregious hack to cope with cases where the scope stack
14753   // does not contain the declaration context, i.e., in an out-of-line
14754   // definition of a class.
14755   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14756   if (!DCScope) {
14757     FakeDCScope.setEntity(DC);
14758     DCScope = &FakeDCScope;
14759   }
14760 
14761   bool AddToScope = true;
14762   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14763                                           TemplateParams, AddToScope);
14764   if (!ND) return nullptr;
14765 
14766   assert(ND->getLexicalDeclContext() == CurContext);
14767 
14768   // If we performed typo correction, we might have added a scope specifier
14769   // and changed the decl context.
14770   DC = ND->getDeclContext();
14771 
14772   // Add the function declaration to the appropriate lookup tables,
14773   // adjusting the redeclarations list as necessary.  We don't
14774   // want to do this yet if the friending class is dependent.
14775   //
14776   // Also update the scope-based lookup if the target context's
14777   // lookup context is in lexical scope.
14778   if (!CurContext->isDependentContext()) {
14779     DC = DC->getRedeclContext();
14780     DC->makeDeclVisibleInContext(ND);
14781     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14782       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14783   }
14784 
14785   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14786                                        D.getIdentifierLoc(), ND,
14787                                        DS.getFriendSpecLoc());
14788   FrD->setAccess(AS_public);
14789   CurContext->addDecl(FrD);
14790 
14791   if (ND->isInvalidDecl()) {
14792     FrD->setInvalidDecl();
14793   } else {
14794     if (DC->isRecord()) CheckFriendAccess(ND);
14795 
14796     FunctionDecl *FD;
14797     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14798       FD = FTD->getTemplatedDecl();
14799     else
14800       FD = cast<FunctionDecl>(ND);
14801 
14802     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14803     // default argument expression, that declaration shall be a definition
14804     // and shall be the only declaration of the function or function
14805     // template in the translation unit.
14806     if (functionDeclHasDefaultArgument(FD)) {
14807       // We can't look at FD->getPreviousDecl() because it may not have been set
14808       // if we're in a dependent context. If the function is known to be a
14809       // redeclaration, we will have narrowed Previous down to the right decl.
14810       if (D.isRedeclaration()) {
14811         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14812         Diag(Previous.getRepresentativeDecl()->getLocation(),
14813              diag::note_previous_declaration);
14814       } else if (!D.isFunctionDefinition())
14815         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14816     }
14817 
14818     // Mark templated-scope function declarations as unsupported.
14819     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14820       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14821         << SS.getScopeRep() << SS.getRange()
14822         << cast<CXXRecordDecl>(CurContext);
14823       FrD->setUnsupportedFriend(true);
14824     }
14825   }
14826 
14827   return ND;
14828 }
14829 
14830 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14831   AdjustDeclIfTemplate(Dcl);
14832 
14833   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14834   if (!Fn) {
14835     Diag(DelLoc, diag::err_deleted_non_function);
14836     return;
14837   }
14838 
14839   // Deleted function does not have a body.
14840   Fn->setWillHaveBody(false);
14841 
14842   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14843     // Don't consider the implicit declaration we generate for explicit
14844     // specializations. FIXME: Do not generate these implicit declarations.
14845     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14846          Prev->getPreviousDecl()) &&
14847         !Prev->isDefined()) {
14848       Diag(DelLoc, diag::err_deleted_decl_not_first);
14849       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14850            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14851                               : diag::note_previous_declaration);
14852     }
14853     // If the declaration wasn't the first, we delete the function anyway for
14854     // recovery.
14855     Fn = Fn->getCanonicalDecl();
14856   }
14857 
14858   // dllimport/dllexport cannot be deleted.
14859   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14860     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14861     Fn->setInvalidDecl();
14862   }
14863 
14864   if (Fn->isDeleted())
14865     return;
14866 
14867   // See if we're deleting a function which is already known to override a
14868   // non-deleted virtual function.
14869   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14870     bool IssuedDiagnostic = false;
14871     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14872       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14873         if (!IssuedDiagnostic) {
14874           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14875           IssuedDiagnostic = true;
14876         }
14877         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14878       }
14879     }
14880     // If this function was implicitly deleted because it was defaulted,
14881     // explain why it was deleted.
14882     if (IssuedDiagnostic && MD->isDefaulted())
14883       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14884                                 /*Diagnose*/true);
14885   }
14886 
14887   // C++11 [basic.start.main]p3:
14888   //   A program that defines main as deleted [...] is ill-formed.
14889   if (Fn->isMain())
14890     Diag(DelLoc, diag::err_deleted_main);
14891 
14892   // C++11 [dcl.fct.def.delete]p4:
14893   //  A deleted function is implicitly inline.
14894   Fn->setImplicitlyInline();
14895   Fn->setDeletedAsWritten();
14896 }
14897 
14898 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14899   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14900 
14901   if (MD) {
14902     if (MD->getParent()->isDependentType()) {
14903       MD->setDefaulted();
14904       MD->setExplicitlyDefaulted();
14905       return;
14906     }
14907 
14908     CXXSpecialMember Member = getSpecialMember(MD);
14909     if (Member == CXXInvalid) {
14910       if (!MD->isInvalidDecl())
14911         Diag(DefaultLoc, diag::err_default_special_members);
14912       return;
14913     }
14914 
14915     MD->setDefaulted();
14916     MD->setExplicitlyDefaulted();
14917 
14918     // Unset that we will have a body for this function. We might not,
14919     // if it turns out to be trivial, and we don't need this marking now
14920     // that we've marked it as defaulted.
14921     MD->setWillHaveBody(false);
14922 
14923     // If this definition appears within the record, do the checking when
14924     // the record is complete.
14925     const FunctionDecl *Primary = MD;
14926     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14927       // Ask the template instantiation pattern that actually had the
14928       // '= default' on it.
14929       Primary = Pattern;
14930 
14931     // If the method was defaulted on its first declaration, we will have
14932     // already performed the checking in CheckCompletedCXXClass. Such a
14933     // declaration doesn't trigger an implicit definition.
14934     if (Primary->getCanonicalDecl()->isDefaulted())
14935       return;
14936 
14937     CheckExplicitlyDefaultedSpecialMember(MD);
14938 
14939     if (!MD->isInvalidDecl())
14940       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14941   } else {
14942     Diag(DefaultLoc, diag::err_default_special_members);
14943   }
14944 }
14945 
14946 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14947   for (Stmt *SubStmt : S->children()) {
14948     if (!SubStmt)
14949       continue;
14950     if (isa<ReturnStmt>(SubStmt))
14951       Self.Diag(SubStmt->getBeginLoc(),
14952                 diag::err_return_in_constructor_handler);
14953     if (!isa<Expr>(SubStmt))
14954       SearchForReturnInStmt(Self, SubStmt);
14955   }
14956 }
14957 
14958 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14959   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14960     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14961     SearchForReturnInStmt(*this, Handler);
14962   }
14963 }
14964 
14965 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14966                                              const CXXMethodDecl *Old) {
14967   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14968   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14969 
14970   if (OldFT->hasExtParameterInfos()) {
14971     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14972       // A parameter of the overriding method should be annotated with noescape
14973       // if the corresponding parameter of the overridden method is annotated.
14974       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14975           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14976         Diag(New->getParamDecl(I)->getLocation(),
14977              diag::warn_overriding_method_missing_noescape);
14978         Diag(Old->getParamDecl(I)->getLocation(),
14979              diag::note_overridden_marked_noescape);
14980       }
14981   }
14982 
14983   // Virtual overrides must have the same code_seg.
14984   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14985   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14986   if ((NewCSA || OldCSA) &&
14987       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14988     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14989     Diag(Old->getLocation(), diag::note_previous_declaration);
14990     return true;
14991   }
14992 
14993   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14994 
14995   // If the calling conventions match, everything is fine
14996   if (NewCC == OldCC)
14997     return false;
14998 
14999   // If the calling conventions mismatch because the new function is static,
15000   // suppress the calling convention mismatch error; the error about static
15001   // function override (err_static_overrides_virtual from
15002   // Sema::CheckFunctionDeclaration) is more clear.
15003   if (New->getStorageClass() == SC_Static)
15004     return false;
15005 
15006   Diag(New->getLocation(),
15007        diag::err_conflicting_overriding_cc_attributes)
15008     << New->getDeclName() << New->getType() << Old->getType();
15009   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
15010   return true;
15011 }
15012 
15013 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
15014                                              const CXXMethodDecl *Old) {
15015   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
15016   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
15017 
15018   if (Context.hasSameType(NewTy, OldTy) ||
15019       NewTy->isDependentType() || OldTy->isDependentType())
15020     return false;
15021 
15022   // Check if the return types are covariant
15023   QualType NewClassTy, OldClassTy;
15024 
15025   /// Both types must be pointers or references to classes.
15026   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
15027     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
15028       NewClassTy = NewPT->getPointeeType();
15029       OldClassTy = OldPT->getPointeeType();
15030     }
15031   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
15032     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
15033       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
15034         NewClassTy = NewRT->getPointeeType();
15035         OldClassTy = OldRT->getPointeeType();
15036       }
15037     }
15038   }
15039 
15040   // The return types aren't either both pointers or references to a class type.
15041   if (NewClassTy.isNull()) {
15042     Diag(New->getLocation(),
15043          diag::err_different_return_type_for_overriding_virtual_function)
15044         << New->getDeclName() << NewTy << OldTy
15045         << New->getReturnTypeSourceRange();
15046     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15047         << Old->getReturnTypeSourceRange();
15048 
15049     return true;
15050   }
15051 
15052   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
15053     // C++14 [class.virtual]p8:
15054     //   If the class type in the covariant return type of D::f differs from
15055     //   that of B::f, the class type in the return type of D::f shall be
15056     //   complete at the point of declaration of D::f or shall be the class
15057     //   type D.
15058     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
15059       if (!RT->isBeingDefined() &&
15060           RequireCompleteType(New->getLocation(), NewClassTy,
15061                               diag::err_covariant_return_incomplete,
15062                               New->getDeclName()))
15063         return true;
15064     }
15065 
15066     // Check if the new class derives from the old class.
15067     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
15068       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
15069           << New->getDeclName() << NewTy << OldTy
15070           << New->getReturnTypeSourceRange();
15071       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15072           << Old->getReturnTypeSourceRange();
15073       return true;
15074     }
15075 
15076     // Check if we the conversion from derived to base is valid.
15077     if (CheckDerivedToBaseConversion(
15078             NewClassTy, OldClassTy,
15079             diag::err_covariant_return_inaccessible_base,
15080             diag::err_covariant_return_ambiguous_derived_to_base_conv,
15081             New->getLocation(), New->getReturnTypeSourceRange(),
15082             New->getDeclName(), nullptr)) {
15083       // FIXME: this note won't trigger for delayed access control
15084       // diagnostics, and it's impossible to get an undelayed error
15085       // here from access control during the original parse because
15086       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
15087       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15088           << Old->getReturnTypeSourceRange();
15089       return true;
15090     }
15091   }
15092 
15093   // The qualifiers of the return types must be the same.
15094   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
15095     Diag(New->getLocation(),
15096          diag::err_covariant_return_type_different_qualifications)
15097         << New->getDeclName() << NewTy << OldTy
15098         << New->getReturnTypeSourceRange();
15099     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15100         << Old->getReturnTypeSourceRange();
15101     return true;
15102   }
15103 
15104 
15105   // The new class type must have the same or less qualifiers as the old type.
15106   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
15107     Diag(New->getLocation(),
15108          diag::err_covariant_return_type_class_type_more_qualified)
15109         << New->getDeclName() << NewTy << OldTy
15110         << New->getReturnTypeSourceRange();
15111     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15112         << Old->getReturnTypeSourceRange();
15113     return true;
15114   }
15115 
15116   return false;
15117 }
15118 
15119 /// Mark the given method pure.
15120 ///
15121 /// \param Method the method to be marked pure.
15122 ///
15123 /// \param InitRange the source range that covers the "0" initializer.
15124 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
15125   SourceLocation EndLoc = InitRange.getEnd();
15126   if (EndLoc.isValid())
15127     Method->setRangeEnd(EndLoc);
15128 
15129   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
15130     Method->setPure();
15131     return false;
15132   }
15133 
15134   if (!Method->isInvalidDecl())
15135     Diag(Method->getLocation(), diag::err_non_virtual_pure)
15136       << Method->getDeclName() << InitRange;
15137   return true;
15138 }
15139 
15140 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15141   if (D->getFriendObjectKind())
15142     Diag(D->getLocation(), diag::err_pure_friend);
15143   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15144     CheckPureMethod(M, ZeroLoc);
15145   else
15146     Diag(D->getLocation(), diag::err_illegal_initializer);
15147 }
15148 
15149 /// Determine whether the given declaration is a global variable or
15150 /// static data member.
15151 static bool isNonlocalVariable(const Decl *D) {
15152   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15153     return Var->hasGlobalStorage();
15154 
15155   return false;
15156 }
15157 
15158 /// Invoked when we are about to parse an initializer for the declaration
15159 /// 'Dcl'.
15160 ///
15161 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15162 /// static data member of class X, names should be looked up in the scope of
15163 /// class X. If the declaration had a scope specifier, a scope will have
15164 /// been created and passed in for this purpose. Otherwise, S will be null.
15165 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15166   // If there is no declaration, there was an error parsing it.
15167   if (!D || D->isInvalidDecl())
15168     return;
15169 
15170   // We will always have a nested name specifier here, but this declaration
15171   // might not be out of line if the specifier names the current namespace:
15172   //   extern int n;
15173   //   int ::n = 0;
15174   if (S && D->isOutOfLine())
15175     EnterDeclaratorContext(S, D->getDeclContext());
15176 
15177   // If we are parsing the initializer for a static data member, push a
15178   // new expression evaluation context that is associated with this static
15179   // data member.
15180   if (isNonlocalVariable(D))
15181     PushExpressionEvaluationContext(
15182         ExpressionEvaluationContext::PotentiallyEvaluated, D);
15183 }
15184 
15185 /// Invoked after we are finished parsing an initializer for the declaration D.
15186 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15187   // If there is no declaration, there was an error parsing it.
15188   if (!D || D->isInvalidDecl())
15189     return;
15190 
15191   if (isNonlocalVariable(D))
15192     PopExpressionEvaluationContext();
15193 
15194   if (S && D->isOutOfLine())
15195     ExitDeclaratorContext(S);
15196 }
15197 
15198 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15199 /// C++ if/switch/while/for statement.
15200 /// e.g: "if (int x = f()) {...}"
15201 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15202   // C++ 6.4p2:
15203   // The declarator shall not specify a function or an array.
15204   // The type-specifier-seq shall not contain typedef and shall not declare a
15205   // new class or enumeration.
15206   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15207          "Parser allowed 'typedef' as storage class of condition decl.");
15208 
15209   Decl *Dcl = ActOnDeclarator(S, D);
15210   if (!Dcl)
15211     return true;
15212 
15213   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15214     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15215       << D.getSourceRange();
15216     return true;
15217   }
15218 
15219   return Dcl;
15220 }
15221 
15222 void Sema::LoadExternalVTableUses() {
15223   if (!ExternalSource)
15224     return;
15225 
15226   SmallVector<ExternalVTableUse, 4> VTables;
15227   ExternalSource->ReadUsedVTables(VTables);
15228   SmallVector<VTableUse, 4> NewUses;
15229   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15230     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15231       = VTablesUsed.find(VTables[I].Record);
15232     // Even if a definition wasn't required before, it may be required now.
15233     if (Pos != VTablesUsed.end()) {
15234       if (!Pos->second && VTables[I].DefinitionRequired)
15235         Pos->second = true;
15236       continue;
15237     }
15238 
15239     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15240     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15241   }
15242 
15243   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15244 }
15245 
15246 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15247                           bool DefinitionRequired) {
15248   // Ignore any vtable uses in unevaluated operands or for classes that do
15249   // not have a vtable.
15250   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15251       CurContext->isDependentContext() || isUnevaluatedContext())
15252     return;
15253   // Do not mark as used if compiling for the device outside of the target
15254   // region.
15255   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15256       !isInOpenMPDeclareTargetContext() &&
15257       !isInOpenMPTargetExecutionDirective()) {
15258     if (!DefinitionRequired)
15259       MarkVirtualMembersReferenced(Loc, Class);
15260     return;
15261   }
15262 
15263   // Try to insert this class into the map.
15264   LoadExternalVTableUses();
15265   Class = Class->getCanonicalDecl();
15266   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15267     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15268   if (!Pos.second) {
15269     // If we already had an entry, check to see if we are promoting this vtable
15270     // to require a definition. If so, we need to reappend to the VTableUses
15271     // list, since we may have already processed the first entry.
15272     if (DefinitionRequired && !Pos.first->second) {
15273       Pos.first->second = true;
15274     } else {
15275       // Otherwise, we can early exit.
15276       return;
15277     }
15278   } else {
15279     // The Microsoft ABI requires that we perform the destructor body
15280     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15281     // the deleting destructor is emitted with the vtable, not with the
15282     // destructor definition as in the Itanium ABI.
15283     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15284       CXXDestructorDecl *DD = Class->getDestructor();
15285       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15286         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15287           // If this is an out-of-line declaration, marking it referenced will
15288           // not do anything. Manually call CheckDestructor to look up operator
15289           // delete().
15290           ContextRAII SavedContext(*this, DD);
15291           CheckDestructor(DD);
15292         } else {
15293           MarkFunctionReferenced(Loc, Class->getDestructor());
15294         }
15295       }
15296     }
15297   }
15298 
15299   // Local classes need to have their virtual members marked
15300   // immediately. For all other classes, we mark their virtual members
15301   // at the end of the translation unit.
15302   if (Class->isLocalClass())
15303     MarkVirtualMembersReferenced(Loc, Class);
15304   else
15305     VTableUses.push_back(std::make_pair(Class, Loc));
15306 }
15307 
15308 bool Sema::DefineUsedVTables() {
15309   LoadExternalVTableUses();
15310   if (VTableUses.empty())
15311     return false;
15312 
15313   // Note: The VTableUses vector could grow as a result of marking
15314   // the members of a class as "used", so we check the size each
15315   // time through the loop and prefer indices (which are stable) to
15316   // iterators (which are not).
15317   bool DefinedAnything = false;
15318   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15319     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15320     if (!Class)
15321       continue;
15322     TemplateSpecializationKind ClassTSK =
15323         Class->getTemplateSpecializationKind();
15324 
15325     SourceLocation Loc = VTableUses[I].second;
15326 
15327     bool DefineVTable = true;
15328 
15329     // If this class has a key function, but that key function is
15330     // defined in another translation unit, we don't need to emit the
15331     // vtable even though we're using it.
15332     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15333     if (KeyFunction && !KeyFunction->hasBody()) {
15334       // The key function is in another translation unit.
15335       DefineVTable = false;
15336       TemplateSpecializationKind TSK =
15337           KeyFunction->getTemplateSpecializationKind();
15338       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15339              TSK != TSK_ImplicitInstantiation &&
15340              "Instantiations don't have key functions");
15341       (void)TSK;
15342     } else if (!KeyFunction) {
15343       // If we have a class with no key function that is the subject
15344       // of an explicit instantiation declaration, suppress the
15345       // vtable; it will live with the explicit instantiation
15346       // definition.
15347       bool IsExplicitInstantiationDeclaration =
15348           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15349       for (auto R : Class->redecls()) {
15350         TemplateSpecializationKind TSK
15351           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15352         if (TSK == TSK_ExplicitInstantiationDeclaration)
15353           IsExplicitInstantiationDeclaration = true;
15354         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15355           IsExplicitInstantiationDeclaration = false;
15356           break;
15357         }
15358       }
15359 
15360       if (IsExplicitInstantiationDeclaration)
15361         DefineVTable = false;
15362     }
15363 
15364     // The exception specifications for all virtual members may be needed even
15365     // if we are not providing an authoritative form of the vtable in this TU.
15366     // We may choose to emit it available_externally anyway.
15367     if (!DefineVTable) {
15368       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15369       continue;
15370     }
15371 
15372     // Mark all of the virtual members of this class as referenced, so
15373     // that we can build a vtable. Then, tell the AST consumer that a
15374     // vtable for this class is required.
15375     DefinedAnything = true;
15376     MarkVirtualMembersReferenced(Loc, Class);
15377     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15378     if (VTablesUsed[Canonical])
15379       Consumer.HandleVTable(Class);
15380 
15381     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15382     // no key function or the key function is inlined. Don't warn in C++ ABIs
15383     // that lack key functions, since the user won't be able to make one.
15384     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15385         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15386       const FunctionDecl *KeyFunctionDef = nullptr;
15387       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15388                            KeyFunctionDef->isInlined())) {
15389         Diag(Class->getLocation(),
15390              ClassTSK == TSK_ExplicitInstantiationDefinition
15391                  ? diag::warn_weak_template_vtable
15392                  : diag::warn_weak_vtable)
15393             << Class;
15394       }
15395     }
15396   }
15397   VTableUses.clear();
15398 
15399   return DefinedAnything;
15400 }
15401 
15402 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15403                                                  const CXXRecordDecl *RD) {
15404   for (const auto *I : RD->methods())
15405     if (I->isVirtual() && !I->isPure())
15406       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15407 }
15408 
15409 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15410                                         const CXXRecordDecl *RD,
15411                                         bool ConstexprOnly) {
15412   // Mark all functions which will appear in RD's vtable as used.
15413   CXXFinalOverriderMap FinalOverriders;
15414   RD->getFinalOverriders(FinalOverriders);
15415   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15416                                             E = FinalOverriders.end();
15417        I != E; ++I) {
15418     for (OverridingMethods::const_iterator OI = I->second.begin(),
15419                                            OE = I->second.end();
15420          OI != OE; ++OI) {
15421       assert(OI->second.size() > 0 && "no final overrider");
15422       CXXMethodDecl *Overrider = OI->second.front().Method;
15423 
15424       // C++ [basic.def.odr]p2:
15425       //   [...] A virtual member function is used if it is not pure. [...]
15426       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15427         MarkFunctionReferenced(Loc, Overrider);
15428     }
15429   }
15430 
15431   // Only classes that have virtual bases need a VTT.
15432   if (RD->getNumVBases() == 0)
15433     return;
15434 
15435   for (const auto &I : RD->bases()) {
15436     const CXXRecordDecl *Base =
15437         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15438     if (Base->getNumVBases() == 0)
15439       continue;
15440     MarkVirtualMembersReferenced(Loc, Base);
15441   }
15442 }
15443 
15444 /// SetIvarInitializers - This routine builds initialization ASTs for the
15445 /// Objective-C implementation whose ivars need be initialized.
15446 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15447   if (!getLangOpts().CPlusPlus)
15448     return;
15449   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15450     SmallVector<ObjCIvarDecl*, 8> ivars;
15451     CollectIvarsToConstructOrDestruct(OID, ivars);
15452     if (ivars.empty())
15453       return;
15454     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15455     for (unsigned i = 0; i < ivars.size(); i++) {
15456       FieldDecl *Field = ivars[i];
15457       if (Field->isInvalidDecl())
15458         continue;
15459 
15460       CXXCtorInitializer *Member;
15461       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15462       InitializationKind InitKind =
15463         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15464 
15465       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15466       ExprResult MemberInit =
15467         InitSeq.Perform(*this, InitEntity, InitKind, None);
15468       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15469       // Note, MemberInit could actually come back empty if no initialization
15470       // is required (e.g., because it would call a trivial default constructor)
15471       if (!MemberInit.get() || MemberInit.isInvalid())
15472         continue;
15473 
15474       Member =
15475         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15476                                          SourceLocation(),
15477                                          MemberInit.getAs<Expr>(),
15478                                          SourceLocation());
15479       AllToInit.push_back(Member);
15480 
15481       // Be sure that the destructor is accessible and is marked as referenced.
15482       if (const RecordType *RecordTy =
15483               Context.getBaseElementType(Field->getType())
15484                   ->getAs<RecordType>()) {
15485         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15486         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15487           MarkFunctionReferenced(Field->getLocation(), Destructor);
15488           CheckDestructorAccess(Field->getLocation(), Destructor,
15489                             PDiag(diag::err_access_dtor_ivar)
15490                               << Context.getBaseElementType(Field->getType()));
15491         }
15492       }
15493     }
15494     ObjCImplementation->setIvarInitializers(Context,
15495                                             AllToInit.data(), AllToInit.size());
15496   }
15497 }
15498 
15499 static
15500 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15501                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15502                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15503                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15504                            Sema &S) {
15505   if (Ctor->isInvalidDecl())
15506     return;
15507 
15508   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15509 
15510   // Target may not be determinable yet, for instance if this is a dependent
15511   // call in an uninstantiated template.
15512   if (Target) {
15513     const FunctionDecl *FNTarget = nullptr;
15514     (void)Target->hasBody(FNTarget);
15515     Target = const_cast<CXXConstructorDecl*>(
15516       cast_or_null<CXXConstructorDecl>(FNTarget));
15517   }
15518 
15519   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15520                      // Avoid dereferencing a null pointer here.
15521                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15522 
15523   if (!Current.insert(Canonical).second)
15524     return;
15525 
15526   // We know that beyond here, we aren't chaining into a cycle.
15527   if (!Target || !Target->isDelegatingConstructor() ||
15528       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15529     Valid.insert(Current.begin(), Current.end());
15530     Current.clear();
15531   // We've hit a cycle.
15532   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15533              Current.count(TCanonical)) {
15534     // If we haven't diagnosed this cycle yet, do so now.
15535     if (!Invalid.count(TCanonical)) {
15536       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15537              diag::warn_delegating_ctor_cycle)
15538         << Ctor;
15539 
15540       // Don't add a note for a function delegating directly to itself.
15541       if (TCanonical != Canonical)
15542         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15543 
15544       CXXConstructorDecl *C = Target;
15545       while (C->getCanonicalDecl() != Canonical) {
15546         const FunctionDecl *FNTarget = nullptr;
15547         (void)C->getTargetConstructor()->hasBody(FNTarget);
15548         assert(FNTarget && "Ctor cycle through bodiless function");
15549 
15550         C = const_cast<CXXConstructorDecl*>(
15551           cast<CXXConstructorDecl>(FNTarget));
15552         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15553       }
15554     }
15555 
15556     Invalid.insert(Current.begin(), Current.end());
15557     Current.clear();
15558   } else {
15559     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15560   }
15561 }
15562 
15563 
15564 void Sema::CheckDelegatingCtorCycles() {
15565   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15566 
15567   for (DelegatingCtorDeclsType::iterator
15568          I = DelegatingCtorDecls.begin(ExternalSource),
15569          E = DelegatingCtorDecls.end();
15570        I != E; ++I)
15571     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15572 
15573   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15574     (*CI)->setInvalidDecl();
15575 }
15576 
15577 namespace {
15578   /// AST visitor that finds references to the 'this' expression.
15579   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15580     Sema &S;
15581 
15582   public:
15583     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15584 
15585     bool VisitCXXThisExpr(CXXThisExpr *E) {
15586       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15587         << E->isImplicit();
15588       return false;
15589     }
15590   };
15591 }
15592 
15593 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15594   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15595   if (!TSInfo)
15596     return false;
15597 
15598   TypeLoc TL = TSInfo->getTypeLoc();
15599   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15600   if (!ProtoTL)
15601     return false;
15602 
15603   // C++11 [expr.prim.general]p3:
15604   //   [The expression this] shall not appear before the optional
15605   //   cv-qualifier-seq and it shall not appear within the declaration of a
15606   //   static member function (although its type and value category are defined
15607   //   within a static member function as they are within a non-static member
15608   //   function). [ Note: this is because declaration matching does not occur
15609   //  until the complete declarator is known. - end note ]
15610   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15611   FindCXXThisExpr Finder(*this);
15612 
15613   // If the return type came after the cv-qualifier-seq, check it now.
15614   if (Proto->hasTrailingReturn() &&
15615       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15616     return true;
15617 
15618   // Check the exception specification.
15619   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15620     return true;
15621 
15622   return checkThisInStaticMemberFunctionAttributes(Method);
15623 }
15624 
15625 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15626   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15627   if (!TSInfo)
15628     return false;
15629 
15630   TypeLoc TL = TSInfo->getTypeLoc();
15631   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15632   if (!ProtoTL)
15633     return false;
15634 
15635   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15636   FindCXXThisExpr Finder(*this);
15637 
15638   switch (Proto->getExceptionSpecType()) {
15639   case EST_Unparsed:
15640   case EST_Uninstantiated:
15641   case EST_Unevaluated:
15642   case EST_BasicNoexcept:
15643   case EST_NoThrow:
15644   case EST_DynamicNone:
15645   case EST_MSAny:
15646   case EST_None:
15647     break;
15648 
15649   case EST_DependentNoexcept:
15650   case EST_NoexceptFalse:
15651   case EST_NoexceptTrue:
15652     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15653       return true;
15654     LLVM_FALLTHROUGH;
15655 
15656   case EST_Dynamic:
15657     for (const auto &E : Proto->exceptions()) {
15658       if (!Finder.TraverseType(E))
15659         return true;
15660     }
15661     break;
15662   }
15663 
15664   return false;
15665 }
15666 
15667 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15668   FindCXXThisExpr Finder(*this);
15669 
15670   // Check attributes.
15671   for (const auto *A : Method->attrs()) {
15672     // FIXME: This should be emitted by tblgen.
15673     Expr *Arg = nullptr;
15674     ArrayRef<Expr *> Args;
15675     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15676       Arg = G->getArg();
15677     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15678       Arg = G->getArg();
15679     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15680       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15681     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15682       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15683     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15684       Arg = ETLF->getSuccessValue();
15685       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15686     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15687       Arg = STLF->getSuccessValue();
15688       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15689     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15690       Arg = LR->getArg();
15691     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15692       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15693     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15694       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15695     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15696       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15697     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15698       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15699     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15700       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15701 
15702     if (Arg && !Finder.TraverseStmt(Arg))
15703       return true;
15704 
15705     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15706       if (!Finder.TraverseStmt(Args[I]))
15707         return true;
15708     }
15709   }
15710 
15711   return false;
15712 }
15713 
15714 void Sema::checkExceptionSpecification(
15715     bool IsTopLevel, ExceptionSpecificationType EST,
15716     ArrayRef<ParsedType> DynamicExceptions,
15717     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15718     SmallVectorImpl<QualType> &Exceptions,
15719     FunctionProtoType::ExceptionSpecInfo &ESI) {
15720   Exceptions.clear();
15721   ESI.Type = EST;
15722   if (EST == EST_Dynamic) {
15723     Exceptions.reserve(DynamicExceptions.size());
15724     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15725       // FIXME: Preserve type source info.
15726       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15727 
15728       if (IsTopLevel) {
15729         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15730         collectUnexpandedParameterPacks(ET, Unexpanded);
15731         if (!Unexpanded.empty()) {
15732           DiagnoseUnexpandedParameterPacks(
15733               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15734               Unexpanded);
15735           continue;
15736         }
15737       }
15738 
15739       // Check that the type is valid for an exception spec, and
15740       // drop it if not.
15741       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15742         Exceptions.push_back(ET);
15743     }
15744     ESI.Exceptions = Exceptions;
15745     return;
15746   }
15747 
15748   if (isComputedNoexcept(EST)) {
15749     assert((NoexceptExpr->isTypeDependent() ||
15750             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15751             Context.BoolTy) &&
15752            "Parser should have made sure that the expression is boolean");
15753     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15754       ESI.Type = EST_BasicNoexcept;
15755       return;
15756     }
15757 
15758     ESI.NoexceptExpr = NoexceptExpr;
15759     return;
15760   }
15761 }
15762 
15763 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15764              ExceptionSpecificationType EST,
15765              SourceRange SpecificationRange,
15766              ArrayRef<ParsedType> DynamicExceptions,
15767              ArrayRef<SourceRange> DynamicExceptionRanges,
15768              Expr *NoexceptExpr) {
15769   if (!MethodD)
15770     return;
15771 
15772   // Dig out the method we're referring to.
15773   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15774     MethodD = FunTmpl->getTemplatedDecl();
15775 
15776   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15777   if (!Method)
15778     return;
15779 
15780   // Check the exception specification.
15781   llvm::SmallVector<QualType, 4> Exceptions;
15782   FunctionProtoType::ExceptionSpecInfo ESI;
15783   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15784                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15785                               ESI);
15786 
15787   // Update the exception specification on the function type.
15788   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15789 
15790   if (Method->isStatic())
15791     checkThisInStaticMemberFunctionExceptionSpec(Method);
15792 
15793   if (Method->isVirtual()) {
15794     // Check overrides, which we previously had to delay.
15795     for (const CXXMethodDecl *O : Method->overridden_methods())
15796       CheckOverridingFunctionExceptionSpec(Method, O);
15797   }
15798 }
15799 
15800 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15801 ///
15802 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15803                                        SourceLocation DeclStart, Declarator &D,
15804                                        Expr *BitWidth,
15805                                        InClassInitStyle InitStyle,
15806                                        AccessSpecifier AS,
15807                                        const ParsedAttr &MSPropertyAttr) {
15808   IdentifierInfo *II = D.getIdentifier();
15809   if (!II) {
15810     Diag(DeclStart, diag::err_anonymous_property);
15811     return nullptr;
15812   }
15813   SourceLocation Loc = D.getIdentifierLoc();
15814 
15815   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15816   QualType T = TInfo->getType();
15817   if (getLangOpts().CPlusPlus) {
15818     CheckExtraCXXDefaultArguments(D);
15819 
15820     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15821                                         UPPC_DataMemberType)) {
15822       D.setInvalidType();
15823       T = Context.IntTy;
15824       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15825     }
15826   }
15827 
15828   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15829 
15830   if (D.getDeclSpec().isInlineSpecified())
15831     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15832         << getLangOpts().CPlusPlus17;
15833   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15834     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15835          diag::err_invalid_thread)
15836       << DeclSpec::getSpecifierName(TSCS);
15837 
15838   // Check to see if this name was declared as a member previously
15839   NamedDecl *PrevDecl = nullptr;
15840   LookupResult Previous(*this, II, Loc, LookupMemberName,
15841                         ForVisibleRedeclaration);
15842   LookupName(Previous, S);
15843   switch (Previous.getResultKind()) {
15844   case LookupResult::Found:
15845   case LookupResult::FoundUnresolvedValue:
15846     PrevDecl = Previous.getAsSingle<NamedDecl>();
15847     break;
15848 
15849   case LookupResult::FoundOverloaded:
15850     PrevDecl = Previous.getRepresentativeDecl();
15851     break;
15852 
15853   case LookupResult::NotFound:
15854   case LookupResult::NotFoundInCurrentInstantiation:
15855   case LookupResult::Ambiguous:
15856     break;
15857   }
15858 
15859   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15860     // Maybe we will complain about the shadowed template parameter.
15861     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15862     // Just pretend that we didn't see the previous declaration.
15863     PrevDecl = nullptr;
15864   }
15865 
15866   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15867     PrevDecl = nullptr;
15868 
15869   SourceLocation TSSL = D.getBeginLoc();
15870   MSPropertyDecl *NewPD =
15871       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15872                              MSPropertyAttr.getPropertyDataGetter(),
15873                              MSPropertyAttr.getPropertyDataSetter());
15874   ProcessDeclAttributes(TUScope, NewPD, D);
15875   NewPD->setAccess(AS);
15876 
15877   if (NewPD->isInvalidDecl())
15878     Record->setInvalidDecl();
15879 
15880   if (D.getDeclSpec().isModulePrivateSpecified())
15881     NewPD->setModulePrivate();
15882 
15883   if (NewPD->isInvalidDecl() && PrevDecl) {
15884     // Don't introduce NewFD into scope; there's already something
15885     // with the same name in the same scope.
15886   } else if (II) {
15887     PushOnScopeChains(NewPD, S);
15888   } else
15889     Record->addDecl(NewPD);
15890 
15891   return NewPD;
15892 }
15893