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     return;
196   // If we're still at noexcept(true) and there's a throw() callee,
197   // change to that specification.
198   case EST_DynamicNone:
199     if (ComputedEST == EST_BasicNoexcept)
200       ComputedEST = EST_DynamicNone;
201     return;
202   case EST_DependentNoexcept:
203     llvm_unreachable(
204         "should not generate implicit declarations for dependent cases");
205   case EST_Dynamic:
206     break;
207   }
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (const auto &E : Proto->exceptions())
214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215       Exceptions.push_back(E);
216 }
217 
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219   if (!E || ComputedEST == EST_MSAny)
220     return;
221 
222   // FIXME:
223   //
224   // C++0x [except.spec]p14:
225   //   [An] implicit exception-specification specifies the type-id T if and
226   // only if T is allowed by the exception-specification of a function directly
227   // invoked by f's implicit definition; f shall allow all exceptions if any
228   // function it directly invokes allows all exceptions, and f shall allow no
229   // exceptions if every function it directly invokes allows no exceptions.
230   //
231   // Note in particular that if an implicit exception-specification is generated
232   // for a function containing a throw-expression, that specification can still
233   // be noexcept(true).
234   //
235   // Note also that 'directly invoked' is not defined in the standard, and there
236   // is no indication that we should only consider potentially-evaluated calls.
237   //
238   // Ultimately we should implement the intent of the standard: the exception
239   // specification should be the set of exceptions which can be thrown by the
240   // implicit definition. For now, we assume that any non-nothrow expression can
241   // throw any exception.
242 
243   if (Self->canThrow(E))
244     ComputedEST = EST_None;
245 }
246 
247 bool
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249                               SourceLocation EqualLoc) {
250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
251                           diag::err_typecheck_decl_incomplete_type)) {
252     Param->setInvalidDecl();
253     return true;
254   }
255 
256   // C++ [dcl.fct.default]p5
257   //   A default argument expression is implicitly converted (clause
258   //   4) to the parameter type. The default argument expression has
259   //   the same semantic constraints as the initializer expression in
260   //   a declaration of a variable of the parameter type, using the
261   //   copy-initialization semantics (8.5).
262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263                                                                     Param);
264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265                                                            EqualLoc);
266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268   if (Result.isInvalid())
269     return true;
270   Arg = Result.getAs<Expr>();
271 
272   CheckCompletedExpr(Arg, EqualLoc);
273   Arg = MaybeCreateExprWithCleanups(Arg);
274 
275   // Okay: add the default argument to the parameter
276   Param->setDefaultArg(Arg);
277 
278   // We have already instantiated this parameter; provide each of the
279   // instantiations with the uninstantiated default argument.
280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
281     = UnparsedDefaultArgInstantiations.find(Param);
282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286     // We're done tracking this parameter's instantiations.
287     UnparsedDefaultArgInstantiations.erase(InstPos);
288   }
289 
290   return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298                                 Expr *DefaultArg) {
299   if (!param || !DefaultArg)
300     return;
301 
302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
303   UnparsedDefaultArgLocs.erase(Param);
304 
305   // Default arguments are only permitted in C++
306   if (!getLangOpts().CPlusPlus) {
307     Diag(EqualLoc, diag::err_param_default_argument)
308       << DefaultArg->getSourceRange();
309     Param->setInvalidDecl();
310     return;
311   }
312 
313   // Check for unexpanded parameter packs.
314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315     Param->setInvalidDecl();
316     return;
317   }
318 
319   // C++11 [dcl.fct.default]p3
320   //   A default argument expression [...] shall not be specified for a
321   //   parameter pack.
322   if (Param->isParameterPack()) {
323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324         << DefaultArg->getSourceRange();
325     return;
326   }
327 
328   // Check that the default argument is well-formed
329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330   if (DefaultArgChecker.Visit(DefaultArg)) {
331     Param->setInvalidDecl();
332     return;
333   }
334 
335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343                                              SourceLocation EqualLoc,
344                                              SourceLocation ArgLoc) {
345   if (!param)
346     return;
347 
348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
349   Param->setUnparsedDefaultArg();
350   UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356                                           SourceLocation EqualLoc) {
357   if (!param)
358     return;
359 
360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
361   Param->setInvalidDecl();
362   UnparsedDefaultArgLocs.erase(Param);
363   Param->setDefaultArg(new(Context)
364                        OpaqueValueExpr(EqualLoc,
365                                        Param->getType().getNonReferenceType(),
366                                        VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375   // C++ [dcl.fct.default]p3
376   //   A default argument expression shall be specified only in the
377   //   parameter-declaration-clause of a function declaration or in a
378   //   template-parameter (14.1). It shall not be specified for a
379   //   parameter pack. If it is specified in a
380   //   parameter-declaration-clause, it shall not occur within a
381   //   declarator or abstract-declarator of a parameter-declaration.
382   bool MightBeFunction = D.isFunctionDeclarationContext();
383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384     DeclaratorChunk &chunk = D.getTypeObject(i);
385     if (chunk.Kind == DeclaratorChunk::Function) {
386       if (MightBeFunction) {
387         // This is a function declaration. It can have default arguments, but
388         // keep looking in case its return type is a function type with default
389         // arguments.
390         MightBeFunction = false;
391         continue;
392       }
393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394            ++argIdx) {
395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396         if (Param->hasUnparsedDefaultArg()) {
397           std::unique_ptr<CachedTokens> Toks =
398               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
399           SourceRange SR;
400           if (Toks->size() > 1)
401             SR = SourceRange((*Toks)[1].getLocation(),
402                              Toks->back().getLocation());
403           else
404             SR = UnparsedDefaultArgLocs[Param];
405           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406             << SR;
407         } else if (Param->getDefaultArg()) {
408           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
409             << Param->getDefaultArg()->getSourceRange();
410           Param->setDefaultArg(nullptr);
411         }
412       }
413     } else if (chunk.Kind != DeclaratorChunk::Paren) {
414       MightBeFunction = false;
415     }
416   }
417 }
418 
419 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
420   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
421     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
422     if (!PVD->hasDefaultArg())
423       return false;
424     if (!PVD->hasInheritedDefaultArg())
425       return true;
426   }
427   return false;
428 }
429 
430 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
431 /// function, once we already know that they have the same
432 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
433 /// error, false otherwise.
434 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
435                                 Scope *S) {
436   bool Invalid = false;
437 
438   // The declaration context corresponding to the scope is the semantic
439   // parent, unless this is a local function declaration, in which case
440   // it is that surrounding function.
441   DeclContext *ScopeDC = New->isLocalExternDecl()
442                              ? New->getLexicalDeclContext()
443                              : New->getDeclContext();
444 
445   // Find the previous declaration for the purpose of default arguments.
446   FunctionDecl *PrevForDefaultArgs = Old;
447   for (/**/; PrevForDefaultArgs;
448        // Don't bother looking back past the latest decl if this is a local
449        // extern declaration; nothing else could work.
450        PrevForDefaultArgs = New->isLocalExternDecl()
451                                 ? nullptr
452                                 : PrevForDefaultArgs->getPreviousDecl()) {
453     // Ignore hidden declarations.
454     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
455       continue;
456 
457     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
458         !New->isCXXClassMember()) {
459       // Ignore default arguments of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       continue;
463     }
464 
465     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
466       // If only one of these is a local function declaration, then they are
467       // declared in different scopes, even though isDeclInScope may think
468       // they're in the same scope. (If both are local, the scope check is
469       // sufficient, and if neither is local, then they are in the same scope.)
470       continue;
471     }
472 
473     // We found the right previous declaration.
474     break;
475   }
476 
477   // C++ [dcl.fct.default]p4:
478   //   For non-template functions, default arguments can be added in
479   //   later declarations of a function in the same
480   //   scope. Declarations in different scopes have completely
481   //   distinct sets of default arguments. That is, declarations in
482   //   inner scopes do not acquire default arguments from
483   //   declarations in outer scopes, and vice versa. In a given
484   //   function declaration, all parameters subsequent to a
485   //   parameter with a default argument shall have default
486   //   arguments supplied in this or previous declarations. A
487   //   default argument shall not be redefined by a later
488   //   declaration (not even to the same value).
489   //
490   // C++ [dcl.fct.default]p6:
491   //   Except for member functions of class templates, the default arguments
492   //   in a member function definition that appears outside of the class
493   //   definition are added to the set of default arguments provided by the
494   //   member function declaration in the class definition.
495   for (unsigned p = 0, NumParams = PrevForDefaultArgs
496                                        ? PrevForDefaultArgs->getNumParams()
497                                        : 0;
498        p < NumParams; ++p) {
499     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
500     ParmVarDecl *NewParam = New->getParamDecl(p);
501 
502     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
503     bool NewParamHasDfl = NewParam->hasDefaultArg();
504 
505     if (OldParamHasDfl && NewParamHasDfl) {
506       unsigned DiagDefaultParamID =
507         diag::err_param_default_argument_redefinition;
508 
509       // MSVC accepts that default parameters be redefined for member functions
510       // of template class. The new default parameter's value is ignored.
511       Invalid = true;
512       if (getLangOpts().MicrosoftExt) {
513         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
514         if (MD && MD->getParent()->getDescribedClassTemplate()) {
515           // Merge the old default argument into the new parameter.
516           NewParam->setHasInheritedDefaultArg();
517           if (OldParam->hasUninstantiatedDefaultArg())
518             NewParam->setUninstantiatedDefaultArg(
519                                       OldParam->getUninstantiatedDefaultArg());
520           else
521             NewParam->setDefaultArg(OldParam->getInit());
522           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
523           Invalid = false;
524         }
525       }
526 
527       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
528       // hint here. Alternatively, we could walk the type-source information
529       // for NewParam to find the last source location in the type... but it
530       // isn't worth the effort right now. This is the kind of test case that
531       // is hard to get right:
532       //   int f(int);
533       //   void g(int (*fp)(int) = f);
534       //   void g(int (*fp)(int) = &f);
535       Diag(NewParam->getLocation(), DiagDefaultParamID)
536         << NewParam->getDefaultArgRange();
537 
538       // Look for the function declaration where the default argument was
539       // actually written, which may be a declaration prior to Old.
540       for (auto Older = PrevForDefaultArgs;
541            OldParam->hasInheritedDefaultArg(); /**/) {
542         Older = Older->getPreviousDecl();
543         OldParam = Older->getParamDecl(p);
544       }
545 
546       Diag(OldParam->getLocation(), diag::note_previous_definition)
547         << OldParam->getDefaultArgRange();
548     } else if (OldParamHasDfl) {
549       // Merge the old default argument into the new parameter unless the new
550       // function is a friend declaration in a template class. In the latter
551       // case the default arguments will be inherited when the friend
552       // declaration will be instantiated.
553       if (New->getFriendObjectKind() == Decl::FOK_None ||
554           !New->getLexicalDeclContext()->isDependentContext()) {
555         // It's important to use getInit() here;  getDefaultArg()
556         // strips off any top-level ExprWithCleanups.
557         NewParam->setHasInheritedDefaultArg();
558         if (OldParam->hasUnparsedDefaultArg())
559           NewParam->setUnparsedDefaultArg();
560         else if (OldParam->hasUninstantiatedDefaultArg())
561           NewParam->setUninstantiatedDefaultArg(
562                                        OldParam->getUninstantiatedDefaultArg());
563         else
564           NewParam->setDefaultArg(OldParam->getInit());
565       }
566     } else if (NewParamHasDfl) {
567       if (New->getDescribedFunctionTemplate()) {
568         // Paragraph 4, quoted above, only applies to non-template functions.
569         Diag(NewParam->getLocation(),
570              diag::err_param_default_argument_template_redecl)
571           << NewParam->getDefaultArgRange();
572         Diag(PrevForDefaultArgs->getLocation(),
573              diag::note_template_prev_declaration)
574             << false;
575       } else if (New->getTemplateSpecializationKind()
576                    != TSK_ImplicitInstantiation &&
577                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
578         // C++ [temp.expr.spec]p21:
579         //   Default function arguments shall not be specified in a declaration
580         //   or a definition for one of the following explicit specializations:
581         //     - the explicit specialization of a function template;
582         //     - the explicit specialization of a member function template;
583         //     - the explicit specialization of a member function of a class
584         //       template where the class template specialization to which the
585         //       member function specialization belongs is implicitly
586         //       instantiated.
587         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
588           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
589           << New->getDeclName()
590           << NewParam->getDefaultArgRange();
591       } else if (New->getDeclContext()->isDependentContext()) {
592         // C++ [dcl.fct.default]p6 (DR217):
593         //   Default arguments for a member function of a class template shall
594         //   be specified on the initial declaration of the member function
595         //   within the class template.
596         //
597         // Reading the tea leaves a bit in DR217 and its reference to DR205
598         // leads me to the conclusion that one cannot add default function
599         // arguments for an out-of-line definition of a member function of a
600         // dependent type.
601         int WhichKind = 2;
602         if (CXXRecordDecl *Record
603               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
604           if (Record->getDescribedClassTemplate())
605             WhichKind = 0;
606           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
607             WhichKind = 1;
608           else
609             WhichKind = 2;
610         }
611 
612         Diag(NewParam->getLocation(),
613              diag::err_param_default_argument_member_template_redecl)
614           << WhichKind
615           << NewParam->getDefaultArgRange();
616       }
617     }
618   }
619 
620   // DR1344: If a default argument is added outside a class definition and that
621   // default argument makes the function a special member function, the program
622   // is ill-formed. This can only happen for constructors.
623   if (isa<CXXConstructorDecl>(New) &&
624       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
625     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
626                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
627     if (NewSM != OldSM) {
628       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
629       assert(NewParam->hasDefaultArg());
630       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
631         << NewParam->getDefaultArgRange() << NewSM;
632       Diag(Old->getLocation(), diag::note_previous_declaration);
633     }
634   }
635 
636   const FunctionDecl *Def;
637   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
638   // template has a constexpr specifier then all its declarations shall
639   // contain the constexpr specifier.
640   if (New->isConstexpr() != Old->isConstexpr()) {
641     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
642       << New << New->isConstexpr();
643     Diag(Old->getLocation(), diag::note_previous_declaration);
644     Invalid = true;
645   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
646              Old->isDefined(Def) &&
647              // If a friend function is inlined but does not have 'inline'
648              // specifier, it is a definition. Do not report attribute conflict
649              // in this case, redefinition will be diagnosed later.
650              (New->isInlineSpecified() ||
651               New->getFriendObjectKind() == Decl::FOK_None)) {
652     // C++11 [dcl.fcn.spec]p4:
653     //   If the definition of a function appears in a translation unit before its
654     //   first declaration as inline, the program is ill-formed.
655     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
656     Diag(Def->getLocation(), diag::note_previous_definition);
657     Invalid = true;
658   }
659 
660   // FIXME: It's not clear what should happen if multiple declarations of a
661   // deduction guide have different explicitness. For now at least we simply
662   // reject any case where the explicitness changes.
663   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
664   if (NewGuide && NewGuide->isExplicitSpecified() !=
665                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
666     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
667       << NewGuide->isExplicitSpecified();
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++1z [dcl.dcl]/8:
720   //   The decl-specifier-seq shall contain only the type-specifier auto
721   //   and cv-qualifiers.
722   auto &DS = D.getDeclSpec();
723   {
724     SmallVector<StringRef, 8> BadSpecifiers;
725     SmallVector<SourceLocation, 8> BadSpecifierLocs;
726     if (auto SCS = DS.getStorageClassSpec()) {
727       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
728       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
729     }
730     if (auto TSCS = DS.getThreadStorageClassSpec()) {
731       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
732       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
733     }
734     if (DS.isConstexprSpecified()) {
735       BadSpecifiers.push_back("constexpr");
736       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
737     }
738     if (DS.isInlineSpecified()) {
739       BadSpecifiers.push_back("inline");
740       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
741     }
742     if (!BadSpecifiers.empty()) {
743       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
744       Err << (int)BadSpecifiers.size()
745           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
746       // Don't add FixItHints to remove the specifiers; we do still respect
747       // them when building the underlying variable.
748       for (auto Loc : BadSpecifierLocs)
749         Err << SourceRange(Loc, Loc);
750     }
751     // We can't recover from it being declared as a typedef.
752     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
753       return nullptr;
754   }
755 
756   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
757   QualType R = TInfo->getType();
758 
759   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
760                                       UPPC_DeclarationType))
761     D.setInvalidType();
762 
763   // The syntax only allows a single ref-qualifier prior to the decomposition
764   // declarator. No other declarator chunks are permitted. Also check the type
765   // specifier here.
766   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
767       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
768       (D.getNumTypeObjects() == 1 &&
769        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
770     Diag(Decomp.getLSquareLoc(),
771          (D.hasGroupingParens() ||
772           (D.getNumTypeObjects() &&
773            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
774              ? diag::err_decomp_decl_parens
775              : diag::err_decomp_decl_type)
776         << R;
777 
778     // In most cases, there's no actual problem with an explicitly-specified
779     // type, but a function type won't work here, and ActOnVariableDeclarator
780     // shouldn't be called for such a type.
781     if (R->isFunctionType())
782       D.setInvalidType();
783   }
784 
785   // Build the BindingDecls.
786   SmallVector<BindingDecl*, 8> Bindings;
787 
788   // Build the BindingDecls.
789   for (auto &B : D.getDecompositionDeclarator().bindings()) {
790     // Check for name conflicts.
791     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
792     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
793                           ForVisibleRedeclaration);
794     LookupName(Previous, S,
795                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
796 
797     // It's not permitted to shadow a template parameter name.
798     if (Previous.isSingleResult() &&
799         Previous.getFoundDecl()->isTemplateParameter()) {
800       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
801                                       Previous.getFoundDecl());
802       Previous.clear();
803     }
804 
805     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
806                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
807     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
808                          /*AllowInlineNamespace*/false);
809     if (!Previous.empty()) {
810       auto *Old = Previous.getRepresentativeDecl();
811       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
812       Diag(Old->getLocation(), diag::note_previous_definition);
813     }
814 
815     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
816     PushOnScopeChains(BD, S, true);
817     Bindings.push_back(BD);
818     ParsingInitForAutoVars.insert(BD);
819   }
820 
821   // There are no prior lookup results for the variable itself, because it
822   // is unnamed.
823   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
824                                Decomp.getLSquareLoc());
825   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
826                         ForVisibleRedeclaration);
827 
828   // Build the variable that holds the non-decomposed object.
829   bool AddToScope = true;
830   NamedDecl *New =
831       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
832                               MultiTemplateParamsArg(), AddToScope, Bindings);
833   if (AddToScope) {
834     S->AddDecl(New);
835     CurContext->addHiddenDecl(New);
836   }
837 
838   if (isInOpenMPDeclareTargetContext())
839     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
840 
841   return New;
842 }
843 
844 static bool checkSimpleDecomposition(
845     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
846     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
847     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
848   if ((int64_t)Bindings.size() != NumElems) {
849     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
850         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
851         << (NumElems < Bindings.size());
852     return true;
853   }
854 
855   unsigned I = 0;
856   for (auto *B : Bindings) {
857     SourceLocation Loc = B->getLocation();
858     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
859     if (E.isInvalid())
860       return true;
861     E = GetInit(Loc, E.get(), I++);
862     if (E.isInvalid())
863       return true;
864     B->setBinding(ElemType, E.get());
865   }
866 
867   return false;
868 }
869 
870 static bool checkArrayLikeDecomposition(Sema &S,
871                                         ArrayRef<BindingDecl *> Bindings,
872                                         ValueDecl *Src, QualType DecompType,
873                                         const llvm::APSInt &NumElems,
874                                         QualType ElemType) {
875   return checkSimpleDecomposition(
876       S, Bindings, Src, DecompType, NumElems, ElemType,
877       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
878         ExprResult E = S.ActOnIntegerConstant(Loc, I);
879         if (E.isInvalid())
880           return ExprError();
881         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
882       });
883 }
884 
885 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
886                                     ValueDecl *Src, QualType DecompType,
887                                     const ConstantArrayType *CAT) {
888   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
889                                      llvm::APSInt(CAT->getSize()),
890                                      CAT->getElementType());
891 }
892 
893 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
894                                      ValueDecl *Src, QualType DecompType,
895                                      const VectorType *VT) {
896   return checkArrayLikeDecomposition(
897       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
898       S.Context.getQualifiedType(VT->getElementType(),
899                                  DecompType.getQualifiers()));
900 }
901 
902 static bool checkComplexDecomposition(Sema &S,
903                                       ArrayRef<BindingDecl *> Bindings,
904                                       ValueDecl *Src, QualType DecompType,
905                                       const ComplexType *CT) {
906   return checkSimpleDecomposition(
907       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
908       S.Context.getQualifiedType(CT->getElementType(),
909                                  DecompType.getQualifiers()),
910       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
911         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
912       });
913 }
914 
915 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
916                                      TemplateArgumentListInfo &Args) {
917   SmallString<128> SS;
918   llvm::raw_svector_ostream OS(SS);
919   bool First = true;
920   for (auto &Arg : Args.arguments()) {
921     if (!First)
922       OS << ", ";
923     Arg.getArgument().print(PrintingPolicy, OS);
924     First = false;
925   }
926   return OS.str();
927 }
928 
929 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
930                                      SourceLocation Loc, StringRef Trait,
931                                      TemplateArgumentListInfo &Args,
932                                      unsigned DiagID) {
933   auto DiagnoseMissing = [&] {
934     if (DiagID)
935       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
936                                                Args);
937     return true;
938   };
939 
940   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
941   NamespaceDecl *Std = S.getStdNamespace();
942   if (!Std)
943     return DiagnoseMissing();
944 
945   // Look up the trait itself, within namespace std. We can diagnose various
946   // problems with this lookup even if we've been asked to not diagnose a
947   // missing specialization, because this can only fail if the user has been
948   // declaring their own names in namespace std or we don't support the
949   // standard library implementation in use.
950   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
951                       Loc, Sema::LookupOrdinaryName);
952   if (!S.LookupQualifiedName(Result, Std))
953     return DiagnoseMissing();
954   if (Result.isAmbiguous())
955     return true;
956 
957   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
958   if (!TraitTD) {
959     Result.suppressDiagnostics();
960     NamedDecl *Found = *Result.begin();
961     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
962     S.Diag(Found->getLocation(), diag::note_declared_at);
963     return true;
964   }
965 
966   // Build the template-id.
967   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
968   if (TraitTy.isNull())
969     return true;
970   if (!S.isCompleteType(Loc, TraitTy)) {
971     if (DiagID)
972       S.RequireCompleteType(
973           Loc, TraitTy, DiagID,
974           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
975     return true;
976   }
977 
978   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
979   assert(RD && "specialization of class template is not a class?");
980 
981   // Look up the member of the trait type.
982   S.LookupQualifiedName(TraitMemberLookup, RD);
983   return TraitMemberLookup.isAmbiguous();
984 }
985 
986 static TemplateArgumentLoc
987 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
988                                    uint64_t I) {
989   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
990   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
991 }
992 
993 static TemplateArgumentLoc
994 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
995   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
996 }
997 
998 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
999 
1000 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1001                                llvm::APSInt &Size) {
1002   EnterExpressionEvaluationContext ContextRAII(
1003       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1004 
1005   DeclarationName Value = S.PP.getIdentifierInfo("value");
1006   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1007 
1008   // Form template argument list for tuple_size<T>.
1009   TemplateArgumentListInfo Args(Loc, Loc);
1010   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1011 
1012   // If there's no tuple_size specialization, it's not tuple-like.
1013   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1014     return IsTupleLike::NotTupleLike;
1015 
1016   // If we get this far, we've committed to the tuple interpretation, but
1017   // we can still fail if there actually isn't a usable ::value.
1018 
1019   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1020     LookupResult &R;
1021     TemplateArgumentListInfo &Args;
1022     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1023         : R(R), Args(Args) {}
1024     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1025       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1026           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1027     }
1028   } Diagnoser(R, Args);
1029 
1030   if (R.empty()) {
1031     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1032     return IsTupleLike::Error;
1033   }
1034 
1035   ExprResult E =
1036       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1037   if (E.isInvalid())
1038     return IsTupleLike::Error;
1039 
1040   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1041   if (E.isInvalid())
1042     return IsTupleLike::Error;
1043 
1044   return IsTupleLike::TupleLike;
1045 }
1046 
1047 /// \return std::tuple_element<I, T>::type.
1048 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1049                                         unsigned I, QualType T) {
1050   // Form template argument list for tuple_element<I, T>.
1051   TemplateArgumentListInfo Args(Loc, Loc);
1052   Args.addArgument(
1053       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1054   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1055 
1056   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1057   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1058   if (lookupStdTypeTraitMember(
1059           S, R, Loc, "tuple_element", Args,
1060           diag::err_decomp_decl_std_tuple_element_not_specialized))
1061     return QualType();
1062 
1063   auto *TD = R.getAsSingle<TypeDecl>();
1064   if (!TD) {
1065     R.suppressDiagnostics();
1066     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1067       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1068     if (!R.empty())
1069       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1070     return QualType();
1071   }
1072 
1073   return S.Context.getTypeDeclType(TD);
1074 }
1075 
1076 namespace {
1077 struct BindingDiagnosticTrap {
1078   Sema &S;
1079   DiagnosticErrorTrap Trap;
1080   BindingDecl *BD;
1081 
1082   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1083       : S(S), Trap(S.Diags), BD(BD) {}
1084   ~BindingDiagnosticTrap() {
1085     if (Trap.hasErrorOccurred())
1086       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1087   }
1088 };
1089 }
1090 
1091 static bool checkTupleLikeDecomposition(Sema &S,
1092                                         ArrayRef<BindingDecl *> Bindings,
1093                                         VarDecl *Src, QualType DecompType,
1094                                         const llvm::APSInt &TupleSize) {
1095   if ((int64_t)Bindings.size() != TupleSize) {
1096     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1097         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1098         << (TupleSize < Bindings.size());
1099     return true;
1100   }
1101 
1102   if (Bindings.empty())
1103     return false;
1104 
1105   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1106 
1107   // [dcl.decomp]p3:
1108   //   The unqualified-id get is looked up in the scope of E by class member
1109   //   access lookup ...
1110   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1111   bool UseMemberGet = false;
1112   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1113     if (auto *RD = DecompType->getAsCXXRecordDecl())
1114       S.LookupQualifiedName(MemberGet, RD);
1115     if (MemberGet.isAmbiguous())
1116       return true;
1117     //   ... and if that finds at least one declaration that is a function
1118     //   template whose first template parameter is a non-type parameter ...
1119     for (NamedDecl *D : MemberGet) {
1120       if (FunctionTemplateDecl *FTD =
1121               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1122         TemplateParameterList *TPL = FTD->getTemplateParameters();
1123         if (TPL->size() != 0 &&
1124             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1125           //   ... the initializer is e.get<i>().
1126           UseMemberGet = true;
1127           break;
1128         }
1129       }
1130     }
1131     S.FilterAcceptableTemplateNames(MemberGet);
1132   }
1133 
1134   unsigned I = 0;
1135   for (auto *B : Bindings) {
1136     BindingDiagnosticTrap Trap(S, B);
1137     SourceLocation Loc = B->getLocation();
1138 
1139     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1140     if (E.isInvalid())
1141       return true;
1142 
1143     //   e is an lvalue if the type of the entity is an lvalue reference and
1144     //   an xvalue otherwise
1145     if (!Src->getType()->isLValueReferenceType())
1146       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1147                                    E.get(), nullptr, VK_XValue);
1148 
1149     TemplateArgumentListInfo Args(Loc, Loc);
1150     Args.addArgument(
1151         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1152 
1153     if (UseMemberGet) {
1154       //   if [lookup of member get] finds at least one declaration, the
1155       //   initializer is e.get<i-1>().
1156       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1157                                      CXXScopeSpec(), SourceLocation(), nullptr,
1158                                      MemberGet, &Args, nullptr);
1159       if (E.isInvalid())
1160         return true;
1161 
1162       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1163     } else {
1164       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1165       //   in the associated namespaces.
1166       Expr *Get = UnresolvedLookupExpr::Create(
1167           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1168           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1169           UnresolvedSetIterator(), UnresolvedSetIterator());
1170 
1171       Expr *Arg = E.get();
1172       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1173     }
1174     if (E.isInvalid())
1175       return true;
1176     Expr *Init = E.get();
1177 
1178     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1179     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1180     if (T.isNull())
1181       return true;
1182 
1183     //   each vi is a variable of type "reference to T" initialized with the
1184     //   initializer, where the reference is an lvalue reference if the
1185     //   initializer is an lvalue and an rvalue reference otherwise
1186     QualType RefType =
1187         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1188     if (RefType.isNull())
1189       return true;
1190     auto *RefVD = VarDecl::Create(
1191         S.Context, Src->getDeclContext(), Loc, Loc,
1192         B->getDeclName().getAsIdentifierInfo(), RefType,
1193         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1194     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1195     RefVD->setTSCSpec(Src->getTSCSpec());
1196     RefVD->setImplicit();
1197     if (Src->isInlineSpecified())
1198       RefVD->setInlineSpecified();
1199     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1200 
1201     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1202     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1203     InitializationSequence Seq(S, Entity, Kind, Init);
1204     E = Seq.Perform(S, Entity, Kind, Init);
1205     if (E.isInvalid())
1206       return true;
1207     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1208     if (E.isInvalid())
1209       return true;
1210     RefVD->setInit(E.get());
1211     RefVD->checkInitIsICE();
1212 
1213     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1214                                    DeclarationNameInfo(B->getDeclName(), Loc),
1215                                    RefVD);
1216     if (E.isInvalid())
1217       return true;
1218 
1219     B->setBinding(T, E.get());
1220     I++;
1221   }
1222 
1223   return false;
1224 }
1225 
1226 /// Find the base class to decompose in a built-in decomposition of a class type.
1227 /// This base class search is, unfortunately, not quite like any other that we
1228 /// perform anywhere else in C++.
1229 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1230                                                 const CXXRecordDecl *RD,
1231                                                 CXXCastPath &BasePath) {
1232   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1233                           CXXBasePath &Path) {
1234     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1235   };
1236 
1237   const CXXRecordDecl *ClassWithFields = nullptr;
1238   AccessSpecifier AS = AS_public;
1239   if (RD->hasDirectFields())
1240     // [dcl.decomp]p4:
1241     //   Otherwise, all of E's non-static data members shall be public direct
1242     //   members of E ...
1243     ClassWithFields = RD;
1244   else {
1245     //   ... or of ...
1246     CXXBasePaths Paths;
1247     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1248     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1249       // If no classes have fields, just decompose RD itself. (This will work
1250       // if and only if zero bindings were provided.)
1251       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1252     }
1253 
1254     CXXBasePath *BestPath = nullptr;
1255     for (auto &P : Paths) {
1256       if (!BestPath)
1257         BestPath = &P;
1258       else if (!S.Context.hasSameType(P.back().Base->getType(),
1259                                       BestPath->back().Base->getType())) {
1260         //   ... the same ...
1261         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1262           << false << RD << BestPath->back().Base->getType()
1263           << P.back().Base->getType();
1264         return DeclAccessPair();
1265       } else if (P.Access < BestPath->Access) {
1266         BestPath = &P;
1267       }
1268     }
1269 
1270     //   ... unambiguous ...
1271     QualType BaseType = BestPath->back().Base->getType();
1272     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1273       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1274         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1275       return DeclAccessPair();
1276     }
1277 
1278     //   ... [accessible, implied by other rules] base class of E.
1279     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1280                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1281     AS = BestPath->Access;
1282 
1283     ClassWithFields = BaseType->getAsCXXRecordDecl();
1284     S.BuildBasePathArray(Paths, BasePath);
1285   }
1286 
1287   // The above search did not check whether the selected class itself has base
1288   // classes with fields, so check that now.
1289   CXXBasePaths Paths;
1290   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1291     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1292       << (ClassWithFields == RD) << RD << ClassWithFields
1293       << Paths.front().back().Base->getType();
1294     return DeclAccessPair();
1295   }
1296 
1297   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1298 }
1299 
1300 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1301                                      ValueDecl *Src, QualType DecompType,
1302                                      const CXXRecordDecl *OrigRD) {
1303   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1304                             diag::err_incomplete_type))
1305     return true;
1306 
1307   CXXCastPath BasePath;
1308   DeclAccessPair BasePair =
1309       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1310   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1311   if (!RD)
1312     return true;
1313   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1314                                                  DecompType.getQualifiers());
1315 
1316   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1317     unsigned NumFields =
1318         std::count_if(RD->field_begin(), RD->field_end(),
1319                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1320     assert(Bindings.size() != NumFields);
1321     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1322         << DecompType << (unsigned)Bindings.size() << NumFields
1323         << (NumFields < Bindings.size());
1324     return true;
1325   };
1326 
1327   //   all of E's non-static data members shall be [...] well-formed
1328   //   when named as e.name in the context of the structured binding,
1329   //   E shall not have an anonymous union member, ...
1330   unsigned I = 0;
1331   for (auto *FD : RD->fields()) {
1332     if (FD->isUnnamedBitfield())
1333       continue;
1334 
1335     if (FD->isAnonymousStructOrUnion()) {
1336       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1337         << DecompType << FD->getType()->isUnionType();
1338       S.Diag(FD->getLocation(), diag::note_declared_at);
1339       return true;
1340     }
1341 
1342     // We have a real field to bind.
1343     if (I >= Bindings.size())
1344       return DiagnoseBadNumberOfBindings();
1345     auto *B = Bindings[I++];
1346     SourceLocation Loc = B->getLocation();
1347 
1348     // The field must be accessible in the context of the structured binding.
1349     // We already checked that the base class is accessible.
1350     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1351     // const_cast here.
1352     S.CheckStructuredBindingMemberAccess(
1353         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1354         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1355                                      BasePair.getAccess(), FD->getAccess())));
1356 
1357     // Initialize the binding to Src.FD.
1358     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1359     if (E.isInvalid())
1360       return true;
1361     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1362                             VK_LValue, &BasePath);
1363     if (E.isInvalid())
1364       return true;
1365     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1366                                   CXXScopeSpec(), FD,
1367                                   DeclAccessPair::make(FD, FD->getAccess()),
1368                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1369     if (E.isInvalid())
1370       return true;
1371 
1372     // If the type of the member is T, the referenced type is cv T, where cv is
1373     // the cv-qualification of the decomposition expression.
1374     //
1375     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1376     // 'const' to the type of the field.
1377     Qualifiers Q = DecompType.getQualifiers();
1378     if (FD->isMutable())
1379       Q.removeConst();
1380     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1381   }
1382 
1383   if (I != Bindings.size())
1384     return DiagnoseBadNumberOfBindings();
1385 
1386   return false;
1387 }
1388 
1389 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1390   QualType DecompType = DD->getType();
1391 
1392   // If the type of the decomposition is dependent, then so is the type of
1393   // each binding.
1394   if (DecompType->isDependentType()) {
1395     for (auto *B : DD->bindings())
1396       B->setType(Context.DependentTy);
1397     return;
1398   }
1399 
1400   DecompType = DecompType.getNonReferenceType();
1401   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1402 
1403   // C++1z [dcl.decomp]/2:
1404   //   If E is an array type [...]
1405   // As an extension, we also support decomposition of built-in complex and
1406   // vector types.
1407   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1408     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1409       DD->setInvalidDecl();
1410     return;
1411   }
1412   if (auto *VT = DecompType->getAs<VectorType>()) {
1413     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1414       DD->setInvalidDecl();
1415     return;
1416   }
1417   if (auto *CT = DecompType->getAs<ComplexType>()) {
1418     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1419       DD->setInvalidDecl();
1420     return;
1421   }
1422 
1423   // C++1z [dcl.decomp]/3:
1424   //   if the expression std::tuple_size<E>::value is a well-formed integral
1425   //   constant expression, [...]
1426   llvm::APSInt TupleSize(32);
1427   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1428   case IsTupleLike::Error:
1429     DD->setInvalidDecl();
1430     return;
1431 
1432   case IsTupleLike::TupleLike:
1433     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1434       DD->setInvalidDecl();
1435     return;
1436 
1437   case IsTupleLike::NotTupleLike:
1438     break;
1439   }
1440 
1441   // C++1z [dcl.dcl]/8:
1442   //   [E shall be of array or non-union class type]
1443   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1444   if (!RD || RD->isUnion()) {
1445     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1446         << DD << !RD << DecompType;
1447     DD->setInvalidDecl();
1448     return;
1449   }
1450 
1451   // C++1z [dcl.decomp]/4:
1452   //   all of E's non-static data members shall be [...] direct members of
1453   //   E or of the same unambiguous public base class of E, ...
1454   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1455     DD->setInvalidDecl();
1456 }
1457 
1458 /// Merge the exception specifications of two variable declarations.
1459 ///
1460 /// This is called when there's a redeclaration of a VarDecl. The function
1461 /// checks if the redeclaration might have an exception specification and
1462 /// validates compatibility and merges the specs if necessary.
1463 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1464   // Shortcut if exceptions are disabled.
1465   if (!getLangOpts().CXXExceptions)
1466     return;
1467 
1468   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1469          "Should only be called if types are otherwise the same.");
1470 
1471   QualType NewType = New->getType();
1472   QualType OldType = Old->getType();
1473 
1474   // We're only interested in pointers and references to functions, as well
1475   // as pointers to member functions.
1476   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1477     NewType = R->getPointeeType();
1478     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1479   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1480     NewType = P->getPointeeType();
1481     OldType = OldType->getAs<PointerType>()->getPointeeType();
1482   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1483     NewType = M->getPointeeType();
1484     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1485   }
1486 
1487   if (!NewType->isFunctionProtoType())
1488     return;
1489 
1490   // There's lots of special cases for functions. For function pointers, system
1491   // libraries are hopefully not as broken so that we don't need these
1492   // workarounds.
1493   if (CheckEquivalentExceptionSpec(
1494         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1495         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1496     New->setInvalidDecl();
1497   }
1498 }
1499 
1500 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1501 /// function declaration are well-formed according to C++
1502 /// [dcl.fct.default].
1503 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1504   unsigned NumParams = FD->getNumParams();
1505   unsigned p;
1506 
1507   // Find first parameter with a default argument
1508   for (p = 0; p < NumParams; ++p) {
1509     ParmVarDecl *Param = FD->getParamDecl(p);
1510     if (Param->hasDefaultArg())
1511       break;
1512   }
1513 
1514   // C++11 [dcl.fct.default]p4:
1515   //   In a given function declaration, each parameter subsequent to a parameter
1516   //   with a default argument shall have a default argument supplied in this or
1517   //   a previous declaration or shall be a function parameter pack. A default
1518   //   argument shall not be redefined by a later declaration (not even to the
1519   //   same value).
1520   unsigned LastMissingDefaultArg = 0;
1521   for (; p < NumParams; ++p) {
1522     ParmVarDecl *Param = FD->getParamDecl(p);
1523     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1524       if (Param->isInvalidDecl())
1525         /* We already complained about this parameter. */;
1526       else if (Param->getIdentifier())
1527         Diag(Param->getLocation(),
1528              diag::err_param_default_argument_missing_name)
1529           << Param->getIdentifier();
1530       else
1531         Diag(Param->getLocation(),
1532              diag::err_param_default_argument_missing);
1533 
1534       LastMissingDefaultArg = p;
1535     }
1536   }
1537 
1538   if (LastMissingDefaultArg > 0) {
1539     // Some default arguments were missing. Clear out all of the
1540     // default arguments up to (and including) the last missing
1541     // default argument, so that we leave the function parameters
1542     // in a semantically valid state.
1543     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1544       ParmVarDecl *Param = FD->getParamDecl(p);
1545       if (Param->hasDefaultArg()) {
1546         Param->setDefaultArg(nullptr);
1547       }
1548     }
1549   }
1550 }
1551 
1552 // CheckConstexprParameterTypes - Check whether a function's parameter types
1553 // are all literal types. If so, return true. If not, produce a suitable
1554 // diagnostic and return false.
1555 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1556                                          const FunctionDecl *FD) {
1557   unsigned ArgIndex = 0;
1558   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1559   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1560                                               e = FT->param_type_end();
1561        i != e; ++i, ++ArgIndex) {
1562     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1563     SourceLocation ParamLoc = PD->getLocation();
1564     if (!(*i)->isDependentType() &&
1565         SemaRef.RequireLiteralType(ParamLoc, *i,
1566                                    diag::err_constexpr_non_literal_param,
1567                                    ArgIndex+1, PD->getSourceRange(),
1568                                    isa<CXXConstructorDecl>(FD)))
1569       return false;
1570   }
1571   return true;
1572 }
1573 
1574 /// Get diagnostic %select index for tag kind for
1575 /// record diagnostic message.
1576 /// WARNING: Indexes apply to particular diagnostics only!
1577 ///
1578 /// \returns diagnostic %select index.
1579 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1580   switch (Tag) {
1581   case TTK_Struct: return 0;
1582   case TTK_Interface: return 1;
1583   case TTK_Class:  return 2;
1584   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1585   }
1586 }
1587 
1588 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1589 // the requirements of a constexpr function definition or a constexpr
1590 // constructor definition. If so, return true. If not, produce appropriate
1591 // diagnostics and return false.
1592 //
1593 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1594 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1595   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1596   if (MD && MD->isInstance()) {
1597     // C++11 [dcl.constexpr]p4:
1598     //  The definition of a constexpr constructor shall satisfy the following
1599     //  constraints:
1600     //  - the class shall not have any virtual base classes;
1601     const CXXRecordDecl *RD = MD->getParent();
1602     if (RD->getNumVBases()) {
1603       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1604         << isa<CXXConstructorDecl>(NewFD)
1605         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1606       for (const auto &I : RD->vbases())
1607         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1608             << I.getSourceRange();
1609       return false;
1610     }
1611   }
1612 
1613   if (!isa<CXXConstructorDecl>(NewFD)) {
1614     // C++11 [dcl.constexpr]p3:
1615     //  The definition of a constexpr function shall satisfy the following
1616     //  constraints:
1617     // - it shall not be virtual;
1618     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1619     if (Method && Method->isVirtual()) {
1620       Method = Method->getCanonicalDecl();
1621       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1622 
1623       // If it's not obvious why this function is virtual, find an overridden
1624       // function which uses the 'virtual' keyword.
1625       const CXXMethodDecl *WrittenVirtual = Method;
1626       while (!WrittenVirtual->isVirtualAsWritten())
1627         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1628       if (WrittenVirtual != Method)
1629         Diag(WrittenVirtual->getLocation(),
1630              diag::note_overridden_virtual_function);
1631       return false;
1632     }
1633 
1634     // - its return type shall be a literal type;
1635     QualType RT = NewFD->getReturnType();
1636     if (!RT->isDependentType() &&
1637         RequireLiteralType(NewFD->getLocation(), RT,
1638                            diag::err_constexpr_non_literal_return))
1639       return false;
1640   }
1641 
1642   // - each of its parameter types shall be a literal type;
1643   if (!CheckConstexprParameterTypes(*this, NewFD))
1644     return false;
1645 
1646   return true;
1647 }
1648 
1649 /// Check the given declaration statement is legal within a constexpr function
1650 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1651 ///
1652 /// \return true if the body is OK (maybe only as an extension), false if we
1653 ///         have diagnosed a problem.
1654 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1655                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1656   // C++11 [dcl.constexpr]p3 and p4:
1657   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1658   //  contain only
1659   for (const auto *DclIt : DS->decls()) {
1660     switch (DclIt->getKind()) {
1661     case Decl::StaticAssert:
1662     case Decl::Using:
1663     case Decl::UsingShadow:
1664     case Decl::UsingDirective:
1665     case Decl::UnresolvedUsingTypename:
1666     case Decl::UnresolvedUsingValue:
1667       //   - static_assert-declarations
1668       //   - using-declarations,
1669       //   - using-directives,
1670       continue;
1671 
1672     case Decl::Typedef:
1673     case Decl::TypeAlias: {
1674       //   - typedef declarations and alias-declarations that do not define
1675       //     classes or enumerations,
1676       const auto *TN = cast<TypedefNameDecl>(DclIt);
1677       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1678         // Don't allow variably-modified types in constexpr functions.
1679         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1680         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1681           << TL.getSourceRange() << TL.getType()
1682           << isa<CXXConstructorDecl>(Dcl);
1683         return false;
1684       }
1685       continue;
1686     }
1687 
1688     case Decl::Enum:
1689     case Decl::CXXRecord:
1690       // C++1y allows types to be defined, not just declared.
1691       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1692         SemaRef.Diag(DS->getBeginLoc(),
1693                      SemaRef.getLangOpts().CPlusPlus14
1694                          ? diag::warn_cxx11_compat_constexpr_type_definition
1695                          : diag::ext_constexpr_type_definition)
1696             << isa<CXXConstructorDecl>(Dcl);
1697       continue;
1698 
1699     case Decl::EnumConstant:
1700     case Decl::IndirectField:
1701     case Decl::ParmVar:
1702       // These can only appear with other declarations which are banned in
1703       // C++11 and permitted in C++1y, so ignore them.
1704       continue;
1705 
1706     case Decl::Var:
1707     case Decl::Decomposition: {
1708       // C++1y [dcl.constexpr]p3 allows anything except:
1709       //   a definition of a variable of non-literal type or of static or
1710       //   thread storage duration or for which no initialization is performed.
1711       const auto *VD = cast<VarDecl>(DclIt);
1712       if (VD->isThisDeclarationADefinition()) {
1713         if (VD->isStaticLocal()) {
1714           SemaRef.Diag(VD->getLocation(),
1715                        diag::err_constexpr_local_var_static)
1716             << isa<CXXConstructorDecl>(Dcl)
1717             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1718           return false;
1719         }
1720         if (!VD->getType()->isDependentType() &&
1721             SemaRef.RequireLiteralType(
1722               VD->getLocation(), VD->getType(),
1723               diag::err_constexpr_local_var_non_literal_type,
1724               isa<CXXConstructorDecl>(Dcl)))
1725           return false;
1726         if (!VD->getType()->isDependentType() &&
1727             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1728           SemaRef.Diag(VD->getLocation(),
1729                        diag::err_constexpr_local_var_no_init)
1730             << isa<CXXConstructorDecl>(Dcl);
1731           return false;
1732         }
1733       }
1734       SemaRef.Diag(VD->getLocation(),
1735                    SemaRef.getLangOpts().CPlusPlus14
1736                     ? diag::warn_cxx11_compat_constexpr_local_var
1737                     : diag::ext_constexpr_local_var)
1738         << isa<CXXConstructorDecl>(Dcl);
1739       continue;
1740     }
1741 
1742     case Decl::NamespaceAlias:
1743     case Decl::Function:
1744       // These are disallowed in C++11 and permitted in C++1y. Allow them
1745       // everywhere as an extension.
1746       if (!Cxx1yLoc.isValid())
1747         Cxx1yLoc = DS->getBeginLoc();
1748       continue;
1749 
1750     default:
1751       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1752           << isa<CXXConstructorDecl>(Dcl);
1753       return false;
1754     }
1755   }
1756 
1757   return true;
1758 }
1759 
1760 /// Check that the given field is initialized within a constexpr constructor.
1761 ///
1762 /// \param Dcl The constexpr constructor being checked.
1763 /// \param Field The field being checked. This may be a member of an anonymous
1764 ///        struct or union nested within the class being checked.
1765 /// \param Inits All declarations, including anonymous struct/union members and
1766 ///        indirect members, for which any initialization was provided.
1767 /// \param Diagnosed Set to true if an error is produced.
1768 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1769                                           const FunctionDecl *Dcl,
1770                                           FieldDecl *Field,
1771                                           llvm::SmallSet<Decl*, 16> &Inits,
1772                                           bool &Diagnosed) {
1773   if (Field->isInvalidDecl())
1774     return;
1775 
1776   if (Field->isUnnamedBitfield())
1777     return;
1778 
1779   // Anonymous unions with no variant members and empty anonymous structs do not
1780   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1781   // indirect fields don't need initializing.
1782   if (Field->isAnonymousStructOrUnion() &&
1783       (Field->getType()->isUnionType()
1784            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1785            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1786     return;
1787 
1788   if (!Inits.count(Field)) {
1789     if (!Diagnosed) {
1790       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1791       Diagnosed = true;
1792     }
1793     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1794   } else if (Field->isAnonymousStructOrUnion()) {
1795     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1796     for (auto *I : RD->fields())
1797       // If an anonymous union contains an anonymous struct of which any member
1798       // is initialized, all members must be initialized.
1799       if (!RD->isUnion() || Inits.count(I))
1800         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1801   }
1802 }
1803 
1804 /// Check the provided statement is allowed in a constexpr function
1805 /// definition.
1806 static bool
1807 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1808                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1809                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1810   // - its function-body shall be [...] a compound-statement that contains only
1811   switch (S->getStmtClass()) {
1812   case Stmt::NullStmtClass:
1813     //   - null statements,
1814     return true;
1815 
1816   case Stmt::DeclStmtClass:
1817     //   - static_assert-declarations
1818     //   - using-declarations,
1819     //   - using-directives,
1820     //   - typedef declarations and alias-declarations that do not define
1821     //     classes or enumerations,
1822     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1823       return false;
1824     return true;
1825 
1826   case Stmt::ReturnStmtClass:
1827     //   - and exactly one return statement;
1828     if (isa<CXXConstructorDecl>(Dcl)) {
1829       // C++1y allows return statements in constexpr constructors.
1830       if (!Cxx1yLoc.isValid())
1831         Cxx1yLoc = S->getBeginLoc();
1832       return true;
1833     }
1834 
1835     ReturnStmts.push_back(S->getBeginLoc());
1836     return true;
1837 
1838   case Stmt::CompoundStmtClass: {
1839     // C++1y allows compound-statements.
1840     if (!Cxx1yLoc.isValid())
1841       Cxx1yLoc = S->getBeginLoc();
1842 
1843     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1844     for (auto *BodyIt : CompStmt->body()) {
1845       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1846                                       Cxx1yLoc, Cxx2aLoc))
1847         return false;
1848     }
1849     return true;
1850   }
1851 
1852   case Stmt::AttributedStmtClass:
1853     if (!Cxx1yLoc.isValid())
1854       Cxx1yLoc = S->getBeginLoc();
1855     return true;
1856 
1857   case Stmt::IfStmtClass: {
1858     // C++1y allows if-statements.
1859     if (!Cxx1yLoc.isValid())
1860       Cxx1yLoc = S->getBeginLoc();
1861 
1862     IfStmt *If = cast<IfStmt>(S);
1863     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1864                                     Cxx1yLoc, Cxx2aLoc))
1865       return false;
1866     if (If->getElse() &&
1867         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1868                                     Cxx1yLoc, Cxx2aLoc))
1869       return false;
1870     return true;
1871   }
1872 
1873   case Stmt::WhileStmtClass:
1874   case Stmt::DoStmtClass:
1875   case Stmt::ForStmtClass:
1876   case Stmt::CXXForRangeStmtClass:
1877   case Stmt::ContinueStmtClass:
1878     // C++1y allows all of these. We don't allow them as extensions in C++11,
1879     // because they don't make sense without variable mutation.
1880     if (!SemaRef.getLangOpts().CPlusPlus14)
1881       break;
1882     if (!Cxx1yLoc.isValid())
1883       Cxx1yLoc = S->getBeginLoc();
1884     for (Stmt *SubStmt : S->children())
1885       if (SubStmt &&
1886           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1887                                       Cxx1yLoc, Cxx2aLoc))
1888         return false;
1889     return true;
1890 
1891   case Stmt::SwitchStmtClass:
1892   case Stmt::CaseStmtClass:
1893   case Stmt::DefaultStmtClass:
1894   case Stmt::BreakStmtClass:
1895     // C++1y allows switch-statements, and since they don't need variable
1896     // mutation, we can reasonably allow them in C++11 as an extension.
1897     if (!Cxx1yLoc.isValid())
1898       Cxx1yLoc = S->getBeginLoc();
1899     for (Stmt *SubStmt : S->children())
1900       if (SubStmt &&
1901           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1902                                       Cxx1yLoc, Cxx2aLoc))
1903         return false;
1904     return true;
1905 
1906   case Stmt::CXXTryStmtClass:
1907     if (Cxx2aLoc.isInvalid())
1908       Cxx2aLoc = S->getBeginLoc();
1909     for (Stmt *SubStmt : S->children()) {
1910       if (SubStmt &&
1911           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1912                                       Cxx1yLoc, Cxx2aLoc))
1913         return false;
1914     }
1915     return true;
1916 
1917   case Stmt::CXXCatchStmtClass:
1918     // Do not bother checking the language mode (already covered by the
1919     // try block check).
1920     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1921                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1922                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1923       return false;
1924     return true;
1925 
1926   default:
1927     if (!isa<Expr>(S))
1928       break;
1929 
1930     // C++1y allows expression-statements.
1931     if (!Cxx1yLoc.isValid())
1932       Cxx1yLoc = S->getBeginLoc();
1933     return true;
1934   }
1935 
1936   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1937       << isa<CXXConstructorDecl>(Dcl);
1938   return false;
1939 }
1940 
1941 /// Check the body for the given constexpr function declaration only contains
1942 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1943 ///
1944 /// \return true if the body is OK, false if we have diagnosed a problem.
1945 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1946   SmallVector<SourceLocation, 4> ReturnStmts;
1947 
1948   if (isa<CXXTryStmt>(Body)) {
1949     // C++11 [dcl.constexpr]p3:
1950     //  The definition of a constexpr function shall satisfy the following
1951     //  constraints: [...]
1952     // - its function-body shall be = delete, = default, or a
1953     //   compound-statement
1954     //
1955     // C++11 [dcl.constexpr]p4:
1956     //  In the definition of a constexpr constructor, [...]
1957     // - its function-body shall not be a function-try-block;
1958     //
1959     // This restriction is lifted in C++2a, as long as inner statements also
1960     // apply the general constexpr rules.
1961     Diag(Body->getBeginLoc(),
1962          !getLangOpts().CPlusPlus2a
1963              ? diag::ext_constexpr_function_try_block_cxx2a
1964              : diag::warn_cxx17_compat_constexpr_function_try_block)
1965         << isa<CXXConstructorDecl>(Dcl);
1966   }
1967 
1968   // - its function-body shall be [...] a compound-statement that contains only
1969   //   [... list of cases ...]
1970   //
1971   // Note that walking the children here is enough to properly check for
1972   // CompoundStmt and CXXTryStmt body.
1973   SourceLocation Cxx1yLoc, Cxx2aLoc;
1974   for (Stmt *SubStmt : Body->children()) {
1975     if (SubStmt &&
1976         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1977                                     Cxx1yLoc, Cxx2aLoc))
1978       return false;
1979   }
1980 
1981   if (Cxx2aLoc.isValid())
1982     Diag(Cxx2aLoc,
1983          getLangOpts().CPlusPlus2a
1984            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1985            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1986       << isa<CXXConstructorDecl>(Dcl);
1987   if (Cxx1yLoc.isValid())
1988     Diag(Cxx1yLoc,
1989          getLangOpts().CPlusPlus14
1990            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1991            : diag::ext_constexpr_body_invalid_stmt)
1992       << isa<CXXConstructorDecl>(Dcl);
1993 
1994   if (const CXXConstructorDecl *Constructor
1995         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1996     const CXXRecordDecl *RD = Constructor->getParent();
1997     // DR1359:
1998     // - every non-variant non-static data member and base class sub-object
1999     //   shall be initialized;
2000     // DR1460:
2001     // - if the class is a union having variant members, exactly one of them
2002     //   shall be initialized;
2003     if (RD->isUnion()) {
2004       if (Constructor->getNumCtorInitializers() == 0 &&
2005           RD->hasVariantMembers()) {
2006         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2007         return false;
2008       }
2009     } else if (!Constructor->isDependentContext() &&
2010                !Constructor->isDelegatingConstructor()) {
2011       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2012 
2013       // Skip detailed checking if we have enough initializers, and we would
2014       // allow at most one initializer per member.
2015       bool AnyAnonStructUnionMembers = false;
2016       unsigned Fields = 0;
2017       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2018            E = RD->field_end(); I != E; ++I, ++Fields) {
2019         if (I->isAnonymousStructOrUnion()) {
2020           AnyAnonStructUnionMembers = true;
2021           break;
2022         }
2023       }
2024       // DR1460:
2025       // - if the class is a union-like class, but is not a union, for each of
2026       //   its anonymous union members having variant members, exactly one of
2027       //   them shall be initialized;
2028       if (AnyAnonStructUnionMembers ||
2029           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2030         // Check initialization of non-static data members. Base classes are
2031         // always initialized so do not need to be checked. Dependent bases
2032         // might not have initializers in the member initializer list.
2033         llvm::SmallSet<Decl*, 16> Inits;
2034         for (const auto *I: Constructor->inits()) {
2035           if (FieldDecl *FD = I->getMember())
2036             Inits.insert(FD);
2037           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2038             Inits.insert(ID->chain_begin(), ID->chain_end());
2039         }
2040 
2041         bool Diagnosed = false;
2042         for (auto *I : RD->fields())
2043           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2044         if (Diagnosed)
2045           return false;
2046       }
2047     }
2048   } else {
2049     if (ReturnStmts.empty()) {
2050       // C++1y doesn't require constexpr functions to contain a 'return'
2051       // statement. We still do, unless the return type might be void, because
2052       // otherwise if there's no return statement, the function cannot
2053       // be used in a core constant expression.
2054       bool OK = getLangOpts().CPlusPlus14 &&
2055                 (Dcl->getReturnType()->isVoidType() ||
2056                  Dcl->getReturnType()->isDependentType());
2057       Diag(Dcl->getLocation(),
2058            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2059               : diag::err_constexpr_body_no_return);
2060       if (!OK)
2061         return false;
2062     } else if (ReturnStmts.size() > 1) {
2063       Diag(ReturnStmts.back(),
2064            getLangOpts().CPlusPlus14
2065              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2066              : diag::ext_constexpr_body_multiple_return);
2067       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2068         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2069     }
2070   }
2071 
2072   // C++11 [dcl.constexpr]p5:
2073   //   if no function argument values exist such that the function invocation
2074   //   substitution would produce a constant expression, the program is
2075   //   ill-formed; no diagnostic required.
2076   // C++11 [dcl.constexpr]p3:
2077   //   - every constructor call and implicit conversion used in initializing the
2078   //     return value shall be one of those allowed in a constant expression.
2079   // C++11 [dcl.constexpr]p4:
2080   //   - every constructor involved in initializing non-static data members and
2081   //     base class sub-objects shall be a constexpr constructor.
2082   SmallVector<PartialDiagnosticAt, 8> Diags;
2083   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2084     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2085       << isa<CXXConstructorDecl>(Dcl);
2086     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2087       Diag(Diags[I].first, Diags[I].second);
2088     // Don't return false here: we allow this for compatibility in
2089     // system headers.
2090   }
2091 
2092   return true;
2093 }
2094 
2095 /// Get the class that is directly named by the current context. This is the
2096 /// class for which an unqualified-id in this scope could name a constructor
2097 /// or destructor.
2098 ///
2099 /// If the scope specifier denotes a class, this will be that class.
2100 /// If the scope specifier is empty, this will be the class whose
2101 /// member-specification we are currently within. Otherwise, there
2102 /// is no such class.
2103 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2104   assert(getLangOpts().CPlusPlus && "No class names in C!");
2105 
2106   if (SS && SS->isInvalid())
2107     return nullptr;
2108 
2109   if (SS && SS->isNotEmpty()) {
2110     DeclContext *DC = computeDeclContext(*SS, true);
2111     return dyn_cast_or_null<CXXRecordDecl>(DC);
2112   }
2113 
2114   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2115 }
2116 
2117 /// isCurrentClassName - Determine whether the identifier II is the
2118 /// name of the class type currently being defined. In the case of
2119 /// nested classes, this will only return true if II is the name of
2120 /// the innermost class.
2121 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2122                               const CXXScopeSpec *SS) {
2123   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2124   return CurDecl && &II == CurDecl->getIdentifier();
2125 }
2126 
2127 /// Determine whether the identifier II is a typo for the name of
2128 /// the class type currently being defined. If so, update it to the identifier
2129 /// that should have been used.
2130 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2131   assert(getLangOpts().CPlusPlus && "No class names in C!");
2132 
2133   if (!getLangOpts().SpellChecking)
2134     return false;
2135 
2136   CXXRecordDecl *CurDecl;
2137   if (SS && SS->isSet() && !SS->isInvalid()) {
2138     DeclContext *DC = computeDeclContext(*SS, true);
2139     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2140   } else
2141     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2142 
2143   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2144       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2145           < II->getLength()) {
2146     II = CurDecl->getIdentifier();
2147     return true;
2148   }
2149 
2150   return false;
2151 }
2152 
2153 /// Determine whether the given class is a base class of the given
2154 /// class, including looking at dependent bases.
2155 static bool findCircularInheritance(const CXXRecordDecl *Class,
2156                                     const CXXRecordDecl *Current) {
2157   SmallVector<const CXXRecordDecl*, 8> Queue;
2158 
2159   Class = Class->getCanonicalDecl();
2160   while (true) {
2161     for (const auto &I : Current->bases()) {
2162       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2163       if (!Base)
2164         continue;
2165 
2166       Base = Base->getDefinition();
2167       if (!Base)
2168         continue;
2169 
2170       if (Base->getCanonicalDecl() == Class)
2171         return true;
2172 
2173       Queue.push_back(Base);
2174     }
2175 
2176     if (Queue.empty())
2177       return false;
2178 
2179     Current = Queue.pop_back_val();
2180   }
2181 
2182   return false;
2183 }
2184 
2185 /// Check the validity of a C++ base class specifier.
2186 ///
2187 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2188 /// and returns NULL otherwise.
2189 CXXBaseSpecifier *
2190 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2191                          SourceRange SpecifierRange,
2192                          bool Virtual, AccessSpecifier Access,
2193                          TypeSourceInfo *TInfo,
2194                          SourceLocation EllipsisLoc) {
2195   QualType BaseType = TInfo->getType();
2196 
2197   // C++ [class.union]p1:
2198   //   A union shall not have base classes.
2199   if (Class->isUnion()) {
2200     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2201       << SpecifierRange;
2202     return nullptr;
2203   }
2204 
2205   if (EllipsisLoc.isValid() &&
2206       !TInfo->getType()->containsUnexpandedParameterPack()) {
2207     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2208       << TInfo->getTypeLoc().getSourceRange();
2209     EllipsisLoc = SourceLocation();
2210   }
2211 
2212   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2213 
2214   if (BaseType->isDependentType()) {
2215     // Make sure that we don't have circular inheritance among our dependent
2216     // bases. For non-dependent bases, the check for completeness below handles
2217     // this.
2218     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2219       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2220           ((BaseDecl = BaseDecl->getDefinition()) &&
2221            findCircularInheritance(Class, BaseDecl))) {
2222         Diag(BaseLoc, diag::err_circular_inheritance)
2223           << BaseType << Context.getTypeDeclType(Class);
2224 
2225         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2226           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2227             << BaseType;
2228 
2229         return nullptr;
2230       }
2231     }
2232 
2233     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2234                                           Class->getTagKind() == TTK_Class,
2235                                           Access, TInfo, EllipsisLoc);
2236   }
2237 
2238   // Base specifiers must be record types.
2239   if (!BaseType->isRecordType()) {
2240     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2241     return nullptr;
2242   }
2243 
2244   // C++ [class.union]p1:
2245   //   A union shall not be used as a base class.
2246   if (BaseType->isUnionType()) {
2247     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2248     return nullptr;
2249   }
2250 
2251   // For the MS ABI, propagate DLL attributes to base class templates.
2252   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2253     if (Attr *ClassAttr = getDLLAttr(Class)) {
2254       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2255               BaseType->getAsCXXRecordDecl())) {
2256         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2257                                             BaseLoc);
2258       }
2259     }
2260   }
2261 
2262   // C++ [class.derived]p2:
2263   //   The class-name in a base-specifier shall not be an incompletely
2264   //   defined class.
2265   if (RequireCompleteType(BaseLoc, BaseType,
2266                           diag::err_incomplete_base_class, SpecifierRange)) {
2267     Class->setInvalidDecl();
2268     return nullptr;
2269   }
2270 
2271   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2272   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2273   assert(BaseDecl && "Record type has no declaration");
2274   BaseDecl = BaseDecl->getDefinition();
2275   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2276   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2277   assert(CXXBaseDecl && "Base type is not a C++ type");
2278 
2279   // Microsoft docs say:
2280   // "If a base-class has a code_seg attribute, derived classes must have the
2281   // same attribute."
2282   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2283   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2284   if ((DerivedCSA || BaseCSA) &&
2285       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2286     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2287     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2288       << CXXBaseDecl;
2289     return nullptr;
2290   }
2291 
2292   // A class which contains a flexible array member is not suitable for use as a
2293   // base class:
2294   //   - If the layout determines that a base comes before another base,
2295   //     the flexible array member would index into the subsequent base.
2296   //   - If the layout determines that base comes before the derived class,
2297   //     the flexible array member would index into the derived class.
2298   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2299     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2300       << CXXBaseDecl->getDeclName();
2301     return nullptr;
2302   }
2303 
2304   // C++ [class]p3:
2305   //   If a class is marked final and it appears as a base-type-specifier in
2306   //   base-clause, the program is ill-formed.
2307   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2308     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2309       << CXXBaseDecl->getDeclName()
2310       << FA->isSpelledAsSealed();
2311     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2312         << CXXBaseDecl->getDeclName() << FA->getRange();
2313     return nullptr;
2314   }
2315 
2316   if (BaseDecl->isInvalidDecl())
2317     Class->setInvalidDecl();
2318 
2319   // Create the base specifier.
2320   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2321                                         Class->getTagKind() == TTK_Class,
2322                                         Access, TInfo, EllipsisLoc);
2323 }
2324 
2325 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2326 /// one entry in the base class list of a class specifier, for
2327 /// example:
2328 ///    class foo : public bar, virtual private baz {
2329 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2330 BaseResult
2331 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2332                          ParsedAttributes &Attributes,
2333                          bool Virtual, AccessSpecifier Access,
2334                          ParsedType basetype, SourceLocation BaseLoc,
2335                          SourceLocation EllipsisLoc) {
2336   if (!classdecl)
2337     return true;
2338 
2339   AdjustDeclIfTemplate(classdecl);
2340   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2341   if (!Class)
2342     return true;
2343 
2344   // We haven't yet attached the base specifiers.
2345   Class->setIsParsingBaseSpecifiers();
2346 
2347   // We do not support any C++11 attributes on base-specifiers yet.
2348   // Diagnose any attributes we see.
2349   for (const ParsedAttr &AL : Attributes) {
2350     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2351       continue;
2352     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2353                           ? (unsigned)diag::warn_unknown_attribute_ignored
2354                           : (unsigned)diag::err_base_specifier_attribute)
2355         << AL.getName();
2356   }
2357 
2358   TypeSourceInfo *TInfo = nullptr;
2359   GetTypeFromParser(basetype, &TInfo);
2360 
2361   if (EllipsisLoc.isInvalid() &&
2362       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2363                                       UPPC_BaseType))
2364     return true;
2365 
2366   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2367                                                       Virtual, Access, TInfo,
2368                                                       EllipsisLoc))
2369     return BaseSpec;
2370   else
2371     Class->setInvalidDecl();
2372 
2373   return true;
2374 }
2375 
2376 /// Use small set to collect indirect bases.  As this is only used
2377 /// locally, there's no need to abstract the small size parameter.
2378 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2379 
2380 /// Recursively add the bases of Type.  Don't add Type itself.
2381 static void
2382 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2383                   const QualType &Type)
2384 {
2385   // Even though the incoming type is a base, it might not be
2386   // a class -- it could be a template parm, for instance.
2387   if (auto Rec = Type->getAs<RecordType>()) {
2388     auto Decl = Rec->getAsCXXRecordDecl();
2389 
2390     // Iterate over its bases.
2391     for (const auto &BaseSpec : Decl->bases()) {
2392       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2393         .getUnqualifiedType();
2394       if (Set.insert(Base).second)
2395         // If we've not already seen it, recurse.
2396         NoteIndirectBases(Context, Set, Base);
2397     }
2398   }
2399 }
2400 
2401 /// Performs the actual work of attaching the given base class
2402 /// specifiers to a C++ class.
2403 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2404                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2405  if (Bases.empty())
2406     return false;
2407 
2408   // Used to keep track of which base types we have already seen, so
2409   // that we can properly diagnose redundant direct base types. Note
2410   // that the key is always the unqualified canonical type of the base
2411   // class.
2412   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2413 
2414   // Used to track indirect bases so we can see if a direct base is
2415   // ambiguous.
2416   IndirectBaseSet IndirectBaseTypes;
2417 
2418   // Copy non-redundant base specifiers into permanent storage.
2419   unsigned NumGoodBases = 0;
2420   bool Invalid = false;
2421   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2422     QualType NewBaseType
2423       = Context.getCanonicalType(Bases[idx]->getType());
2424     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2425 
2426     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2427     if (KnownBase) {
2428       // C++ [class.mi]p3:
2429       //   A class shall not be specified as a direct base class of a
2430       //   derived class more than once.
2431       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2432           << KnownBase->getType() << Bases[idx]->getSourceRange();
2433 
2434       // Delete the duplicate base class specifier; we're going to
2435       // overwrite its pointer later.
2436       Context.Deallocate(Bases[idx]);
2437 
2438       Invalid = true;
2439     } else {
2440       // Okay, add this new base class.
2441       KnownBase = Bases[idx];
2442       Bases[NumGoodBases++] = Bases[idx];
2443 
2444       // Note this base's direct & indirect bases, if there could be ambiguity.
2445       if (Bases.size() > 1)
2446         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2447 
2448       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2449         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2450         if (Class->isInterface() &&
2451               (!RD->isInterfaceLike() ||
2452                KnownBase->getAccessSpecifier() != AS_public)) {
2453           // The Microsoft extension __interface does not permit bases that
2454           // are not themselves public interfaces.
2455           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2456               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2457               << RD->getSourceRange();
2458           Invalid = true;
2459         }
2460         if (RD->hasAttr<WeakAttr>())
2461           Class->addAttr(WeakAttr::CreateImplicit(Context));
2462       }
2463     }
2464   }
2465 
2466   // Attach the remaining base class specifiers to the derived class.
2467   Class->setBases(Bases.data(), NumGoodBases);
2468 
2469   // Check that the only base classes that are duplicate are virtual.
2470   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2471     // Check whether this direct base is inaccessible due to ambiguity.
2472     QualType BaseType = Bases[idx]->getType();
2473 
2474     // Skip all dependent types in templates being used as base specifiers.
2475     // Checks below assume that the base specifier is a CXXRecord.
2476     if (BaseType->isDependentType())
2477       continue;
2478 
2479     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2480       .getUnqualifiedType();
2481 
2482     if (IndirectBaseTypes.count(CanonicalBase)) {
2483       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2484                          /*DetectVirtual=*/true);
2485       bool found
2486         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2487       assert(found);
2488       (void)found;
2489 
2490       if (Paths.isAmbiguous(CanonicalBase))
2491         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2492             << BaseType << getAmbiguousPathsDisplayString(Paths)
2493             << Bases[idx]->getSourceRange();
2494       else
2495         assert(Bases[idx]->isVirtual());
2496     }
2497 
2498     // Delete the base class specifier, since its data has been copied
2499     // into the CXXRecordDecl.
2500     Context.Deallocate(Bases[idx]);
2501   }
2502 
2503   return Invalid;
2504 }
2505 
2506 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2507 /// class, after checking whether there are any duplicate base
2508 /// classes.
2509 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2510                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2511   if (!ClassDecl || Bases.empty())
2512     return;
2513 
2514   AdjustDeclIfTemplate(ClassDecl);
2515   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2516 }
2517 
2518 /// Determine whether the type \p Derived is a C++ class that is
2519 /// derived from the type \p Base.
2520 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2521   if (!getLangOpts().CPlusPlus)
2522     return false;
2523 
2524   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2525   if (!DerivedRD)
2526     return false;
2527 
2528   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2529   if (!BaseRD)
2530     return false;
2531 
2532   // If either the base or the derived type is invalid, don't try to
2533   // check whether one is derived from the other.
2534   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2535     return false;
2536 
2537   // FIXME: In a modules build, do we need the entire path to be visible for us
2538   // to be able to use the inheritance relationship?
2539   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2540     return false;
2541 
2542   return DerivedRD->isDerivedFrom(BaseRD);
2543 }
2544 
2545 /// Determine whether the type \p Derived is a C++ class that is
2546 /// derived from the type \p Base.
2547 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2548                          CXXBasePaths &Paths) {
2549   if (!getLangOpts().CPlusPlus)
2550     return false;
2551 
2552   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2553   if (!DerivedRD)
2554     return false;
2555 
2556   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2557   if (!BaseRD)
2558     return false;
2559 
2560   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2561     return false;
2562 
2563   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2564 }
2565 
2566 static void BuildBasePathArray(const CXXBasePath &Path,
2567                                CXXCastPath &BasePathArray) {
2568   // We first go backward and check if we have a virtual base.
2569   // FIXME: It would be better if CXXBasePath had the base specifier for
2570   // the nearest virtual base.
2571   unsigned Start = 0;
2572   for (unsigned I = Path.size(); I != 0; --I) {
2573     if (Path[I - 1].Base->isVirtual()) {
2574       Start = I - 1;
2575       break;
2576     }
2577   }
2578 
2579   // Now add all bases.
2580   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2581     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2582 }
2583 
2584 
2585 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2586                               CXXCastPath &BasePathArray) {
2587   assert(BasePathArray.empty() && "Base path array must be empty!");
2588   assert(Paths.isRecordingPaths() && "Must record paths!");
2589   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2590 }
2591 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2592 /// conversion (where Derived and Base are class types) is
2593 /// well-formed, meaning that the conversion is unambiguous (and
2594 /// that all of the base classes are accessible). Returns true
2595 /// and emits a diagnostic if the code is ill-formed, returns false
2596 /// otherwise. Loc is the location where this routine should point to
2597 /// if there is an error, and Range is the source range to highlight
2598 /// if there is an error.
2599 ///
2600 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2601 /// diagnostic for the respective type of error will be suppressed, but the
2602 /// check for ill-formed code will still be performed.
2603 bool
2604 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2605                                    unsigned InaccessibleBaseID,
2606                                    unsigned AmbigiousBaseConvID,
2607                                    SourceLocation Loc, SourceRange Range,
2608                                    DeclarationName Name,
2609                                    CXXCastPath *BasePath,
2610                                    bool IgnoreAccess) {
2611   // First, determine whether the path from Derived to Base is
2612   // ambiguous. This is slightly more expensive than checking whether
2613   // the Derived to Base conversion exists, because here we need to
2614   // explore multiple paths to determine if there is an ambiguity.
2615   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2616                      /*DetectVirtual=*/false);
2617   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2618   if (!DerivationOkay)
2619     return true;
2620 
2621   const CXXBasePath *Path = nullptr;
2622   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2623     Path = &Paths.front();
2624 
2625   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2626   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2627   // user to access such bases.
2628   if (!Path && getLangOpts().MSVCCompat) {
2629     for (const CXXBasePath &PossiblePath : Paths) {
2630       if (PossiblePath.size() == 1) {
2631         Path = &PossiblePath;
2632         if (AmbigiousBaseConvID)
2633           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2634               << Base << Derived << Range;
2635         break;
2636       }
2637     }
2638   }
2639 
2640   if (Path) {
2641     if (!IgnoreAccess) {
2642       // Check that the base class can be accessed.
2643       switch (
2644           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2645       case AR_inaccessible:
2646         return true;
2647       case AR_accessible:
2648       case AR_dependent:
2649       case AR_delayed:
2650         break;
2651       }
2652     }
2653 
2654     // Build a base path if necessary.
2655     if (BasePath)
2656       ::BuildBasePathArray(*Path, *BasePath);
2657     return false;
2658   }
2659 
2660   if (AmbigiousBaseConvID) {
2661     // We know that the derived-to-base conversion is ambiguous, and
2662     // we're going to produce a diagnostic. Perform the derived-to-base
2663     // search just one more time to compute all of the possible paths so
2664     // that we can print them out. This is more expensive than any of
2665     // the previous derived-to-base checks we've done, but at this point
2666     // performance isn't as much of an issue.
2667     Paths.clear();
2668     Paths.setRecordingPaths(true);
2669     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2670     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2671     (void)StillOkay;
2672 
2673     // Build up a textual representation of the ambiguous paths, e.g.,
2674     // D -> B -> A, that will be used to illustrate the ambiguous
2675     // conversions in the diagnostic. We only print one of the paths
2676     // to each base class subobject.
2677     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2678 
2679     Diag(Loc, AmbigiousBaseConvID)
2680     << Derived << Base << PathDisplayStr << Range << Name;
2681   }
2682   return true;
2683 }
2684 
2685 bool
2686 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2687                                    SourceLocation Loc, SourceRange Range,
2688                                    CXXCastPath *BasePath,
2689                                    bool IgnoreAccess) {
2690   return CheckDerivedToBaseConversion(
2691       Derived, Base, diag::err_upcast_to_inaccessible_base,
2692       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2693       BasePath, IgnoreAccess);
2694 }
2695 
2696 
2697 /// Builds a string representing ambiguous paths from a
2698 /// specific derived class to different subobjects of the same base
2699 /// class.
2700 ///
2701 /// This function builds a string that can be used in error messages
2702 /// to show the different paths that one can take through the
2703 /// inheritance hierarchy to go from the derived class to different
2704 /// subobjects of a base class. The result looks something like this:
2705 /// @code
2706 /// struct D -> struct B -> struct A
2707 /// struct D -> struct C -> struct A
2708 /// @endcode
2709 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2710   std::string PathDisplayStr;
2711   std::set<unsigned> DisplayedPaths;
2712   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2713        Path != Paths.end(); ++Path) {
2714     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2715       // We haven't displayed a path to this particular base
2716       // class subobject yet.
2717       PathDisplayStr += "\n    ";
2718       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2719       for (CXXBasePath::const_iterator Element = Path->begin();
2720            Element != Path->end(); ++Element)
2721         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2722     }
2723   }
2724 
2725   return PathDisplayStr;
2726 }
2727 
2728 //===----------------------------------------------------------------------===//
2729 // C++ class member Handling
2730 //===----------------------------------------------------------------------===//
2731 
2732 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2733 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2734                                 SourceLocation ColonLoc,
2735                                 const ParsedAttributesView &Attrs) {
2736   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2737   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2738                                                   ASLoc, ColonLoc);
2739   CurContext->addHiddenDecl(ASDecl);
2740   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2741 }
2742 
2743 /// CheckOverrideControl - Check C++11 override control semantics.
2744 void Sema::CheckOverrideControl(NamedDecl *D) {
2745   if (D->isInvalidDecl())
2746     return;
2747 
2748   // We only care about "override" and "final" declarations.
2749   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2750     return;
2751 
2752   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2753 
2754   // We can't check dependent instance methods.
2755   if (MD && MD->isInstance() &&
2756       (MD->getParent()->hasAnyDependentBases() ||
2757        MD->getType()->isDependentType()))
2758     return;
2759 
2760   if (MD && !MD->isVirtual()) {
2761     // If we have a non-virtual method, check if if hides a virtual method.
2762     // (In that case, it's most likely the method has the wrong type.)
2763     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2764     FindHiddenVirtualMethods(MD, OverloadedMethods);
2765 
2766     if (!OverloadedMethods.empty()) {
2767       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2768         Diag(OA->getLocation(),
2769              diag::override_keyword_hides_virtual_member_function)
2770           << "override" << (OverloadedMethods.size() > 1);
2771       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2772         Diag(FA->getLocation(),
2773              diag::override_keyword_hides_virtual_member_function)
2774           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2775           << (OverloadedMethods.size() > 1);
2776       }
2777       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2778       MD->setInvalidDecl();
2779       return;
2780     }
2781     // Fall through into the general case diagnostic.
2782     // FIXME: We might want to attempt typo correction here.
2783   }
2784 
2785   if (!MD || !MD->isVirtual()) {
2786     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2787       Diag(OA->getLocation(),
2788            diag::override_keyword_only_allowed_on_virtual_member_functions)
2789         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2790       D->dropAttr<OverrideAttr>();
2791     }
2792     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2793       Diag(FA->getLocation(),
2794            diag::override_keyword_only_allowed_on_virtual_member_functions)
2795         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2796         << FixItHint::CreateRemoval(FA->getLocation());
2797       D->dropAttr<FinalAttr>();
2798     }
2799     return;
2800   }
2801 
2802   // C++11 [class.virtual]p5:
2803   //   If a function is marked with the virt-specifier override and
2804   //   does not override a member function of a base class, the program is
2805   //   ill-formed.
2806   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2807   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2808     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2809       << MD->getDeclName();
2810 }
2811 
2812 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2813   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2814     return;
2815   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2816   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2817     return;
2818 
2819   SourceLocation Loc = MD->getLocation();
2820   SourceLocation SpellingLoc = Loc;
2821   if (getSourceManager().isMacroArgExpansion(Loc))
2822     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2823   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2824   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2825       return;
2826 
2827   if (MD->size_overridden_methods() > 0) {
2828     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2829                           ? diag::warn_destructor_marked_not_override_overriding
2830                           : diag::warn_function_marked_not_override_overriding;
2831     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2832     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2833     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2834   }
2835 }
2836 
2837 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2838 /// function overrides a virtual member function marked 'final', according to
2839 /// C++11 [class.virtual]p4.
2840 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2841                                                   const CXXMethodDecl *Old) {
2842   FinalAttr *FA = Old->getAttr<FinalAttr>();
2843   if (!FA)
2844     return false;
2845 
2846   Diag(New->getLocation(), diag::err_final_function_overridden)
2847     << New->getDeclName()
2848     << FA->isSpelledAsSealed();
2849   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2850   return true;
2851 }
2852 
2853 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2854   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2855   // FIXME: Destruction of ObjC lifetime types has side-effects.
2856   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2857     return !RD->isCompleteDefinition() ||
2858            !RD->hasTrivialDefaultConstructor() ||
2859            !RD->hasTrivialDestructor();
2860   return false;
2861 }
2862 
2863 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2864   ParsedAttributesView::const_iterator Itr =
2865       llvm::find_if(list, [](const ParsedAttr &AL) {
2866         return AL.isDeclspecPropertyAttribute();
2867       });
2868   if (Itr != list.end())
2869     return &*Itr;
2870   return nullptr;
2871 }
2872 
2873 // Check if there is a field shadowing.
2874 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2875                                       DeclarationName FieldName,
2876                                       const CXXRecordDecl *RD,
2877                                       bool DeclIsField) {
2878   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2879     return;
2880 
2881   // To record a shadowed field in a base
2882   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2883   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2884                            CXXBasePath &Path) {
2885     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2886     // Record an ambiguous path directly
2887     if (Bases.find(Base) != Bases.end())
2888       return true;
2889     for (const auto Field : Base->lookup(FieldName)) {
2890       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2891           Field->getAccess() != AS_private) {
2892         assert(Field->getAccess() != AS_none);
2893         assert(Bases.find(Base) == Bases.end());
2894         Bases[Base] = Field;
2895         return true;
2896       }
2897     }
2898     return false;
2899   };
2900 
2901   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2902                      /*DetectVirtual=*/true);
2903   if (!RD->lookupInBases(FieldShadowed, Paths))
2904     return;
2905 
2906   for (const auto &P : Paths) {
2907     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2908     auto It = Bases.find(Base);
2909     // Skip duplicated bases
2910     if (It == Bases.end())
2911       continue;
2912     auto BaseField = It->second;
2913     assert(BaseField->getAccess() != AS_private);
2914     if (AS_none !=
2915         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2916       Diag(Loc, diag::warn_shadow_field)
2917         << FieldName << RD << Base << DeclIsField;
2918       Diag(BaseField->getLocation(), diag::note_shadow_field);
2919       Bases.erase(It);
2920     }
2921   }
2922 }
2923 
2924 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2925 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2926 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2927 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2928 /// present (but parsing it has been deferred).
2929 NamedDecl *
2930 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2931                                MultiTemplateParamsArg TemplateParameterLists,
2932                                Expr *BW, const VirtSpecifiers &VS,
2933                                InClassInitStyle InitStyle) {
2934   const DeclSpec &DS = D.getDeclSpec();
2935   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2936   DeclarationName Name = NameInfo.getName();
2937   SourceLocation Loc = NameInfo.getLoc();
2938 
2939   // For anonymous bitfields, the location should point to the type.
2940   if (Loc.isInvalid())
2941     Loc = D.getBeginLoc();
2942 
2943   Expr *BitWidth = static_cast<Expr*>(BW);
2944 
2945   assert(isa<CXXRecordDecl>(CurContext));
2946   assert(!DS.isFriendSpecified());
2947 
2948   bool isFunc = D.isDeclarationOfFunction();
2949   const ParsedAttr *MSPropertyAttr =
2950       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2951 
2952   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2953     // The Microsoft extension __interface only permits public member functions
2954     // and prohibits constructors, destructors, operators, non-public member
2955     // functions, static methods and data members.
2956     unsigned InvalidDecl;
2957     bool ShowDeclName = true;
2958     if (!isFunc &&
2959         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2960       InvalidDecl = 0;
2961     else if (!isFunc)
2962       InvalidDecl = 1;
2963     else if (AS != AS_public)
2964       InvalidDecl = 2;
2965     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2966       InvalidDecl = 3;
2967     else switch (Name.getNameKind()) {
2968       case DeclarationName::CXXConstructorName:
2969         InvalidDecl = 4;
2970         ShowDeclName = false;
2971         break;
2972 
2973       case DeclarationName::CXXDestructorName:
2974         InvalidDecl = 5;
2975         ShowDeclName = false;
2976         break;
2977 
2978       case DeclarationName::CXXOperatorName:
2979       case DeclarationName::CXXConversionFunctionName:
2980         InvalidDecl = 6;
2981         break;
2982 
2983       default:
2984         InvalidDecl = 0;
2985         break;
2986     }
2987 
2988     if (InvalidDecl) {
2989       if (ShowDeclName)
2990         Diag(Loc, diag::err_invalid_member_in_interface)
2991           << (InvalidDecl-1) << Name;
2992       else
2993         Diag(Loc, diag::err_invalid_member_in_interface)
2994           << (InvalidDecl-1) << "";
2995       return nullptr;
2996     }
2997   }
2998 
2999   // C++ 9.2p6: A member shall not be declared to have automatic storage
3000   // duration (auto, register) or with the extern storage-class-specifier.
3001   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3002   // data members and cannot be applied to names declared const or static,
3003   // and cannot be applied to reference members.
3004   switch (DS.getStorageClassSpec()) {
3005   case DeclSpec::SCS_unspecified:
3006   case DeclSpec::SCS_typedef:
3007   case DeclSpec::SCS_static:
3008     break;
3009   case DeclSpec::SCS_mutable:
3010     if (isFunc) {
3011       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3012 
3013       // FIXME: It would be nicer if the keyword was ignored only for this
3014       // declarator. Otherwise we could get follow-up errors.
3015       D.getMutableDeclSpec().ClearStorageClassSpecs();
3016     }
3017     break;
3018   default:
3019     Diag(DS.getStorageClassSpecLoc(),
3020          diag::err_storageclass_invalid_for_member);
3021     D.getMutableDeclSpec().ClearStorageClassSpecs();
3022     break;
3023   }
3024 
3025   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3026                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3027                       !isFunc);
3028 
3029   if (DS.isConstexprSpecified() && isInstField) {
3030     SemaDiagnosticBuilder B =
3031         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3032     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3033     if (InitStyle == ICIS_NoInit) {
3034       B << 0 << 0;
3035       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3036         B << FixItHint::CreateRemoval(ConstexprLoc);
3037       else {
3038         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3039         D.getMutableDeclSpec().ClearConstexprSpec();
3040         const char *PrevSpec;
3041         unsigned DiagID;
3042         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3043             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3044         (void)Failed;
3045         assert(!Failed && "Making a constexpr member const shouldn't fail");
3046       }
3047     } else {
3048       B << 1;
3049       const char *PrevSpec;
3050       unsigned DiagID;
3051       if (D.getMutableDeclSpec().SetStorageClassSpec(
3052           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3053           Context.getPrintingPolicy())) {
3054         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3055                "This is the only DeclSpec that should fail to be applied");
3056         B << 1;
3057       } else {
3058         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3059         isInstField = false;
3060       }
3061     }
3062   }
3063 
3064   NamedDecl *Member;
3065   if (isInstField) {
3066     CXXScopeSpec &SS = D.getCXXScopeSpec();
3067 
3068     // Data members must have identifiers for names.
3069     if (!Name.isIdentifier()) {
3070       Diag(Loc, diag::err_bad_variable_name)
3071         << Name;
3072       return nullptr;
3073     }
3074 
3075     IdentifierInfo *II = Name.getAsIdentifierInfo();
3076 
3077     // Member field could not be with "template" keyword.
3078     // So TemplateParameterLists should be empty in this case.
3079     if (TemplateParameterLists.size()) {
3080       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3081       if (TemplateParams->size()) {
3082         // There is no such thing as a member field template.
3083         Diag(D.getIdentifierLoc(), diag::err_template_member)
3084             << II
3085             << SourceRange(TemplateParams->getTemplateLoc(),
3086                 TemplateParams->getRAngleLoc());
3087       } else {
3088         // There is an extraneous 'template<>' for this member.
3089         Diag(TemplateParams->getTemplateLoc(),
3090             diag::err_template_member_noparams)
3091             << II
3092             << SourceRange(TemplateParams->getTemplateLoc(),
3093                 TemplateParams->getRAngleLoc());
3094       }
3095       return nullptr;
3096     }
3097 
3098     if (SS.isSet() && !SS.isInvalid()) {
3099       // The user provided a superfluous scope specifier inside a class
3100       // definition:
3101       //
3102       // class X {
3103       //   int X::member;
3104       // };
3105       if (DeclContext *DC = computeDeclContext(SS, false))
3106         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3107                                      D.getName().getKind() ==
3108                                          UnqualifiedIdKind::IK_TemplateId);
3109       else
3110         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3111           << Name << SS.getRange();
3112 
3113       SS.clear();
3114     }
3115 
3116     if (MSPropertyAttr) {
3117       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3118                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3119       if (!Member)
3120         return nullptr;
3121       isInstField = false;
3122     } else {
3123       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3124                                 BitWidth, InitStyle, AS);
3125       if (!Member)
3126         return nullptr;
3127     }
3128 
3129     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3130   } else {
3131     Member = HandleDeclarator(S, D, TemplateParameterLists);
3132     if (!Member)
3133       return nullptr;
3134 
3135     // Non-instance-fields can't have a bitfield.
3136     if (BitWidth) {
3137       if (Member->isInvalidDecl()) {
3138         // don't emit another diagnostic.
3139       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3140         // C++ 9.6p3: A bit-field shall not be a static member.
3141         // "static member 'A' cannot be a bit-field"
3142         Diag(Loc, diag::err_static_not_bitfield)
3143           << Name << BitWidth->getSourceRange();
3144       } else if (isa<TypedefDecl>(Member)) {
3145         // "typedef member 'x' cannot be a bit-field"
3146         Diag(Loc, diag::err_typedef_not_bitfield)
3147           << Name << BitWidth->getSourceRange();
3148       } else {
3149         // A function typedef ("typedef int f(); f a;").
3150         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3151         Diag(Loc, diag::err_not_integral_type_bitfield)
3152           << Name << cast<ValueDecl>(Member)->getType()
3153           << BitWidth->getSourceRange();
3154       }
3155 
3156       BitWidth = nullptr;
3157       Member->setInvalidDecl();
3158     }
3159 
3160     NamedDecl *NonTemplateMember = Member;
3161     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3162       NonTemplateMember = FunTmpl->getTemplatedDecl();
3163     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3164       NonTemplateMember = VarTmpl->getTemplatedDecl();
3165 
3166     Member->setAccess(AS);
3167 
3168     // If we have declared a member function template or static data member
3169     // template, set the access of the templated declaration as well.
3170     if (NonTemplateMember != Member)
3171       NonTemplateMember->setAccess(AS);
3172 
3173     // C++ [temp.deduct.guide]p3:
3174     //   A deduction guide [...] for a member class template [shall be
3175     //   declared] with the same access [as the template].
3176     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3177       auto *TD = DG->getDeducedTemplate();
3178       if (AS != TD->getAccess()) {
3179         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3180         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3181             << TD->getAccess();
3182         const AccessSpecDecl *LastAccessSpec = nullptr;
3183         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3184           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3185             LastAccessSpec = AccessSpec;
3186         }
3187         assert(LastAccessSpec && "differing access with no access specifier");
3188         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3189             << AS;
3190       }
3191     }
3192   }
3193 
3194   if (VS.isOverrideSpecified())
3195     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3196   if (VS.isFinalSpecified())
3197     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3198                                             VS.isFinalSpelledSealed()));
3199 
3200   if (VS.getLastLocation().isValid()) {
3201     // Update the end location of a method that has a virt-specifiers.
3202     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3203       MD->setRangeEnd(VS.getLastLocation());
3204   }
3205 
3206   CheckOverrideControl(Member);
3207 
3208   assert((Name || isInstField) && "No identifier for non-field ?");
3209 
3210   if (isInstField) {
3211     FieldDecl *FD = cast<FieldDecl>(Member);
3212     FieldCollector->Add(FD);
3213 
3214     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3215       // Remember all explicit private FieldDecls that have a name, no side
3216       // effects and are not part of a dependent type declaration.
3217       if (!FD->isImplicit() && FD->getDeclName() &&
3218           FD->getAccess() == AS_private &&
3219           !FD->hasAttr<UnusedAttr>() &&
3220           !FD->getParent()->isDependentContext() &&
3221           !InitializationHasSideEffects(*FD))
3222         UnusedPrivateFields.insert(FD);
3223     }
3224   }
3225 
3226   return Member;
3227 }
3228 
3229 namespace {
3230   class UninitializedFieldVisitor
3231       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3232     Sema &S;
3233     // List of Decls to generate a warning on.  Also remove Decls that become
3234     // initialized.
3235     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3236     // List of base classes of the record.  Classes are removed after their
3237     // initializers.
3238     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3239     // Vector of decls to be removed from the Decl set prior to visiting the
3240     // nodes.  These Decls may have been initialized in the prior initializer.
3241     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3242     // If non-null, add a note to the warning pointing back to the constructor.
3243     const CXXConstructorDecl *Constructor;
3244     // Variables to hold state when processing an initializer list.  When
3245     // InitList is true, special case initialization of FieldDecls matching
3246     // InitListFieldDecl.
3247     bool InitList;
3248     FieldDecl *InitListFieldDecl;
3249     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3250 
3251   public:
3252     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3253     UninitializedFieldVisitor(Sema &S,
3254                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3255                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3256       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3257         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3258 
3259     // Returns true if the use of ME is not an uninitialized use.
3260     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3261                                          bool CheckReferenceOnly) {
3262       llvm::SmallVector<FieldDecl*, 4> Fields;
3263       bool ReferenceField = false;
3264       while (ME) {
3265         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3266         if (!FD)
3267           return false;
3268         Fields.push_back(FD);
3269         if (FD->getType()->isReferenceType())
3270           ReferenceField = true;
3271         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3272       }
3273 
3274       // Binding a reference to an uninitialized field is not an
3275       // uninitialized use.
3276       if (CheckReferenceOnly && !ReferenceField)
3277         return true;
3278 
3279       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3280       // Discard the first field since it is the field decl that is being
3281       // initialized.
3282       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3283         UsedFieldIndex.push_back((*I)->getFieldIndex());
3284       }
3285 
3286       for (auto UsedIter = UsedFieldIndex.begin(),
3287                 UsedEnd = UsedFieldIndex.end(),
3288                 OrigIter = InitFieldIndex.begin(),
3289                 OrigEnd = InitFieldIndex.end();
3290            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3291         if (*UsedIter < *OrigIter)
3292           return true;
3293         if (*UsedIter > *OrigIter)
3294           break;
3295       }
3296 
3297       return false;
3298     }
3299 
3300     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3301                           bool AddressOf) {
3302       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3303         return;
3304 
3305       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3306       // or union.
3307       MemberExpr *FieldME = ME;
3308 
3309       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3310 
3311       Expr *Base = ME;
3312       while (MemberExpr *SubME =
3313                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3314 
3315         if (isa<VarDecl>(SubME->getMemberDecl()))
3316           return;
3317 
3318         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3319           if (!FD->isAnonymousStructOrUnion())
3320             FieldME = SubME;
3321 
3322         if (!FieldME->getType().isPODType(S.Context))
3323           AllPODFields = false;
3324 
3325         Base = SubME->getBase();
3326       }
3327 
3328       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3329         return;
3330 
3331       if (AddressOf && AllPODFields)
3332         return;
3333 
3334       ValueDecl* FoundVD = FieldME->getMemberDecl();
3335 
3336       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3337         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3338           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3339         }
3340 
3341         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3342           QualType T = BaseCast->getType();
3343           if (T->isPointerType() &&
3344               BaseClasses.count(T->getPointeeType())) {
3345             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3346                 << T->getPointeeType() << FoundVD;
3347           }
3348         }
3349       }
3350 
3351       if (!Decls.count(FoundVD))
3352         return;
3353 
3354       const bool IsReference = FoundVD->getType()->isReferenceType();
3355 
3356       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3357         // Special checking for initializer lists.
3358         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3359           return;
3360         }
3361       } else {
3362         // Prevent double warnings on use of unbounded references.
3363         if (CheckReferenceOnly && !IsReference)
3364           return;
3365       }
3366 
3367       unsigned diag = IsReference
3368           ? diag::warn_reference_field_is_uninit
3369           : diag::warn_field_is_uninit;
3370       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3371       if (Constructor)
3372         S.Diag(Constructor->getLocation(),
3373                diag::note_uninit_in_this_constructor)
3374           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3375 
3376     }
3377 
3378     void HandleValue(Expr *E, bool AddressOf) {
3379       E = E->IgnoreParens();
3380 
3381       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3382         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3383                          AddressOf /*AddressOf*/);
3384         return;
3385       }
3386 
3387       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3388         Visit(CO->getCond());
3389         HandleValue(CO->getTrueExpr(), AddressOf);
3390         HandleValue(CO->getFalseExpr(), AddressOf);
3391         return;
3392       }
3393 
3394       if (BinaryConditionalOperator *BCO =
3395               dyn_cast<BinaryConditionalOperator>(E)) {
3396         Visit(BCO->getCond());
3397         HandleValue(BCO->getFalseExpr(), AddressOf);
3398         return;
3399       }
3400 
3401       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3402         HandleValue(OVE->getSourceExpr(), AddressOf);
3403         return;
3404       }
3405 
3406       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3407         switch (BO->getOpcode()) {
3408         default:
3409           break;
3410         case(BO_PtrMemD):
3411         case(BO_PtrMemI):
3412           HandleValue(BO->getLHS(), AddressOf);
3413           Visit(BO->getRHS());
3414           return;
3415         case(BO_Comma):
3416           Visit(BO->getLHS());
3417           HandleValue(BO->getRHS(), AddressOf);
3418           return;
3419         }
3420       }
3421 
3422       Visit(E);
3423     }
3424 
3425     void CheckInitListExpr(InitListExpr *ILE) {
3426       InitFieldIndex.push_back(0);
3427       for (auto Child : ILE->children()) {
3428         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3429           CheckInitListExpr(SubList);
3430         } else {
3431           Visit(Child);
3432         }
3433         ++InitFieldIndex.back();
3434       }
3435       InitFieldIndex.pop_back();
3436     }
3437 
3438     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3439                           FieldDecl *Field, const Type *BaseClass) {
3440       // Remove Decls that may have been initialized in the previous
3441       // initializer.
3442       for (ValueDecl* VD : DeclsToRemove)
3443         Decls.erase(VD);
3444       DeclsToRemove.clear();
3445 
3446       Constructor = FieldConstructor;
3447       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3448 
3449       if (ILE && Field) {
3450         InitList = true;
3451         InitListFieldDecl = Field;
3452         InitFieldIndex.clear();
3453         CheckInitListExpr(ILE);
3454       } else {
3455         InitList = false;
3456         Visit(E);
3457       }
3458 
3459       if (Field)
3460         Decls.erase(Field);
3461       if (BaseClass)
3462         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3463     }
3464 
3465     void VisitMemberExpr(MemberExpr *ME) {
3466       // All uses of unbounded reference fields will warn.
3467       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3468     }
3469 
3470     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3471       if (E->getCastKind() == CK_LValueToRValue) {
3472         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3473         return;
3474       }
3475 
3476       Inherited::VisitImplicitCastExpr(E);
3477     }
3478 
3479     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3480       if (E->getConstructor()->isCopyConstructor()) {
3481         Expr *ArgExpr = E->getArg(0);
3482         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3483           if (ILE->getNumInits() == 1)
3484             ArgExpr = ILE->getInit(0);
3485         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3486           if (ICE->getCastKind() == CK_NoOp)
3487             ArgExpr = ICE->getSubExpr();
3488         HandleValue(ArgExpr, false /*AddressOf*/);
3489         return;
3490       }
3491       Inherited::VisitCXXConstructExpr(E);
3492     }
3493 
3494     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3495       Expr *Callee = E->getCallee();
3496       if (isa<MemberExpr>(Callee)) {
3497         HandleValue(Callee, false /*AddressOf*/);
3498         for (auto Arg : E->arguments())
3499           Visit(Arg);
3500         return;
3501       }
3502 
3503       Inherited::VisitCXXMemberCallExpr(E);
3504     }
3505 
3506     void VisitCallExpr(CallExpr *E) {
3507       // Treat std::move as a use.
3508       if (E->isCallToStdMove()) {
3509         HandleValue(E->getArg(0), /*AddressOf=*/false);
3510         return;
3511       }
3512 
3513       Inherited::VisitCallExpr(E);
3514     }
3515 
3516     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3517       Expr *Callee = E->getCallee();
3518 
3519       if (isa<UnresolvedLookupExpr>(Callee))
3520         return Inherited::VisitCXXOperatorCallExpr(E);
3521 
3522       Visit(Callee);
3523       for (auto Arg : E->arguments())
3524         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3525     }
3526 
3527     void VisitBinaryOperator(BinaryOperator *E) {
3528       // If a field assignment is detected, remove the field from the
3529       // uninitiailized field set.
3530       if (E->getOpcode() == BO_Assign)
3531         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3532           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3533             if (!FD->getType()->isReferenceType())
3534               DeclsToRemove.push_back(FD);
3535 
3536       if (E->isCompoundAssignmentOp()) {
3537         HandleValue(E->getLHS(), false /*AddressOf*/);
3538         Visit(E->getRHS());
3539         return;
3540       }
3541 
3542       Inherited::VisitBinaryOperator(E);
3543     }
3544 
3545     void VisitUnaryOperator(UnaryOperator *E) {
3546       if (E->isIncrementDecrementOp()) {
3547         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3548         return;
3549       }
3550       if (E->getOpcode() == UO_AddrOf) {
3551         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3552           HandleValue(ME->getBase(), true /*AddressOf*/);
3553           return;
3554         }
3555       }
3556 
3557       Inherited::VisitUnaryOperator(E);
3558     }
3559   };
3560 
3561   // Diagnose value-uses of fields to initialize themselves, e.g.
3562   //   foo(foo)
3563   // where foo is not also a parameter to the constructor.
3564   // Also diagnose across field uninitialized use such as
3565   //   x(y), y(x)
3566   // TODO: implement -Wuninitialized and fold this into that framework.
3567   static void DiagnoseUninitializedFields(
3568       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3569 
3570     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3571                                            Constructor->getLocation())) {
3572       return;
3573     }
3574 
3575     if (Constructor->isInvalidDecl())
3576       return;
3577 
3578     const CXXRecordDecl *RD = Constructor->getParent();
3579 
3580     if (RD->getDescribedClassTemplate())
3581       return;
3582 
3583     // Holds fields that are uninitialized.
3584     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3585 
3586     // At the beginning, all fields are uninitialized.
3587     for (auto *I : RD->decls()) {
3588       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3589         UninitializedFields.insert(FD);
3590       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3591         UninitializedFields.insert(IFD->getAnonField());
3592       }
3593     }
3594 
3595     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3596     for (auto I : RD->bases())
3597       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3598 
3599     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3600       return;
3601 
3602     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3603                                                    UninitializedFields,
3604                                                    UninitializedBaseClasses);
3605 
3606     for (const auto *FieldInit : Constructor->inits()) {
3607       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3608         break;
3609 
3610       Expr *InitExpr = FieldInit->getInit();
3611       if (!InitExpr)
3612         continue;
3613 
3614       if (CXXDefaultInitExpr *Default =
3615               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3616         InitExpr = Default->getExpr();
3617         if (!InitExpr)
3618           continue;
3619         // In class initializers will point to the constructor.
3620         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3621                                               FieldInit->getAnyMember(),
3622                                               FieldInit->getBaseClass());
3623       } else {
3624         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3625                                               FieldInit->getAnyMember(),
3626                                               FieldInit->getBaseClass());
3627       }
3628     }
3629   }
3630 } // namespace
3631 
3632 /// Enter a new C++ default initializer scope. After calling this, the
3633 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3634 /// parsing or instantiating the initializer failed.
3635 void Sema::ActOnStartCXXInClassMemberInitializer() {
3636   // Create a synthetic function scope to represent the call to the constructor
3637   // that notionally surrounds a use of this initializer.
3638   PushFunctionScope();
3639 }
3640 
3641 /// This is invoked after parsing an in-class initializer for a
3642 /// non-static C++ class member, and after instantiating an in-class initializer
3643 /// in a class template. Such actions are deferred until the class is complete.
3644 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3645                                                   SourceLocation InitLoc,
3646                                                   Expr *InitExpr) {
3647   // Pop the notional constructor scope we created earlier.
3648   PopFunctionScopeInfo(nullptr, D);
3649 
3650   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3651   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3652          "must set init style when field is created");
3653 
3654   if (!InitExpr) {
3655     D->setInvalidDecl();
3656     if (FD)
3657       FD->removeInClassInitializer();
3658     return;
3659   }
3660 
3661   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3662     FD->setInvalidDecl();
3663     FD->removeInClassInitializer();
3664     return;
3665   }
3666 
3667   ExprResult Init = InitExpr;
3668   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3669     InitializedEntity Entity =
3670         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3671     InitializationKind Kind =
3672         FD->getInClassInitStyle() == ICIS_ListInit
3673             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3674                                                    InitExpr->getBeginLoc(),
3675                                                    InitExpr->getEndLoc())
3676             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3677     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3678     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3679     if (Init.isInvalid()) {
3680       FD->setInvalidDecl();
3681       return;
3682     }
3683   }
3684 
3685   // C++11 [class.base.init]p7:
3686   //   The initialization of each base and member constitutes a
3687   //   full-expression.
3688   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3689   if (Init.isInvalid()) {
3690     FD->setInvalidDecl();
3691     return;
3692   }
3693 
3694   InitExpr = Init.get();
3695 
3696   FD->setInClassInitializer(InitExpr);
3697 }
3698 
3699 /// Find the direct and/or virtual base specifiers that
3700 /// correspond to the given base type, for use in base initialization
3701 /// within a constructor.
3702 static bool FindBaseInitializer(Sema &SemaRef,
3703                                 CXXRecordDecl *ClassDecl,
3704                                 QualType BaseType,
3705                                 const CXXBaseSpecifier *&DirectBaseSpec,
3706                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3707   // First, check for a direct base class.
3708   DirectBaseSpec = nullptr;
3709   for (const auto &Base : ClassDecl->bases()) {
3710     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3711       // We found a direct base of this type. That's what we're
3712       // initializing.
3713       DirectBaseSpec = &Base;
3714       break;
3715     }
3716   }
3717 
3718   // Check for a virtual base class.
3719   // FIXME: We might be able to short-circuit this if we know in advance that
3720   // there are no virtual bases.
3721   VirtualBaseSpec = nullptr;
3722   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3723     // We haven't found a base yet; search the class hierarchy for a
3724     // virtual base class.
3725     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3726                        /*DetectVirtual=*/false);
3727     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3728                               SemaRef.Context.getTypeDeclType(ClassDecl),
3729                               BaseType, Paths)) {
3730       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3731            Path != Paths.end(); ++Path) {
3732         if (Path->back().Base->isVirtual()) {
3733           VirtualBaseSpec = Path->back().Base;
3734           break;
3735         }
3736       }
3737     }
3738   }
3739 
3740   return DirectBaseSpec || VirtualBaseSpec;
3741 }
3742 
3743 /// Handle a C++ member initializer using braced-init-list syntax.
3744 MemInitResult
3745 Sema::ActOnMemInitializer(Decl *ConstructorD,
3746                           Scope *S,
3747                           CXXScopeSpec &SS,
3748                           IdentifierInfo *MemberOrBase,
3749                           ParsedType TemplateTypeTy,
3750                           const DeclSpec &DS,
3751                           SourceLocation IdLoc,
3752                           Expr *InitList,
3753                           SourceLocation EllipsisLoc) {
3754   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3755                              DS, IdLoc, InitList,
3756                              EllipsisLoc);
3757 }
3758 
3759 /// Handle a C++ member initializer using parentheses syntax.
3760 MemInitResult
3761 Sema::ActOnMemInitializer(Decl *ConstructorD,
3762                           Scope *S,
3763                           CXXScopeSpec &SS,
3764                           IdentifierInfo *MemberOrBase,
3765                           ParsedType TemplateTypeTy,
3766                           const DeclSpec &DS,
3767                           SourceLocation IdLoc,
3768                           SourceLocation LParenLoc,
3769                           ArrayRef<Expr *> Args,
3770                           SourceLocation RParenLoc,
3771                           SourceLocation EllipsisLoc) {
3772   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3773   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3774                              DS, IdLoc, List, EllipsisLoc);
3775 }
3776 
3777 namespace {
3778 
3779 // Callback to only accept typo corrections that can be a valid C++ member
3780 // intializer: either a non-static field member or a base class.
3781 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3782 public:
3783   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3784       : ClassDecl(ClassDecl) {}
3785 
3786   bool ValidateCandidate(const TypoCorrection &candidate) override {
3787     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3788       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3789         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3790       return isa<TypeDecl>(ND);
3791     }
3792     return false;
3793   }
3794 
3795 private:
3796   CXXRecordDecl *ClassDecl;
3797 };
3798 
3799 }
3800 
3801 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3802                                              CXXScopeSpec &SS,
3803                                              ParsedType TemplateTypeTy,
3804                                              IdentifierInfo *MemberOrBase) {
3805   if (SS.getScopeRep() || TemplateTypeTy)
3806     return nullptr;
3807   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3808   if (Result.empty())
3809     return nullptr;
3810   ValueDecl *Member;
3811   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3812       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3813     return Member;
3814   return nullptr;
3815 }
3816 
3817 /// Handle a C++ member initializer.
3818 MemInitResult
3819 Sema::BuildMemInitializer(Decl *ConstructorD,
3820                           Scope *S,
3821                           CXXScopeSpec &SS,
3822                           IdentifierInfo *MemberOrBase,
3823                           ParsedType TemplateTypeTy,
3824                           const DeclSpec &DS,
3825                           SourceLocation IdLoc,
3826                           Expr *Init,
3827                           SourceLocation EllipsisLoc) {
3828   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3829   if (!Res.isUsable())
3830     return true;
3831   Init = Res.get();
3832 
3833   if (!ConstructorD)
3834     return true;
3835 
3836   AdjustDeclIfTemplate(ConstructorD);
3837 
3838   CXXConstructorDecl *Constructor
3839     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3840   if (!Constructor) {
3841     // The user wrote a constructor initializer on a function that is
3842     // not a C++ constructor. Ignore the error for now, because we may
3843     // have more member initializers coming; we'll diagnose it just
3844     // once in ActOnMemInitializers.
3845     return true;
3846   }
3847 
3848   CXXRecordDecl *ClassDecl = Constructor->getParent();
3849 
3850   // C++ [class.base.init]p2:
3851   //   Names in a mem-initializer-id are looked up in the scope of the
3852   //   constructor's class and, if not found in that scope, are looked
3853   //   up in the scope containing the constructor's definition.
3854   //   [Note: if the constructor's class contains a member with the
3855   //   same name as a direct or virtual base class of the class, a
3856   //   mem-initializer-id naming the member or base class and composed
3857   //   of a single identifier refers to the class member. A
3858   //   mem-initializer-id for the hidden base class may be specified
3859   //   using a qualified name. ]
3860 
3861   // Look for a member, first.
3862   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3863           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3864     if (EllipsisLoc.isValid())
3865       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3866           << MemberOrBase
3867           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3868 
3869     return BuildMemberInitializer(Member, Init, IdLoc);
3870   }
3871   // It didn't name a member, so see if it names a class.
3872   QualType BaseType;
3873   TypeSourceInfo *TInfo = nullptr;
3874 
3875   if (TemplateTypeTy) {
3876     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3877   } else if (DS.getTypeSpecType() == TST_decltype) {
3878     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3879   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3880     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3881     return true;
3882   } else {
3883     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3884     LookupParsedName(R, S, &SS);
3885 
3886     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3887     if (!TyD) {
3888       if (R.isAmbiguous()) return true;
3889 
3890       // We don't want access-control diagnostics here.
3891       R.suppressDiagnostics();
3892 
3893       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3894         bool NotUnknownSpecialization = false;
3895         DeclContext *DC = computeDeclContext(SS, false);
3896         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3897           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3898 
3899         if (!NotUnknownSpecialization) {
3900           // When the scope specifier can refer to a member of an unknown
3901           // specialization, we take it as a type name.
3902           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3903                                        SS.getWithLocInContext(Context),
3904                                        *MemberOrBase, IdLoc);
3905           if (BaseType.isNull())
3906             return true;
3907 
3908           TInfo = Context.CreateTypeSourceInfo(BaseType);
3909           DependentNameTypeLoc TL =
3910               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3911           if (!TL.isNull()) {
3912             TL.setNameLoc(IdLoc);
3913             TL.setElaboratedKeywordLoc(SourceLocation());
3914             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3915           }
3916 
3917           R.clear();
3918           R.setLookupName(MemberOrBase);
3919         }
3920       }
3921 
3922       // If no results were found, try to correct typos.
3923       TypoCorrection Corr;
3924       if (R.empty() && BaseType.isNull() &&
3925           (Corr = CorrectTypo(
3926                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3927                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3928                CTK_ErrorRecovery, ClassDecl))) {
3929         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3930           // We have found a non-static data member with a similar
3931           // name to what was typed; complain and initialize that
3932           // member.
3933           diagnoseTypo(Corr,
3934                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3935                          << MemberOrBase << true);
3936           return BuildMemberInitializer(Member, Init, IdLoc);
3937         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3938           const CXXBaseSpecifier *DirectBaseSpec;
3939           const CXXBaseSpecifier *VirtualBaseSpec;
3940           if (FindBaseInitializer(*this, ClassDecl,
3941                                   Context.getTypeDeclType(Type),
3942                                   DirectBaseSpec, VirtualBaseSpec)) {
3943             // We have found a direct or virtual base class with a
3944             // similar name to what was typed; complain and initialize
3945             // that base class.
3946             diagnoseTypo(Corr,
3947                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3948                            << MemberOrBase << false,
3949                          PDiag() /*Suppress note, we provide our own.*/);
3950 
3951             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3952                                                               : VirtualBaseSpec;
3953             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3954                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3955 
3956             TyD = Type;
3957           }
3958         }
3959       }
3960 
3961       if (!TyD && BaseType.isNull()) {
3962         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3963           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3964         return true;
3965       }
3966     }
3967 
3968     if (BaseType.isNull()) {
3969       BaseType = Context.getTypeDeclType(TyD);
3970       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3971       if (SS.isSet()) {
3972         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3973                                              BaseType);
3974         TInfo = Context.CreateTypeSourceInfo(BaseType);
3975         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3976         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3977         TL.setElaboratedKeywordLoc(SourceLocation());
3978         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3979       }
3980     }
3981   }
3982 
3983   if (!TInfo)
3984     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3985 
3986   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3987 }
3988 
3989 MemInitResult
3990 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3991                              SourceLocation IdLoc) {
3992   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3993   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3994   assert((DirectMember || IndirectMember) &&
3995          "Member must be a FieldDecl or IndirectFieldDecl");
3996 
3997   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3998     return true;
3999 
4000   if (Member->isInvalidDecl())
4001     return true;
4002 
4003   MultiExprArg Args;
4004   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4005     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4006   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4007     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4008   } else {
4009     // Template instantiation doesn't reconstruct ParenListExprs for us.
4010     Args = Init;
4011   }
4012 
4013   SourceRange InitRange = Init->getSourceRange();
4014 
4015   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4016     // Can't check initialization for a member of dependent type or when
4017     // any of the arguments are type-dependent expressions.
4018     DiscardCleanupsInEvaluationContext();
4019   } else {
4020     bool InitList = false;
4021     if (isa<InitListExpr>(Init)) {
4022       InitList = true;
4023       Args = Init;
4024     }
4025 
4026     // Initialize the member.
4027     InitializedEntity MemberEntity =
4028       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4029                    : InitializedEntity::InitializeMember(IndirectMember,
4030                                                          nullptr);
4031     InitializationKind Kind =
4032         InitList ? InitializationKind::CreateDirectList(
4033                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4034                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4035                                                     InitRange.getEnd());
4036 
4037     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4038     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4039                                             nullptr);
4040     if (MemberInit.isInvalid())
4041       return true;
4042 
4043     // C++11 [class.base.init]p7:
4044     //   The initialization of each base and member constitutes a
4045     //   full-expression.
4046     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4047                                      /*DiscardedValue*/ false);
4048     if (MemberInit.isInvalid())
4049       return true;
4050 
4051     Init = MemberInit.get();
4052   }
4053 
4054   if (DirectMember) {
4055     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4056                                             InitRange.getBegin(), Init,
4057                                             InitRange.getEnd());
4058   } else {
4059     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4060                                             InitRange.getBegin(), Init,
4061                                             InitRange.getEnd());
4062   }
4063 }
4064 
4065 MemInitResult
4066 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4067                                  CXXRecordDecl *ClassDecl) {
4068   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4069   if (!LangOpts.CPlusPlus11)
4070     return Diag(NameLoc, diag::err_delegating_ctor)
4071       << TInfo->getTypeLoc().getLocalSourceRange();
4072   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4073 
4074   bool InitList = true;
4075   MultiExprArg Args = Init;
4076   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4077     InitList = false;
4078     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4079   }
4080 
4081   SourceRange InitRange = Init->getSourceRange();
4082   // Initialize the object.
4083   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4084                                      QualType(ClassDecl->getTypeForDecl(), 0));
4085   InitializationKind Kind =
4086       InitList ? InitializationKind::CreateDirectList(
4087                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4088                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4089                                                   InitRange.getEnd());
4090   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4091   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4092                                               Args, nullptr);
4093   if (DelegationInit.isInvalid())
4094     return true;
4095 
4096   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4097          "Delegating constructor with no target?");
4098 
4099   // C++11 [class.base.init]p7:
4100   //   The initialization of each base and member constitutes a
4101   //   full-expression.
4102   DelegationInit = ActOnFinishFullExpr(
4103       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4104   if (DelegationInit.isInvalid())
4105     return true;
4106 
4107   // If we are in a dependent context, template instantiation will
4108   // perform this type-checking again. Just save the arguments that we
4109   // received in a ParenListExpr.
4110   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4111   // of the information that we have about the base
4112   // initializer. However, deconstructing the ASTs is a dicey process,
4113   // and this approach is far more likely to get the corner cases right.
4114   if (CurContext->isDependentContext())
4115     DelegationInit = Init;
4116 
4117   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4118                                           DelegationInit.getAs<Expr>(),
4119                                           InitRange.getEnd());
4120 }
4121 
4122 MemInitResult
4123 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4124                            Expr *Init, CXXRecordDecl *ClassDecl,
4125                            SourceLocation EllipsisLoc) {
4126   SourceLocation BaseLoc
4127     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4128 
4129   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4130     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4131              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4132 
4133   // C++ [class.base.init]p2:
4134   //   [...] Unless the mem-initializer-id names a nonstatic data
4135   //   member of the constructor's class or a direct or virtual base
4136   //   of that class, the mem-initializer is ill-formed. A
4137   //   mem-initializer-list can initialize a base class using any
4138   //   name that denotes that base class type.
4139   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4140 
4141   SourceRange InitRange = Init->getSourceRange();
4142   if (EllipsisLoc.isValid()) {
4143     // This is a pack expansion.
4144     if (!BaseType->containsUnexpandedParameterPack())  {
4145       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4146         << SourceRange(BaseLoc, InitRange.getEnd());
4147 
4148       EllipsisLoc = SourceLocation();
4149     }
4150   } else {
4151     // Check for any unexpanded parameter packs.
4152     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4153       return true;
4154 
4155     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4156       return true;
4157   }
4158 
4159   // Check for direct and virtual base classes.
4160   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4161   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4162   if (!Dependent) {
4163     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4164                                        BaseType))
4165       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4166 
4167     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4168                         VirtualBaseSpec);
4169 
4170     // C++ [base.class.init]p2:
4171     // Unless the mem-initializer-id names a nonstatic data member of the
4172     // constructor's class or a direct or virtual base of that class, the
4173     // mem-initializer is ill-formed.
4174     if (!DirectBaseSpec && !VirtualBaseSpec) {
4175       // If the class has any dependent bases, then it's possible that
4176       // one of those types will resolve to the same type as
4177       // BaseType. Therefore, just treat this as a dependent base
4178       // class initialization.  FIXME: Should we try to check the
4179       // initialization anyway? It seems odd.
4180       if (ClassDecl->hasAnyDependentBases())
4181         Dependent = true;
4182       else
4183         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4184           << BaseType << Context.getTypeDeclType(ClassDecl)
4185           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4186     }
4187   }
4188 
4189   if (Dependent) {
4190     DiscardCleanupsInEvaluationContext();
4191 
4192     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4193                                             /*IsVirtual=*/false,
4194                                             InitRange.getBegin(), Init,
4195                                             InitRange.getEnd(), EllipsisLoc);
4196   }
4197 
4198   // C++ [base.class.init]p2:
4199   //   If a mem-initializer-id is ambiguous because it designates both
4200   //   a direct non-virtual base class and an inherited virtual base
4201   //   class, the mem-initializer is ill-formed.
4202   if (DirectBaseSpec && VirtualBaseSpec)
4203     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4204       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4205 
4206   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4207   if (!BaseSpec)
4208     BaseSpec = VirtualBaseSpec;
4209 
4210   // Initialize the base.
4211   bool InitList = true;
4212   MultiExprArg Args = Init;
4213   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4214     InitList = false;
4215     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4216   }
4217 
4218   InitializedEntity BaseEntity =
4219     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4220   InitializationKind Kind =
4221       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4222                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4223                                                   InitRange.getEnd());
4224   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4225   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4226   if (BaseInit.isInvalid())
4227     return true;
4228 
4229   // C++11 [class.base.init]p7:
4230   //   The initialization of each base and member constitutes a
4231   //   full-expression.
4232   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4233                                  /*DiscardedValue*/ false);
4234   if (BaseInit.isInvalid())
4235     return true;
4236 
4237   // If we are in a dependent context, template instantiation will
4238   // perform this type-checking again. Just save the arguments that we
4239   // received in a ParenListExpr.
4240   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4241   // of the information that we have about the base
4242   // initializer. However, deconstructing the ASTs is a dicey process,
4243   // and this approach is far more likely to get the corner cases right.
4244   if (CurContext->isDependentContext())
4245     BaseInit = Init;
4246 
4247   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4248                                           BaseSpec->isVirtual(),
4249                                           InitRange.getBegin(),
4250                                           BaseInit.getAs<Expr>(),
4251                                           InitRange.getEnd(), EllipsisLoc);
4252 }
4253 
4254 // Create a static_cast\<T&&>(expr).
4255 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4256   if (T.isNull()) T = E->getType();
4257   QualType TargetType = SemaRef.BuildReferenceType(
4258       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4259   SourceLocation ExprLoc = E->getBeginLoc();
4260   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4261       TargetType, ExprLoc);
4262 
4263   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4264                                    SourceRange(ExprLoc, ExprLoc),
4265                                    E->getSourceRange()).get();
4266 }
4267 
4268 /// ImplicitInitializerKind - How an implicit base or member initializer should
4269 /// initialize its base or member.
4270 enum ImplicitInitializerKind {
4271   IIK_Default,
4272   IIK_Copy,
4273   IIK_Move,
4274   IIK_Inherit
4275 };
4276 
4277 static bool
4278 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4279                              ImplicitInitializerKind ImplicitInitKind,
4280                              CXXBaseSpecifier *BaseSpec,
4281                              bool IsInheritedVirtualBase,
4282                              CXXCtorInitializer *&CXXBaseInit) {
4283   InitializedEntity InitEntity
4284     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4285                                         IsInheritedVirtualBase);
4286 
4287   ExprResult BaseInit;
4288 
4289   switch (ImplicitInitKind) {
4290   case IIK_Inherit:
4291   case IIK_Default: {
4292     InitializationKind InitKind
4293       = InitializationKind::CreateDefault(Constructor->getLocation());
4294     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4295     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4296     break;
4297   }
4298 
4299   case IIK_Move:
4300   case IIK_Copy: {
4301     bool Moving = ImplicitInitKind == IIK_Move;
4302     ParmVarDecl *Param = Constructor->getParamDecl(0);
4303     QualType ParamType = Param->getType().getNonReferenceType();
4304 
4305     Expr *CopyCtorArg =
4306       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4307                           SourceLocation(), Param, false,
4308                           Constructor->getLocation(), ParamType,
4309                           VK_LValue, nullptr);
4310 
4311     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4312 
4313     // Cast to the base class to avoid ambiguities.
4314     QualType ArgTy =
4315       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4316                                        ParamType.getQualifiers());
4317 
4318     if (Moving) {
4319       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4320     }
4321 
4322     CXXCastPath BasePath;
4323     BasePath.push_back(BaseSpec);
4324     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4325                                             CK_UncheckedDerivedToBase,
4326                                             Moving ? VK_XValue : VK_LValue,
4327                                             &BasePath).get();
4328 
4329     InitializationKind InitKind
4330       = InitializationKind::CreateDirect(Constructor->getLocation(),
4331                                          SourceLocation(), SourceLocation());
4332     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4333     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4334     break;
4335   }
4336   }
4337 
4338   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4339   if (BaseInit.isInvalid())
4340     return true;
4341 
4342   CXXBaseInit =
4343     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4344                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4345                                                         SourceLocation()),
4346                                              BaseSpec->isVirtual(),
4347                                              SourceLocation(),
4348                                              BaseInit.getAs<Expr>(),
4349                                              SourceLocation(),
4350                                              SourceLocation());
4351 
4352   return false;
4353 }
4354 
4355 static bool RefersToRValueRef(Expr *MemRef) {
4356   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4357   return Referenced->getType()->isRValueReferenceType();
4358 }
4359 
4360 static bool
4361 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4362                                ImplicitInitializerKind ImplicitInitKind,
4363                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4364                                CXXCtorInitializer *&CXXMemberInit) {
4365   if (Field->isInvalidDecl())
4366     return true;
4367 
4368   SourceLocation Loc = Constructor->getLocation();
4369 
4370   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4371     bool Moving = ImplicitInitKind == IIK_Move;
4372     ParmVarDecl *Param = Constructor->getParamDecl(0);
4373     QualType ParamType = Param->getType().getNonReferenceType();
4374 
4375     // Suppress copying zero-width bitfields.
4376     if (Field->isZeroLengthBitField(SemaRef.Context))
4377       return false;
4378 
4379     Expr *MemberExprBase =
4380       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4381                           SourceLocation(), Param, false,
4382                           Loc, ParamType, VK_LValue, nullptr);
4383 
4384     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4385 
4386     if (Moving) {
4387       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4388     }
4389 
4390     // Build a reference to this field within the parameter.
4391     CXXScopeSpec SS;
4392     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4393                               Sema::LookupMemberName);
4394     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4395                                   : cast<ValueDecl>(Field), AS_public);
4396     MemberLookup.resolveKind();
4397     ExprResult CtorArg
4398       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4399                                          ParamType, Loc,
4400                                          /*IsArrow=*/false,
4401                                          SS,
4402                                          /*TemplateKWLoc=*/SourceLocation(),
4403                                          /*FirstQualifierInScope=*/nullptr,
4404                                          MemberLookup,
4405                                          /*TemplateArgs=*/nullptr,
4406                                          /*S*/nullptr);
4407     if (CtorArg.isInvalid())
4408       return true;
4409 
4410     // C++11 [class.copy]p15:
4411     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4412     //     with static_cast<T&&>(x.m);
4413     if (RefersToRValueRef(CtorArg.get())) {
4414       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4415     }
4416 
4417     InitializedEntity Entity =
4418         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4419                                                        /*Implicit*/ true)
4420                  : InitializedEntity::InitializeMember(Field, nullptr,
4421                                                        /*Implicit*/ true);
4422 
4423     // Direct-initialize to use the copy constructor.
4424     InitializationKind InitKind =
4425       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4426 
4427     Expr *CtorArgE = CtorArg.getAs<Expr>();
4428     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4429     ExprResult MemberInit =
4430         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4431     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4432     if (MemberInit.isInvalid())
4433       return true;
4434 
4435     if (Indirect)
4436       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4437           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4438     else
4439       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4440           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4441     return false;
4442   }
4443 
4444   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4445          "Unhandled implicit init kind!");
4446 
4447   QualType FieldBaseElementType =
4448     SemaRef.Context.getBaseElementType(Field->getType());
4449 
4450   if (FieldBaseElementType->isRecordType()) {
4451     InitializedEntity InitEntity =
4452         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4453                                                        /*Implicit*/ true)
4454                  : InitializedEntity::InitializeMember(Field, nullptr,
4455                                                        /*Implicit*/ true);
4456     InitializationKind InitKind =
4457       InitializationKind::CreateDefault(Loc);
4458 
4459     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4460     ExprResult MemberInit =
4461       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4462 
4463     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4464     if (MemberInit.isInvalid())
4465       return true;
4466 
4467     if (Indirect)
4468       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4469                                                                Indirect, Loc,
4470                                                                Loc,
4471                                                                MemberInit.get(),
4472                                                                Loc);
4473     else
4474       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4475                                                                Field, Loc, Loc,
4476                                                                MemberInit.get(),
4477                                                                Loc);
4478     return false;
4479   }
4480 
4481   if (!Field->getParent()->isUnion()) {
4482     if (FieldBaseElementType->isReferenceType()) {
4483       SemaRef.Diag(Constructor->getLocation(),
4484                    diag::err_uninitialized_member_in_ctor)
4485       << (int)Constructor->isImplicit()
4486       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4487       << 0 << Field->getDeclName();
4488       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4489       return true;
4490     }
4491 
4492     if (FieldBaseElementType.isConstQualified()) {
4493       SemaRef.Diag(Constructor->getLocation(),
4494                    diag::err_uninitialized_member_in_ctor)
4495       << (int)Constructor->isImplicit()
4496       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4497       << 1 << Field->getDeclName();
4498       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4499       return true;
4500     }
4501   }
4502 
4503   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4504     // ARC and Weak:
4505     //   Default-initialize Objective-C pointers to NULL.
4506     CXXMemberInit
4507       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4508                                                  Loc, Loc,
4509                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4510                                                  Loc);
4511     return false;
4512   }
4513 
4514   // Nothing to initialize.
4515   CXXMemberInit = nullptr;
4516   return false;
4517 }
4518 
4519 namespace {
4520 struct BaseAndFieldInfo {
4521   Sema &S;
4522   CXXConstructorDecl *Ctor;
4523   bool AnyErrorsInInits;
4524   ImplicitInitializerKind IIK;
4525   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4526   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4527   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4528 
4529   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4530     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4531     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4532     if (Ctor->getInheritedConstructor())
4533       IIK = IIK_Inherit;
4534     else if (Generated && Ctor->isCopyConstructor())
4535       IIK = IIK_Copy;
4536     else if (Generated && Ctor->isMoveConstructor())
4537       IIK = IIK_Move;
4538     else
4539       IIK = IIK_Default;
4540   }
4541 
4542   bool isImplicitCopyOrMove() const {
4543     switch (IIK) {
4544     case IIK_Copy:
4545     case IIK_Move:
4546       return true;
4547 
4548     case IIK_Default:
4549     case IIK_Inherit:
4550       return false;
4551     }
4552 
4553     llvm_unreachable("Invalid ImplicitInitializerKind!");
4554   }
4555 
4556   bool addFieldInitializer(CXXCtorInitializer *Init) {
4557     AllToInit.push_back(Init);
4558 
4559     // Check whether this initializer makes the field "used".
4560     if (Init->getInit()->HasSideEffects(S.Context))
4561       S.UnusedPrivateFields.remove(Init->getAnyMember());
4562 
4563     return false;
4564   }
4565 
4566   bool isInactiveUnionMember(FieldDecl *Field) {
4567     RecordDecl *Record = Field->getParent();
4568     if (!Record->isUnion())
4569       return false;
4570 
4571     if (FieldDecl *Active =
4572             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4573       return Active != Field->getCanonicalDecl();
4574 
4575     // In an implicit copy or move constructor, ignore any in-class initializer.
4576     if (isImplicitCopyOrMove())
4577       return true;
4578 
4579     // If there's no explicit initialization, the field is active only if it
4580     // has an in-class initializer...
4581     if (Field->hasInClassInitializer())
4582       return false;
4583     // ... or it's an anonymous struct or union whose class has an in-class
4584     // initializer.
4585     if (!Field->isAnonymousStructOrUnion())
4586       return true;
4587     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4588     return !FieldRD->hasInClassInitializer();
4589   }
4590 
4591   /// Determine whether the given field is, or is within, a union member
4592   /// that is inactive (because there was an initializer given for a different
4593   /// member of the union, or because the union was not initialized at all).
4594   bool isWithinInactiveUnionMember(FieldDecl *Field,
4595                                    IndirectFieldDecl *Indirect) {
4596     if (!Indirect)
4597       return isInactiveUnionMember(Field);
4598 
4599     for (auto *C : Indirect->chain()) {
4600       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4601       if (Field && isInactiveUnionMember(Field))
4602         return true;
4603     }
4604     return false;
4605   }
4606 };
4607 }
4608 
4609 /// Determine whether the given type is an incomplete or zero-lenfgth
4610 /// array type.
4611 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4612   if (T->isIncompleteArrayType())
4613     return true;
4614 
4615   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4616     if (!ArrayT->getSize())
4617       return true;
4618 
4619     T = ArrayT->getElementType();
4620   }
4621 
4622   return false;
4623 }
4624 
4625 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4626                                     FieldDecl *Field,
4627                                     IndirectFieldDecl *Indirect = nullptr) {
4628   if (Field->isInvalidDecl())
4629     return false;
4630 
4631   // Overwhelmingly common case: we have a direct initializer for this field.
4632   if (CXXCtorInitializer *Init =
4633           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4634     return Info.addFieldInitializer(Init);
4635 
4636   // C++11 [class.base.init]p8:
4637   //   if the entity is a non-static data member that has a
4638   //   brace-or-equal-initializer and either
4639   //   -- the constructor's class is a union and no other variant member of that
4640   //      union is designated by a mem-initializer-id or
4641   //   -- the constructor's class is not a union, and, if the entity is a member
4642   //      of an anonymous union, no other member of that union is designated by
4643   //      a mem-initializer-id,
4644   //   the entity is initialized as specified in [dcl.init].
4645   //
4646   // We also apply the same rules to handle anonymous structs within anonymous
4647   // unions.
4648   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4649     return false;
4650 
4651   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4652     ExprResult DIE =
4653         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4654     if (DIE.isInvalid())
4655       return true;
4656 
4657     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4658     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4659 
4660     CXXCtorInitializer *Init;
4661     if (Indirect)
4662       Init = new (SemaRef.Context)
4663           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4664                              SourceLocation(), DIE.get(), SourceLocation());
4665     else
4666       Init = new (SemaRef.Context)
4667           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4668                              SourceLocation(), DIE.get(), SourceLocation());
4669     return Info.addFieldInitializer(Init);
4670   }
4671 
4672   // Don't initialize incomplete or zero-length arrays.
4673   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4674     return false;
4675 
4676   // Don't try to build an implicit initializer if there were semantic
4677   // errors in any of the initializers (and therefore we might be
4678   // missing some that the user actually wrote).
4679   if (Info.AnyErrorsInInits)
4680     return false;
4681 
4682   CXXCtorInitializer *Init = nullptr;
4683   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4684                                      Indirect, Init))
4685     return true;
4686 
4687   if (!Init)
4688     return false;
4689 
4690   return Info.addFieldInitializer(Init);
4691 }
4692 
4693 bool
4694 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4695                                CXXCtorInitializer *Initializer) {
4696   assert(Initializer->isDelegatingInitializer());
4697   Constructor->setNumCtorInitializers(1);
4698   CXXCtorInitializer **initializer =
4699     new (Context) CXXCtorInitializer*[1];
4700   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4701   Constructor->setCtorInitializers(initializer);
4702 
4703   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4704     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4705     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4706   }
4707 
4708   DelegatingCtorDecls.push_back(Constructor);
4709 
4710   DiagnoseUninitializedFields(*this, Constructor);
4711 
4712   return false;
4713 }
4714 
4715 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4716                                ArrayRef<CXXCtorInitializer *> Initializers) {
4717   if (Constructor->isDependentContext()) {
4718     // Just store the initializers as written, they will be checked during
4719     // instantiation.
4720     if (!Initializers.empty()) {
4721       Constructor->setNumCtorInitializers(Initializers.size());
4722       CXXCtorInitializer **baseOrMemberInitializers =
4723         new (Context) CXXCtorInitializer*[Initializers.size()];
4724       memcpy(baseOrMemberInitializers, Initializers.data(),
4725              Initializers.size() * sizeof(CXXCtorInitializer*));
4726       Constructor->setCtorInitializers(baseOrMemberInitializers);
4727     }
4728 
4729     // Let template instantiation know whether we had errors.
4730     if (AnyErrors)
4731       Constructor->setInvalidDecl();
4732 
4733     return false;
4734   }
4735 
4736   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4737 
4738   // We need to build the initializer AST according to order of construction
4739   // and not what user specified in the Initializers list.
4740   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4741   if (!ClassDecl)
4742     return true;
4743 
4744   bool HadError = false;
4745 
4746   for (unsigned i = 0; i < Initializers.size(); i++) {
4747     CXXCtorInitializer *Member = Initializers[i];
4748 
4749     if (Member->isBaseInitializer())
4750       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4751     else {
4752       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4753 
4754       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4755         for (auto *C : F->chain()) {
4756           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4757           if (FD && FD->getParent()->isUnion())
4758             Info.ActiveUnionMember.insert(std::make_pair(
4759                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4760         }
4761       } else if (FieldDecl *FD = Member->getMember()) {
4762         if (FD->getParent()->isUnion())
4763           Info.ActiveUnionMember.insert(std::make_pair(
4764               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4765       }
4766     }
4767   }
4768 
4769   // Keep track of the direct virtual bases.
4770   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4771   for (auto &I : ClassDecl->bases()) {
4772     if (I.isVirtual())
4773       DirectVBases.insert(&I);
4774   }
4775 
4776   // Push virtual bases before others.
4777   for (auto &VBase : ClassDecl->vbases()) {
4778     if (CXXCtorInitializer *Value
4779         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4780       // [class.base.init]p7, per DR257:
4781       //   A mem-initializer where the mem-initializer-id names a virtual base
4782       //   class is ignored during execution of a constructor of any class that
4783       //   is not the most derived class.
4784       if (ClassDecl->isAbstract()) {
4785         // FIXME: Provide a fixit to remove the base specifier. This requires
4786         // tracking the location of the associated comma for a base specifier.
4787         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4788           << VBase.getType() << ClassDecl;
4789         DiagnoseAbstractType(ClassDecl);
4790       }
4791 
4792       Info.AllToInit.push_back(Value);
4793     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4794       // [class.base.init]p8, per DR257:
4795       //   If a given [...] base class is not named by a mem-initializer-id
4796       //   [...] and the entity is not a virtual base class of an abstract
4797       //   class, then [...] the entity is default-initialized.
4798       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4799       CXXCtorInitializer *CXXBaseInit;
4800       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4801                                        &VBase, IsInheritedVirtualBase,
4802                                        CXXBaseInit)) {
4803         HadError = true;
4804         continue;
4805       }
4806 
4807       Info.AllToInit.push_back(CXXBaseInit);
4808     }
4809   }
4810 
4811   // Non-virtual bases.
4812   for (auto &Base : ClassDecl->bases()) {
4813     // Virtuals are in the virtual base list and already constructed.
4814     if (Base.isVirtual())
4815       continue;
4816 
4817     if (CXXCtorInitializer *Value
4818           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4819       Info.AllToInit.push_back(Value);
4820     } else if (!AnyErrors) {
4821       CXXCtorInitializer *CXXBaseInit;
4822       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4823                                        &Base, /*IsInheritedVirtualBase=*/false,
4824                                        CXXBaseInit)) {
4825         HadError = true;
4826         continue;
4827       }
4828 
4829       Info.AllToInit.push_back(CXXBaseInit);
4830     }
4831   }
4832 
4833   // Fields.
4834   for (auto *Mem : ClassDecl->decls()) {
4835     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4836       // C++ [class.bit]p2:
4837       //   A declaration for a bit-field that omits the identifier declares an
4838       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4839       //   initialized.
4840       if (F->isUnnamedBitfield())
4841         continue;
4842 
4843       // If we're not generating the implicit copy/move constructor, then we'll
4844       // handle anonymous struct/union fields based on their individual
4845       // indirect fields.
4846       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4847         continue;
4848 
4849       if (CollectFieldInitializer(*this, Info, F))
4850         HadError = true;
4851       continue;
4852     }
4853 
4854     // Beyond this point, we only consider default initialization.
4855     if (Info.isImplicitCopyOrMove())
4856       continue;
4857 
4858     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4859       if (F->getType()->isIncompleteArrayType()) {
4860         assert(ClassDecl->hasFlexibleArrayMember() &&
4861                "Incomplete array type is not valid");
4862         continue;
4863       }
4864 
4865       // Initialize each field of an anonymous struct individually.
4866       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4867         HadError = true;
4868 
4869       continue;
4870     }
4871   }
4872 
4873   unsigned NumInitializers = Info.AllToInit.size();
4874   if (NumInitializers > 0) {
4875     Constructor->setNumCtorInitializers(NumInitializers);
4876     CXXCtorInitializer **baseOrMemberInitializers =
4877       new (Context) CXXCtorInitializer*[NumInitializers];
4878     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4879            NumInitializers * sizeof(CXXCtorInitializer*));
4880     Constructor->setCtorInitializers(baseOrMemberInitializers);
4881 
4882     // Constructors implicitly reference the base and member
4883     // destructors.
4884     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4885                                            Constructor->getParent());
4886   }
4887 
4888   return HadError;
4889 }
4890 
4891 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4892   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4893     const RecordDecl *RD = RT->getDecl();
4894     if (RD->isAnonymousStructOrUnion()) {
4895       for (auto *Field : RD->fields())
4896         PopulateKeysForFields(Field, IdealInits);
4897       return;
4898     }
4899   }
4900   IdealInits.push_back(Field->getCanonicalDecl());
4901 }
4902 
4903 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4904   return Context.getCanonicalType(BaseType).getTypePtr();
4905 }
4906 
4907 static const void *GetKeyForMember(ASTContext &Context,
4908                                    CXXCtorInitializer *Member) {
4909   if (!Member->isAnyMemberInitializer())
4910     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4911 
4912   return Member->getAnyMember()->getCanonicalDecl();
4913 }
4914 
4915 static void DiagnoseBaseOrMemInitializerOrder(
4916     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4917     ArrayRef<CXXCtorInitializer *> Inits) {
4918   if (Constructor->getDeclContext()->isDependentContext())
4919     return;
4920 
4921   // Don't check initializers order unless the warning is enabled at the
4922   // location of at least one initializer.
4923   bool ShouldCheckOrder = false;
4924   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4925     CXXCtorInitializer *Init = Inits[InitIndex];
4926     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4927                                  Init->getSourceLocation())) {
4928       ShouldCheckOrder = true;
4929       break;
4930     }
4931   }
4932   if (!ShouldCheckOrder)
4933     return;
4934 
4935   // Build the list of bases and members in the order that they'll
4936   // actually be initialized.  The explicit initializers should be in
4937   // this same order but may be missing things.
4938   SmallVector<const void*, 32> IdealInitKeys;
4939 
4940   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4941 
4942   // 1. Virtual bases.
4943   for (const auto &VBase : ClassDecl->vbases())
4944     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4945 
4946   // 2. Non-virtual bases.
4947   for (const auto &Base : ClassDecl->bases()) {
4948     if (Base.isVirtual())
4949       continue;
4950     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4951   }
4952 
4953   // 3. Direct fields.
4954   for (auto *Field : ClassDecl->fields()) {
4955     if (Field->isUnnamedBitfield())
4956       continue;
4957 
4958     PopulateKeysForFields(Field, IdealInitKeys);
4959   }
4960 
4961   unsigned NumIdealInits = IdealInitKeys.size();
4962   unsigned IdealIndex = 0;
4963 
4964   CXXCtorInitializer *PrevInit = nullptr;
4965   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4966     CXXCtorInitializer *Init = Inits[InitIndex];
4967     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4968 
4969     // Scan forward to try to find this initializer in the idealized
4970     // initializers list.
4971     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4972       if (InitKey == IdealInitKeys[IdealIndex])
4973         break;
4974 
4975     // If we didn't find this initializer, it must be because we
4976     // scanned past it on a previous iteration.  That can only
4977     // happen if we're out of order;  emit a warning.
4978     if (IdealIndex == NumIdealInits && PrevInit) {
4979       Sema::SemaDiagnosticBuilder D =
4980         SemaRef.Diag(PrevInit->getSourceLocation(),
4981                      diag::warn_initializer_out_of_order);
4982 
4983       if (PrevInit->isAnyMemberInitializer())
4984         D << 0 << PrevInit->getAnyMember()->getDeclName();
4985       else
4986         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4987 
4988       if (Init->isAnyMemberInitializer())
4989         D << 0 << Init->getAnyMember()->getDeclName();
4990       else
4991         D << 1 << Init->getTypeSourceInfo()->getType();
4992 
4993       // Move back to the initializer's location in the ideal list.
4994       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4995         if (InitKey == IdealInitKeys[IdealIndex])
4996           break;
4997 
4998       assert(IdealIndex < NumIdealInits &&
4999              "initializer not found in initializer list");
5000     }
5001 
5002     PrevInit = Init;
5003   }
5004 }
5005 
5006 namespace {
5007 bool CheckRedundantInit(Sema &S,
5008                         CXXCtorInitializer *Init,
5009                         CXXCtorInitializer *&PrevInit) {
5010   if (!PrevInit) {
5011     PrevInit = Init;
5012     return false;
5013   }
5014 
5015   if (FieldDecl *Field = Init->getAnyMember())
5016     S.Diag(Init->getSourceLocation(),
5017            diag::err_multiple_mem_initialization)
5018       << Field->getDeclName()
5019       << Init->getSourceRange();
5020   else {
5021     const Type *BaseClass = Init->getBaseClass();
5022     assert(BaseClass && "neither field nor base");
5023     S.Diag(Init->getSourceLocation(),
5024            diag::err_multiple_base_initialization)
5025       << QualType(BaseClass, 0)
5026       << Init->getSourceRange();
5027   }
5028   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5029     << 0 << PrevInit->getSourceRange();
5030 
5031   return true;
5032 }
5033 
5034 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5035 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5036 
5037 bool CheckRedundantUnionInit(Sema &S,
5038                              CXXCtorInitializer *Init,
5039                              RedundantUnionMap &Unions) {
5040   FieldDecl *Field = Init->getAnyMember();
5041   RecordDecl *Parent = Field->getParent();
5042   NamedDecl *Child = Field;
5043 
5044   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5045     if (Parent->isUnion()) {
5046       UnionEntry &En = Unions[Parent];
5047       if (En.first && En.first != Child) {
5048         S.Diag(Init->getSourceLocation(),
5049                diag::err_multiple_mem_union_initialization)
5050           << Field->getDeclName()
5051           << Init->getSourceRange();
5052         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5053           << 0 << En.second->getSourceRange();
5054         return true;
5055       }
5056       if (!En.first) {
5057         En.first = Child;
5058         En.second = Init;
5059       }
5060       if (!Parent->isAnonymousStructOrUnion())
5061         return false;
5062     }
5063 
5064     Child = Parent;
5065     Parent = cast<RecordDecl>(Parent->getDeclContext());
5066   }
5067 
5068   return false;
5069 }
5070 }
5071 
5072 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5073 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5074                                 SourceLocation ColonLoc,
5075                                 ArrayRef<CXXCtorInitializer*> MemInits,
5076                                 bool AnyErrors) {
5077   if (!ConstructorDecl)
5078     return;
5079 
5080   AdjustDeclIfTemplate(ConstructorDecl);
5081 
5082   CXXConstructorDecl *Constructor
5083     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5084 
5085   if (!Constructor) {
5086     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5087     return;
5088   }
5089 
5090   // Mapping for the duplicate initializers check.
5091   // For member initializers, this is keyed with a FieldDecl*.
5092   // For base initializers, this is keyed with a Type*.
5093   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5094 
5095   // Mapping for the inconsistent anonymous-union initializers check.
5096   RedundantUnionMap MemberUnions;
5097 
5098   bool HadError = false;
5099   for (unsigned i = 0; i < MemInits.size(); i++) {
5100     CXXCtorInitializer *Init = MemInits[i];
5101 
5102     // Set the source order index.
5103     Init->setSourceOrder(i);
5104 
5105     if (Init->isAnyMemberInitializer()) {
5106       const void *Key = GetKeyForMember(Context, Init);
5107       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5108           CheckRedundantUnionInit(*this, Init, MemberUnions))
5109         HadError = true;
5110     } else if (Init->isBaseInitializer()) {
5111       const void *Key = GetKeyForMember(Context, Init);
5112       if (CheckRedundantInit(*this, Init, Members[Key]))
5113         HadError = true;
5114     } else {
5115       assert(Init->isDelegatingInitializer());
5116       // This must be the only initializer
5117       if (MemInits.size() != 1) {
5118         Diag(Init->getSourceLocation(),
5119              diag::err_delegating_initializer_alone)
5120           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5121         // We will treat this as being the only initializer.
5122       }
5123       SetDelegatingInitializer(Constructor, MemInits[i]);
5124       // Return immediately as the initializer is set.
5125       return;
5126     }
5127   }
5128 
5129   if (HadError)
5130     return;
5131 
5132   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5133 
5134   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5135 
5136   DiagnoseUninitializedFields(*this, Constructor);
5137 }
5138 
5139 void
5140 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5141                                              CXXRecordDecl *ClassDecl) {
5142   // Ignore dependent contexts. Also ignore unions, since their members never
5143   // have destructors implicitly called.
5144   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5145     return;
5146 
5147   // FIXME: all the access-control diagnostics are positioned on the
5148   // field/base declaration.  That's probably good; that said, the
5149   // user might reasonably want to know why the destructor is being
5150   // emitted, and we currently don't say.
5151 
5152   // Non-static data members.
5153   for (auto *Field : ClassDecl->fields()) {
5154     if (Field->isInvalidDecl())
5155       continue;
5156 
5157     // Don't destroy incomplete or zero-length arrays.
5158     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5159       continue;
5160 
5161     QualType FieldType = Context.getBaseElementType(Field->getType());
5162 
5163     const RecordType* RT = FieldType->getAs<RecordType>();
5164     if (!RT)
5165       continue;
5166 
5167     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5168     if (FieldClassDecl->isInvalidDecl())
5169       continue;
5170     if (FieldClassDecl->hasIrrelevantDestructor())
5171       continue;
5172     // The destructor for an implicit anonymous union member is never invoked.
5173     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5174       continue;
5175 
5176     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5177     assert(Dtor && "No dtor found for FieldClassDecl!");
5178     CheckDestructorAccess(Field->getLocation(), Dtor,
5179                           PDiag(diag::err_access_dtor_field)
5180                             << Field->getDeclName()
5181                             << FieldType);
5182 
5183     MarkFunctionReferenced(Location, Dtor);
5184     DiagnoseUseOfDecl(Dtor, Location);
5185   }
5186 
5187   // We only potentially invoke the destructors of potentially constructed
5188   // subobjects.
5189   bool VisitVirtualBases = !ClassDecl->isAbstract();
5190 
5191   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5192 
5193   // Bases.
5194   for (const auto &Base : ClassDecl->bases()) {
5195     // Bases are always records in a well-formed non-dependent class.
5196     const RecordType *RT = Base.getType()->getAs<RecordType>();
5197 
5198     // Remember direct virtual bases.
5199     if (Base.isVirtual()) {
5200       if (!VisitVirtualBases)
5201         continue;
5202       DirectVirtualBases.insert(RT);
5203     }
5204 
5205     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5206     // If our base class is invalid, we probably can't get its dtor anyway.
5207     if (BaseClassDecl->isInvalidDecl())
5208       continue;
5209     if (BaseClassDecl->hasIrrelevantDestructor())
5210       continue;
5211 
5212     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5213     assert(Dtor && "No dtor found for BaseClassDecl!");
5214 
5215     // FIXME: caret should be on the start of the class name
5216     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5217                           PDiag(diag::err_access_dtor_base)
5218                               << Base.getType() << Base.getSourceRange(),
5219                           Context.getTypeDeclType(ClassDecl));
5220 
5221     MarkFunctionReferenced(Location, Dtor);
5222     DiagnoseUseOfDecl(Dtor, Location);
5223   }
5224 
5225   if (!VisitVirtualBases)
5226     return;
5227 
5228   // Virtual bases.
5229   for (const auto &VBase : ClassDecl->vbases()) {
5230     // Bases are always records in a well-formed non-dependent class.
5231     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5232 
5233     // Ignore direct virtual bases.
5234     if (DirectVirtualBases.count(RT))
5235       continue;
5236 
5237     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5238     // If our base class is invalid, we probably can't get its dtor anyway.
5239     if (BaseClassDecl->isInvalidDecl())
5240       continue;
5241     if (BaseClassDecl->hasIrrelevantDestructor())
5242       continue;
5243 
5244     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5245     assert(Dtor && "No dtor found for BaseClassDecl!");
5246     if (CheckDestructorAccess(
5247             ClassDecl->getLocation(), Dtor,
5248             PDiag(diag::err_access_dtor_vbase)
5249                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5250             Context.getTypeDeclType(ClassDecl)) ==
5251         AR_accessible) {
5252       CheckDerivedToBaseConversion(
5253           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5254           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5255           SourceRange(), DeclarationName(), nullptr);
5256     }
5257 
5258     MarkFunctionReferenced(Location, Dtor);
5259     DiagnoseUseOfDecl(Dtor, Location);
5260   }
5261 }
5262 
5263 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5264   if (!CDtorDecl)
5265     return;
5266 
5267   if (CXXConstructorDecl *Constructor
5268       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5269     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5270     DiagnoseUninitializedFields(*this, Constructor);
5271   }
5272 }
5273 
5274 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5275   if (!getLangOpts().CPlusPlus)
5276     return false;
5277 
5278   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5279   if (!RD)
5280     return false;
5281 
5282   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5283   // class template specialization here, but doing so breaks a lot of code.
5284 
5285   // We can't answer whether something is abstract until it has a
5286   // definition. If it's currently being defined, we'll walk back
5287   // over all the declarations when we have a full definition.
5288   const CXXRecordDecl *Def = RD->getDefinition();
5289   if (!Def || Def->isBeingDefined())
5290     return false;
5291 
5292   return RD->isAbstract();
5293 }
5294 
5295 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5296                                   TypeDiagnoser &Diagnoser) {
5297   if (!isAbstractType(Loc, T))
5298     return false;
5299 
5300   T = Context.getBaseElementType(T);
5301   Diagnoser.diagnose(*this, Loc, T);
5302   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5303   return true;
5304 }
5305 
5306 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5307   // Check if we've already emitted the list of pure virtual functions
5308   // for this class.
5309   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5310     return;
5311 
5312   // If the diagnostic is suppressed, don't emit the notes. We're only
5313   // going to emit them once, so try to attach them to a diagnostic we're
5314   // actually going to show.
5315   if (Diags.isLastDiagnosticIgnored())
5316     return;
5317 
5318   CXXFinalOverriderMap FinalOverriders;
5319   RD->getFinalOverriders(FinalOverriders);
5320 
5321   // Keep a set of seen pure methods so we won't diagnose the same method
5322   // more than once.
5323   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5324 
5325   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5326                                    MEnd = FinalOverriders.end();
5327        M != MEnd;
5328        ++M) {
5329     for (OverridingMethods::iterator SO = M->second.begin(),
5330                                   SOEnd = M->second.end();
5331          SO != SOEnd; ++SO) {
5332       // C++ [class.abstract]p4:
5333       //   A class is abstract if it contains or inherits at least one
5334       //   pure virtual function for which the final overrider is pure
5335       //   virtual.
5336 
5337       //
5338       if (SO->second.size() != 1)
5339         continue;
5340 
5341       if (!SO->second.front().Method->isPure())
5342         continue;
5343 
5344       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5345         continue;
5346 
5347       Diag(SO->second.front().Method->getLocation(),
5348            diag::note_pure_virtual_function)
5349         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5350     }
5351   }
5352 
5353   if (!PureVirtualClassDiagSet)
5354     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5355   PureVirtualClassDiagSet->insert(RD);
5356 }
5357 
5358 namespace {
5359 struct AbstractUsageInfo {
5360   Sema &S;
5361   CXXRecordDecl *Record;
5362   CanQualType AbstractType;
5363   bool Invalid;
5364 
5365   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5366     : S(S), Record(Record),
5367       AbstractType(S.Context.getCanonicalType(
5368                    S.Context.getTypeDeclType(Record))),
5369       Invalid(false) {}
5370 
5371   void DiagnoseAbstractType() {
5372     if (Invalid) return;
5373     S.DiagnoseAbstractType(Record);
5374     Invalid = true;
5375   }
5376 
5377   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5378 };
5379 
5380 struct CheckAbstractUsage {
5381   AbstractUsageInfo &Info;
5382   const NamedDecl *Ctx;
5383 
5384   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5385     : Info(Info), Ctx(Ctx) {}
5386 
5387   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5388     switch (TL.getTypeLocClass()) {
5389 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5390 #define TYPELOC(CLASS, PARENT) \
5391     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5392 #include "clang/AST/TypeLocNodes.def"
5393     }
5394   }
5395 
5396   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5397     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5398     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5399       if (!TL.getParam(I))
5400         continue;
5401 
5402       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5403       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5404     }
5405   }
5406 
5407   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5408     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5409   }
5410 
5411   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5412     // Visit the type parameters from a permissive context.
5413     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5414       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5415       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5416         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5417           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5418       // TODO: other template argument types?
5419     }
5420   }
5421 
5422   // Visit pointee types from a permissive context.
5423 #define CheckPolymorphic(Type) \
5424   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5425     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5426   }
5427   CheckPolymorphic(PointerTypeLoc)
5428   CheckPolymorphic(ReferenceTypeLoc)
5429   CheckPolymorphic(MemberPointerTypeLoc)
5430   CheckPolymorphic(BlockPointerTypeLoc)
5431   CheckPolymorphic(AtomicTypeLoc)
5432 
5433   /// Handle all the types we haven't given a more specific
5434   /// implementation for above.
5435   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5436     // Every other kind of type that we haven't called out already
5437     // that has an inner type is either (1) sugar or (2) contains that
5438     // inner type in some way as a subobject.
5439     if (TypeLoc Next = TL.getNextTypeLoc())
5440       return Visit(Next, Sel);
5441 
5442     // If there's no inner type and we're in a permissive context,
5443     // don't diagnose.
5444     if (Sel == Sema::AbstractNone) return;
5445 
5446     // Check whether the type matches the abstract type.
5447     QualType T = TL.getType();
5448     if (T->isArrayType()) {
5449       Sel = Sema::AbstractArrayType;
5450       T = Info.S.Context.getBaseElementType(T);
5451     }
5452     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5453     if (CT != Info.AbstractType) return;
5454 
5455     // It matched; do some magic.
5456     if (Sel == Sema::AbstractArrayType) {
5457       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5458         << T << TL.getSourceRange();
5459     } else {
5460       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5461         << Sel << T << TL.getSourceRange();
5462     }
5463     Info.DiagnoseAbstractType();
5464   }
5465 };
5466 
5467 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5468                                   Sema::AbstractDiagSelID Sel) {
5469   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5470 }
5471 
5472 }
5473 
5474 /// Check for invalid uses of an abstract type in a method declaration.
5475 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5476                                     CXXMethodDecl *MD) {
5477   // No need to do the check on definitions, which require that
5478   // the return/param types be complete.
5479   if (MD->doesThisDeclarationHaveABody())
5480     return;
5481 
5482   // For safety's sake, just ignore it if we don't have type source
5483   // information.  This should never happen for non-implicit methods,
5484   // but...
5485   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5486     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5487 }
5488 
5489 /// Check for invalid uses of an abstract type within a class definition.
5490 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5491                                     CXXRecordDecl *RD) {
5492   for (auto *D : RD->decls()) {
5493     if (D->isImplicit()) continue;
5494 
5495     // Methods and method templates.
5496     if (isa<CXXMethodDecl>(D)) {
5497       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5498     } else if (isa<FunctionTemplateDecl>(D)) {
5499       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5500       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5501 
5502     // Fields and static variables.
5503     } else if (isa<FieldDecl>(D)) {
5504       FieldDecl *FD = cast<FieldDecl>(D);
5505       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5506         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5507     } else if (isa<VarDecl>(D)) {
5508       VarDecl *VD = cast<VarDecl>(D);
5509       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5510         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5511 
5512     // Nested classes and class templates.
5513     } else if (isa<CXXRecordDecl>(D)) {
5514       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5515     } else if (isa<ClassTemplateDecl>(D)) {
5516       CheckAbstractClassUsage(Info,
5517                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5518     }
5519   }
5520 }
5521 
5522 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5523   Attr *ClassAttr = getDLLAttr(Class);
5524   if (!ClassAttr)
5525     return;
5526 
5527   assert(ClassAttr->getKind() == attr::DLLExport);
5528 
5529   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5530 
5531   if (TSK == TSK_ExplicitInstantiationDeclaration)
5532     // Don't go any further if this is just an explicit instantiation
5533     // declaration.
5534     return;
5535 
5536   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5537     S.MarkVTableUsed(Class->getLocation(), Class, true);
5538 
5539   for (Decl *Member : Class->decls()) {
5540     // Defined static variables that are members of an exported base
5541     // class must be marked export too.
5542     auto *VD = dyn_cast<VarDecl>(Member);
5543     if (VD && Member->getAttr<DLLExportAttr>() &&
5544         VD->getStorageClass() == SC_Static &&
5545         TSK == TSK_ImplicitInstantiation)
5546       S.MarkVariableReferenced(VD->getLocation(), VD);
5547 
5548     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5549     if (!MD)
5550       continue;
5551 
5552     if (Member->getAttr<DLLExportAttr>()) {
5553       if (MD->isUserProvided()) {
5554         // Instantiate non-default class member functions ...
5555 
5556         // .. except for certain kinds of template specializations.
5557         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5558           continue;
5559 
5560         S.MarkFunctionReferenced(Class->getLocation(), MD);
5561 
5562         // The function will be passed to the consumer when its definition is
5563         // encountered.
5564       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5565                  MD->isCopyAssignmentOperator() ||
5566                  MD->isMoveAssignmentOperator()) {
5567         // Synthesize and instantiate non-trivial implicit methods, explicitly
5568         // defaulted methods, and the copy and move assignment operators. The
5569         // latter are exported even if they are trivial, because the address of
5570         // an operator can be taken and should compare equal across libraries.
5571         DiagnosticErrorTrap Trap(S.Diags);
5572         S.MarkFunctionReferenced(Class->getLocation(), MD);
5573         if (Trap.hasErrorOccurred()) {
5574           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5575               << Class << !S.getLangOpts().CPlusPlus11;
5576           break;
5577         }
5578 
5579         // There is no later point when we will see the definition of this
5580         // function, so pass it to the consumer now.
5581         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5582       }
5583     }
5584   }
5585 }
5586 
5587 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5588                                                         CXXRecordDecl *Class) {
5589   // Only the MS ABI has default constructor closures, so we don't need to do
5590   // this semantic checking anywhere else.
5591   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5592     return;
5593 
5594   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5595   for (Decl *Member : Class->decls()) {
5596     // Look for exported default constructors.
5597     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5598     if (!CD || !CD->isDefaultConstructor())
5599       continue;
5600     auto *Attr = CD->getAttr<DLLExportAttr>();
5601     if (!Attr)
5602       continue;
5603 
5604     // If the class is non-dependent, mark the default arguments as ODR-used so
5605     // that we can properly codegen the constructor closure.
5606     if (!Class->isDependentContext()) {
5607       for (ParmVarDecl *PD : CD->parameters()) {
5608         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5609         S.DiscardCleanupsInEvaluationContext();
5610       }
5611     }
5612 
5613     if (LastExportedDefaultCtor) {
5614       S.Diag(LastExportedDefaultCtor->getLocation(),
5615              diag::err_attribute_dll_ambiguous_default_ctor)
5616           << Class;
5617       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5618           << CD->getDeclName();
5619       return;
5620     }
5621     LastExportedDefaultCtor = CD;
5622   }
5623 }
5624 
5625 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5626   // Mark any compiler-generated routines with the implicit code_seg attribute.
5627   for (auto *Method : Class->methods()) {
5628     if (Method->isUserProvided())
5629       continue;
5630     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5631       Method->addAttr(A);
5632   }
5633 }
5634 
5635 /// Check class-level dllimport/dllexport attribute.
5636 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5637   Attr *ClassAttr = getDLLAttr(Class);
5638 
5639   // MSVC inherits DLL attributes to partial class template specializations.
5640   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5641     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5642       if (Attr *TemplateAttr =
5643               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5644         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5645         A->setInherited(true);
5646         ClassAttr = A;
5647       }
5648     }
5649   }
5650 
5651   if (!ClassAttr)
5652     return;
5653 
5654   if (!Class->isExternallyVisible()) {
5655     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5656         << Class << ClassAttr;
5657     return;
5658   }
5659 
5660   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5661       !ClassAttr->isInherited()) {
5662     // Diagnose dll attributes on members of class with dll attribute.
5663     for (Decl *Member : Class->decls()) {
5664       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5665         continue;
5666       InheritableAttr *MemberAttr = getDLLAttr(Member);
5667       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5668         continue;
5669 
5670       Diag(MemberAttr->getLocation(),
5671              diag::err_attribute_dll_member_of_dll_class)
5672           << MemberAttr << ClassAttr;
5673       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5674       Member->setInvalidDecl();
5675     }
5676   }
5677 
5678   if (Class->getDescribedClassTemplate())
5679     // Don't inherit dll attribute until the template is instantiated.
5680     return;
5681 
5682   // The class is either imported or exported.
5683   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5684 
5685   // Check if this was a dllimport attribute propagated from a derived class to
5686   // a base class template specialization. We don't apply these attributes to
5687   // static data members.
5688   const bool PropagatedImport =
5689       !ClassExported &&
5690       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5691 
5692   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5693 
5694   // Ignore explicit dllexport on explicit class template instantiation declarations.
5695   if (ClassExported && !ClassAttr->isInherited() &&
5696       TSK == TSK_ExplicitInstantiationDeclaration) {
5697     Class->dropAttr<DLLExportAttr>();
5698     return;
5699   }
5700 
5701   // Force declaration of implicit members so they can inherit the attribute.
5702   ForceDeclarationOfImplicitMembers(Class);
5703 
5704   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5705   // seem to be true in practice?
5706 
5707   for (Decl *Member : Class->decls()) {
5708     VarDecl *VD = dyn_cast<VarDecl>(Member);
5709     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5710 
5711     // Only methods and static fields inherit the attributes.
5712     if (!VD && !MD)
5713       continue;
5714 
5715     if (MD) {
5716       // Don't process deleted methods.
5717       if (MD->isDeleted())
5718         continue;
5719 
5720       if (MD->isInlined()) {
5721         // MinGW does not import or export inline methods.
5722         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5723             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5724           continue;
5725 
5726         // MSVC versions before 2015 don't export the move assignment operators
5727         // and move constructor, so don't attempt to import/export them if
5728         // we have a definition.
5729         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5730         if ((MD->isMoveAssignmentOperator() ||
5731              (Ctor && Ctor->isMoveConstructor())) &&
5732             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5733           continue;
5734 
5735         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5736         // operator is exported anyway.
5737         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5738             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5739           continue;
5740       }
5741     }
5742 
5743     // Don't apply dllimport attributes to static data members of class template
5744     // instantiations when the attribute is propagated from a derived class.
5745     if (VD && PropagatedImport)
5746       continue;
5747 
5748     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5749       continue;
5750 
5751     if (!getDLLAttr(Member)) {
5752       InheritableAttr *NewAttr = nullptr;
5753 
5754       // Do not export/import inline function when -fno-dllexport-inlines is
5755       // passed. But add attribute for later local static var check.
5756       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5757           TSK != TSK_ExplicitInstantiationDeclaration &&
5758           TSK != TSK_ExplicitInstantiationDefinition) {
5759         if (ClassExported) {
5760           NewAttr = ::new (getASTContext())
5761             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5762                                      getASTContext(),
5763                                      ClassAttr->getSpellingListIndex());
5764         } else {
5765           NewAttr = ::new (getASTContext())
5766             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5767                                      getASTContext(),
5768                                      ClassAttr->getSpellingListIndex());
5769         }
5770       } else {
5771         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5772       }
5773 
5774       NewAttr->setInherited(true);
5775       Member->addAttr(NewAttr);
5776 
5777       if (MD) {
5778         // Propagate DLLAttr to friend re-declarations of MD that have already
5779         // been constructed.
5780         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5781              FD = FD->getPreviousDecl()) {
5782           if (FD->getFriendObjectKind() == Decl::FOK_None)
5783             continue;
5784           assert(!getDLLAttr(FD) &&
5785                  "friend re-decl should not already have a DLLAttr");
5786           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5787           NewAttr->setInherited(true);
5788           FD->addAttr(NewAttr);
5789         }
5790       }
5791     }
5792   }
5793 
5794   if (ClassExported)
5795     DelayedDllExportClasses.push_back(Class);
5796 }
5797 
5798 /// Perform propagation of DLL attributes from a derived class to a
5799 /// templated base class for MS compatibility.
5800 void Sema::propagateDLLAttrToBaseClassTemplate(
5801     CXXRecordDecl *Class, Attr *ClassAttr,
5802     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5803   if (getDLLAttr(
5804           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5805     // If the base class template has a DLL attribute, don't try to change it.
5806     return;
5807   }
5808 
5809   auto TSK = BaseTemplateSpec->getSpecializationKind();
5810   if (!getDLLAttr(BaseTemplateSpec) &&
5811       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5812        TSK == TSK_ImplicitInstantiation)) {
5813     // The template hasn't been instantiated yet (or it has, but only as an
5814     // explicit instantiation declaration or implicit instantiation, which means
5815     // we haven't codegenned any members yet), so propagate the attribute.
5816     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5817     NewAttr->setInherited(true);
5818     BaseTemplateSpec->addAttr(NewAttr);
5819 
5820     // If this was an import, mark that we propagated it from a derived class to
5821     // a base class template specialization.
5822     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5823       ImportAttr->setPropagatedToBaseTemplate();
5824 
5825     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5826     // needs to be run again to work see the new attribute. Otherwise this will
5827     // get run whenever the template is instantiated.
5828     if (TSK != TSK_Undeclared)
5829       checkClassLevelDLLAttribute(BaseTemplateSpec);
5830 
5831     return;
5832   }
5833 
5834   if (getDLLAttr(BaseTemplateSpec)) {
5835     // The template has already been specialized or instantiated with an
5836     // attribute, explicitly or through propagation. We should not try to change
5837     // it.
5838     return;
5839   }
5840 
5841   // The template was previously instantiated or explicitly specialized without
5842   // a dll attribute, It's too late for us to add an attribute, so warn that
5843   // this is unsupported.
5844   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5845       << BaseTemplateSpec->isExplicitSpecialization();
5846   Diag(ClassAttr->getLocation(), diag::note_attribute);
5847   if (BaseTemplateSpec->isExplicitSpecialization()) {
5848     Diag(BaseTemplateSpec->getLocation(),
5849            diag::note_template_class_explicit_specialization_was_here)
5850         << BaseTemplateSpec;
5851   } else {
5852     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5853            diag::note_template_class_instantiation_was_here)
5854         << BaseTemplateSpec;
5855   }
5856 }
5857 
5858 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5859                                         SourceLocation DefaultLoc) {
5860   switch (S.getSpecialMember(MD)) {
5861   case Sema::CXXDefaultConstructor:
5862     S.DefineImplicitDefaultConstructor(DefaultLoc,
5863                                        cast<CXXConstructorDecl>(MD));
5864     break;
5865   case Sema::CXXCopyConstructor:
5866     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5867     break;
5868   case Sema::CXXCopyAssignment:
5869     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5870     break;
5871   case Sema::CXXDestructor:
5872     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5873     break;
5874   case Sema::CXXMoveConstructor:
5875     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5876     break;
5877   case Sema::CXXMoveAssignment:
5878     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5879     break;
5880   case Sema::CXXInvalid:
5881     llvm_unreachable("Invalid special member.");
5882   }
5883 }
5884 
5885 /// Determine whether a type is permitted to be passed or returned in
5886 /// registers, per C++ [class.temporary]p3.
5887 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5888                                TargetInfo::CallingConvKind CCK) {
5889   if (D->isDependentType() || D->isInvalidDecl())
5890     return false;
5891 
5892   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5893   // The PS4 platform ABI follows the behavior of Clang 3.2.
5894   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5895     return !D->hasNonTrivialDestructorForCall() &&
5896            !D->hasNonTrivialCopyConstructorForCall();
5897 
5898   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5899     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5900     bool DtorIsTrivialForCall = false;
5901 
5902     // If a class has at least one non-deleted, trivial copy constructor, it
5903     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5904     //
5905     // Note: This permits classes with non-trivial copy or move ctors to be
5906     // passed in registers, so long as they *also* have a trivial copy ctor,
5907     // which is non-conforming.
5908     if (D->needsImplicitCopyConstructor()) {
5909       if (!D->defaultedCopyConstructorIsDeleted()) {
5910         if (D->hasTrivialCopyConstructor())
5911           CopyCtorIsTrivial = true;
5912         if (D->hasTrivialCopyConstructorForCall())
5913           CopyCtorIsTrivialForCall = true;
5914       }
5915     } else {
5916       for (const CXXConstructorDecl *CD : D->ctors()) {
5917         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5918           if (CD->isTrivial())
5919             CopyCtorIsTrivial = true;
5920           if (CD->isTrivialForCall())
5921             CopyCtorIsTrivialForCall = true;
5922         }
5923       }
5924     }
5925 
5926     if (D->needsImplicitDestructor()) {
5927       if (!D->defaultedDestructorIsDeleted() &&
5928           D->hasTrivialDestructorForCall())
5929         DtorIsTrivialForCall = true;
5930     } else if (const auto *DD = D->getDestructor()) {
5931       if (!DD->isDeleted() && DD->isTrivialForCall())
5932         DtorIsTrivialForCall = true;
5933     }
5934 
5935     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5936     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5937       return true;
5938 
5939     // If a class has a destructor, we'd really like to pass it indirectly
5940     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5941     // impossible for small types, which it will pass in a single register or
5942     // stack slot. Most objects with dtors are large-ish, so handle that early.
5943     // We can't call out all large objects as being indirect because there are
5944     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5945     // how we pass large POD types.
5946 
5947     // Note: This permits small classes with nontrivial destructors to be
5948     // passed in registers, which is non-conforming.
5949     if (CopyCtorIsTrivial &&
5950         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5951       return true;
5952     return false;
5953   }
5954 
5955   // Per C++ [class.temporary]p3, the relevant condition is:
5956   //   each copy constructor, move constructor, and destructor of X is
5957   //   either trivial or deleted, and X has at least one non-deleted copy
5958   //   or move constructor
5959   bool HasNonDeletedCopyOrMove = false;
5960 
5961   if (D->needsImplicitCopyConstructor() &&
5962       !D->defaultedCopyConstructorIsDeleted()) {
5963     if (!D->hasTrivialCopyConstructorForCall())
5964       return false;
5965     HasNonDeletedCopyOrMove = true;
5966   }
5967 
5968   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5969       !D->defaultedMoveConstructorIsDeleted()) {
5970     if (!D->hasTrivialMoveConstructorForCall())
5971       return false;
5972     HasNonDeletedCopyOrMove = true;
5973   }
5974 
5975   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5976       !D->hasTrivialDestructorForCall())
5977     return false;
5978 
5979   for (const CXXMethodDecl *MD : D->methods()) {
5980     if (MD->isDeleted())
5981       continue;
5982 
5983     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5984     if (CD && CD->isCopyOrMoveConstructor())
5985       HasNonDeletedCopyOrMove = true;
5986     else if (!isa<CXXDestructorDecl>(MD))
5987       continue;
5988 
5989     if (!MD->isTrivialForCall())
5990       return false;
5991   }
5992 
5993   return HasNonDeletedCopyOrMove;
5994 }
5995 
5996 /// Perform semantic checks on a class definition that has been
5997 /// completing, introducing implicitly-declared members, checking for
5998 /// abstract types, etc.
5999 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6000   if (!Record)
6001     return;
6002 
6003   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6004     AbstractUsageInfo Info(*this, Record);
6005     CheckAbstractClassUsage(Info, Record);
6006   }
6007 
6008   // If this is not an aggregate type and has no user-declared constructor,
6009   // complain about any non-static data members of reference or const scalar
6010   // type, since they will never get initializers.
6011   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6012       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6013       !Record->isLambda()) {
6014     bool Complained = false;
6015     for (const auto *F : Record->fields()) {
6016       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6017         continue;
6018 
6019       if (F->getType()->isReferenceType() ||
6020           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6021         if (!Complained) {
6022           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6023             << Record->getTagKind() << Record;
6024           Complained = true;
6025         }
6026 
6027         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6028           << F->getType()->isReferenceType()
6029           << F->getDeclName();
6030       }
6031     }
6032   }
6033 
6034   if (Record->getIdentifier()) {
6035     // C++ [class.mem]p13:
6036     //   If T is the name of a class, then each of the following shall have a
6037     //   name different from T:
6038     //     - every member of every anonymous union that is a member of class T.
6039     //
6040     // C++ [class.mem]p14:
6041     //   In addition, if class T has a user-declared constructor (12.1), every
6042     //   non-static data member of class T shall have a name different from T.
6043     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6044     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6045          ++I) {
6046       NamedDecl *D = (*I)->getUnderlyingDecl();
6047       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6048            Record->hasUserDeclaredConstructor()) ||
6049           isa<IndirectFieldDecl>(D)) {
6050         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6051           << D->getDeclName();
6052         break;
6053       }
6054     }
6055   }
6056 
6057   // Warn if the class has virtual methods but non-virtual public destructor.
6058   if (Record->isPolymorphic() && !Record->isDependentType()) {
6059     CXXDestructorDecl *dtor = Record->getDestructor();
6060     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6061         !Record->hasAttr<FinalAttr>())
6062       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6063            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6064   }
6065 
6066   if (Record->isAbstract()) {
6067     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6068       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6069         << FA->isSpelledAsSealed();
6070       DiagnoseAbstractType(Record);
6071     }
6072   }
6073 
6074   // See if trivial_abi has to be dropped.
6075   if (Record->hasAttr<TrivialABIAttr>())
6076     checkIllFormedTrivialABIStruct(*Record);
6077 
6078   // Set HasTrivialSpecialMemberForCall if the record has attribute
6079   // "trivial_abi".
6080   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6081 
6082   if (HasTrivialABI)
6083     Record->setHasTrivialSpecialMemberForCall();
6084 
6085   bool HasMethodWithOverrideControl = false,
6086        HasOverridingMethodWithoutOverrideControl = false;
6087   if (!Record->isDependentType()) {
6088     for (auto *M : Record->methods()) {
6089       // See if a method overloads virtual methods in a base
6090       // class without overriding any.
6091       if (!M->isStatic())
6092         DiagnoseHiddenVirtualMethods(M);
6093       if (M->hasAttr<OverrideAttr>())
6094         HasMethodWithOverrideControl = true;
6095       else if (M->size_overridden_methods() > 0)
6096         HasOverridingMethodWithoutOverrideControl = true;
6097       // Check whether the explicitly-defaulted special members are valid.
6098       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6099         CheckExplicitlyDefaultedSpecialMember(M);
6100 
6101       // For an explicitly defaulted or deleted special member, we defer
6102       // determining triviality until the class is complete. That time is now!
6103       CXXSpecialMember CSM = getSpecialMember(M);
6104       if (!M->isImplicit() && !M->isUserProvided()) {
6105         if (CSM != CXXInvalid) {
6106           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6107           // Inform the class that we've finished declaring this member.
6108           Record->finishedDefaultedOrDeletedMember(M);
6109           M->setTrivialForCall(
6110               HasTrivialABI ||
6111               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6112           Record->setTrivialForCallFlags(M);
6113         }
6114       }
6115 
6116       // Set triviality for the purpose of calls if this is a user-provided
6117       // copy/move constructor or destructor.
6118       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6119            CSM == CXXDestructor) && M->isUserProvided()) {
6120         M->setTrivialForCall(HasTrivialABI);
6121         Record->setTrivialForCallFlags(M);
6122       }
6123 
6124       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6125           M->hasAttr<DLLExportAttr>()) {
6126         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6127             M->isTrivial() &&
6128             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6129              CSM == CXXDestructor))
6130           M->dropAttr<DLLExportAttr>();
6131 
6132         if (M->hasAttr<DLLExportAttr>()) {
6133           DefineImplicitSpecialMember(*this, M, M->getLocation());
6134           ActOnFinishInlineFunctionDef(M);
6135         }
6136       }
6137     }
6138   }
6139 
6140   if (HasMethodWithOverrideControl &&
6141       HasOverridingMethodWithoutOverrideControl) {
6142     // At least one method has the 'override' control declared.
6143     // Diagnose all other overridden methods which do not have 'override' specified on them.
6144     for (auto *M : Record->methods())
6145       DiagnoseAbsenceOfOverrideControl(M);
6146   }
6147 
6148   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6149   // whether this class uses any C++ features that are implemented
6150   // completely differently in MSVC, and if so, emit a diagnostic.
6151   // That diagnostic defaults to an error, but we allow projects to
6152   // map it down to a warning (or ignore it).  It's a fairly common
6153   // practice among users of the ms_struct pragma to mass-annotate
6154   // headers, sweeping up a bunch of types that the project doesn't
6155   // really rely on MSVC-compatible layout for.  We must therefore
6156   // support "ms_struct except for C++ stuff" as a secondary ABI.
6157   if (Record->isMsStruct(Context) &&
6158       (Record->isPolymorphic() || Record->getNumBases())) {
6159     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6160   }
6161 
6162   checkClassLevelDLLAttribute(Record);
6163   checkClassLevelCodeSegAttribute(Record);
6164 
6165   bool ClangABICompat4 =
6166       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6167   TargetInfo::CallingConvKind CCK =
6168       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6169   bool CanPass = canPassInRegisters(*this, Record, CCK);
6170 
6171   // Do not change ArgPassingRestrictions if it has already been set to
6172   // APK_CanNeverPassInRegs.
6173   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6174     Record->setArgPassingRestrictions(CanPass
6175                                           ? RecordDecl::APK_CanPassInRegs
6176                                           : RecordDecl::APK_CannotPassInRegs);
6177 
6178   // If canPassInRegisters returns true despite the record having a non-trivial
6179   // destructor, the record is destructed in the callee. This happens only when
6180   // the record or one of its subobjects has a field annotated with trivial_abi
6181   // or a field qualified with ObjC __strong/__weak.
6182   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6183     Record->setParamDestroyedInCallee(true);
6184   else if (Record->hasNonTrivialDestructor())
6185     Record->setParamDestroyedInCallee(CanPass);
6186 
6187   if (getLangOpts().ForceEmitVTables) {
6188     // If we want to emit all the vtables, we need to mark it as used.  This
6189     // is especially required for cases like vtable assumption loads.
6190     MarkVTableUsed(Record->getInnerLocStart(), Record);
6191   }
6192 }
6193 
6194 /// Look up the special member function that would be called by a special
6195 /// member function for a subobject of class type.
6196 ///
6197 /// \param Class The class type of the subobject.
6198 /// \param CSM The kind of special member function.
6199 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6200 /// \param ConstRHS True if this is a copy operation with a const object
6201 ///        on its RHS, that is, if the argument to the outer special member
6202 ///        function is 'const' and this is not a field marked 'mutable'.
6203 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6204     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6205     unsigned FieldQuals, bool ConstRHS) {
6206   unsigned LHSQuals = 0;
6207   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6208     LHSQuals = FieldQuals;
6209 
6210   unsigned RHSQuals = FieldQuals;
6211   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6212     RHSQuals = 0;
6213   else if (ConstRHS)
6214     RHSQuals |= Qualifiers::Const;
6215 
6216   return S.LookupSpecialMember(Class, CSM,
6217                                RHSQuals & Qualifiers::Const,
6218                                RHSQuals & Qualifiers::Volatile,
6219                                false,
6220                                LHSQuals & Qualifiers::Const,
6221                                LHSQuals & Qualifiers::Volatile);
6222 }
6223 
6224 class Sema::InheritedConstructorInfo {
6225   Sema &S;
6226   SourceLocation UseLoc;
6227 
6228   /// A mapping from the base classes through which the constructor was
6229   /// inherited to the using shadow declaration in that base class (or a null
6230   /// pointer if the constructor was declared in that base class).
6231   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6232       InheritedFromBases;
6233 
6234 public:
6235   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6236                            ConstructorUsingShadowDecl *Shadow)
6237       : S(S), UseLoc(UseLoc) {
6238     bool DiagnosedMultipleConstructedBases = false;
6239     CXXRecordDecl *ConstructedBase = nullptr;
6240     UsingDecl *ConstructedBaseUsing = nullptr;
6241 
6242     // Find the set of such base class subobjects and check that there's a
6243     // unique constructed subobject.
6244     for (auto *D : Shadow->redecls()) {
6245       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6246       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6247       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6248 
6249       InheritedFromBases.insert(
6250           std::make_pair(DNominatedBase->getCanonicalDecl(),
6251                          DShadow->getNominatedBaseClassShadowDecl()));
6252       if (DShadow->constructsVirtualBase())
6253         InheritedFromBases.insert(
6254             std::make_pair(DConstructedBase->getCanonicalDecl(),
6255                            DShadow->getConstructedBaseClassShadowDecl()));
6256       else
6257         assert(DNominatedBase == DConstructedBase);
6258 
6259       // [class.inhctor.init]p2:
6260       //   If the constructor was inherited from multiple base class subobjects
6261       //   of type B, the program is ill-formed.
6262       if (!ConstructedBase) {
6263         ConstructedBase = DConstructedBase;
6264         ConstructedBaseUsing = D->getUsingDecl();
6265       } else if (ConstructedBase != DConstructedBase &&
6266                  !Shadow->isInvalidDecl()) {
6267         if (!DiagnosedMultipleConstructedBases) {
6268           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6269               << Shadow->getTargetDecl();
6270           S.Diag(ConstructedBaseUsing->getLocation(),
6271                diag::note_ambiguous_inherited_constructor_using)
6272               << ConstructedBase;
6273           DiagnosedMultipleConstructedBases = true;
6274         }
6275         S.Diag(D->getUsingDecl()->getLocation(),
6276                diag::note_ambiguous_inherited_constructor_using)
6277             << DConstructedBase;
6278       }
6279     }
6280 
6281     if (DiagnosedMultipleConstructedBases)
6282       Shadow->setInvalidDecl();
6283   }
6284 
6285   /// Find the constructor to use for inherited construction of a base class,
6286   /// and whether that base class constructor inherits the constructor from a
6287   /// virtual base class (in which case it won't actually invoke it).
6288   std::pair<CXXConstructorDecl *, bool>
6289   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6290     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6291     if (It == InheritedFromBases.end())
6292       return std::make_pair(nullptr, false);
6293 
6294     // This is an intermediary class.
6295     if (It->second)
6296       return std::make_pair(
6297           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6298           It->second->constructsVirtualBase());
6299 
6300     // This is the base class from which the constructor was inherited.
6301     return std::make_pair(Ctor, false);
6302   }
6303 };
6304 
6305 /// Is the special member function which would be selected to perform the
6306 /// specified operation on the specified class type a constexpr constructor?
6307 static bool
6308 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6309                          Sema::CXXSpecialMember CSM, unsigned Quals,
6310                          bool ConstRHS,
6311                          CXXConstructorDecl *InheritedCtor = nullptr,
6312                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6313   // If we're inheriting a constructor, see if we need to call it for this base
6314   // class.
6315   if (InheritedCtor) {
6316     assert(CSM == Sema::CXXDefaultConstructor);
6317     auto BaseCtor =
6318         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6319     if (BaseCtor)
6320       return BaseCtor->isConstexpr();
6321   }
6322 
6323   if (CSM == Sema::CXXDefaultConstructor)
6324     return ClassDecl->hasConstexprDefaultConstructor();
6325 
6326   Sema::SpecialMemberOverloadResult SMOR =
6327       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6328   if (!SMOR.getMethod())
6329     // A constructor we wouldn't select can't be "involved in initializing"
6330     // anything.
6331     return true;
6332   return SMOR.getMethod()->isConstexpr();
6333 }
6334 
6335 /// Determine whether the specified special member function would be constexpr
6336 /// if it were implicitly defined.
6337 static bool defaultedSpecialMemberIsConstexpr(
6338     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6339     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6340     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6341   if (!S.getLangOpts().CPlusPlus11)
6342     return false;
6343 
6344   // C++11 [dcl.constexpr]p4:
6345   // In the definition of a constexpr constructor [...]
6346   bool Ctor = true;
6347   switch (CSM) {
6348   case Sema::CXXDefaultConstructor:
6349     if (Inherited)
6350       break;
6351     // Since default constructor lookup is essentially trivial (and cannot
6352     // involve, for instance, template instantiation), we compute whether a
6353     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6354     //
6355     // This is important for performance; we need to know whether the default
6356     // constructor is constexpr to determine whether the type is a literal type.
6357     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6358 
6359   case Sema::CXXCopyConstructor:
6360   case Sema::CXXMoveConstructor:
6361     // For copy or move constructors, we need to perform overload resolution.
6362     break;
6363 
6364   case Sema::CXXCopyAssignment:
6365   case Sema::CXXMoveAssignment:
6366     if (!S.getLangOpts().CPlusPlus14)
6367       return false;
6368     // In C++1y, we need to perform overload resolution.
6369     Ctor = false;
6370     break;
6371 
6372   case Sema::CXXDestructor:
6373   case Sema::CXXInvalid:
6374     return false;
6375   }
6376 
6377   //   -- if the class is a non-empty union, or for each non-empty anonymous
6378   //      union member of a non-union class, exactly one non-static data member
6379   //      shall be initialized; [DR1359]
6380   //
6381   // If we squint, this is guaranteed, since exactly one non-static data member
6382   // will be initialized (if the constructor isn't deleted), we just don't know
6383   // which one.
6384   if (Ctor && ClassDecl->isUnion())
6385     return CSM == Sema::CXXDefaultConstructor
6386                ? ClassDecl->hasInClassInitializer() ||
6387                      !ClassDecl->hasVariantMembers()
6388                : true;
6389 
6390   //   -- the class shall not have any virtual base classes;
6391   if (Ctor && ClassDecl->getNumVBases())
6392     return false;
6393 
6394   // C++1y [class.copy]p26:
6395   //   -- [the class] is a literal type, and
6396   if (!Ctor && !ClassDecl->isLiteral())
6397     return false;
6398 
6399   //   -- every constructor involved in initializing [...] base class
6400   //      sub-objects shall be a constexpr constructor;
6401   //   -- the assignment operator selected to copy/move each direct base
6402   //      class is a constexpr function, and
6403   for (const auto &B : ClassDecl->bases()) {
6404     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6405     if (!BaseType) continue;
6406 
6407     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6408     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6409                                   InheritedCtor, Inherited))
6410       return false;
6411   }
6412 
6413   //   -- every constructor involved in initializing non-static data members
6414   //      [...] shall be a constexpr constructor;
6415   //   -- every non-static data member and base class sub-object shall be
6416   //      initialized
6417   //   -- for each non-static data member of X that is of class type (or array
6418   //      thereof), the assignment operator selected to copy/move that member is
6419   //      a constexpr function
6420   for (const auto *F : ClassDecl->fields()) {
6421     if (F->isInvalidDecl())
6422       continue;
6423     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6424       continue;
6425     QualType BaseType = S.Context.getBaseElementType(F->getType());
6426     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6427       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6428       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6429                                     BaseType.getCVRQualifiers(),
6430                                     ConstArg && !F->isMutable()))
6431         return false;
6432     } else if (CSM == Sema::CXXDefaultConstructor) {
6433       return false;
6434     }
6435   }
6436 
6437   // All OK, it's constexpr!
6438   return true;
6439 }
6440 
6441 static Sema::ImplicitExceptionSpecification
6442 ComputeDefaultedSpecialMemberExceptionSpec(
6443     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6444     Sema::InheritedConstructorInfo *ICI);
6445 
6446 static Sema::ImplicitExceptionSpecification
6447 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6448   auto CSM = S.getSpecialMember(MD);
6449   if (CSM != Sema::CXXInvalid)
6450     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6451 
6452   auto *CD = cast<CXXConstructorDecl>(MD);
6453   assert(CD->getInheritedConstructor() &&
6454          "only special members have implicit exception specs");
6455   Sema::InheritedConstructorInfo ICI(
6456       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6457   return ComputeDefaultedSpecialMemberExceptionSpec(
6458       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6459 }
6460 
6461 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6462                                                             CXXMethodDecl *MD) {
6463   FunctionProtoType::ExtProtoInfo EPI;
6464 
6465   // Build an exception specification pointing back at this member.
6466   EPI.ExceptionSpec.Type = EST_Unevaluated;
6467   EPI.ExceptionSpec.SourceDecl = MD;
6468 
6469   // Set the calling convention to the default for C++ instance methods.
6470   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6471       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6472                                             /*IsCXXMethod=*/true));
6473   return EPI;
6474 }
6475 
6476 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6477   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6478   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6479     return;
6480 
6481   // Evaluate the exception specification.
6482   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6483   auto ESI = IES.getExceptionSpec();
6484 
6485   // Update the type of the special member to use it.
6486   UpdateExceptionSpec(MD, ESI);
6487 
6488   // A user-provided destructor can be defined outside the class. When that
6489   // happens, be sure to update the exception specification on both
6490   // declarations.
6491   const FunctionProtoType *CanonicalFPT =
6492     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6493   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6494     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6495 }
6496 
6497 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6498   CXXRecordDecl *RD = MD->getParent();
6499   CXXSpecialMember CSM = getSpecialMember(MD);
6500 
6501   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6502          "not an explicitly-defaulted special member");
6503 
6504   // Whether this was the first-declared instance of the constructor.
6505   // This affects whether we implicitly add an exception spec and constexpr.
6506   bool First = MD == MD->getCanonicalDecl();
6507 
6508   bool HadError = false;
6509 
6510   // C++11 [dcl.fct.def.default]p1:
6511   //   A function that is explicitly defaulted shall
6512   //     -- be a special member function (checked elsewhere),
6513   //     -- have the same type (except for ref-qualifiers, and except that a
6514   //        copy operation can take a non-const reference) as an implicit
6515   //        declaration, and
6516   //     -- not have default arguments.
6517   // C++2a changes the second bullet to instead delete the function if it's
6518   // defaulted on its first declaration, unless it's "an assignment operator,
6519   // and its return type differs or its parameter type is not a reference".
6520   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6521   bool ShouldDeleteForTypeMismatch = false;
6522   unsigned ExpectedParams = 1;
6523   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6524     ExpectedParams = 0;
6525   if (MD->getNumParams() != ExpectedParams) {
6526     // This checks for default arguments: a copy or move constructor with a
6527     // default argument is classified as a default constructor, and assignment
6528     // operations and destructors can't have default arguments.
6529     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6530       << CSM << MD->getSourceRange();
6531     HadError = true;
6532   } else if (MD->isVariadic()) {
6533     if (DeleteOnTypeMismatch)
6534       ShouldDeleteForTypeMismatch = true;
6535     else {
6536       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6537         << CSM << MD->getSourceRange();
6538       HadError = true;
6539     }
6540   }
6541 
6542   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6543 
6544   bool CanHaveConstParam = false;
6545   if (CSM == CXXCopyConstructor)
6546     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6547   else if (CSM == CXXCopyAssignment)
6548     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6549 
6550   QualType ReturnType = Context.VoidTy;
6551   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6552     // Check for return type matching.
6553     ReturnType = Type->getReturnType();
6554 
6555     QualType DeclType = Context.getTypeDeclType(RD);
6556     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6557     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6558 
6559     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6560       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6561         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6562       HadError = true;
6563     }
6564 
6565     // A defaulted special member cannot have cv-qualifiers.
6566     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6567       if (DeleteOnTypeMismatch)
6568         ShouldDeleteForTypeMismatch = true;
6569       else {
6570         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6571           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6572         HadError = true;
6573       }
6574     }
6575   }
6576 
6577   // Check for parameter type matching.
6578   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6579   bool HasConstParam = false;
6580   if (ExpectedParams && ArgType->isReferenceType()) {
6581     // Argument must be reference to possibly-const T.
6582     QualType ReferentType = ArgType->getPointeeType();
6583     HasConstParam = ReferentType.isConstQualified();
6584 
6585     if (ReferentType.isVolatileQualified()) {
6586       if (DeleteOnTypeMismatch)
6587         ShouldDeleteForTypeMismatch = true;
6588       else {
6589         Diag(MD->getLocation(),
6590              diag::err_defaulted_special_member_volatile_param) << CSM;
6591         HadError = true;
6592       }
6593     }
6594 
6595     if (HasConstParam && !CanHaveConstParam) {
6596       if (DeleteOnTypeMismatch)
6597         ShouldDeleteForTypeMismatch = true;
6598       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6599         Diag(MD->getLocation(),
6600              diag::err_defaulted_special_member_copy_const_param)
6601           << (CSM == CXXCopyAssignment);
6602         // FIXME: Explain why this special member can't be const.
6603         HadError = true;
6604       } else {
6605         Diag(MD->getLocation(),
6606              diag::err_defaulted_special_member_move_const_param)
6607           << (CSM == CXXMoveAssignment);
6608         HadError = true;
6609       }
6610     }
6611   } else if (ExpectedParams) {
6612     // A copy assignment operator can take its argument by value, but a
6613     // defaulted one cannot.
6614     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6615     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6616     HadError = true;
6617   }
6618 
6619   // C++11 [dcl.fct.def.default]p2:
6620   //   An explicitly-defaulted function may be declared constexpr only if it
6621   //   would have been implicitly declared as constexpr,
6622   // Do not apply this rule to members of class templates, since core issue 1358
6623   // makes such functions always instantiate to constexpr functions. For
6624   // functions which cannot be constexpr (for non-constructors in C++11 and for
6625   // destructors in C++1y), this is checked elsewhere.
6626   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6627                                                      HasConstParam);
6628   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6629                                  : isa<CXXConstructorDecl>(MD)) &&
6630       MD->isConstexpr() && !Constexpr &&
6631       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6632     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6633     // FIXME: Explain why the special member can't be constexpr.
6634     HadError = true;
6635   }
6636 
6637   //   and may have an explicit exception-specification only if it is compatible
6638   //   with the exception-specification on the implicit declaration.
6639   if (Type->hasExceptionSpec()) {
6640     // Delay the check if this is the first declaration of the special member,
6641     // since we may not have parsed some necessary in-class initializers yet.
6642     if (First) {
6643       // If the exception specification needs to be instantiated, do so now,
6644       // before we clobber it with an EST_Unevaluated specification below.
6645       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6646         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6647         Type = MD->getType()->getAs<FunctionProtoType>();
6648       }
6649       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6650     } else
6651       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6652   }
6653 
6654   //   If a function is explicitly defaulted on its first declaration,
6655   if (First) {
6656     //  -- it is implicitly considered to be constexpr if the implicit
6657     //     definition would be,
6658     MD->setConstexpr(Constexpr);
6659 
6660     //  -- it is implicitly considered to have the same exception-specification
6661     //     as if it had been implicitly declared,
6662     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6663     EPI.ExceptionSpec.Type = EST_Unevaluated;
6664     EPI.ExceptionSpec.SourceDecl = MD;
6665     MD->setType(Context.getFunctionType(ReturnType,
6666                                         llvm::makeArrayRef(&ArgType,
6667                                                            ExpectedParams),
6668                                         EPI));
6669   }
6670 
6671   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6672     if (First) {
6673       SetDeclDeleted(MD, MD->getLocation());
6674       if (!inTemplateInstantiation() && !HadError) {
6675         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6676         if (ShouldDeleteForTypeMismatch) {
6677           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6678         } else {
6679           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6680         }
6681       }
6682       if (ShouldDeleteForTypeMismatch && !HadError) {
6683         Diag(MD->getLocation(),
6684              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6685       }
6686     } else {
6687       // C++11 [dcl.fct.def.default]p4:
6688       //   [For a] user-provided explicitly-defaulted function [...] if such a
6689       //   function is implicitly defined as deleted, the program is ill-formed.
6690       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6691       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6692       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6693       HadError = true;
6694     }
6695   }
6696 
6697   if (HadError)
6698     MD->setInvalidDecl();
6699 }
6700 
6701 /// Check whether the exception specification provided for an
6702 /// explicitly-defaulted special member matches the exception specification
6703 /// that would have been generated for an implicit special member, per
6704 /// C++11 [dcl.fct.def.default]p2.
6705 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6706     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6707   // If the exception specification was explicitly specified but hadn't been
6708   // parsed when the method was defaulted, grab it now.
6709   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6710     SpecifiedType =
6711         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6712 
6713   // Compute the implicit exception specification.
6714   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6715                                                        /*IsCXXMethod=*/true);
6716   FunctionProtoType::ExtProtoInfo EPI(CC);
6717   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6718   EPI.ExceptionSpec = IES.getExceptionSpec();
6719   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6720     Context.getFunctionType(Context.VoidTy, None, EPI));
6721 
6722   // Ensure that it matches.
6723   CheckEquivalentExceptionSpec(
6724     PDiag(diag::err_incorrect_defaulted_exception_spec)
6725       << getSpecialMember(MD), PDiag(),
6726     ImplicitType, SourceLocation(),
6727     SpecifiedType, MD->getLocation());
6728 }
6729 
6730 void Sema::CheckDelayedMemberExceptionSpecs() {
6731   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6732   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6733   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6734 
6735   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6736   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6737   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6738 
6739   // Perform any deferred checking of exception specifications for virtual
6740   // destructors.
6741   for (auto &Check : Overriding)
6742     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6743 
6744   // Perform any deferred checking of exception specifications for befriended
6745   // special members.
6746   for (auto &Check : Equivalent)
6747     CheckEquivalentExceptionSpec(Check.second, Check.first);
6748 
6749   // Check that any explicitly-defaulted methods have exception specifications
6750   // compatible with their implicit exception specifications.
6751   for (auto &Spec : Defaulted)
6752     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6753 }
6754 
6755 namespace {
6756 /// CRTP base class for visiting operations performed by a special member
6757 /// function (or inherited constructor).
6758 template<typename Derived>
6759 struct SpecialMemberVisitor {
6760   Sema &S;
6761   CXXMethodDecl *MD;
6762   Sema::CXXSpecialMember CSM;
6763   Sema::InheritedConstructorInfo *ICI;
6764 
6765   // Properties of the special member, computed for convenience.
6766   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6767 
6768   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6769                        Sema::InheritedConstructorInfo *ICI)
6770       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6771     switch (CSM) {
6772     case Sema::CXXDefaultConstructor:
6773     case Sema::CXXCopyConstructor:
6774     case Sema::CXXMoveConstructor:
6775       IsConstructor = true;
6776       break;
6777     case Sema::CXXCopyAssignment:
6778     case Sema::CXXMoveAssignment:
6779       IsAssignment = true;
6780       break;
6781     case Sema::CXXDestructor:
6782       break;
6783     case Sema::CXXInvalid:
6784       llvm_unreachable("invalid special member kind");
6785     }
6786 
6787     if (MD->getNumParams()) {
6788       if (const ReferenceType *RT =
6789               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6790         ConstArg = RT->getPointeeType().isConstQualified();
6791     }
6792   }
6793 
6794   Derived &getDerived() { return static_cast<Derived&>(*this); }
6795 
6796   /// Is this a "move" special member?
6797   bool isMove() const {
6798     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6799   }
6800 
6801   /// Look up the corresponding special member in the given class.
6802   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6803                                              unsigned Quals, bool IsMutable) {
6804     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6805                                        ConstArg && !IsMutable);
6806   }
6807 
6808   /// Look up the constructor for the specified base class to see if it's
6809   /// overridden due to this being an inherited constructor.
6810   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6811     if (!ICI)
6812       return {};
6813     assert(CSM == Sema::CXXDefaultConstructor);
6814     auto *BaseCtor =
6815       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6816     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6817       return MD;
6818     return {};
6819   }
6820 
6821   /// A base or member subobject.
6822   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6823 
6824   /// Get the location to use for a subobject in diagnostics.
6825   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6826     // FIXME: For an indirect virtual base, the direct base leading to
6827     // the indirect virtual base would be a more useful choice.
6828     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6829       return B->getBaseTypeLoc();
6830     else
6831       return Subobj.get<FieldDecl*>()->getLocation();
6832   }
6833 
6834   enum BasesToVisit {
6835     /// Visit all non-virtual (direct) bases.
6836     VisitNonVirtualBases,
6837     /// Visit all direct bases, virtual or not.
6838     VisitDirectBases,
6839     /// Visit all non-virtual bases, and all virtual bases if the class
6840     /// is not abstract.
6841     VisitPotentiallyConstructedBases,
6842     /// Visit all direct or virtual bases.
6843     VisitAllBases
6844   };
6845 
6846   // Visit the bases and members of the class.
6847   bool visit(BasesToVisit Bases) {
6848     CXXRecordDecl *RD = MD->getParent();
6849 
6850     if (Bases == VisitPotentiallyConstructedBases)
6851       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6852 
6853     for (auto &B : RD->bases())
6854       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6855           getDerived().visitBase(&B))
6856         return true;
6857 
6858     if (Bases == VisitAllBases)
6859       for (auto &B : RD->vbases())
6860         if (getDerived().visitBase(&B))
6861           return true;
6862 
6863     for (auto *F : RD->fields())
6864       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6865           getDerived().visitField(F))
6866         return true;
6867 
6868     return false;
6869   }
6870 };
6871 }
6872 
6873 namespace {
6874 struct SpecialMemberDeletionInfo
6875     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6876   bool Diagnose;
6877 
6878   SourceLocation Loc;
6879 
6880   bool AllFieldsAreConst;
6881 
6882   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6883                             Sema::CXXSpecialMember CSM,
6884                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6885       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6886         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6887 
6888   bool inUnion() const { return MD->getParent()->isUnion(); }
6889 
6890   Sema::CXXSpecialMember getEffectiveCSM() {
6891     return ICI ? Sema::CXXInvalid : CSM;
6892   }
6893 
6894   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6895 
6896   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6897   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6898 
6899   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6900   bool shouldDeleteForField(FieldDecl *FD);
6901   bool shouldDeleteForAllConstMembers();
6902 
6903   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6904                                      unsigned Quals);
6905   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6906                                     Sema::SpecialMemberOverloadResult SMOR,
6907                                     bool IsDtorCallInCtor);
6908 
6909   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6910 };
6911 }
6912 
6913 /// Is the given special member inaccessible when used on the given
6914 /// sub-object.
6915 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6916                                              CXXMethodDecl *target) {
6917   /// If we're operating on a base class, the object type is the
6918   /// type of this special member.
6919   QualType objectTy;
6920   AccessSpecifier access = target->getAccess();
6921   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6922     objectTy = S.Context.getTypeDeclType(MD->getParent());
6923     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6924 
6925   // If we're operating on a field, the object type is the type of the field.
6926   } else {
6927     objectTy = S.Context.getTypeDeclType(target->getParent());
6928   }
6929 
6930   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6931 }
6932 
6933 /// Check whether we should delete a special member due to the implicit
6934 /// definition containing a call to a special member of a subobject.
6935 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6936     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6937     bool IsDtorCallInCtor) {
6938   CXXMethodDecl *Decl = SMOR.getMethod();
6939   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6940 
6941   int DiagKind = -1;
6942 
6943   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6944     DiagKind = !Decl ? 0 : 1;
6945   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6946     DiagKind = 2;
6947   else if (!isAccessible(Subobj, Decl))
6948     DiagKind = 3;
6949   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6950            !Decl->isTrivial()) {
6951     // A member of a union must have a trivial corresponding special member.
6952     // As a weird special case, a destructor call from a union's constructor
6953     // must be accessible and non-deleted, but need not be trivial. Such a
6954     // destructor is never actually called, but is semantically checked as
6955     // if it were.
6956     DiagKind = 4;
6957   }
6958 
6959   if (DiagKind == -1)
6960     return false;
6961 
6962   if (Diagnose) {
6963     if (Field) {
6964       S.Diag(Field->getLocation(),
6965              diag::note_deleted_special_member_class_subobject)
6966         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6967         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6968     } else {
6969       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6970       S.Diag(Base->getBeginLoc(),
6971              diag::note_deleted_special_member_class_subobject)
6972           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6973           << Base->getType() << DiagKind << IsDtorCallInCtor
6974           << /*IsObjCPtr*/false;
6975     }
6976 
6977     if (DiagKind == 1)
6978       S.NoteDeletedFunction(Decl);
6979     // FIXME: Explain inaccessibility if DiagKind == 3.
6980   }
6981 
6982   return true;
6983 }
6984 
6985 /// Check whether we should delete a special member function due to having a
6986 /// direct or virtual base class or non-static data member of class type M.
6987 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6988     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6989   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6990   bool IsMutable = Field && Field->isMutable();
6991 
6992   // C++11 [class.ctor]p5:
6993   // -- any direct or virtual base class, or non-static data member with no
6994   //    brace-or-equal-initializer, has class type M (or array thereof) and
6995   //    either M has no default constructor or overload resolution as applied
6996   //    to M's default constructor results in an ambiguity or in a function
6997   //    that is deleted or inaccessible
6998   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6999   // -- a direct or virtual base class B that cannot be copied/moved because
7000   //    overload resolution, as applied to B's corresponding special member,
7001   //    results in an ambiguity or a function that is deleted or inaccessible
7002   //    from the defaulted special member
7003   // C++11 [class.dtor]p5:
7004   // -- any direct or virtual base class [...] has a type with a destructor
7005   //    that is deleted or inaccessible
7006   if (!(CSM == Sema::CXXDefaultConstructor &&
7007         Field && Field->hasInClassInitializer()) &&
7008       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7009                                    false))
7010     return true;
7011 
7012   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7013   // -- any direct or virtual base class or non-static data member has a
7014   //    type with a destructor that is deleted or inaccessible
7015   if (IsConstructor) {
7016     Sema::SpecialMemberOverloadResult SMOR =
7017         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7018                               false, false, false, false, false);
7019     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7020       return true;
7021   }
7022 
7023   return false;
7024 }
7025 
7026 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7027     FieldDecl *FD, QualType FieldType) {
7028   // The defaulted special functions are defined as deleted if this is a variant
7029   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7030   // type under ARC.
7031   if (!FieldType.hasNonTrivialObjCLifetime())
7032     return false;
7033 
7034   // Don't make the defaulted default constructor defined as deleted if the
7035   // member has an in-class initializer.
7036   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7037     return false;
7038 
7039   if (Diagnose) {
7040     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7041     S.Diag(FD->getLocation(),
7042            diag::note_deleted_special_member_class_subobject)
7043         << getEffectiveCSM() << ParentClass << /*IsField*/true
7044         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7045   }
7046 
7047   return true;
7048 }
7049 
7050 /// Check whether we should delete a special member function due to the class
7051 /// having a particular direct or virtual base class.
7052 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7053   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7054   // If program is correct, BaseClass cannot be null, but if it is, the error
7055   // must be reported elsewhere.
7056   if (!BaseClass)
7057     return false;
7058   // If we have an inheriting constructor, check whether we're calling an
7059   // inherited constructor instead of a default constructor.
7060   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7061   if (auto *BaseCtor = SMOR.getMethod()) {
7062     // Note that we do not check access along this path; other than that,
7063     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7064     // FIXME: Check that the base has a usable destructor! Sink this into
7065     // shouldDeleteForClassSubobject.
7066     if (BaseCtor->isDeleted() && Diagnose) {
7067       S.Diag(Base->getBeginLoc(),
7068              diag::note_deleted_special_member_class_subobject)
7069           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7070           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7071           << /*IsObjCPtr*/false;
7072       S.NoteDeletedFunction(BaseCtor);
7073     }
7074     return BaseCtor->isDeleted();
7075   }
7076   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7077 }
7078 
7079 /// Check whether we should delete a special member function due to the class
7080 /// having a particular non-static data member.
7081 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7082   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7083   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7084 
7085   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7086     return true;
7087 
7088   if (CSM == Sema::CXXDefaultConstructor) {
7089     // For a default constructor, all references must be initialized in-class
7090     // and, if a union, it must have a non-const member.
7091     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7092       if (Diagnose)
7093         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7094           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7095       return true;
7096     }
7097     // C++11 [class.ctor]p5: any non-variant non-static data member of
7098     // const-qualified type (or array thereof) with no
7099     // brace-or-equal-initializer does not have a user-provided default
7100     // constructor.
7101     if (!inUnion() && FieldType.isConstQualified() &&
7102         !FD->hasInClassInitializer() &&
7103         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7104       if (Diagnose)
7105         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7106           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7107       return true;
7108     }
7109 
7110     if (inUnion() && !FieldType.isConstQualified())
7111       AllFieldsAreConst = false;
7112   } else if (CSM == Sema::CXXCopyConstructor) {
7113     // For a copy constructor, data members must not be of rvalue reference
7114     // type.
7115     if (FieldType->isRValueReferenceType()) {
7116       if (Diagnose)
7117         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7118           << MD->getParent() << FD << FieldType;
7119       return true;
7120     }
7121   } else if (IsAssignment) {
7122     // For an assignment operator, data members must not be of reference type.
7123     if (FieldType->isReferenceType()) {
7124       if (Diagnose)
7125         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7126           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7127       return true;
7128     }
7129     if (!FieldRecord && FieldType.isConstQualified()) {
7130       // C++11 [class.copy]p23:
7131       // -- a non-static data member of const non-class type (or array thereof)
7132       if (Diagnose)
7133         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7134           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7135       return true;
7136     }
7137   }
7138 
7139   if (FieldRecord) {
7140     // Some additional restrictions exist on the variant members.
7141     if (!inUnion() && FieldRecord->isUnion() &&
7142         FieldRecord->isAnonymousStructOrUnion()) {
7143       bool AllVariantFieldsAreConst = true;
7144 
7145       // FIXME: Handle anonymous unions declared within anonymous unions.
7146       for (auto *UI : FieldRecord->fields()) {
7147         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7148 
7149         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7150           return true;
7151 
7152         if (!UnionFieldType.isConstQualified())
7153           AllVariantFieldsAreConst = false;
7154 
7155         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7156         if (UnionFieldRecord &&
7157             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7158                                           UnionFieldType.getCVRQualifiers()))
7159           return true;
7160       }
7161 
7162       // At least one member in each anonymous union must be non-const
7163       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7164           !FieldRecord->field_empty()) {
7165         if (Diagnose)
7166           S.Diag(FieldRecord->getLocation(),
7167                  diag::note_deleted_default_ctor_all_const)
7168             << !!ICI << MD->getParent() << /*anonymous union*/1;
7169         return true;
7170       }
7171 
7172       // Don't check the implicit member of the anonymous union type.
7173       // This is technically non-conformant, but sanity demands it.
7174       return false;
7175     }
7176 
7177     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7178                                       FieldType.getCVRQualifiers()))
7179       return true;
7180   }
7181 
7182   return false;
7183 }
7184 
7185 /// C++11 [class.ctor] p5:
7186 ///   A defaulted default constructor for a class X is defined as deleted if
7187 /// X is a union and all of its variant members are of const-qualified type.
7188 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7189   // This is a silly definition, because it gives an empty union a deleted
7190   // default constructor. Don't do that.
7191   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7192     bool AnyFields = false;
7193     for (auto *F : MD->getParent()->fields())
7194       if ((AnyFields = !F->isUnnamedBitfield()))
7195         break;
7196     if (!AnyFields)
7197       return false;
7198     if (Diagnose)
7199       S.Diag(MD->getParent()->getLocation(),
7200              diag::note_deleted_default_ctor_all_const)
7201         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7202     return true;
7203   }
7204   return false;
7205 }
7206 
7207 /// Determine whether a defaulted special member function should be defined as
7208 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7209 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7210 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7211                                      InheritedConstructorInfo *ICI,
7212                                      bool Diagnose) {
7213   if (MD->isInvalidDecl())
7214     return false;
7215   CXXRecordDecl *RD = MD->getParent();
7216   assert(!RD->isDependentType() && "do deletion after instantiation");
7217   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7218     return false;
7219 
7220   // C++11 [expr.lambda.prim]p19:
7221   //   The closure type associated with a lambda-expression has a
7222   //   deleted (8.4.3) default constructor and a deleted copy
7223   //   assignment operator.
7224   // C++2a adds back these operators if the lambda has no capture-default.
7225   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7226       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7227     if (Diagnose)
7228       Diag(RD->getLocation(), diag::note_lambda_decl);
7229     return true;
7230   }
7231 
7232   // For an anonymous struct or union, the copy and assignment special members
7233   // will never be used, so skip the check. For an anonymous union declared at
7234   // namespace scope, the constructor and destructor are used.
7235   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7236       RD->isAnonymousStructOrUnion())
7237     return false;
7238 
7239   // C++11 [class.copy]p7, p18:
7240   //   If the class definition declares a move constructor or move assignment
7241   //   operator, an implicitly declared copy constructor or copy assignment
7242   //   operator is defined as deleted.
7243   if (MD->isImplicit() &&
7244       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7245     CXXMethodDecl *UserDeclaredMove = nullptr;
7246 
7247     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7248     // deletion of the corresponding copy operation, not both copy operations.
7249     // MSVC 2015 has adopted the standards conforming behavior.
7250     bool DeletesOnlyMatchingCopy =
7251         getLangOpts().MSVCCompat &&
7252         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7253 
7254     if (RD->hasUserDeclaredMoveConstructor() &&
7255         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7256       if (!Diagnose) return true;
7257 
7258       // Find any user-declared move constructor.
7259       for (auto *I : RD->ctors()) {
7260         if (I->isMoveConstructor()) {
7261           UserDeclaredMove = I;
7262           break;
7263         }
7264       }
7265       assert(UserDeclaredMove);
7266     } else if (RD->hasUserDeclaredMoveAssignment() &&
7267                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7268       if (!Diagnose) return true;
7269 
7270       // Find any user-declared move assignment operator.
7271       for (auto *I : RD->methods()) {
7272         if (I->isMoveAssignmentOperator()) {
7273           UserDeclaredMove = I;
7274           break;
7275         }
7276       }
7277       assert(UserDeclaredMove);
7278     }
7279 
7280     if (UserDeclaredMove) {
7281       Diag(UserDeclaredMove->getLocation(),
7282            diag::note_deleted_copy_user_declared_move)
7283         << (CSM == CXXCopyAssignment) << RD
7284         << UserDeclaredMove->isMoveAssignmentOperator();
7285       return true;
7286     }
7287   }
7288 
7289   // Do access control from the special member function
7290   ContextRAII MethodContext(*this, MD);
7291 
7292   // C++11 [class.dtor]p5:
7293   // -- for a virtual destructor, lookup of the non-array deallocation function
7294   //    results in an ambiguity or in a function that is deleted or inaccessible
7295   if (CSM == CXXDestructor && MD->isVirtual()) {
7296     FunctionDecl *OperatorDelete = nullptr;
7297     DeclarationName Name =
7298       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7299     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7300                                  OperatorDelete, /*Diagnose*/false)) {
7301       if (Diagnose)
7302         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7303       return true;
7304     }
7305   }
7306 
7307   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7308 
7309   // Per DR1611, do not consider virtual bases of constructors of abstract
7310   // classes, since we are not going to construct them.
7311   // Per DR1658, do not consider virtual bases of destructors of abstract
7312   // classes either.
7313   // Per DR2180, for assignment operators we only assign (and thus only
7314   // consider) direct bases.
7315   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7316                                  : SMI.VisitPotentiallyConstructedBases))
7317     return true;
7318 
7319   if (SMI.shouldDeleteForAllConstMembers())
7320     return true;
7321 
7322   if (getLangOpts().CUDA) {
7323     // We should delete the special member in CUDA mode if target inference
7324     // failed.
7325     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7326     // is treated as certain special member, which may not reflect what special
7327     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7328     // expects CSM to match MD, therefore recalculate CSM.
7329     assert(ICI || CSM == getSpecialMember(MD));
7330     auto RealCSM = CSM;
7331     if (ICI)
7332       RealCSM = getSpecialMember(MD);
7333 
7334     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7335                                                    SMI.ConstArg, Diagnose);
7336   }
7337 
7338   return false;
7339 }
7340 
7341 /// Perform lookup for a special member of the specified kind, and determine
7342 /// whether it is trivial. If the triviality can be determined without the
7343 /// lookup, skip it. This is intended for use when determining whether a
7344 /// special member of a containing object is trivial, and thus does not ever
7345 /// perform overload resolution for default constructors.
7346 ///
7347 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7348 /// member that was most likely to be intended to be trivial, if any.
7349 ///
7350 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7351 /// determine whether the special member is trivial.
7352 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7353                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7354                                      bool ConstRHS,
7355                                      Sema::TrivialABIHandling TAH,
7356                                      CXXMethodDecl **Selected) {
7357   if (Selected)
7358     *Selected = nullptr;
7359 
7360   switch (CSM) {
7361   case Sema::CXXInvalid:
7362     llvm_unreachable("not a special member");
7363 
7364   case Sema::CXXDefaultConstructor:
7365     // C++11 [class.ctor]p5:
7366     //   A default constructor is trivial if:
7367     //    - all the [direct subobjects] have trivial default constructors
7368     //
7369     // Note, no overload resolution is performed in this case.
7370     if (RD->hasTrivialDefaultConstructor())
7371       return true;
7372 
7373     if (Selected) {
7374       // If there's a default constructor which could have been trivial, dig it
7375       // out. Otherwise, if there's any user-provided default constructor, point
7376       // to that as an example of why there's not a trivial one.
7377       CXXConstructorDecl *DefCtor = nullptr;
7378       if (RD->needsImplicitDefaultConstructor())
7379         S.DeclareImplicitDefaultConstructor(RD);
7380       for (auto *CI : RD->ctors()) {
7381         if (!CI->isDefaultConstructor())
7382           continue;
7383         DefCtor = CI;
7384         if (!DefCtor->isUserProvided())
7385           break;
7386       }
7387 
7388       *Selected = DefCtor;
7389     }
7390 
7391     return false;
7392 
7393   case Sema::CXXDestructor:
7394     // C++11 [class.dtor]p5:
7395     //   A destructor is trivial if:
7396     //    - all the direct [subobjects] have trivial destructors
7397     if (RD->hasTrivialDestructor() ||
7398         (TAH == Sema::TAH_ConsiderTrivialABI &&
7399          RD->hasTrivialDestructorForCall()))
7400       return true;
7401 
7402     if (Selected) {
7403       if (RD->needsImplicitDestructor())
7404         S.DeclareImplicitDestructor(RD);
7405       *Selected = RD->getDestructor();
7406     }
7407 
7408     return false;
7409 
7410   case Sema::CXXCopyConstructor:
7411     // C++11 [class.copy]p12:
7412     //   A copy constructor is trivial if:
7413     //    - the constructor selected to copy each direct [subobject] is trivial
7414     if (RD->hasTrivialCopyConstructor() ||
7415         (TAH == Sema::TAH_ConsiderTrivialABI &&
7416          RD->hasTrivialCopyConstructorForCall())) {
7417       if (Quals == Qualifiers::Const)
7418         // We must either select the trivial copy constructor or reach an
7419         // ambiguity; no need to actually perform overload resolution.
7420         return true;
7421     } else if (!Selected) {
7422       return false;
7423     }
7424     // In C++98, we are not supposed to perform overload resolution here, but we
7425     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7426     // cases like B as having a non-trivial copy constructor:
7427     //   struct A { template<typename T> A(T&); };
7428     //   struct B { mutable A a; };
7429     goto NeedOverloadResolution;
7430 
7431   case Sema::CXXCopyAssignment:
7432     // C++11 [class.copy]p25:
7433     //   A copy assignment operator is trivial if:
7434     //    - the assignment operator selected to copy each direct [subobject] is
7435     //      trivial
7436     if (RD->hasTrivialCopyAssignment()) {
7437       if (Quals == Qualifiers::Const)
7438         return true;
7439     } else if (!Selected) {
7440       return false;
7441     }
7442     // In C++98, we are not supposed to perform overload resolution here, but we
7443     // treat that as a language defect.
7444     goto NeedOverloadResolution;
7445 
7446   case Sema::CXXMoveConstructor:
7447   case Sema::CXXMoveAssignment:
7448   NeedOverloadResolution:
7449     Sema::SpecialMemberOverloadResult SMOR =
7450         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7451 
7452     // The standard doesn't describe how to behave if the lookup is ambiguous.
7453     // We treat it as not making the member non-trivial, just like the standard
7454     // mandates for the default constructor. This should rarely matter, because
7455     // the member will also be deleted.
7456     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7457       return true;
7458 
7459     if (!SMOR.getMethod()) {
7460       assert(SMOR.getKind() ==
7461              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7462       return false;
7463     }
7464 
7465     // We deliberately don't check if we found a deleted special member. We're
7466     // not supposed to!
7467     if (Selected)
7468       *Selected = SMOR.getMethod();
7469 
7470     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7471         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7472       return SMOR.getMethod()->isTrivialForCall();
7473     return SMOR.getMethod()->isTrivial();
7474   }
7475 
7476   llvm_unreachable("unknown special method kind");
7477 }
7478 
7479 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7480   for (auto *CI : RD->ctors())
7481     if (!CI->isImplicit())
7482       return CI;
7483 
7484   // Look for constructor templates.
7485   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7486   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7487     if (CXXConstructorDecl *CD =
7488           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7489       return CD;
7490   }
7491 
7492   return nullptr;
7493 }
7494 
7495 /// The kind of subobject we are checking for triviality. The values of this
7496 /// enumeration are used in diagnostics.
7497 enum TrivialSubobjectKind {
7498   /// The subobject is a base class.
7499   TSK_BaseClass,
7500   /// The subobject is a non-static data member.
7501   TSK_Field,
7502   /// The object is actually the complete object.
7503   TSK_CompleteObject
7504 };
7505 
7506 /// Check whether the special member selected for a given type would be trivial.
7507 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7508                                       QualType SubType, bool ConstRHS,
7509                                       Sema::CXXSpecialMember CSM,
7510                                       TrivialSubobjectKind Kind,
7511                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7512   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7513   if (!SubRD)
7514     return true;
7515 
7516   CXXMethodDecl *Selected;
7517   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7518                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7519     return true;
7520 
7521   if (Diagnose) {
7522     if (ConstRHS)
7523       SubType.addConst();
7524 
7525     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7526       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7527         << Kind << SubType.getUnqualifiedType();
7528       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7529         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7530     } else if (!Selected)
7531       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7532         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7533     else if (Selected->isUserProvided()) {
7534       if (Kind == TSK_CompleteObject)
7535         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7536           << Kind << SubType.getUnqualifiedType() << CSM;
7537       else {
7538         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7539           << Kind << SubType.getUnqualifiedType() << CSM;
7540         S.Diag(Selected->getLocation(), diag::note_declared_at);
7541       }
7542     } else {
7543       if (Kind != TSK_CompleteObject)
7544         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7545           << Kind << SubType.getUnqualifiedType() << CSM;
7546 
7547       // Explain why the defaulted or deleted special member isn't trivial.
7548       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7549                                Diagnose);
7550     }
7551   }
7552 
7553   return false;
7554 }
7555 
7556 /// Check whether the members of a class type allow a special member to be
7557 /// trivial.
7558 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7559                                      Sema::CXXSpecialMember CSM,
7560                                      bool ConstArg,
7561                                      Sema::TrivialABIHandling TAH,
7562                                      bool Diagnose) {
7563   for (const auto *FI : RD->fields()) {
7564     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7565       continue;
7566 
7567     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7568 
7569     // Pretend anonymous struct or union members are members of this class.
7570     if (FI->isAnonymousStructOrUnion()) {
7571       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7572                                     CSM, ConstArg, TAH, Diagnose))
7573         return false;
7574       continue;
7575     }
7576 
7577     // C++11 [class.ctor]p5:
7578     //   A default constructor is trivial if [...]
7579     //    -- no non-static data member of its class has a
7580     //       brace-or-equal-initializer
7581     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7582       if (Diagnose)
7583         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7584       return false;
7585     }
7586 
7587     // Objective C ARC 4.3.5:
7588     //   [...] nontrivally ownership-qualified types are [...] not trivially
7589     //   default constructible, copy constructible, move constructible, copy
7590     //   assignable, move assignable, or destructible [...]
7591     if (FieldType.hasNonTrivialObjCLifetime()) {
7592       if (Diagnose)
7593         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7594           << RD << FieldType.getObjCLifetime();
7595       return false;
7596     }
7597 
7598     bool ConstRHS = ConstArg && !FI->isMutable();
7599     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7600                                    CSM, TSK_Field, TAH, Diagnose))
7601       return false;
7602   }
7603 
7604   return true;
7605 }
7606 
7607 /// Diagnose why the specified class does not have a trivial special member of
7608 /// the given kind.
7609 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7610   QualType Ty = Context.getRecordType(RD);
7611 
7612   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7613   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7614                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7615                             /*Diagnose*/true);
7616 }
7617 
7618 /// Determine whether a defaulted or deleted special member function is trivial,
7619 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7620 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7621 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7622                                   TrivialABIHandling TAH, bool Diagnose) {
7623   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7624 
7625   CXXRecordDecl *RD = MD->getParent();
7626 
7627   bool ConstArg = false;
7628 
7629   // C++11 [class.copy]p12, p25: [DR1593]
7630   //   A [special member] is trivial if [...] its parameter-type-list is
7631   //   equivalent to the parameter-type-list of an implicit declaration [...]
7632   switch (CSM) {
7633   case CXXDefaultConstructor:
7634   case CXXDestructor:
7635     // Trivial default constructors and destructors cannot have parameters.
7636     break;
7637 
7638   case CXXCopyConstructor:
7639   case CXXCopyAssignment: {
7640     // Trivial copy operations always have const, non-volatile parameter types.
7641     ConstArg = true;
7642     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7643     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7644     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7645       if (Diagnose)
7646         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7647           << Param0->getSourceRange() << Param0->getType()
7648           << Context.getLValueReferenceType(
7649                Context.getRecordType(RD).withConst());
7650       return false;
7651     }
7652     break;
7653   }
7654 
7655   case CXXMoveConstructor:
7656   case CXXMoveAssignment: {
7657     // Trivial move operations always have non-cv-qualified parameters.
7658     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7659     const RValueReferenceType *RT =
7660       Param0->getType()->getAs<RValueReferenceType>();
7661     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7662       if (Diagnose)
7663         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7664           << Param0->getSourceRange() << Param0->getType()
7665           << Context.getRValueReferenceType(Context.getRecordType(RD));
7666       return false;
7667     }
7668     break;
7669   }
7670 
7671   case CXXInvalid:
7672     llvm_unreachable("not a special member");
7673   }
7674 
7675   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7676     if (Diagnose)
7677       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7678            diag::note_nontrivial_default_arg)
7679         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7680     return false;
7681   }
7682   if (MD->isVariadic()) {
7683     if (Diagnose)
7684       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7685     return false;
7686   }
7687 
7688   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7689   //   A copy/move [constructor or assignment operator] is trivial if
7690   //    -- the [member] selected to copy/move each direct base class subobject
7691   //       is trivial
7692   //
7693   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7694   //   A [default constructor or destructor] is trivial if
7695   //    -- all the direct base classes have trivial [default constructors or
7696   //       destructors]
7697   for (const auto &BI : RD->bases())
7698     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7699                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7700       return false;
7701 
7702   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7703   //   A copy/move [constructor or assignment operator] for a class X is
7704   //   trivial if
7705   //    -- for each non-static data member of X that is of class type (or array
7706   //       thereof), the constructor selected to copy/move that member is
7707   //       trivial
7708   //
7709   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7710   //   A [default constructor or destructor] is trivial if
7711   //    -- for all of the non-static data members of its class that are of class
7712   //       type (or array thereof), each such class has a trivial [default
7713   //       constructor or destructor]
7714   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7715     return false;
7716 
7717   // C++11 [class.dtor]p5:
7718   //   A destructor is trivial if [...]
7719   //    -- the destructor is not virtual
7720   if (CSM == CXXDestructor && MD->isVirtual()) {
7721     if (Diagnose)
7722       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7723     return false;
7724   }
7725 
7726   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7727   //   A [special member] for class X is trivial if [...]
7728   //    -- class X has no virtual functions and no virtual base classes
7729   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7730     if (!Diagnose)
7731       return false;
7732 
7733     if (RD->getNumVBases()) {
7734       // Check for virtual bases. We already know that the corresponding
7735       // member in all bases is trivial, so vbases must all be direct.
7736       CXXBaseSpecifier &BS = *RD->vbases_begin();
7737       assert(BS.isVirtual());
7738       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7739       return false;
7740     }
7741 
7742     // Must have a virtual method.
7743     for (const auto *MI : RD->methods()) {
7744       if (MI->isVirtual()) {
7745         SourceLocation MLoc = MI->getBeginLoc();
7746         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7747         return false;
7748       }
7749     }
7750 
7751     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7752   }
7753 
7754   // Looks like it's trivial!
7755   return true;
7756 }
7757 
7758 namespace {
7759 struct FindHiddenVirtualMethod {
7760   Sema *S;
7761   CXXMethodDecl *Method;
7762   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7763   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7764 
7765 private:
7766   /// Check whether any most overridden method from MD in Methods
7767   static bool CheckMostOverridenMethods(
7768       const CXXMethodDecl *MD,
7769       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7770     if (MD->size_overridden_methods() == 0)
7771       return Methods.count(MD->getCanonicalDecl());
7772     for (const CXXMethodDecl *O : MD->overridden_methods())
7773       if (CheckMostOverridenMethods(O, Methods))
7774         return true;
7775     return false;
7776   }
7777 
7778 public:
7779   /// Member lookup function that determines whether a given C++
7780   /// method overloads virtual methods in a base class without overriding any,
7781   /// to be used with CXXRecordDecl::lookupInBases().
7782   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7783     RecordDecl *BaseRecord =
7784         Specifier->getType()->getAs<RecordType>()->getDecl();
7785 
7786     DeclarationName Name = Method->getDeclName();
7787     assert(Name.getNameKind() == DeclarationName::Identifier);
7788 
7789     bool foundSameNameMethod = false;
7790     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7791     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7792          Path.Decls = Path.Decls.slice(1)) {
7793       NamedDecl *D = Path.Decls.front();
7794       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7795         MD = MD->getCanonicalDecl();
7796         foundSameNameMethod = true;
7797         // Interested only in hidden virtual methods.
7798         if (!MD->isVirtual())
7799           continue;
7800         // If the method we are checking overrides a method from its base
7801         // don't warn about the other overloaded methods. Clang deviates from
7802         // GCC by only diagnosing overloads of inherited virtual functions that
7803         // do not override any other virtual functions in the base. GCC's
7804         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7805         // function from a base class. These cases may be better served by a
7806         // warning (not specific to virtual functions) on call sites when the
7807         // call would select a different function from the base class, were it
7808         // visible.
7809         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7810         if (!S->IsOverload(Method, MD, false))
7811           return true;
7812         // Collect the overload only if its hidden.
7813         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7814           overloadedMethods.push_back(MD);
7815       }
7816     }
7817 
7818     if (foundSameNameMethod)
7819       OverloadedMethods.append(overloadedMethods.begin(),
7820                                overloadedMethods.end());
7821     return foundSameNameMethod;
7822   }
7823 };
7824 } // end anonymous namespace
7825 
7826 /// Add the most overriden methods from MD to Methods
7827 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7828                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7829   if (MD->size_overridden_methods() == 0)
7830     Methods.insert(MD->getCanonicalDecl());
7831   else
7832     for (const CXXMethodDecl *O : MD->overridden_methods())
7833       AddMostOverridenMethods(O, Methods);
7834 }
7835 
7836 /// Check if a method overloads virtual methods in a base class without
7837 /// overriding any.
7838 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7839                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7840   if (!MD->getDeclName().isIdentifier())
7841     return;
7842 
7843   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7844                      /*bool RecordPaths=*/false,
7845                      /*bool DetectVirtual=*/false);
7846   FindHiddenVirtualMethod FHVM;
7847   FHVM.Method = MD;
7848   FHVM.S = this;
7849 
7850   // Keep the base methods that were overridden or introduced in the subclass
7851   // by 'using' in a set. A base method not in this set is hidden.
7852   CXXRecordDecl *DC = MD->getParent();
7853   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7854   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7855     NamedDecl *ND = *I;
7856     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7857       ND = shad->getTargetDecl();
7858     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7859       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7860   }
7861 
7862   if (DC->lookupInBases(FHVM, Paths))
7863     OverloadedMethods = FHVM.OverloadedMethods;
7864 }
7865 
7866 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7867                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7868   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7869     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7870     PartialDiagnostic PD = PDiag(
7871          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7872     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7873     Diag(overloadedMD->getLocation(), PD);
7874   }
7875 }
7876 
7877 /// Diagnose methods which overload virtual methods in a base class
7878 /// without overriding any.
7879 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7880   if (MD->isInvalidDecl())
7881     return;
7882 
7883   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7884     return;
7885 
7886   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7887   FindHiddenVirtualMethods(MD, OverloadedMethods);
7888   if (!OverloadedMethods.empty()) {
7889     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7890       << MD << (OverloadedMethods.size() > 1);
7891 
7892     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7893   }
7894 }
7895 
7896 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7897   auto PrintDiagAndRemoveAttr = [&]() {
7898     // No diagnostics if this is a template instantiation.
7899     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7900       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7901            diag::ext_cannot_use_trivial_abi) << &RD;
7902     RD.dropAttr<TrivialABIAttr>();
7903   };
7904 
7905   // Ill-formed if the struct has virtual functions.
7906   if (RD.isPolymorphic()) {
7907     PrintDiagAndRemoveAttr();
7908     return;
7909   }
7910 
7911   for (const auto &B : RD.bases()) {
7912     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7913     // virtual base.
7914     if ((!B.getType()->isDependentType() &&
7915          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7916         B.isVirtual()) {
7917       PrintDiagAndRemoveAttr();
7918       return;
7919     }
7920   }
7921 
7922   for (const auto *FD : RD.fields()) {
7923     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7924     // non-trivial for the purpose of calls.
7925     QualType FT = FD->getType();
7926     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7927       PrintDiagAndRemoveAttr();
7928       return;
7929     }
7930 
7931     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7932       if (!RT->isDependentType() &&
7933           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7934         PrintDiagAndRemoveAttr();
7935         return;
7936       }
7937   }
7938 }
7939 
7940 void Sema::ActOnFinishCXXMemberSpecification(
7941     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7942     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7943   if (!TagDecl)
7944     return;
7945 
7946   AdjustDeclIfTemplate(TagDecl);
7947 
7948   for (const ParsedAttr &AL : AttrList) {
7949     if (AL.getKind() != ParsedAttr::AT_Visibility)
7950       continue;
7951     AL.setInvalid();
7952     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7953         << AL.getName();
7954   }
7955 
7956   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7957               // strict aliasing violation!
7958               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7959               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7960 
7961   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7962 }
7963 
7964 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7965 /// special functions, such as the default constructor, copy
7966 /// constructor, or destructor, to the given C++ class (C++
7967 /// [special]p1).  This routine can only be executed just before the
7968 /// definition of the class is complete.
7969 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7970   if (ClassDecl->needsImplicitDefaultConstructor()) {
7971     ++ASTContext::NumImplicitDefaultConstructors;
7972 
7973     if (ClassDecl->hasInheritedConstructor())
7974       DeclareImplicitDefaultConstructor(ClassDecl);
7975   }
7976 
7977   if (ClassDecl->needsImplicitCopyConstructor()) {
7978     ++ASTContext::NumImplicitCopyConstructors;
7979 
7980     // If the properties or semantics of the copy constructor couldn't be
7981     // determined while the class was being declared, force a declaration
7982     // of it now.
7983     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7984         ClassDecl->hasInheritedConstructor())
7985       DeclareImplicitCopyConstructor(ClassDecl);
7986     // For the MS ABI we need to know whether the copy ctor is deleted. A
7987     // prerequisite for deleting the implicit copy ctor is that the class has a
7988     // move ctor or move assignment that is either user-declared or whose
7989     // semantics are inherited from a subobject. FIXME: We should provide a more
7990     // direct way for CodeGen to ask whether the constructor was deleted.
7991     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7992              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7993               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7994               ClassDecl->hasUserDeclaredMoveAssignment() ||
7995               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7996       DeclareImplicitCopyConstructor(ClassDecl);
7997   }
7998 
7999   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8000     ++ASTContext::NumImplicitMoveConstructors;
8001 
8002     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8003         ClassDecl->hasInheritedConstructor())
8004       DeclareImplicitMoveConstructor(ClassDecl);
8005   }
8006 
8007   if (ClassDecl->needsImplicitCopyAssignment()) {
8008     ++ASTContext::NumImplicitCopyAssignmentOperators;
8009 
8010     // If we have a dynamic class, then the copy assignment operator may be
8011     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8012     // it shows up in the right place in the vtable and that we diagnose
8013     // problems with the implicit exception specification.
8014     if (ClassDecl->isDynamicClass() ||
8015         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8016         ClassDecl->hasInheritedAssignment())
8017       DeclareImplicitCopyAssignment(ClassDecl);
8018   }
8019 
8020   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8021     ++ASTContext::NumImplicitMoveAssignmentOperators;
8022 
8023     // Likewise for the move assignment operator.
8024     if (ClassDecl->isDynamicClass() ||
8025         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8026         ClassDecl->hasInheritedAssignment())
8027       DeclareImplicitMoveAssignment(ClassDecl);
8028   }
8029 
8030   if (ClassDecl->needsImplicitDestructor()) {
8031     ++ASTContext::NumImplicitDestructors;
8032 
8033     // If we have a dynamic class, then the destructor may be virtual, so we
8034     // have to declare the destructor immediately. This ensures that, e.g., it
8035     // shows up in the right place in the vtable and that we diagnose problems
8036     // with the implicit exception specification.
8037     if (ClassDecl->isDynamicClass() ||
8038         ClassDecl->needsOverloadResolutionForDestructor())
8039       DeclareImplicitDestructor(ClassDecl);
8040   }
8041 }
8042 
8043 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8044   if (!D)
8045     return 0;
8046 
8047   // The order of template parameters is not important here. All names
8048   // get added to the same scope.
8049   SmallVector<TemplateParameterList *, 4> ParameterLists;
8050 
8051   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8052     D = TD->getTemplatedDecl();
8053 
8054   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8055     ParameterLists.push_back(PSD->getTemplateParameters());
8056 
8057   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8058     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8059       ParameterLists.push_back(DD->getTemplateParameterList(i));
8060 
8061     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8062       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8063         ParameterLists.push_back(FTD->getTemplateParameters());
8064     }
8065   }
8066 
8067   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8068     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8069       ParameterLists.push_back(TD->getTemplateParameterList(i));
8070 
8071     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8072       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8073         ParameterLists.push_back(CTD->getTemplateParameters());
8074     }
8075   }
8076 
8077   unsigned Count = 0;
8078   for (TemplateParameterList *Params : ParameterLists) {
8079     if (Params->size() > 0)
8080       // Ignore explicit specializations; they don't contribute to the template
8081       // depth.
8082       ++Count;
8083     for (NamedDecl *Param : *Params) {
8084       if (Param->getDeclName()) {
8085         S->AddDecl(Param);
8086         IdResolver.AddDecl(Param);
8087       }
8088     }
8089   }
8090 
8091   return Count;
8092 }
8093 
8094 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8095   if (!RecordD) return;
8096   AdjustDeclIfTemplate(RecordD);
8097   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8098   PushDeclContext(S, Record);
8099 }
8100 
8101 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8102   if (!RecordD) return;
8103   PopDeclContext();
8104 }
8105 
8106 /// This is used to implement the constant expression evaluation part of the
8107 /// attribute enable_if extension. There is nothing in standard C++ which would
8108 /// require reentering parameters.
8109 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8110   if (!Param)
8111     return;
8112 
8113   S->AddDecl(Param);
8114   if (Param->getDeclName())
8115     IdResolver.AddDecl(Param);
8116 }
8117 
8118 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8119 /// parsing a top-level (non-nested) C++ class, and we are now
8120 /// parsing those parts of the given Method declaration that could
8121 /// not be parsed earlier (C++ [class.mem]p2), such as default
8122 /// arguments. This action should enter the scope of the given
8123 /// Method declaration as if we had just parsed the qualified method
8124 /// name. However, it should not bring the parameters into scope;
8125 /// that will be performed by ActOnDelayedCXXMethodParameter.
8126 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8127 }
8128 
8129 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8130 /// C++ method declaration. We're (re-)introducing the given
8131 /// function parameter into scope for use in parsing later parts of
8132 /// the method declaration. For example, we could see an
8133 /// ActOnParamDefaultArgument event for this parameter.
8134 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8135   if (!ParamD)
8136     return;
8137 
8138   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8139 
8140   // If this parameter has an unparsed default argument, clear it out
8141   // to make way for the parsed default argument.
8142   if (Param->hasUnparsedDefaultArg())
8143     Param->setDefaultArg(nullptr);
8144 
8145   S->AddDecl(Param);
8146   if (Param->getDeclName())
8147     IdResolver.AddDecl(Param);
8148 }
8149 
8150 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8151 /// processing the delayed method declaration for Method. The method
8152 /// declaration is now considered finished. There may be a separate
8153 /// ActOnStartOfFunctionDef action later (not necessarily
8154 /// immediately!) for this method, if it was also defined inside the
8155 /// class body.
8156 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8157   if (!MethodD)
8158     return;
8159 
8160   AdjustDeclIfTemplate(MethodD);
8161 
8162   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8163 
8164   // Now that we have our default arguments, check the constructor
8165   // again. It could produce additional diagnostics or affect whether
8166   // the class has implicitly-declared destructors, among other
8167   // things.
8168   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8169     CheckConstructor(Constructor);
8170 
8171   // Check the default arguments, which we may have added.
8172   if (!Method->isInvalidDecl())
8173     CheckCXXDefaultArguments(Method);
8174 }
8175 
8176 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8177 /// the well-formedness of the constructor declarator @p D with type @p
8178 /// R. If there are any errors in the declarator, this routine will
8179 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8180 /// will be updated to reflect a well-formed type for the constructor and
8181 /// returned.
8182 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8183                                           StorageClass &SC) {
8184   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8185 
8186   // C++ [class.ctor]p3:
8187   //   A constructor shall not be virtual (10.3) or static (9.4). A
8188   //   constructor can be invoked for a const, volatile or const
8189   //   volatile object. A constructor shall not be declared const,
8190   //   volatile, or const volatile (9.3.2).
8191   if (isVirtual) {
8192     if (!D.isInvalidType())
8193       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8194         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8195         << SourceRange(D.getIdentifierLoc());
8196     D.setInvalidType();
8197   }
8198   if (SC == SC_Static) {
8199     if (!D.isInvalidType())
8200       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8201         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8202         << SourceRange(D.getIdentifierLoc());
8203     D.setInvalidType();
8204     SC = SC_None;
8205   }
8206 
8207   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8208     diagnoseIgnoredQualifiers(
8209         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8210         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8211         D.getDeclSpec().getRestrictSpecLoc(),
8212         D.getDeclSpec().getAtomicSpecLoc());
8213     D.setInvalidType();
8214   }
8215 
8216   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8217   if (FTI.hasMethodTypeQualifiers()) {
8218     FTI.MethodQualifiers->forEachQualifier(
8219         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8220           Diag(SL, diag::err_invalid_qualified_constructor)
8221               << QualName << SourceRange(SL);
8222         });
8223     D.setInvalidType();
8224   }
8225 
8226   // C++0x [class.ctor]p4:
8227   //   A constructor shall not be declared with a ref-qualifier.
8228   if (FTI.hasRefQualifier()) {
8229     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8230       << FTI.RefQualifierIsLValueRef
8231       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8232     D.setInvalidType();
8233   }
8234 
8235   // Rebuild the function type "R" without any type qualifiers (in
8236   // case any of the errors above fired) and with "void" as the
8237   // return type, since constructors don't have return types.
8238   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8239   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8240     return R;
8241 
8242   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8243   EPI.TypeQuals = Qualifiers();
8244   EPI.RefQualifier = RQ_None;
8245 
8246   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8247 }
8248 
8249 /// CheckConstructor - Checks a fully-formed constructor for
8250 /// well-formedness, issuing any diagnostics required. Returns true if
8251 /// the constructor declarator is invalid.
8252 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8253   CXXRecordDecl *ClassDecl
8254     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8255   if (!ClassDecl)
8256     return Constructor->setInvalidDecl();
8257 
8258   // C++ [class.copy]p3:
8259   //   A declaration of a constructor for a class X is ill-formed if
8260   //   its first parameter is of type (optionally cv-qualified) X and
8261   //   either there are no other parameters or else all other
8262   //   parameters have default arguments.
8263   if (!Constructor->isInvalidDecl() &&
8264       ((Constructor->getNumParams() == 1) ||
8265        (Constructor->getNumParams() > 1 &&
8266         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8267       Constructor->getTemplateSpecializationKind()
8268                                               != TSK_ImplicitInstantiation) {
8269     QualType ParamType = Constructor->getParamDecl(0)->getType();
8270     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8271     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8272       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8273       const char *ConstRef
8274         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8275                                                         : " const &";
8276       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8277         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8278 
8279       // FIXME: Rather that making the constructor invalid, we should endeavor
8280       // to fix the type.
8281       Constructor->setInvalidDecl();
8282     }
8283   }
8284 }
8285 
8286 /// CheckDestructor - Checks a fully-formed destructor definition for
8287 /// well-formedness, issuing any diagnostics required.  Returns true
8288 /// on error.
8289 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8290   CXXRecordDecl *RD = Destructor->getParent();
8291 
8292   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8293     SourceLocation Loc;
8294 
8295     if (!Destructor->isImplicit())
8296       Loc = Destructor->getLocation();
8297     else
8298       Loc = RD->getLocation();
8299 
8300     // If we have a virtual destructor, look up the deallocation function
8301     if (FunctionDecl *OperatorDelete =
8302             FindDeallocationFunctionForDestructor(Loc, RD)) {
8303       Expr *ThisArg = nullptr;
8304 
8305       // If the notional 'delete this' expression requires a non-trivial
8306       // conversion from 'this' to the type of a destroying operator delete's
8307       // first parameter, perform that conversion now.
8308       if (OperatorDelete->isDestroyingOperatorDelete()) {
8309         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8310         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8311           // C++ [class.dtor]p13:
8312           //   ... as if for the expression 'delete this' appearing in a
8313           //   non-virtual destructor of the destructor's class.
8314           ContextRAII SwitchContext(*this, Destructor);
8315           ExprResult This =
8316               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8317           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8318           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8319           if (This.isInvalid()) {
8320             // FIXME: Register this as a context note so that it comes out
8321             // in the right order.
8322             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8323             return true;
8324           }
8325           ThisArg = This.get();
8326         }
8327       }
8328 
8329       DiagnoseUseOfDecl(OperatorDelete, Loc);
8330       MarkFunctionReferenced(Loc, OperatorDelete);
8331       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8332     }
8333   }
8334 
8335   return false;
8336 }
8337 
8338 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8339 /// the well-formednes of the destructor declarator @p D with type @p
8340 /// R. If there are any errors in the declarator, this routine will
8341 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8342 /// will be updated to reflect a well-formed type for the destructor and
8343 /// returned.
8344 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8345                                          StorageClass& SC) {
8346   // C++ [class.dtor]p1:
8347   //   [...] A typedef-name that names a class is a class-name
8348   //   (7.1.3); however, a typedef-name that names a class shall not
8349   //   be used as the identifier in the declarator for a destructor
8350   //   declaration.
8351   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8352   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8353     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8354       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8355   else if (const TemplateSpecializationType *TST =
8356              DeclaratorType->getAs<TemplateSpecializationType>())
8357     if (TST->isTypeAlias())
8358       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8359         << DeclaratorType << 1;
8360 
8361   // C++ [class.dtor]p2:
8362   //   A destructor is used to destroy objects of its class type. A
8363   //   destructor takes no parameters, and no return type can be
8364   //   specified for it (not even void). The address of a destructor
8365   //   shall not be taken. A destructor shall not be static. A
8366   //   destructor can be invoked for a const, volatile or const
8367   //   volatile object. A destructor shall not be declared const,
8368   //   volatile or const volatile (9.3.2).
8369   if (SC == SC_Static) {
8370     if (!D.isInvalidType())
8371       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8372         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8373         << SourceRange(D.getIdentifierLoc())
8374         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8375 
8376     SC = SC_None;
8377   }
8378   if (!D.isInvalidType()) {
8379     // Destructors don't have return types, but the parser will
8380     // happily parse something like:
8381     //
8382     //   class X {
8383     //     float ~X();
8384     //   };
8385     //
8386     // The return type will be eliminated later.
8387     if (D.getDeclSpec().hasTypeSpecifier())
8388       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8389         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8390         << SourceRange(D.getIdentifierLoc());
8391     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8392       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8393                                 SourceLocation(),
8394                                 D.getDeclSpec().getConstSpecLoc(),
8395                                 D.getDeclSpec().getVolatileSpecLoc(),
8396                                 D.getDeclSpec().getRestrictSpecLoc(),
8397                                 D.getDeclSpec().getAtomicSpecLoc());
8398       D.setInvalidType();
8399     }
8400   }
8401 
8402   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8403   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8404     FTI.MethodQualifiers->forEachQualifier(
8405         [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8406           Diag(SL, diag::err_invalid_qualified_destructor)
8407               << QualName << SourceRange(SL);
8408         });
8409     D.setInvalidType();
8410   }
8411 
8412   // C++0x [class.dtor]p2:
8413   //   A destructor shall not be declared with a ref-qualifier.
8414   if (FTI.hasRefQualifier()) {
8415     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8416       << FTI.RefQualifierIsLValueRef
8417       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8418     D.setInvalidType();
8419   }
8420 
8421   // Make sure we don't have any parameters.
8422   if (FTIHasNonVoidParameters(FTI)) {
8423     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8424 
8425     // Delete the parameters.
8426     FTI.freeParams();
8427     D.setInvalidType();
8428   }
8429 
8430   // Make sure the destructor isn't variadic.
8431   if (FTI.isVariadic) {
8432     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8433     D.setInvalidType();
8434   }
8435 
8436   // Rebuild the function type "R" without any type qualifiers or
8437   // parameters (in case any of the errors above fired) and with
8438   // "void" as the return type, since destructors don't have return
8439   // types.
8440   if (!D.isInvalidType())
8441     return R;
8442 
8443   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8444   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8445   EPI.Variadic = false;
8446   EPI.TypeQuals = Qualifiers();
8447   EPI.RefQualifier = RQ_None;
8448   return Context.getFunctionType(Context.VoidTy, None, EPI);
8449 }
8450 
8451 static void extendLeft(SourceRange &R, SourceRange Before) {
8452   if (Before.isInvalid())
8453     return;
8454   R.setBegin(Before.getBegin());
8455   if (R.getEnd().isInvalid())
8456     R.setEnd(Before.getEnd());
8457 }
8458 
8459 static void extendRight(SourceRange &R, SourceRange After) {
8460   if (After.isInvalid())
8461     return;
8462   if (R.getBegin().isInvalid())
8463     R.setBegin(After.getBegin());
8464   R.setEnd(After.getEnd());
8465 }
8466 
8467 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8468 /// well-formednes of the conversion function declarator @p D with
8469 /// type @p R. If there are any errors in the declarator, this routine
8470 /// will emit diagnostics and return true. Otherwise, it will return
8471 /// false. Either way, the type @p R will be updated to reflect a
8472 /// well-formed type for the conversion operator.
8473 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8474                                      StorageClass& SC) {
8475   // C++ [class.conv.fct]p1:
8476   //   Neither parameter types nor return type can be specified. The
8477   //   type of a conversion function (8.3.5) is "function taking no
8478   //   parameter returning conversion-type-id."
8479   if (SC == SC_Static) {
8480     if (!D.isInvalidType())
8481       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8482         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8483         << D.getName().getSourceRange();
8484     D.setInvalidType();
8485     SC = SC_None;
8486   }
8487 
8488   TypeSourceInfo *ConvTSI = nullptr;
8489   QualType ConvType =
8490       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8491 
8492   const DeclSpec &DS = D.getDeclSpec();
8493   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8494     // Conversion functions don't have return types, but the parser will
8495     // happily parse something like:
8496     //
8497     //   class X {
8498     //     float operator bool();
8499     //   };
8500     //
8501     // The return type will be changed later anyway.
8502     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8503       << SourceRange(DS.getTypeSpecTypeLoc())
8504       << SourceRange(D.getIdentifierLoc());
8505     D.setInvalidType();
8506   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8507     // It's also plausible that the user writes type qualifiers in the wrong
8508     // place, such as:
8509     //   struct S { const operator int(); };
8510     // FIXME: we could provide a fixit to move the qualifiers onto the
8511     // conversion type.
8512     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8513         << SourceRange(D.getIdentifierLoc()) << 0;
8514     D.setInvalidType();
8515   }
8516 
8517   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8518 
8519   // Make sure we don't have any parameters.
8520   if (Proto->getNumParams() > 0) {
8521     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8522 
8523     // Delete the parameters.
8524     D.getFunctionTypeInfo().freeParams();
8525     D.setInvalidType();
8526   } else if (Proto->isVariadic()) {
8527     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8528     D.setInvalidType();
8529   }
8530 
8531   // Diagnose "&operator bool()" and other such nonsense.  This
8532   // is actually a gcc extension which we don't support.
8533   if (Proto->getReturnType() != ConvType) {
8534     bool NeedsTypedef = false;
8535     SourceRange Before, After;
8536 
8537     // Walk the chunks and extract information on them for our diagnostic.
8538     bool PastFunctionChunk = false;
8539     for (auto &Chunk : D.type_objects()) {
8540       switch (Chunk.Kind) {
8541       case DeclaratorChunk::Function:
8542         if (!PastFunctionChunk) {
8543           if (Chunk.Fun.HasTrailingReturnType) {
8544             TypeSourceInfo *TRT = nullptr;
8545             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8546             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8547           }
8548           PastFunctionChunk = true;
8549           break;
8550         }
8551         LLVM_FALLTHROUGH;
8552       case DeclaratorChunk::Array:
8553         NeedsTypedef = true;
8554         extendRight(After, Chunk.getSourceRange());
8555         break;
8556 
8557       case DeclaratorChunk::Pointer:
8558       case DeclaratorChunk::BlockPointer:
8559       case DeclaratorChunk::Reference:
8560       case DeclaratorChunk::MemberPointer:
8561       case DeclaratorChunk::Pipe:
8562         extendLeft(Before, Chunk.getSourceRange());
8563         break;
8564 
8565       case DeclaratorChunk::Paren:
8566         extendLeft(Before, Chunk.Loc);
8567         extendRight(After, Chunk.EndLoc);
8568         break;
8569       }
8570     }
8571 
8572     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8573                          After.isValid()  ? After.getBegin() :
8574                                             D.getIdentifierLoc();
8575     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8576     DB << Before << After;
8577 
8578     if (!NeedsTypedef) {
8579       DB << /*don't need a typedef*/0;
8580 
8581       // If we can provide a correct fix-it hint, do so.
8582       if (After.isInvalid() && ConvTSI) {
8583         SourceLocation InsertLoc =
8584             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8585         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8586            << FixItHint::CreateInsertionFromRange(
8587                   InsertLoc, CharSourceRange::getTokenRange(Before))
8588            << FixItHint::CreateRemoval(Before);
8589       }
8590     } else if (!Proto->getReturnType()->isDependentType()) {
8591       DB << /*typedef*/1 << Proto->getReturnType();
8592     } else if (getLangOpts().CPlusPlus11) {
8593       DB << /*alias template*/2 << Proto->getReturnType();
8594     } else {
8595       DB << /*might not be fixable*/3;
8596     }
8597 
8598     // Recover by incorporating the other type chunks into the result type.
8599     // Note, this does *not* change the name of the function. This is compatible
8600     // with the GCC extension:
8601     //   struct S { &operator int(); } s;
8602     //   int &r = s.operator int(); // ok in GCC
8603     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8604     ConvType = Proto->getReturnType();
8605   }
8606 
8607   // C++ [class.conv.fct]p4:
8608   //   The conversion-type-id shall not represent a function type nor
8609   //   an array type.
8610   if (ConvType->isArrayType()) {
8611     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8612     ConvType = Context.getPointerType(ConvType);
8613     D.setInvalidType();
8614   } else if (ConvType->isFunctionType()) {
8615     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8616     ConvType = Context.getPointerType(ConvType);
8617     D.setInvalidType();
8618   }
8619 
8620   // Rebuild the function type "R" without any parameters (in case any
8621   // of the errors above fired) and with the conversion type as the
8622   // return type.
8623   if (D.isInvalidType())
8624     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8625 
8626   // C++0x explicit conversion operators.
8627   if (DS.isExplicitSpecified())
8628     Diag(DS.getExplicitSpecLoc(),
8629          getLangOpts().CPlusPlus11
8630              ? diag::warn_cxx98_compat_explicit_conversion_functions
8631              : diag::ext_explicit_conversion_functions)
8632         << SourceRange(DS.getExplicitSpecLoc());
8633 }
8634 
8635 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8636 /// the declaration of the given C++ conversion function. This routine
8637 /// is responsible for recording the conversion function in the C++
8638 /// class, if possible.
8639 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8640   assert(Conversion && "Expected to receive a conversion function declaration");
8641 
8642   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8643 
8644   // Make sure we aren't redeclaring the conversion function.
8645   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8646 
8647   // C++ [class.conv.fct]p1:
8648   //   [...] A conversion function is never used to convert a
8649   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8650   //   same object type (or a reference to it), to a (possibly
8651   //   cv-qualified) base class of that type (or a reference to it),
8652   //   or to (possibly cv-qualified) void.
8653   // FIXME: Suppress this warning if the conversion function ends up being a
8654   // virtual function that overrides a virtual function in a base class.
8655   QualType ClassType
8656     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8657   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8658     ConvType = ConvTypeRef->getPointeeType();
8659   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8660       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8661     /* Suppress diagnostics for instantiations. */;
8662   else if (ConvType->isRecordType()) {
8663     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8664     if (ConvType == ClassType)
8665       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8666         << ClassType;
8667     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8668       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8669         <<  ClassType << ConvType;
8670   } else if (ConvType->isVoidType()) {
8671     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8672       << ClassType << ConvType;
8673   }
8674 
8675   if (FunctionTemplateDecl *ConversionTemplate
8676                                 = Conversion->getDescribedFunctionTemplate())
8677     return ConversionTemplate;
8678 
8679   return Conversion;
8680 }
8681 
8682 namespace {
8683 /// Utility class to accumulate and print a diagnostic listing the invalid
8684 /// specifier(s) on a declaration.
8685 struct BadSpecifierDiagnoser {
8686   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8687       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8688   ~BadSpecifierDiagnoser() {
8689     Diagnostic << Specifiers;
8690   }
8691 
8692   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8693     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8694   }
8695   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8696     return check(SpecLoc,
8697                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8698   }
8699   void check(SourceLocation SpecLoc, const char *Spec) {
8700     if (SpecLoc.isInvalid()) return;
8701     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8702     if (!Specifiers.empty()) Specifiers += " ";
8703     Specifiers += Spec;
8704   }
8705 
8706   Sema &S;
8707   Sema::SemaDiagnosticBuilder Diagnostic;
8708   std::string Specifiers;
8709 };
8710 }
8711 
8712 /// Check the validity of a declarator that we parsed for a deduction-guide.
8713 /// These aren't actually declarators in the grammar, so we need to check that
8714 /// the user didn't specify any pieces that are not part of the deduction-guide
8715 /// grammar.
8716 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8717                                          StorageClass &SC) {
8718   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8719   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8720   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8721 
8722   // C++ [temp.deduct.guide]p3:
8723   //   A deduction-gide shall be declared in the same scope as the
8724   //   corresponding class template.
8725   if (!CurContext->getRedeclContext()->Equals(
8726           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8727     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8728       << GuidedTemplateDecl;
8729     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8730   }
8731 
8732   auto &DS = D.getMutableDeclSpec();
8733   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8734   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8735       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8736       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8737     BadSpecifierDiagnoser Diagnoser(
8738         *this, D.getIdentifierLoc(),
8739         diag::err_deduction_guide_invalid_specifier);
8740 
8741     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8742     DS.ClearStorageClassSpecs();
8743     SC = SC_None;
8744 
8745     // 'explicit' is permitted.
8746     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8747     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8748     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8749     DS.ClearConstexprSpec();
8750 
8751     Diagnoser.check(DS.getConstSpecLoc(), "const");
8752     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8753     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8754     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8755     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8756     DS.ClearTypeQualifiers();
8757 
8758     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8759     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8760     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8761     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8762     DS.ClearTypeSpecType();
8763   }
8764 
8765   if (D.isInvalidType())
8766     return;
8767 
8768   // Check the declarator is simple enough.
8769   bool FoundFunction = false;
8770   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8771     if (Chunk.Kind == DeclaratorChunk::Paren)
8772       continue;
8773     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8774       Diag(D.getDeclSpec().getBeginLoc(),
8775            diag::err_deduction_guide_with_complex_decl)
8776           << D.getSourceRange();
8777       break;
8778     }
8779     if (!Chunk.Fun.hasTrailingReturnType()) {
8780       Diag(D.getName().getBeginLoc(),
8781            diag::err_deduction_guide_no_trailing_return_type);
8782       break;
8783     }
8784 
8785     // Check that the return type is written as a specialization of
8786     // the template specified as the deduction-guide's name.
8787     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8788     TypeSourceInfo *TSI = nullptr;
8789     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8790     assert(TSI && "deduction guide has valid type but invalid return type?");
8791     bool AcceptableReturnType = false;
8792     bool MightInstantiateToSpecialization = false;
8793     if (auto RetTST =
8794             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8795       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8796       bool TemplateMatches =
8797           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8798       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8799         AcceptableReturnType = true;
8800       else {
8801         // This could still instantiate to the right type, unless we know it
8802         // names the wrong class template.
8803         auto *TD = SpecifiedName.getAsTemplateDecl();
8804         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8805                                              !TemplateMatches);
8806       }
8807     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8808       MightInstantiateToSpecialization = true;
8809     }
8810 
8811     if (!AcceptableReturnType) {
8812       Diag(TSI->getTypeLoc().getBeginLoc(),
8813            diag::err_deduction_guide_bad_trailing_return_type)
8814           << GuidedTemplate << TSI->getType()
8815           << MightInstantiateToSpecialization
8816           << TSI->getTypeLoc().getSourceRange();
8817     }
8818 
8819     // Keep going to check that we don't have any inner declarator pieces (we
8820     // could still have a function returning a pointer to a function).
8821     FoundFunction = true;
8822   }
8823 
8824   if (D.isFunctionDefinition())
8825     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8826 }
8827 
8828 //===----------------------------------------------------------------------===//
8829 // Namespace Handling
8830 //===----------------------------------------------------------------------===//
8831 
8832 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8833 /// reopened.
8834 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8835                                             SourceLocation Loc,
8836                                             IdentifierInfo *II, bool *IsInline,
8837                                             NamespaceDecl *PrevNS) {
8838   assert(*IsInline != PrevNS->isInline());
8839 
8840   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8841   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8842   // inline namespaces, with the intention of bringing names into namespace std.
8843   //
8844   // We support this just well enough to get that case working; this is not
8845   // sufficient to support reopening namespaces as inline in general.
8846   if (*IsInline && II && II->getName().startswith("__atomic") &&
8847       S.getSourceManager().isInSystemHeader(Loc)) {
8848     // Mark all prior declarations of the namespace as inline.
8849     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8850          NS = NS->getPreviousDecl())
8851       NS->setInline(*IsInline);
8852     // Patch up the lookup table for the containing namespace. This isn't really
8853     // correct, but it's good enough for this particular case.
8854     for (auto *I : PrevNS->decls())
8855       if (auto *ND = dyn_cast<NamedDecl>(I))
8856         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8857     return;
8858   }
8859 
8860   if (PrevNS->isInline())
8861     // The user probably just forgot the 'inline', so suggest that it
8862     // be added back.
8863     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8864       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8865   else
8866     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8867 
8868   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8869   *IsInline = PrevNS->isInline();
8870 }
8871 
8872 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8873 /// definition.
8874 Decl *Sema::ActOnStartNamespaceDef(
8875     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8876     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8877     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8878   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8879   // For anonymous namespace, take the location of the left brace.
8880   SourceLocation Loc = II ? IdentLoc : LBrace;
8881   bool IsInline = InlineLoc.isValid();
8882   bool IsInvalid = false;
8883   bool IsStd = false;
8884   bool AddToKnown = false;
8885   Scope *DeclRegionScope = NamespcScope->getParent();
8886 
8887   NamespaceDecl *PrevNS = nullptr;
8888   if (II) {
8889     // C++ [namespace.def]p2:
8890     //   The identifier in an original-namespace-definition shall not
8891     //   have been previously defined in the declarative region in
8892     //   which the original-namespace-definition appears. The
8893     //   identifier in an original-namespace-definition is the name of
8894     //   the namespace. Subsequently in that declarative region, it is
8895     //   treated as an original-namespace-name.
8896     //
8897     // Since namespace names are unique in their scope, and we don't
8898     // look through using directives, just look for any ordinary names
8899     // as if by qualified name lookup.
8900     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8901                    ForExternalRedeclaration);
8902     LookupQualifiedName(R, CurContext->getRedeclContext());
8903     NamedDecl *PrevDecl =
8904         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8905     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8906 
8907     if (PrevNS) {
8908       // This is an extended namespace definition.
8909       if (IsInline != PrevNS->isInline())
8910         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8911                                         &IsInline, PrevNS);
8912     } else if (PrevDecl) {
8913       // This is an invalid name redefinition.
8914       Diag(Loc, diag::err_redefinition_different_kind)
8915         << II;
8916       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8917       IsInvalid = true;
8918       // Continue on to push Namespc as current DeclContext and return it.
8919     } else if (II->isStr("std") &&
8920                CurContext->getRedeclContext()->isTranslationUnit()) {
8921       // This is the first "real" definition of the namespace "std", so update
8922       // our cache of the "std" namespace to point at this definition.
8923       PrevNS = getStdNamespace();
8924       IsStd = true;
8925       AddToKnown = !IsInline;
8926     } else {
8927       // We've seen this namespace for the first time.
8928       AddToKnown = !IsInline;
8929     }
8930   } else {
8931     // Anonymous namespaces.
8932 
8933     // Determine whether the parent already has an anonymous namespace.
8934     DeclContext *Parent = CurContext->getRedeclContext();
8935     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8936       PrevNS = TU->getAnonymousNamespace();
8937     } else {
8938       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8939       PrevNS = ND->getAnonymousNamespace();
8940     }
8941 
8942     if (PrevNS && IsInline != PrevNS->isInline())
8943       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8944                                       &IsInline, PrevNS);
8945   }
8946 
8947   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8948                                                  StartLoc, Loc, II, PrevNS);
8949   if (IsInvalid)
8950     Namespc->setInvalidDecl();
8951 
8952   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8953   AddPragmaAttributes(DeclRegionScope, Namespc);
8954 
8955   // FIXME: Should we be merging attributes?
8956   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8957     PushNamespaceVisibilityAttr(Attr, Loc);
8958 
8959   if (IsStd)
8960     StdNamespace = Namespc;
8961   if (AddToKnown)
8962     KnownNamespaces[Namespc] = false;
8963 
8964   if (II) {
8965     PushOnScopeChains(Namespc, DeclRegionScope);
8966   } else {
8967     // Link the anonymous namespace into its parent.
8968     DeclContext *Parent = CurContext->getRedeclContext();
8969     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8970       TU->setAnonymousNamespace(Namespc);
8971     } else {
8972       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8973     }
8974 
8975     CurContext->addDecl(Namespc);
8976 
8977     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8978     //   behaves as if it were replaced by
8979     //     namespace unique { /* empty body */ }
8980     //     using namespace unique;
8981     //     namespace unique { namespace-body }
8982     //   where all occurrences of 'unique' in a translation unit are
8983     //   replaced by the same identifier and this identifier differs
8984     //   from all other identifiers in the entire program.
8985 
8986     // We just create the namespace with an empty name and then add an
8987     // implicit using declaration, just like the standard suggests.
8988     //
8989     // CodeGen enforces the "universally unique" aspect by giving all
8990     // declarations semantically contained within an anonymous
8991     // namespace internal linkage.
8992 
8993     if (!PrevNS) {
8994       UD = UsingDirectiveDecl::Create(Context, Parent,
8995                                       /* 'using' */ LBrace,
8996                                       /* 'namespace' */ SourceLocation(),
8997                                       /* qualifier */ NestedNameSpecifierLoc(),
8998                                       /* identifier */ SourceLocation(),
8999                                       Namespc,
9000                                       /* Ancestor */ Parent);
9001       UD->setImplicit();
9002       Parent->addDecl(UD);
9003     }
9004   }
9005 
9006   ActOnDocumentableDecl(Namespc);
9007 
9008   // Although we could have an invalid decl (i.e. the namespace name is a
9009   // redefinition), push it as current DeclContext and try to continue parsing.
9010   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9011   // for the namespace has the declarations that showed up in that particular
9012   // namespace definition.
9013   PushDeclContext(NamespcScope, Namespc);
9014   return Namespc;
9015 }
9016 
9017 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9018 /// is a namespace alias, returns the namespace it points to.
9019 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9020   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9021     return AD->getNamespace();
9022   return dyn_cast_or_null<NamespaceDecl>(D);
9023 }
9024 
9025 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9026 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9027 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9028   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9029   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9030   Namespc->setRBraceLoc(RBrace);
9031   PopDeclContext();
9032   if (Namespc->hasAttr<VisibilityAttr>())
9033     PopPragmaVisibility(true, RBrace);
9034 }
9035 
9036 CXXRecordDecl *Sema::getStdBadAlloc() const {
9037   return cast_or_null<CXXRecordDecl>(
9038                                   StdBadAlloc.get(Context.getExternalSource()));
9039 }
9040 
9041 EnumDecl *Sema::getStdAlignValT() const {
9042   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9043 }
9044 
9045 NamespaceDecl *Sema::getStdNamespace() const {
9046   return cast_or_null<NamespaceDecl>(
9047                                  StdNamespace.get(Context.getExternalSource()));
9048 }
9049 
9050 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9051   if (!StdExperimentalNamespaceCache) {
9052     if (auto Std = getStdNamespace()) {
9053       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9054                           SourceLocation(), LookupNamespaceName);
9055       if (!LookupQualifiedName(Result, Std) ||
9056           !(StdExperimentalNamespaceCache =
9057                 Result.getAsSingle<NamespaceDecl>()))
9058         Result.suppressDiagnostics();
9059     }
9060   }
9061   return StdExperimentalNamespaceCache;
9062 }
9063 
9064 namespace {
9065 
9066 enum UnsupportedSTLSelect {
9067   USS_InvalidMember,
9068   USS_MissingMember,
9069   USS_NonTrivial,
9070   USS_Other
9071 };
9072 
9073 struct InvalidSTLDiagnoser {
9074   Sema &S;
9075   SourceLocation Loc;
9076   QualType TyForDiags;
9077 
9078   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9079                       const VarDecl *VD = nullptr) {
9080     {
9081       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9082                << TyForDiags << ((int)Sel);
9083       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9084         assert(!Name.empty());
9085         D << Name;
9086       }
9087     }
9088     if (Sel == USS_InvalidMember) {
9089       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9090           << VD << VD->getSourceRange();
9091     }
9092     return QualType();
9093   }
9094 };
9095 } // namespace
9096 
9097 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9098                                            SourceLocation Loc) {
9099   assert(getLangOpts().CPlusPlus &&
9100          "Looking for comparison category type outside of C++.");
9101 
9102   // Check if we've already successfully checked the comparison category type
9103   // before. If so, skip checking it again.
9104   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9105   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9106     return Info->getType();
9107 
9108   // If lookup failed
9109   if (!Info) {
9110     std::string NameForDiags = "std::";
9111     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9112     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9113         << NameForDiags;
9114     return QualType();
9115   }
9116 
9117   assert(Info->Kind == Kind);
9118   assert(Info->Record);
9119 
9120   // Update the Record decl in case we encountered a forward declaration on our
9121   // first pass. FIXME: This is a bit of a hack.
9122   if (Info->Record->hasDefinition())
9123     Info->Record = Info->Record->getDefinition();
9124 
9125   // Use an elaborated type for diagnostics which has a name containing the
9126   // prepended 'std' namespace but not any inline namespace names.
9127   QualType TyForDiags = [&]() {
9128     auto *NNS =
9129         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9130     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9131   }();
9132 
9133   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9134     return QualType();
9135 
9136   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9137 
9138   if (!Info->Record->isTriviallyCopyable())
9139     return UnsupportedSTLError(USS_NonTrivial);
9140 
9141   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9142     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9143     // Tolerate empty base classes.
9144     if (Base->isEmpty())
9145       continue;
9146     // Reject STL implementations which have at least one non-empty base.
9147     return UnsupportedSTLError();
9148   }
9149 
9150   // Check that the STL has implemented the types using a single integer field.
9151   // This expectation allows better codegen for builtin operators. We require:
9152   //   (1) The class has exactly one field.
9153   //   (2) The field is an integral or enumeration type.
9154   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9155   if (std::distance(FIt, FEnd) != 1 ||
9156       !FIt->getType()->isIntegralOrEnumerationType()) {
9157     return UnsupportedSTLError();
9158   }
9159 
9160   // Build each of the require values and store them in Info.
9161   for (ComparisonCategoryResult CCR :
9162        ComparisonCategories::getPossibleResultsForType(Kind)) {
9163     StringRef MemName = ComparisonCategories::getResultString(CCR);
9164     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9165 
9166     if (!ValInfo)
9167       return UnsupportedSTLError(USS_MissingMember, MemName);
9168 
9169     VarDecl *VD = ValInfo->VD;
9170     assert(VD && "should not be null!");
9171 
9172     // Attempt to diagnose reasons why the STL definition of this type
9173     // might be foobar, including it failing to be a constant expression.
9174     // TODO Handle more ways the lookup or result can be invalid.
9175     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9176         !VD->checkInitIsICE())
9177       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9178 
9179     // Attempt to evaluate the var decl as a constant expression and extract
9180     // the value of its first field as a ICE. If this fails, the STL
9181     // implementation is not supported.
9182     if (!ValInfo->hasValidIntValue())
9183       return UnsupportedSTLError();
9184 
9185     MarkVariableReferenced(Loc, VD);
9186   }
9187 
9188   // We've successfully built the required types and expressions. Update
9189   // the cache and return the newly cached value.
9190   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9191   return Info->getType();
9192 }
9193 
9194 /// Retrieve the special "std" namespace, which may require us to
9195 /// implicitly define the namespace.
9196 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9197   if (!StdNamespace) {
9198     // The "std" namespace has not yet been defined, so build one implicitly.
9199     StdNamespace = NamespaceDecl::Create(Context,
9200                                          Context.getTranslationUnitDecl(),
9201                                          /*Inline=*/false,
9202                                          SourceLocation(), SourceLocation(),
9203                                          &PP.getIdentifierTable().get("std"),
9204                                          /*PrevDecl=*/nullptr);
9205     getStdNamespace()->setImplicit(true);
9206   }
9207 
9208   return getStdNamespace();
9209 }
9210 
9211 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9212   assert(getLangOpts().CPlusPlus &&
9213          "Looking for std::initializer_list outside of C++.");
9214 
9215   // We're looking for implicit instantiations of
9216   // template <typename E> class std::initializer_list.
9217 
9218   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9219     return false;
9220 
9221   ClassTemplateDecl *Template = nullptr;
9222   const TemplateArgument *Arguments = nullptr;
9223 
9224   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9225 
9226     ClassTemplateSpecializationDecl *Specialization =
9227         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9228     if (!Specialization)
9229       return false;
9230 
9231     Template = Specialization->getSpecializedTemplate();
9232     Arguments = Specialization->getTemplateArgs().data();
9233   } else if (const TemplateSpecializationType *TST =
9234                  Ty->getAs<TemplateSpecializationType>()) {
9235     Template = dyn_cast_or_null<ClassTemplateDecl>(
9236         TST->getTemplateName().getAsTemplateDecl());
9237     Arguments = TST->getArgs();
9238   }
9239   if (!Template)
9240     return false;
9241 
9242   if (!StdInitializerList) {
9243     // Haven't recognized std::initializer_list yet, maybe this is it.
9244     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9245     if (TemplateClass->getIdentifier() !=
9246             &PP.getIdentifierTable().get("initializer_list") ||
9247         !getStdNamespace()->InEnclosingNamespaceSetOf(
9248             TemplateClass->getDeclContext()))
9249       return false;
9250     // This is a template called std::initializer_list, but is it the right
9251     // template?
9252     TemplateParameterList *Params = Template->getTemplateParameters();
9253     if (Params->getMinRequiredArguments() != 1)
9254       return false;
9255     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9256       return false;
9257 
9258     // It's the right template.
9259     StdInitializerList = Template;
9260   }
9261 
9262   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9263     return false;
9264 
9265   // This is an instance of std::initializer_list. Find the argument type.
9266   if (Element)
9267     *Element = Arguments[0].getAsType();
9268   return true;
9269 }
9270 
9271 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9272   NamespaceDecl *Std = S.getStdNamespace();
9273   if (!Std) {
9274     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9275     return nullptr;
9276   }
9277 
9278   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9279                       Loc, Sema::LookupOrdinaryName);
9280   if (!S.LookupQualifiedName(Result, Std)) {
9281     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9282     return nullptr;
9283   }
9284   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9285   if (!Template) {
9286     Result.suppressDiagnostics();
9287     // We found something weird. Complain about the first thing we found.
9288     NamedDecl *Found = *Result.begin();
9289     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9290     return nullptr;
9291   }
9292 
9293   // We found some template called std::initializer_list. Now verify that it's
9294   // correct.
9295   TemplateParameterList *Params = Template->getTemplateParameters();
9296   if (Params->getMinRequiredArguments() != 1 ||
9297       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9298     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9299     return nullptr;
9300   }
9301 
9302   return Template;
9303 }
9304 
9305 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9306   if (!StdInitializerList) {
9307     StdInitializerList = LookupStdInitializerList(*this, Loc);
9308     if (!StdInitializerList)
9309       return QualType();
9310   }
9311 
9312   TemplateArgumentListInfo Args(Loc, Loc);
9313   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9314                                        Context.getTrivialTypeSourceInfo(Element,
9315                                                                         Loc)));
9316   return Context.getCanonicalType(
9317       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9318 }
9319 
9320 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9321   // C++ [dcl.init.list]p2:
9322   //   A constructor is an initializer-list constructor if its first parameter
9323   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9324   //   std::initializer_list<E> for some type E, and either there are no other
9325   //   parameters or else all other parameters have default arguments.
9326   if (Ctor->getNumParams() < 1 ||
9327       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9328     return false;
9329 
9330   QualType ArgType = Ctor->getParamDecl(0)->getType();
9331   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9332     ArgType = RT->getPointeeType().getUnqualifiedType();
9333 
9334   return isStdInitializerList(ArgType, nullptr);
9335 }
9336 
9337 /// Determine whether a using statement is in a context where it will be
9338 /// apply in all contexts.
9339 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9340   switch (CurContext->getDeclKind()) {
9341     case Decl::TranslationUnit:
9342       return true;
9343     case Decl::LinkageSpec:
9344       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9345     default:
9346       return false;
9347   }
9348 }
9349 
9350 namespace {
9351 
9352 // Callback to only accept typo corrections that are namespaces.
9353 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9354 public:
9355   bool ValidateCandidate(const TypoCorrection &candidate) override {
9356     if (NamedDecl *ND = candidate.getCorrectionDecl())
9357       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9358     return false;
9359   }
9360 };
9361 
9362 }
9363 
9364 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9365                                        CXXScopeSpec &SS,
9366                                        SourceLocation IdentLoc,
9367                                        IdentifierInfo *Ident) {
9368   R.clear();
9369   if (TypoCorrection Corrected =
9370           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9371                         llvm::make_unique<NamespaceValidatorCCC>(),
9372                         Sema::CTK_ErrorRecovery)) {
9373     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9374       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9375       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9376                               Ident->getName().equals(CorrectedStr);
9377       S.diagnoseTypo(Corrected,
9378                      S.PDiag(diag::err_using_directive_member_suggest)
9379                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9380                      S.PDiag(diag::note_namespace_defined_here));
9381     } else {
9382       S.diagnoseTypo(Corrected,
9383                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9384                      S.PDiag(diag::note_namespace_defined_here));
9385     }
9386     R.addDecl(Corrected.getFoundDecl());
9387     return true;
9388   }
9389   return false;
9390 }
9391 
9392 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9393                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9394                                 SourceLocation IdentLoc,
9395                                 IdentifierInfo *NamespcName,
9396                                 const ParsedAttributesView &AttrList) {
9397   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9398   assert(NamespcName && "Invalid NamespcName.");
9399   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9400 
9401   // This can only happen along a recovery path.
9402   while (S->isTemplateParamScope())
9403     S = S->getParent();
9404   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9405 
9406   UsingDirectiveDecl *UDir = nullptr;
9407   NestedNameSpecifier *Qualifier = nullptr;
9408   if (SS.isSet())
9409     Qualifier = SS.getScopeRep();
9410 
9411   // Lookup namespace name.
9412   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9413   LookupParsedName(R, S, &SS);
9414   if (R.isAmbiguous())
9415     return nullptr;
9416 
9417   if (R.empty()) {
9418     R.clear();
9419     // Allow "using namespace std;" or "using namespace ::std;" even if
9420     // "std" hasn't been defined yet, for GCC compatibility.
9421     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9422         NamespcName->isStr("std")) {
9423       Diag(IdentLoc, diag::ext_using_undefined_std);
9424       R.addDecl(getOrCreateStdNamespace());
9425       R.resolveKind();
9426     }
9427     // Otherwise, attempt typo correction.
9428     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9429   }
9430 
9431   if (!R.empty()) {
9432     NamedDecl *Named = R.getRepresentativeDecl();
9433     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9434     assert(NS && "expected namespace decl");
9435 
9436     // The use of a nested name specifier may trigger deprecation warnings.
9437     DiagnoseUseOfDecl(Named, IdentLoc);
9438 
9439     // C++ [namespace.udir]p1:
9440     //   A using-directive specifies that the names in the nominated
9441     //   namespace can be used in the scope in which the
9442     //   using-directive appears after the using-directive. During
9443     //   unqualified name lookup (3.4.1), the names appear as if they
9444     //   were declared in the nearest enclosing namespace which
9445     //   contains both the using-directive and the nominated
9446     //   namespace. [Note: in this context, "contains" means "contains
9447     //   directly or indirectly". ]
9448 
9449     // Find enclosing context containing both using-directive and
9450     // nominated namespace.
9451     DeclContext *CommonAncestor = NS;
9452     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9453       CommonAncestor = CommonAncestor->getParent();
9454 
9455     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9456                                       SS.getWithLocInContext(Context),
9457                                       IdentLoc, Named, CommonAncestor);
9458 
9459     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9460         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9461       Diag(IdentLoc, diag::warn_using_directive_in_header);
9462     }
9463 
9464     PushUsingDirective(S, UDir);
9465   } else {
9466     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9467   }
9468 
9469   if (UDir)
9470     ProcessDeclAttributeList(S, UDir, AttrList);
9471 
9472   return UDir;
9473 }
9474 
9475 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9476   // If the scope has an associated entity and the using directive is at
9477   // namespace or translation unit scope, add the UsingDirectiveDecl into
9478   // its lookup structure so qualified name lookup can find it.
9479   DeclContext *Ctx = S->getEntity();
9480   if (Ctx && !Ctx->isFunctionOrMethod())
9481     Ctx->addDecl(UDir);
9482   else
9483     // Otherwise, it is at block scope. The using-directives will affect lookup
9484     // only to the end of the scope.
9485     S->PushUsingDirective(UDir);
9486 }
9487 
9488 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9489                                   SourceLocation UsingLoc,
9490                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9491                                   UnqualifiedId &Name,
9492                                   SourceLocation EllipsisLoc,
9493                                   const ParsedAttributesView &AttrList) {
9494   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9495 
9496   if (SS.isEmpty()) {
9497     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9498     return nullptr;
9499   }
9500 
9501   switch (Name.getKind()) {
9502   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9503   case UnqualifiedIdKind::IK_Identifier:
9504   case UnqualifiedIdKind::IK_OperatorFunctionId:
9505   case UnqualifiedIdKind::IK_LiteralOperatorId:
9506   case UnqualifiedIdKind::IK_ConversionFunctionId:
9507     break;
9508 
9509   case UnqualifiedIdKind::IK_ConstructorName:
9510   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9511     // C++11 inheriting constructors.
9512     Diag(Name.getBeginLoc(),
9513          getLangOpts().CPlusPlus11
9514              ? diag::warn_cxx98_compat_using_decl_constructor
9515              : diag::err_using_decl_constructor)
9516         << SS.getRange();
9517 
9518     if (getLangOpts().CPlusPlus11) break;
9519 
9520     return nullptr;
9521 
9522   case UnqualifiedIdKind::IK_DestructorName:
9523     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9524     return nullptr;
9525 
9526   case UnqualifiedIdKind::IK_TemplateId:
9527     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9528         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9529     return nullptr;
9530 
9531   case UnqualifiedIdKind::IK_DeductionGuideName:
9532     llvm_unreachable("cannot parse qualified deduction guide name");
9533   }
9534 
9535   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9536   DeclarationName TargetName = TargetNameInfo.getName();
9537   if (!TargetName)
9538     return nullptr;
9539 
9540   // Warn about access declarations.
9541   if (UsingLoc.isInvalid()) {
9542     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9543                                  ? diag::err_access_decl
9544                                  : diag::warn_access_decl_deprecated)
9545         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9546   }
9547 
9548   if (EllipsisLoc.isInvalid()) {
9549     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9550         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9551       return nullptr;
9552   } else {
9553     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9554         !TargetNameInfo.containsUnexpandedParameterPack()) {
9555       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9556         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9557       EllipsisLoc = SourceLocation();
9558     }
9559   }
9560 
9561   NamedDecl *UD =
9562       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9563                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9564                             /*IsInstantiation*/false);
9565   if (UD)
9566     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9567 
9568   return UD;
9569 }
9570 
9571 /// Determine whether a using declaration considers the given
9572 /// declarations as "equivalent", e.g., if they are redeclarations of
9573 /// the same entity or are both typedefs of the same type.
9574 static bool
9575 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9576   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9577     return true;
9578 
9579   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9580     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9581       return Context.hasSameType(TD1->getUnderlyingType(),
9582                                  TD2->getUnderlyingType());
9583 
9584   return false;
9585 }
9586 
9587 
9588 /// Determines whether to create a using shadow decl for a particular
9589 /// decl, given the set of decls existing prior to this using lookup.
9590 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9591                                 const LookupResult &Previous,
9592                                 UsingShadowDecl *&PrevShadow) {
9593   // Diagnose finding a decl which is not from a base class of the
9594   // current class.  We do this now because there are cases where this
9595   // function will silently decide not to build a shadow decl, which
9596   // will pre-empt further diagnostics.
9597   //
9598   // We don't need to do this in C++11 because we do the check once on
9599   // the qualifier.
9600   //
9601   // FIXME: diagnose the following if we care enough:
9602   //   struct A { int foo; };
9603   //   struct B : A { using A::foo; };
9604   //   template <class T> struct C : A {};
9605   //   template <class T> struct D : C<T> { using B::foo; } // <---
9606   // This is invalid (during instantiation) in C++03 because B::foo
9607   // resolves to the using decl in B, which is not a base class of D<T>.
9608   // We can't diagnose it immediately because C<T> is an unknown
9609   // specialization.  The UsingShadowDecl in D<T> then points directly
9610   // to A::foo, which will look well-formed when we instantiate.
9611   // The right solution is to not collapse the shadow-decl chain.
9612   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9613     DeclContext *OrigDC = Orig->getDeclContext();
9614 
9615     // Handle enums and anonymous structs.
9616     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9617     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9618     while (OrigRec->isAnonymousStructOrUnion())
9619       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9620 
9621     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9622       if (OrigDC == CurContext) {
9623         Diag(Using->getLocation(),
9624              diag::err_using_decl_nested_name_specifier_is_current_class)
9625           << Using->getQualifierLoc().getSourceRange();
9626         Diag(Orig->getLocation(), diag::note_using_decl_target);
9627         Using->setInvalidDecl();
9628         return true;
9629       }
9630 
9631       Diag(Using->getQualifierLoc().getBeginLoc(),
9632            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9633         << Using->getQualifier()
9634         << cast<CXXRecordDecl>(CurContext)
9635         << Using->getQualifierLoc().getSourceRange();
9636       Diag(Orig->getLocation(), diag::note_using_decl_target);
9637       Using->setInvalidDecl();
9638       return true;
9639     }
9640   }
9641 
9642   if (Previous.empty()) return false;
9643 
9644   NamedDecl *Target = Orig;
9645   if (isa<UsingShadowDecl>(Target))
9646     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9647 
9648   // If the target happens to be one of the previous declarations, we
9649   // don't have a conflict.
9650   //
9651   // FIXME: but we might be increasing its access, in which case we
9652   // should redeclare it.
9653   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9654   bool FoundEquivalentDecl = false;
9655   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9656          I != E; ++I) {
9657     NamedDecl *D = (*I)->getUnderlyingDecl();
9658     // We can have UsingDecls in our Previous results because we use the same
9659     // LookupResult for checking whether the UsingDecl itself is a valid
9660     // redeclaration.
9661     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9662       continue;
9663 
9664     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9665       // C++ [class.mem]p19:
9666       //   If T is the name of a class, then [every named member other than
9667       //   a non-static data member] shall have a name different from T
9668       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9669           !isa<IndirectFieldDecl>(Target) &&
9670           !isa<UnresolvedUsingValueDecl>(Target) &&
9671           DiagnoseClassNameShadow(
9672               CurContext,
9673               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9674         return true;
9675     }
9676 
9677     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9678       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9679         PrevShadow = Shadow;
9680       FoundEquivalentDecl = true;
9681     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9682       // We don't conflict with an existing using shadow decl of an equivalent
9683       // declaration, but we're not a redeclaration of it.
9684       FoundEquivalentDecl = true;
9685     }
9686 
9687     if (isVisible(D))
9688       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9689   }
9690 
9691   if (FoundEquivalentDecl)
9692     return false;
9693 
9694   if (FunctionDecl *FD = Target->getAsFunction()) {
9695     NamedDecl *OldDecl = nullptr;
9696     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9697                           /*IsForUsingDecl*/ true)) {
9698     case Ovl_Overload:
9699       return false;
9700 
9701     case Ovl_NonFunction:
9702       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9703       break;
9704 
9705     // We found a decl with the exact signature.
9706     case Ovl_Match:
9707       // If we're in a record, we want to hide the target, so we
9708       // return true (without a diagnostic) to tell the caller not to
9709       // build a shadow decl.
9710       if (CurContext->isRecord())
9711         return true;
9712 
9713       // If we're not in a record, this is an error.
9714       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9715       break;
9716     }
9717 
9718     Diag(Target->getLocation(), diag::note_using_decl_target);
9719     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9720     Using->setInvalidDecl();
9721     return true;
9722   }
9723 
9724   // Target is not a function.
9725 
9726   if (isa<TagDecl>(Target)) {
9727     // No conflict between a tag and a non-tag.
9728     if (!Tag) return false;
9729 
9730     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9731     Diag(Target->getLocation(), diag::note_using_decl_target);
9732     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9733     Using->setInvalidDecl();
9734     return true;
9735   }
9736 
9737   // No conflict between a tag and a non-tag.
9738   if (!NonTag) return false;
9739 
9740   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9741   Diag(Target->getLocation(), diag::note_using_decl_target);
9742   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9743   Using->setInvalidDecl();
9744   return true;
9745 }
9746 
9747 /// Determine whether a direct base class is a virtual base class.
9748 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9749   if (!Derived->getNumVBases())
9750     return false;
9751   for (auto &B : Derived->bases())
9752     if (B.getType()->getAsCXXRecordDecl() == Base)
9753       return B.isVirtual();
9754   llvm_unreachable("not a direct base class");
9755 }
9756 
9757 /// Builds a shadow declaration corresponding to a 'using' declaration.
9758 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9759                                             UsingDecl *UD,
9760                                             NamedDecl *Orig,
9761                                             UsingShadowDecl *PrevDecl) {
9762   // If we resolved to another shadow declaration, just coalesce them.
9763   NamedDecl *Target = Orig;
9764   if (isa<UsingShadowDecl>(Target)) {
9765     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9766     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9767   }
9768 
9769   NamedDecl *NonTemplateTarget = Target;
9770   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9771     NonTemplateTarget = TargetTD->getTemplatedDecl();
9772 
9773   UsingShadowDecl *Shadow;
9774   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9775     bool IsVirtualBase =
9776         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9777                             UD->getQualifier()->getAsRecordDecl());
9778     Shadow = ConstructorUsingShadowDecl::Create(
9779         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9780   } else {
9781     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9782                                      Target);
9783   }
9784   UD->addShadowDecl(Shadow);
9785 
9786   Shadow->setAccess(UD->getAccess());
9787   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9788     Shadow->setInvalidDecl();
9789 
9790   Shadow->setPreviousDecl(PrevDecl);
9791 
9792   if (S)
9793     PushOnScopeChains(Shadow, S);
9794   else
9795     CurContext->addDecl(Shadow);
9796 
9797 
9798   return Shadow;
9799 }
9800 
9801 /// Hides a using shadow declaration.  This is required by the current
9802 /// using-decl implementation when a resolvable using declaration in a
9803 /// class is followed by a declaration which would hide or override
9804 /// one or more of the using decl's targets; for example:
9805 ///
9806 ///   struct Base { void foo(int); };
9807 ///   struct Derived : Base {
9808 ///     using Base::foo;
9809 ///     void foo(int);
9810 ///   };
9811 ///
9812 /// The governing language is C++03 [namespace.udecl]p12:
9813 ///
9814 ///   When a using-declaration brings names from a base class into a
9815 ///   derived class scope, member functions in the derived class
9816 ///   override and/or hide member functions with the same name and
9817 ///   parameter types in a base class (rather than conflicting).
9818 ///
9819 /// There are two ways to implement this:
9820 ///   (1) optimistically create shadow decls when they're not hidden
9821 ///       by existing declarations, or
9822 ///   (2) don't create any shadow decls (or at least don't make them
9823 ///       visible) until we've fully parsed/instantiated the class.
9824 /// The problem with (1) is that we might have to retroactively remove
9825 /// a shadow decl, which requires several O(n) operations because the
9826 /// decl structures are (very reasonably) not designed for removal.
9827 /// (2) avoids this but is very fiddly and phase-dependent.
9828 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9829   if (Shadow->getDeclName().getNameKind() ==
9830         DeclarationName::CXXConversionFunctionName)
9831     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9832 
9833   // Remove it from the DeclContext...
9834   Shadow->getDeclContext()->removeDecl(Shadow);
9835 
9836   // ...and the scope, if applicable...
9837   if (S) {
9838     S->RemoveDecl(Shadow);
9839     IdResolver.RemoveDecl(Shadow);
9840   }
9841 
9842   // ...and the using decl.
9843   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9844 
9845   // TODO: complain somehow if Shadow was used.  It shouldn't
9846   // be possible for this to happen, because...?
9847 }
9848 
9849 /// Find the base specifier for a base class with the given type.
9850 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9851                                                 QualType DesiredBase,
9852                                                 bool &AnyDependentBases) {
9853   // Check whether the named type is a direct base class.
9854   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9855   for (auto &Base : Derived->bases()) {
9856     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9857     if (CanonicalDesiredBase == BaseType)
9858       return &Base;
9859     if (BaseType->isDependentType())
9860       AnyDependentBases = true;
9861   }
9862   return nullptr;
9863 }
9864 
9865 namespace {
9866 class UsingValidatorCCC : public CorrectionCandidateCallback {
9867 public:
9868   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9869                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9870       : HasTypenameKeyword(HasTypenameKeyword),
9871         IsInstantiation(IsInstantiation), OldNNS(NNS),
9872         RequireMemberOf(RequireMemberOf) {}
9873 
9874   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9875     NamedDecl *ND = Candidate.getCorrectionDecl();
9876 
9877     // Keywords are not valid here.
9878     if (!ND || isa<NamespaceDecl>(ND))
9879       return false;
9880 
9881     // Completely unqualified names are invalid for a 'using' declaration.
9882     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9883       return false;
9884 
9885     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9886     // reject.
9887 
9888     if (RequireMemberOf) {
9889       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9890       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9891         // No-one ever wants a using-declaration to name an injected-class-name
9892         // of a base class, unless they're declaring an inheriting constructor.
9893         ASTContext &Ctx = ND->getASTContext();
9894         if (!Ctx.getLangOpts().CPlusPlus11)
9895           return false;
9896         QualType FoundType = Ctx.getRecordType(FoundRecord);
9897 
9898         // Check that the injected-class-name is named as a member of its own
9899         // type; we don't want to suggest 'using Derived::Base;', since that
9900         // means something else.
9901         NestedNameSpecifier *Specifier =
9902             Candidate.WillReplaceSpecifier()
9903                 ? Candidate.getCorrectionSpecifier()
9904                 : OldNNS;
9905         if (!Specifier->getAsType() ||
9906             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9907           return false;
9908 
9909         // Check that this inheriting constructor declaration actually names a
9910         // direct base class of the current class.
9911         bool AnyDependentBases = false;
9912         if (!findDirectBaseWithType(RequireMemberOf,
9913                                     Ctx.getRecordType(FoundRecord),
9914                                     AnyDependentBases) &&
9915             !AnyDependentBases)
9916           return false;
9917       } else {
9918         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9919         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9920           return false;
9921 
9922         // FIXME: Check that the base class member is accessible?
9923       }
9924     } else {
9925       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9926       if (FoundRecord && FoundRecord->isInjectedClassName())
9927         return false;
9928     }
9929 
9930     if (isa<TypeDecl>(ND))
9931       return HasTypenameKeyword || !IsInstantiation;
9932 
9933     return !HasTypenameKeyword;
9934   }
9935 
9936 private:
9937   bool HasTypenameKeyword;
9938   bool IsInstantiation;
9939   NestedNameSpecifier *OldNNS;
9940   CXXRecordDecl *RequireMemberOf;
9941 };
9942 } // end anonymous namespace
9943 
9944 /// Builds a using declaration.
9945 ///
9946 /// \param IsInstantiation - Whether this call arises from an
9947 ///   instantiation of an unresolved using declaration.  We treat
9948 ///   the lookup differently for these declarations.
9949 NamedDecl *Sema::BuildUsingDeclaration(
9950     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9951     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9952     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9953     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9954   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9955   SourceLocation IdentLoc = NameInfo.getLoc();
9956   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9957 
9958   // FIXME: We ignore attributes for now.
9959 
9960   // For an inheriting constructor declaration, the name of the using
9961   // declaration is the name of a constructor in this class, not in the
9962   // base class.
9963   DeclarationNameInfo UsingName = NameInfo;
9964   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9965     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9966       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9967           Context.getCanonicalType(Context.getRecordType(RD))));
9968 
9969   // Do the redeclaration lookup in the current scope.
9970   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9971                         ForVisibleRedeclaration);
9972   Previous.setHideTags(false);
9973   if (S) {
9974     LookupName(Previous, S);
9975 
9976     // It is really dumb that we have to do this.
9977     LookupResult::Filter F = Previous.makeFilter();
9978     while (F.hasNext()) {
9979       NamedDecl *D = F.next();
9980       if (!isDeclInScope(D, CurContext, S))
9981         F.erase();
9982       // If we found a local extern declaration that's not ordinarily visible,
9983       // and this declaration is being added to a non-block scope, ignore it.
9984       // We're only checking for scope conflicts here, not also for violations
9985       // of the linkage rules.
9986       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9987                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9988         F.erase();
9989     }
9990     F.done();
9991   } else {
9992     assert(IsInstantiation && "no scope in non-instantiation");
9993     if (CurContext->isRecord())
9994       LookupQualifiedName(Previous, CurContext);
9995     else {
9996       // No redeclaration check is needed here; in non-member contexts we
9997       // diagnosed all possible conflicts with other using-declarations when
9998       // building the template:
9999       //
10000       // For a dependent non-type using declaration, the only valid case is
10001       // if we instantiate to a single enumerator. We check for conflicts
10002       // between shadow declarations we introduce, and we check in the template
10003       // definition for conflicts between a non-type using declaration and any
10004       // other declaration, which together covers all cases.
10005       //
10006       // A dependent typename using declaration will never successfully
10007       // instantiate, since it will always name a class member, so we reject
10008       // that in the template definition.
10009     }
10010   }
10011 
10012   // Check for invalid redeclarations.
10013   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10014                                   SS, IdentLoc, Previous))
10015     return nullptr;
10016 
10017   // Check for bad qualifiers.
10018   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10019                               IdentLoc))
10020     return nullptr;
10021 
10022   DeclContext *LookupContext = computeDeclContext(SS);
10023   NamedDecl *D;
10024   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10025   if (!LookupContext || EllipsisLoc.isValid()) {
10026     if (HasTypenameKeyword) {
10027       // FIXME: not all declaration name kinds are legal here
10028       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10029                                               UsingLoc, TypenameLoc,
10030                                               QualifierLoc,
10031                                               IdentLoc, NameInfo.getName(),
10032                                               EllipsisLoc);
10033     } else {
10034       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10035                                            QualifierLoc, NameInfo, EllipsisLoc);
10036     }
10037     D->setAccess(AS);
10038     CurContext->addDecl(D);
10039     return D;
10040   }
10041 
10042   auto Build = [&](bool Invalid) {
10043     UsingDecl *UD =
10044         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10045                           UsingName, HasTypenameKeyword);
10046     UD->setAccess(AS);
10047     CurContext->addDecl(UD);
10048     UD->setInvalidDecl(Invalid);
10049     return UD;
10050   };
10051   auto BuildInvalid = [&]{ return Build(true); };
10052   auto BuildValid = [&]{ return Build(false); };
10053 
10054   if (RequireCompleteDeclContext(SS, LookupContext))
10055     return BuildInvalid();
10056 
10057   // Look up the target name.
10058   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10059 
10060   // Unlike most lookups, we don't always want to hide tag
10061   // declarations: tag names are visible through the using declaration
10062   // even if hidden by ordinary names, *except* in a dependent context
10063   // where it's important for the sanity of two-phase lookup.
10064   if (!IsInstantiation)
10065     R.setHideTags(false);
10066 
10067   // For the purposes of this lookup, we have a base object type
10068   // equal to that of the current context.
10069   if (CurContext->isRecord()) {
10070     R.setBaseObjectType(
10071                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10072   }
10073 
10074   LookupQualifiedName(R, LookupContext);
10075 
10076   // Try to correct typos if possible. If constructor name lookup finds no
10077   // results, that means the named class has no explicit constructors, and we
10078   // suppressed declaring implicit ones (probably because it's dependent or
10079   // invalid).
10080   if (R.empty() &&
10081       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10082     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10083     // it will believe that glibc provides a ::gets in cases where it does not,
10084     // and will try to pull it into namespace std with a using-declaration.
10085     // Just ignore the using-declaration in that case.
10086     auto *II = NameInfo.getName().getAsIdentifierInfo();
10087     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10088         CurContext->isStdNamespace() &&
10089         isa<TranslationUnitDecl>(LookupContext) &&
10090         getSourceManager().isInSystemHeader(UsingLoc))
10091       return nullptr;
10092     if (TypoCorrection Corrected = CorrectTypo(
10093             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10094             llvm::make_unique<UsingValidatorCCC>(
10095                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10096                 dyn_cast<CXXRecordDecl>(CurContext)),
10097             CTK_ErrorRecovery)) {
10098       // We reject candidates where DroppedSpecifier == true, hence the
10099       // literal '0' below.
10100       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10101                                 << NameInfo.getName() << LookupContext << 0
10102                                 << SS.getRange());
10103 
10104       // If we picked a correction with no attached Decl we can't do anything
10105       // useful with it, bail out.
10106       NamedDecl *ND = Corrected.getCorrectionDecl();
10107       if (!ND)
10108         return BuildInvalid();
10109 
10110       // If we corrected to an inheriting constructor, handle it as one.
10111       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10112       if (RD && RD->isInjectedClassName()) {
10113         // The parent of the injected class name is the class itself.
10114         RD = cast<CXXRecordDecl>(RD->getParent());
10115 
10116         // Fix up the information we'll use to build the using declaration.
10117         if (Corrected.WillReplaceSpecifier()) {
10118           NestedNameSpecifierLocBuilder Builder;
10119           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10120                               QualifierLoc.getSourceRange());
10121           QualifierLoc = Builder.getWithLocInContext(Context);
10122         }
10123 
10124         // In this case, the name we introduce is the name of a derived class
10125         // constructor.
10126         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10127         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10128             Context.getCanonicalType(Context.getRecordType(CurClass))));
10129         UsingName.setNamedTypeInfo(nullptr);
10130         for (auto *Ctor : LookupConstructors(RD))
10131           R.addDecl(Ctor);
10132         R.resolveKind();
10133       } else {
10134         // FIXME: Pick up all the declarations if we found an overloaded
10135         // function.
10136         UsingName.setName(ND->getDeclName());
10137         R.addDecl(ND);
10138       }
10139     } else {
10140       Diag(IdentLoc, diag::err_no_member)
10141         << NameInfo.getName() << LookupContext << SS.getRange();
10142       return BuildInvalid();
10143     }
10144   }
10145 
10146   if (R.isAmbiguous())
10147     return BuildInvalid();
10148 
10149   if (HasTypenameKeyword) {
10150     // If we asked for a typename and got a non-type decl, error out.
10151     if (!R.getAsSingle<TypeDecl>()) {
10152       Diag(IdentLoc, diag::err_using_typename_non_type);
10153       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10154         Diag((*I)->getUnderlyingDecl()->getLocation(),
10155              diag::note_using_decl_target);
10156       return BuildInvalid();
10157     }
10158   } else {
10159     // If we asked for a non-typename and we got a type, error out,
10160     // but only if this is an instantiation of an unresolved using
10161     // decl.  Otherwise just silently find the type name.
10162     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10163       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10164       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10165       return BuildInvalid();
10166     }
10167   }
10168 
10169   // C++14 [namespace.udecl]p6:
10170   // A using-declaration shall not name a namespace.
10171   if (R.getAsSingle<NamespaceDecl>()) {
10172     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10173       << SS.getRange();
10174     return BuildInvalid();
10175   }
10176 
10177   // C++14 [namespace.udecl]p7:
10178   // A using-declaration shall not name a scoped enumerator.
10179   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10180     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10181       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10182         << SS.getRange();
10183       return BuildInvalid();
10184     }
10185   }
10186 
10187   UsingDecl *UD = BuildValid();
10188 
10189   // Some additional rules apply to inheriting constructors.
10190   if (UsingName.getName().getNameKind() ==
10191         DeclarationName::CXXConstructorName) {
10192     // Suppress access diagnostics; the access check is instead performed at the
10193     // point of use for an inheriting constructor.
10194     R.suppressDiagnostics();
10195     if (CheckInheritingConstructorUsingDecl(UD))
10196       return UD;
10197   }
10198 
10199   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10200     UsingShadowDecl *PrevDecl = nullptr;
10201     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10202       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10203   }
10204 
10205   return UD;
10206 }
10207 
10208 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10209                                     ArrayRef<NamedDecl *> Expansions) {
10210   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10211          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10212          isa<UsingPackDecl>(InstantiatedFrom));
10213 
10214   auto *UPD =
10215       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10216   UPD->setAccess(InstantiatedFrom->getAccess());
10217   CurContext->addDecl(UPD);
10218   return UPD;
10219 }
10220 
10221 /// Additional checks for a using declaration referring to a constructor name.
10222 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10223   assert(!UD->hasTypename() && "expecting a constructor name");
10224 
10225   const Type *SourceType = UD->getQualifier()->getAsType();
10226   assert(SourceType &&
10227          "Using decl naming constructor doesn't have type in scope spec.");
10228   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10229 
10230   // Check whether the named type is a direct base class.
10231   bool AnyDependentBases = false;
10232   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10233                                       AnyDependentBases);
10234   if (!Base && !AnyDependentBases) {
10235     Diag(UD->getUsingLoc(),
10236          diag::err_using_decl_constructor_not_in_direct_base)
10237       << UD->getNameInfo().getSourceRange()
10238       << QualType(SourceType, 0) << TargetClass;
10239     UD->setInvalidDecl();
10240     return true;
10241   }
10242 
10243   if (Base)
10244     Base->setInheritConstructors();
10245 
10246   return false;
10247 }
10248 
10249 /// Checks that the given using declaration is not an invalid
10250 /// redeclaration.  Note that this is checking only for the using decl
10251 /// itself, not for any ill-formedness among the UsingShadowDecls.
10252 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10253                                        bool HasTypenameKeyword,
10254                                        const CXXScopeSpec &SS,
10255                                        SourceLocation NameLoc,
10256                                        const LookupResult &Prev) {
10257   NestedNameSpecifier *Qual = SS.getScopeRep();
10258 
10259   // C++03 [namespace.udecl]p8:
10260   // C++0x [namespace.udecl]p10:
10261   //   A using-declaration is a declaration and can therefore be used
10262   //   repeatedly where (and only where) multiple declarations are
10263   //   allowed.
10264   //
10265   // That's in non-member contexts.
10266   if (!CurContext->getRedeclContext()->isRecord()) {
10267     // A dependent qualifier outside a class can only ever resolve to an
10268     // enumeration type. Therefore it conflicts with any other non-type
10269     // declaration in the same scope.
10270     // FIXME: How should we check for dependent type-type conflicts at block
10271     // scope?
10272     if (Qual->isDependent() && !HasTypenameKeyword) {
10273       for (auto *D : Prev) {
10274         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10275           bool OldCouldBeEnumerator =
10276               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10277           Diag(NameLoc,
10278                OldCouldBeEnumerator ? diag::err_redefinition
10279                                     : diag::err_redefinition_different_kind)
10280               << Prev.getLookupName();
10281           Diag(D->getLocation(), diag::note_previous_definition);
10282           return true;
10283         }
10284       }
10285     }
10286     return false;
10287   }
10288 
10289   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10290     NamedDecl *D = *I;
10291 
10292     bool DTypename;
10293     NestedNameSpecifier *DQual;
10294     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10295       DTypename = UD->hasTypename();
10296       DQual = UD->getQualifier();
10297     } else if (UnresolvedUsingValueDecl *UD
10298                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10299       DTypename = false;
10300       DQual = UD->getQualifier();
10301     } else if (UnresolvedUsingTypenameDecl *UD
10302                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10303       DTypename = true;
10304       DQual = UD->getQualifier();
10305     } else continue;
10306 
10307     // using decls differ if one says 'typename' and the other doesn't.
10308     // FIXME: non-dependent using decls?
10309     if (HasTypenameKeyword != DTypename) continue;
10310 
10311     // using decls differ if they name different scopes (but note that
10312     // template instantiation can cause this check to trigger when it
10313     // didn't before instantiation).
10314     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10315         Context.getCanonicalNestedNameSpecifier(DQual))
10316       continue;
10317 
10318     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10319     Diag(D->getLocation(), diag::note_using_decl) << 1;
10320     return true;
10321   }
10322 
10323   return false;
10324 }
10325 
10326 
10327 /// Checks that the given nested-name qualifier used in a using decl
10328 /// in the current context is appropriately related to the current
10329 /// scope.  If an error is found, diagnoses it and returns true.
10330 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10331                                    bool HasTypename,
10332                                    const CXXScopeSpec &SS,
10333                                    const DeclarationNameInfo &NameInfo,
10334                                    SourceLocation NameLoc) {
10335   DeclContext *NamedContext = computeDeclContext(SS);
10336 
10337   if (!CurContext->isRecord()) {
10338     // C++03 [namespace.udecl]p3:
10339     // C++0x [namespace.udecl]p8:
10340     //   A using-declaration for a class member shall be a member-declaration.
10341 
10342     // If we weren't able to compute a valid scope, it might validly be a
10343     // dependent class scope or a dependent enumeration unscoped scope. If
10344     // we have a 'typename' keyword, the scope must resolve to a class type.
10345     if ((HasTypename && !NamedContext) ||
10346         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10347       auto *RD = NamedContext
10348                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10349                      : nullptr;
10350       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10351         RD = nullptr;
10352 
10353       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10354         << SS.getRange();
10355 
10356       // If we have a complete, non-dependent source type, try to suggest a
10357       // way to get the same effect.
10358       if (!RD)
10359         return true;
10360 
10361       // Find what this using-declaration was referring to.
10362       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10363       R.setHideTags(false);
10364       R.suppressDiagnostics();
10365       LookupQualifiedName(R, RD);
10366 
10367       if (R.getAsSingle<TypeDecl>()) {
10368         if (getLangOpts().CPlusPlus11) {
10369           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10370           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10371             << 0 // alias declaration
10372             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10373                                           NameInfo.getName().getAsString() +
10374                                               " = ");
10375         } else {
10376           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10377           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10378           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10379             << 1 // typedef declaration
10380             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10381             << FixItHint::CreateInsertion(
10382                    InsertLoc, " " + NameInfo.getName().getAsString());
10383         }
10384       } else if (R.getAsSingle<VarDecl>()) {
10385         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10386         // repeating the type of the static data member here.
10387         FixItHint FixIt;
10388         if (getLangOpts().CPlusPlus11) {
10389           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10390           FixIt = FixItHint::CreateReplacement(
10391               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10392         }
10393 
10394         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10395           << 2 // reference declaration
10396           << FixIt;
10397       } else if (R.getAsSingle<EnumConstantDecl>()) {
10398         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10399         // repeating the type of the enumeration here, and we can't do so if
10400         // the type is anonymous.
10401         FixItHint FixIt;
10402         if (getLangOpts().CPlusPlus11) {
10403           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10404           FixIt = FixItHint::CreateReplacement(
10405               UsingLoc,
10406               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10407         }
10408 
10409         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10410           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10411           << FixIt;
10412       }
10413       return true;
10414     }
10415 
10416     // Otherwise, this might be valid.
10417     return false;
10418   }
10419 
10420   // The current scope is a record.
10421 
10422   // If the named context is dependent, we can't decide much.
10423   if (!NamedContext) {
10424     // FIXME: in C++0x, we can diagnose if we can prove that the
10425     // nested-name-specifier does not refer to a base class, which is
10426     // still possible in some cases.
10427 
10428     // Otherwise we have to conservatively report that things might be
10429     // okay.
10430     return false;
10431   }
10432 
10433   if (!NamedContext->isRecord()) {
10434     // Ideally this would point at the last name in the specifier,
10435     // but we don't have that level of source info.
10436     Diag(SS.getRange().getBegin(),
10437          diag::err_using_decl_nested_name_specifier_is_not_class)
10438       << SS.getScopeRep() << SS.getRange();
10439     return true;
10440   }
10441 
10442   if (!NamedContext->isDependentContext() &&
10443       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10444     return true;
10445 
10446   if (getLangOpts().CPlusPlus11) {
10447     // C++11 [namespace.udecl]p3:
10448     //   In a using-declaration used as a member-declaration, the
10449     //   nested-name-specifier shall name a base class of the class
10450     //   being defined.
10451 
10452     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10453                                  cast<CXXRecordDecl>(NamedContext))) {
10454       if (CurContext == NamedContext) {
10455         Diag(NameLoc,
10456              diag::err_using_decl_nested_name_specifier_is_current_class)
10457           << SS.getRange();
10458         return true;
10459       }
10460 
10461       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10462         Diag(SS.getRange().getBegin(),
10463              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10464           << SS.getScopeRep()
10465           << cast<CXXRecordDecl>(CurContext)
10466           << SS.getRange();
10467       }
10468       return true;
10469     }
10470 
10471     return false;
10472   }
10473 
10474   // C++03 [namespace.udecl]p4:
10475   //   A using-declaration used as a member-declaration shall refer
10476   //   to a member of a base class of the class being defined [etc.].
10477 
10478   // Salient point: SS doesn't have to name a base class as long as
10479   // lookup only finds members from base classes.  Therefore we can
10480   // diagnose here only if we can prove that that can't happen,
10481   // i.e. if the class hierarchies provably don't intersect.
10482 
10483   // TODO: it would be nice if "definitely valid" results were cached
10484   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10485   // need to be repeated.
10486 
10487   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10488   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10489     Bases.insert(Base);
10490     return true;
10491   };
10492 
10493   // Collect all bases. Return false if we find a dependent base.
10494   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10495     return false;
10496 
10497   // Returns true if the base is dependent or is one of the accumulated base
10498   // classes.
10499   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10500     return !Bases.count(Base);
10501   };
10502 
10503   // Return false if the class has a dependent base or if it or one
10504   // of its bases is present in the base set of the current context.
10505   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10506       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10507     return false;
10508 
10509   Diag(SS.getRange().getBegin(),
10510        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10511     << SS.getScopeRep()
10512     << cast<CXXRecordDecl>(CurContext)
10513     << SS.getRange();
10514 
10515   return true;
10516 }
10517 
10518 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10519                                   MultiTemplateParamsArg TemplateParamLists,
10520                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10521                                   const ParsedAttributesView &AttrList,
10522                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10523   // Skip up to the relevant declaration scope.
10524   while (S->isTemplateParamScope())
10525     S = S->getParent();
10526   assert((S->getFlags() & Scope::DeclScope) &&
10527          "got alias-declaration outside of declaration scope");
10528 
10529   if (Type.isInvalid())
10530     return nullptr;
10531 
10532   bool Invalid = false;
10533   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10534   TypeSourceInfo *TInfo = nullptr;
10535   GetTypeFromParser(Type.get(), &TInfo);
10536 
10537   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10538     return nullptr;
10539 
10540   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10541                                       UPPC_DeclarationType)) {
10542     Invalid = true;
10543     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10544                                              TInfo->getTypeLoc().getBeginLoc());
10545   }
10546 
10547   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10548                         TemplateParamLists.size()
10549                             ? forRedeclarationInCurContext()
10550                             : ForVisibleRedeclaration);
10551   LookupName(Previous, S);
10552 
10553   // Warn about shadowing the name of a template parameter.
10554   if (Previous.isSingleResult() &&
10555       Previous.getFoundDecl()->isTemplateParameter()) {
10556     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10557     Previous.clear();
10558   }
10559 
10560   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10561          "name in alias declaration must be an identifier");
10562   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10563                                                Name.StartLocation,
10564                                                Name.Identifier, TInfo);
10565 
10566   NewTD->setAccess(AS);
10567 
10568   if (Invalid)
10569     NewTD->setInvalidDecl();
10570 
10571   ProcessDeclAttributeList(S, NewTD, AttrList);
10572   AddPragmaAttributes(S, NewTD);
10573 
10574   CheckTypedefForVariablyModifiedType(S, NewTD);
10575   Invalid |= NewTD->isInvalidDecl();
10576 
10577   bool Redeclaration = false;
10578 
10579   NamedDecl *NewND;
10580   if (TemplateParamLists.size()) {
10581     TypeAliasTemplateDecl *OldDecl = nullptr;
10582     TemplateParameterList *OldTemplateParams = nullptr;
10583 
10584     if (TemplateParamLists.size() != 1) {
10585       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10586         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10587          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10588     }
10589     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10590 
10591     // Check that we can declare a template here.
10592     if (CheckTemplateDeclScope(S, TemplateParams))
10593       return nullptr;
10594 
10595     // Only consider previous declarations in the same scope.
10596     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10597                          /*ExplicitInstantiationOrSpecialization*/false);
10598     if (!Previous.empty()) {
10599       Redeclaration = true;
10600 
10601       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10602       if (!OldDecl && !Invalid) {
10603         Diag(UsingLoc, diag::err_redefinition_different_kind)
10604           << Name.Identifier;
10605 
10606         NamedDecl *OldD = Previous.getRepresentativeDecl();
10607         if (OldD->getLocation().isValid())
10608           Diag(OldD->getLocation(), diag::note_previous_definition);
10609 
10610         Invalid = true;
10611       }
10612 
10613       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10614         if (TemplateParameterListsAreEqual(TemplateParams,
10615                                            OldDecl->getTemplateParameters(),
10616                                            /*Complain=*/true,
10617                                            TPL_TemplateMatch))
10618           OldTemplateParams =
10619               OldDecl->getMostRecentDecl()->getTemplateParameters();
10620         else
10621           Invalid = true;
10622 
10623         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10624         if (!Invalid &&
10625             !Context.hasSameType(OldTD->getUnderlyingType(),
10626                                  NewTD->getUnderlyingType())) {
10627           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10628           // but we can't reasonably accept it.
10629           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10630             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10631           if (OldTD->getLocation().isValid())
10632             Diag(OldTD->getLocation(), diag::note_previous_definition);
10633           Invalid = true;
10634         }
10635       }
10636     }
10637 
10638     // Merge any previous default template arguments into our parameters,
10639     // and check the parameter list.
10640     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10641                                    TPC_TypeAliasTemplate))
10642       return nullptr;
10643 
10644     TypeAliasTemplateDecl *NewDecl =
10645       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10646                                     Name.Identifier, TemplateParams,
10647                                     NewTD);
10648     NewTD->setDescribedAliasTemplate(NewDecl);
10649 
10650     NewDecl->setAccess(AS);
10651 
10652     if (Invalid)
10653       NewDecl->setInvalidDecl();
10654     else if (OldDecl) {
10655       NewDecl->setPreviousDecl(OldDecl);
10656       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10657     }
10658 
10659     NewND = NewDecl;
10660   } else {
10661     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10662       setTagNameForLinkagePurposes(TD, NewTD);
10663       handleTagNumbering(TD, S);
10664     }
10665     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10666     NewND = NewTD;
10667   }
10668 
10669   PushOnScopeChains(NewND, S);
10670   ActOnDocumentableDecl(NewND);
10671   return NewND;
10672 }
10673 
10674 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10675                                    SourceLocation AliasLoc,
10676                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10677                                    SourceLocation IdentLoc,
10678                                    IdentifierInfo *Ident) {
10679 
10680   // Lookup the namespace name.
10681   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10682   LookupParsedName(R, S, &SS);
10683 
10684   if (R.isAmbiguous())
10685     return nullptr;
10686 
10687   if (R.empty()) {
10688     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10689       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10690       return nullptr;
10691     }
10692   }
10693   assert(!R.isAmbiguous() && !R.empty());
10694   NamedDecl *ND = R.getRepresentativeDecl();
10695 
10696   // Check if we have a previous declaration with the same name.
10697   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10698                      ForVisibleRedeclaration);
10699   LookupName(PrevR, S);
10700 
10701   // Check we're not shadowing a template parameter.
10702   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10703     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10704     PrevR.clear();
10705   }
10706 
10707   // Filter out any other lookup result from an enclosing scope.
10708   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10709                        /*AllowInlineNamespace*/false);
10710 
10711   // Find the previous declaration and check that we can redeclare it.
10712   NamespaceAliasDecl *Prev = nullptr;
10713   if (PrevR.isSingleResult()) {
10714     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10715     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10716       // We already have an alias with the same name that points to the same
10717       // namespace; check that it matches.
10718       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10719         Prev = AD;
10720       } else if (isVisible(PrevDecl)) {
10721         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10722           << Alias;
10723         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10724           << AD->getNamespace();
10725         return nullptr;
10726       }
10727     } else if (isVisible(PrevDecl)) {
10728       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10729                             ? diag::err_redefinition
10730                             : diag::err_redefinition_different_kind;
10731       Diag(AliasLoc, DiagID) << Alias;
10732       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10733       return nullptr;
10734     }
10735   }
10736 
10737   // The use of a nested name specifier may trigger deprecation warnings.
10738   DiagnoseUseOfDecl(ND, IdentLoc);
10739 
10740   NamespaceAliasDecl *AliasDecl =
10741     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10742                                Alias, SS.getWithLocInContext(Context),
10743                                IdentLoc, ND);
10744   if (Prev)
10745     AliasDecl->setPreviousDecl(Prev);
10746 
10747   PushOnScopeChains(AliasDecl, S);
10748   return AliasDecl;
10749 }
10750 
10751 namespace {
10752 struct SpecialMemberExceptionSpecInfo
10753     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10754   SourceLocation Loc;
10755   Sema::ImplicitExceptionSpecification ExceptSpec;
10756 
10757   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10758                                  Sema::CXXSpecialMember CSM,
10759                                  Sema::InheritedConstructorInfo *ICI,
10760                                  SourceLocation Loc)
10761       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10762 
10763   bool visitBase(CXXBaseSpecifier *Base);
10764   bool visitField(FieldDecl *FD);
10765 
10766   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10767                            unsigned Quals);
10768 
10769   void visitSubobjectCall(Subobject Subobj,
10770                           Sema::SpecialMemberOverloadResult SMOR);
10771 };
10772 }
10773 
10774 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10775   auto *RT = Base->getType()->getAs<RecordType>();
10776   if (!RT)
10777     return false;
10778 
10779   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10780   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10781   if (auto *BaseCtor = SMOR.getMethod()) {
10782     visitSubobjectCall(Base, BaseCtor);
10783     return false;
10784   }
10785 
10786   visitClassSubobject(BaseClass, Base, 0);
10787   return false;
10788 }
10789 
10790 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10791   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10792     Expr *E = FD->getInClassInitializer();
10793     if (!E)
10794       // FIXME: It's a little wasteful to build and throw away a
10795       // CXXDefaultInitExpr here.
10796       // FIXME: We should have a single context note pointing at Loc, and
10797       // this location should be MD->getLocation() instead, since that's
10798       // the location where we actually use the default init expression.
10799       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10800     if (E)
10801       ExceptSpec.CalledExpr(E);
10802   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10803                             ->getAs<RecordType>()) {
10804     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10805                         FD->getType().getCVRQualifiers());
10806   }
10807   return false;
10808 }
10809 
10810 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10811                                                          Subobject Subobj,
10812                                                          unsigned Quals) {
10813   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10814   bool IsMutable = Field && Field->isMutable();
10815   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10816 }
10817 
10818 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10819     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10820   // Note, if lookup fails, it doesn't matter what exception specification we
10821   // choose because the special member will be deleted.
10822   if (CXXMethodDecl *MD = SMOR.getMethod())
10823     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10824 }
10825 
10826 namespace {
10827 /// RAII object to register a special member as being currently declared.
10828 struct ComputingExceptionSpec {
10829   Sema &S;
10830 
10831   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10832       : S(S) {
10833     Sema::CodeSynthesisContext Ctx;
10834     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10835     Ctx.PointOfInstantiation = Loc;
10836     Ctx.Entity = MD;
10837     S.pushCodeSynthesisContext(Ctx);
10838   }
10839   ~ComputingExceptionSpec() {
10840     S.popCodeSynthesisContext();
10841   }
10842 };
10843 }
10844 
10845 static Sema::ImplicitExceptionSpecification
10846 ComputeDefaultedSpecialMemberExceptionSpec(
10847     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10848     Sema::InheritedConstructorInfo *ICI) {
10849   ComputingExceptionSpec CES(S, MD, Loc);
10850 
10851   CXXRecordDecl *ClassDecl = MD->getParent();
10852 
10853   // C++ [except.spec]p14:
10854   //   An implicitly declared special member function (Clause 12) shall have an
10855   //   exception-specification. [...]
10856   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10857   if (ClassDecl->isInvalidDecl())
10858     return Info.ExceptSpec;
10859 
10860   // FIXME: If this diagnostic fires, we're probably missing a check for
10861   // attempting to resolve an exception specification before it's known
10862   // at a higher level.
10863   if (S.RequireCompleteType(MD->getLocation(),
10864                             S.Context.getRecordType(ClassDecl),
10865                             diag::err_exception_spec_incomplete_type))
10866     return Info.ExceptSpec;
10867 
10868   // C++1z [except.spec]p7:
10869   //   [Look for exceptions thrown by] a constructor selected [...] to
10870   //   initialize a potentially constructed subobject,
10871   // C++1z [except.spec]p8:
10872   //   The exception specification for an implicitly-declared destructor, or a
10873   //   destructor without a noexcept-specifier, is potentially-throwing if and
10874   //   only if any of the destructors for any of its potentially constructed
10875   //   subojects is potentially throwing.
10876   // FIXME: We respect the first rule but ignore the "potentially constructed"
10877   // in the second rule to resolve a core issue (no number yet) that would have
10878   // us reject:
10879   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10880   //   struct B : A {};
10881   //   struct C : B { void f(); };
10882   // ... due to giving B::~B() a non-throwing exception specification.
10883   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10884                                 : Info.VisitAllBases);
10885 
10886   return Info.ExceptSpec;
10887 }
10888 
10889 namespace {
10890 /// RAII object to register a special member as being currently declared.
10891 struct DeclaringSpecialMember {
10892   Sema &S;
10893   Sema::SpecialMemberDecl D;
10894   Sema::ContextRAII SavedContext;
10895   bool WasAlreadyBeingDeclared;
10896 
10897   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10898       : S(S), D(RD, CSM), SavedContext(S, RD) {
10899     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10900     if (WasAlreadyBeingDeclared)
10901       // This almost never happens, but if it does, ensure that our cache
10902       // doesn't contain a stale result.
10903       S.SpecialMemberCache.clear();
10904     else {
10905       // Register a note to be produced if we encounter an error while
10906       // declaring the special member.
10907       Sema::CodeSynthesisContext Ctx;
10908       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10909       // FIXME: We don't have a location to use here. Using the class's
10910       // location maintains the fiction that we declare all special members
10911       // with the class, but (1) it's not clear that lying about that helps our
10912       // users understand what's going on, and (2) there may be outer contexts
10913       // on the stack (some of which are relevant) and printing them exposes
10914       // our lies.
10915       Ctx.PointOfInstantiation = RD->getLocation();
10916       Ctx.Entity = RD;
10917       Ctx.SpecialMember = CSM;
10918       S.pushCodeSynthesisContext(Ctx);
10919     }
10920   }
10921   ~DeclaringSpecialMember() {
10922     if (!WasAlreadyBeingDeclared) {
10923       S.SpecialMembersBeingDeclared.erase(D);
10924       S.popCodeSynthesisContext();
10925     }
10926   }
10927 
10928   /// Are we already trying to declare this special member?
10929   bool isAlreadyBeingDeclared() const {
10930     return WasAlreadyBeingDeclared;
10931   }
10932 };
10933 }
10934 
10935 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10936   // Look up any existing declarations, but don't trigger declaration of all
10937   // implicit special members with this name.
10938   DeclarationName Name = FD->getDeclName();
10939   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10940                  ForExternalRedeclaration);
10941   for (auto *D : FD->getParent()->lookup(Name))
10942     if (auto *Acceptable = R.getAcceptableDecl(D))
10943       R.addDecl(Acceptable);
10944   R.resolveKind();
10945   R.suppressDiagnostics();
10946 
10947   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10948 }
10949 
10950 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10951                                           QualType ResultTy,
10952                                           ArrayRef<QualType> Args) {
10953   // Build an exception specification pointing back at this constructor.
10954   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10955 
10956   if (getLangOpts().OpenCLCPlusPlus) {
10957     // OpenCL: Implicitly defaulted special member are of the generic address
10958     // space.
10959     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
10960   }
10961 
10962   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10963   SpecialMem->setType(QT);
10964 }
10965 
10966 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10967                                                      CXXRecordDecl *ClassDecl) {
10968   // C++ [class.ctor]p5:
10969   //   A default constructor for a class X is a constructor of class X
10970   //   that can be called without an argument. If there is no
10971   //   user-declared constructor for class X, a default constructor is
10972   //   implicitly declared. An implicitly-declared default constructor
10973   //   is an inline public member of its class.
10974   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10975          "Should not build implicit default constructor!");
10976 
10977   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10978   if (DSM.isAlreadyBeingDeclared())
10979     return nullptr;
10980 
10981   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10982                                                      CXXDefaultConstructor,
10983                                                      false);
10984 
10985   // Create the actual constructor declaration.
10986   CanQualType ClassType
10987     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10988   SourceLocation ClassLoc = ClassDecl->getLocation();
10989   DeclarationName Name
10990     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10991   DeclarationNameInfo NameInfo(Name, ClassLoc);
10992   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10993       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10994       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10995       /*isImplicitlyDeclared=*/true, Constexpr);
10996   DefaultCon->setAccess(AS_public);
10997   DefaultCon->setDefaulted();
10998 
10999   if (getLangOpts().CUDA) {
11000     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11001                                             DefaultCon,
11002                                             /* ConstRHS */ false,
11003                                             /* Diagnose */ false);
11004   }
11005 
11006   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11007 
11008   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11009   // constructors is easy to compute.
11010   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11011 
11012   // Note that we have declared this constructor.
11013   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
11014 
11015   Scope *S = getScopeForContext(ClassDecl);
11016   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11017 
11018   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11019     SetDeclDeleted(DefaultCon, ClassLoc);
11020 
11021   if (S)
11022     PushOnScopeChains(DefaultCon, S, false);
11023   ClassDecl->addDecl(DefaultCon);
11024 
11025   return DefaultCon;
11026 }
11027 
11028 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11029                                             CXXConstructorDecl *Constructor) {
11030   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11031           !Constructor->doesThisDeclarationHaveABody() &&
11032           !Constructor->isDeleted()) &&
11033     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11034   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11035     return;
11036 
11037   CXXRecordDecl *ClassDecl = Constructor->getParent();
11038   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11039 
11040   SynthesizedFunctionScope Scope(*this, Constructor);
11041 
11042   // The exception specification is needed because we are defining the
11043   // function.
11044   ResolveExceptionSpec(CurrentLocation,
11045                        Constructor->getType()->castAs<FunctionProtoType>());
11046   MarkVTableUsed(CurrentLocation, ClassDecl);
11047 
11048   // Add a context note for diagnostics produced after this point.
11049   Scope.addContextNote(CurrentLocation);
11050 
11051   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11052     Constructor->setInvalidDecl();
11053     return;
11054   }
11055 
11056   SourceLocation Loc = Constructor->getEndLoc().isValid()
11057                            ? Constructor->getEndLoc()
11058                            : Constructor->getLocation();
11059   Constructor->setBody(new (Context) CompoundStmt(Loc));
11060   Constructor->markUsed(Context);
11061 
11062   if (ASTMutationListener *L = getASTMutationListener()) {
11063     L->CompletedImplicitDefinition(Constructor);
11064   }
11065 
11066   DiagnoseUninitializedFields(*this, Constructor);
11067 }
11068 
11069 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11070   // Perform any delayed checks on exception specifications.
11071   CheckDelayedMemberExceptionSpecs();
11072 }
11073 
11074 /// Find or create the fake constructor we synthesize to model constructing an
11075 /// object of a derived class via a constructor of a base class.
11076 CXXConstructorDecl *
11077 Sema::findInheritingConstructor(SourceLocation Loc,
11078                                 CXXConstructorDecl *BaseCtor,
11079                                 ConstructorUsingShadowDecl *Shadow) {
11080   CXXRecordDecl *Derived = Shadow->getParent();
11081   SourceLocation UsingLoc = Shadow->getLocation();
11082 
11083   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11084   // For now we use the name of the base class constructor as a member of the
11085   // derived class to indicate a (fake) inherited constructor name.
11086   DeclarationName Name = BaseCtor->getDeclName();
11087 
11088   // Check to see if we already have a fake constructor for this inherited
11089   // constructor call.
11090   for (NamedDecl *Ctor : Derived->lookup(Name))
11091     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11092                                ->getInheritedConstructor()
11093                                .getConstructor(),
11094                            BaseCtor))
11095       return cast<CXXConstructorDecl>(Ctor);
11096 
11097   DeclarationNameInfo NameInfo(Name, UsingLoc);
11098   TypeSourceInfo *TInfo =
11099       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11100   FunctionProtoTypeLoc ProtoLoc =
11101       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11102 
11103   // Check the inherited constructor is valid and find the list of base classes
11104   // from which it was inherited.
11105   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11106 
11107   bool Constexpr =
11108       BaseCtor->isConstexpr() &&
11109       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11110                                         false, BaseCtor, &ICI);
11111 
11112   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11113       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11114       BaseCtor->isExplicit(), /*Inline=*/true,
11115       /*ImplicitlyDeclared=*/true, Constexpr,
11116       InheritedConstructor(Shadow, BaseCtor));
11117   if (Shadow->isInvalidDecl())
11118     DerivedCtor->setInvalidDecl();
11119 
11120   // Build an unevaluated exception specification for this fake constructor.
11121   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11122   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11123   EPI.ExceptionSpec.Type = EST_Unevaluated;
11124   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11125   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11126                                                FPT->getParamTypes(), EPI));
11127 
11128   // Build the parameter declarations.
11129   SmallVector<ParmVarDecl *, 16> ParamDecls;
11130   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11131     TypeSourceInfo *TInfo =
11132         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11133     ParmVarDecl *PD = ParmVarDecl::Create(
11134         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11135         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11136     PD->setScopeInfo(0, I);
11137     PD->setImplicit();
11138     // Ensure attributes are propagated onto parameters (this matters for
11139     // format, pass_object_size, ...).
11140     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11141     ParamDecls.push_back(PD);
11142     ProtoLoc.setParam(I, PD);
11143   }
11144 
11145   // Set up the new constructor.
11146   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11147   DerivedCtor->setAccess(BaseCtor->getAccess());
11148   DerivedCtor->setParams(ParamDecls);
11149   Derived->addDecl(DerivedCtor);
11150 
11151   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11152     SetDeclDeleted(DerivedCtor, UsingLoc);
11153 
11154   return DerivedCtor;
11155 }
11156 
11157 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11158   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11159                                Ctor->getInheritedConstructor().getShadowDecl());
11160   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11161                             /*Diagnose*/true);
11162 }
11163 
11164 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11165                                        CXXConstructorDecl *Constructor) {
11166   CXXRecordDecl *ClassDecl = Constructor->getParent();
11167   assert(Constructor->getInheritedConstructor() &&
11168          !Constructor->doesThisDeclarationHaveABody() &&
11169          !Constructor->isDeleted());
11170   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11171     return;
11172 
11173   // Initializations are performed "as if by a defaulted default constructor",
11174   // so enter the appropriate scope.
11175   SynthesizedFunctionScope Scope(*this, Constructor);
11176 
11177   // The exception specification is needed because we are defining the
11178   // function.
11179   ResolveExceptionSpec(CurrentLocation,
11180                        Constructor->getType()->castAs<FunctionProtoType>());
11181   MarkVTableUsed(CurrentLocation, ClassDecl);
11182 
11183   // Add a context note for diagnostics produced after this point.
11184   Scope.addContextNote(CurrentLocation);
11185 
11186   ConstructorUsingShadowDecl *Shadow =
11187       Constructor->getInheritedConstructor().getShadowDecl();
11188   CXXConstructorDecl *InheritedCtor =
11189       Constructor->getInheritedConstructor().getConstructor();
11190 
11191   // [class.inhctor.init]p1:
11192   //   initialization proceeds as if a defaulted default constructor is used to
11193   //   initialize the D object and each base class subobject from which the
11194   //   constructor was inherited
11195 
11196   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11197   CXXRecordDecl *RD = Shadow->getParent();
11198   SourceLocation InitLoc = Shadow->getLocation();
11199 
11200   // Build explicit initializers for all base classes from which the
11201   // constructor was inherited.
11202   SmallVector<CXXCtorInitializer*, 8> Inits;
11203   for (bool VBase : {false, true}) {
11204     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11205       if (B.isVirtual() != VBase)
11206         continue;
11207 
11208       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11209       if (!BaseRD)
11210         continue;
11211 
11212       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11213       if (!BaseCtor.first)
11214         continue;
11215 
11216       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11217       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11218           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11219 
11220       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11221       Inits.push_back(new (Context) CXXCtorInitializer(
11222           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11223           SourceLocation()));
11224     }
11225   }
11226 
11227   // We now proceed as if for a defaulted default constructor, with the relevant
11228   // initializers replaced.
11229 
11230   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11231     Constructor->setInvalidDecl();
11232     return;
11233   }
11234 
11235   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11236   Constructor->markUsed(Context);
11237 
11238   if (ASTMutationListener *L = getASTMutationListener()) {
11239     L->CompletedImplicitDefinition(Constructor);
11240   }
11241 
11242   DiagnoseUninitializedFields(*this, Constructor);
11243 }
11244 
11245 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11246   // C++ [class.dtor]p2:
11247   //   If a class has no user-declared destructor, a destructor is
11248   //   declared implicitly. An implicitly-declared destructor is an
11249   //   inline public member of its class.
11250   assert(ClassDecl->needsImplicitDestructor());
11251 
11252   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11253   if (DSM.isAlreadyBeingDeclared())
11254     return nullptr;
11255 
11256   // Create the actual destructor declaration.
11257   CanQualType ClassType
11258     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11259   SourceLocation ClassLoc = ClassDecl->getLocation();
11260   DeclarationName Name
11261     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11262   DeclarationNameInfo NameInfo(Name, ClassLoc);
11263   CXXDestructorDecl *Destructor
11264       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11265                                   QualType(), nullptr, /*isInline=*/true,
11266                                   /*isImplicitlyDeclared=*/true);
11267   Destructor->setAccess(AS_public);
11268   Destructor->setDefaulted();
11269 
11270   if (getLangOpts().CUDA) {
11271     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11272                                             Destructor,
11273                                             /* ConstRHS */ false,
11274                                             /* Diagnose */ false);
11275   }
11276 
11277   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11278 
11279   // We don't need to use SpecialMemberIsTrivial here; triviality for
11280   // destructors is easy to compute.
11281   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11282   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11283                                 ClassDecl->hasTrivialDestructorForCall());
11284 
11285   // Note that we have declared this destructor.
11286   ++ASTContext::NumImplicitDestructorsDeclared;
11287 
11288   Scope *S = getScopeForContext(ClassDecl);
11289   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11290 
11291   // We can't check whether an implicit destructor is deleted before we complete
11292   // the definition of the class, because its validity depends on the alignment
11293   // of the class. We'll check this from ActOnFields once the class is complete.
11294   if (ClassDecl->isCompleteDefinition() &&
11295       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11296     SetDeclDeleted(Destructor, ClassLoc);
11297 
11298   // Introduce this destructor into its scope.
11299   if (S)
11300     PushOnScopeChains(Destructor, S, false);
11301   ClassDecl->addDecl(Destructor);
11302 
11303   return Destructor;
11304 }
11305 
11306 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11307                                     CXXDestructorDecl *Destructor) {
11308   assert((Destructor->isDefaulted() &&
11309           !Destructor->doesThisDeclarationHaveABody() &&
11310           !Destructor->isDeleted()) &&
11311          "DefineImplicitDestructor - call it for implicit default dtor");
11312   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11313     return;
11314 
11315   CXXRecordDecl *ClassDecl = Destructor->getParent();
11316   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11317 
11318   SynthesizedFunctionScope Scope(*this, Destructor);
11319 
11320   // The exception specification is needed because we are defining the
11321   // function.
11322   ResolveExceptionSpec(CurrentLocation,
11323                        Destructor->getType()->castAs<FunctionProtoType>());
11324   MarkVTableUsed(CurrentLocation, ClassDecl);
11325 
11326   // Add a context note for diagnostics produced after this point.
11327   Scope.addContextNote(CurrentLocation);
11328 
11329   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11330                                          Destructor->getParent());
11331 
11332   if (CheckDestructor(Destructor)) {
11333     Destructor->setInvalidDecl();
11334     return;
11335   }
11336 
11337   SourceLocation Loc = Destructor->getEndLoc().isValid()
11338                            ? Destructor->getEndLoc()
11339                            : Destructor->getLocation();
11340   Destructor->setBody(new (Context) CompoundStmt(Loc));
11341   Destructor->markUsed(Context);
11342 
11343   if (ASTMutationListener *L = getASTMutationListener()) {
11344     L->CompletedImplicitDefinition(Destructor);
11345   }
11346 }
11347 
11348 /// Perform any semantic analysis which needs to be delayed until all
11349 /// pending class member declarations have been parsed.
11350 void Sema::ActOnFinishCXXMemberDecls() {
11351   // If the context is an invalid C++ class, just suppress these checks.
11352   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11353     if (Record->isInvalidDecl()) {
11354       DelayedOverridingExceptionSpecChecks.clear();
11355       DelayedEquivalentExceptionSpecChecks.clear();
11356       DelayedDefaultedMemberExceptionSpecs.clear();
11357       return;
11358     }
11359     checkForMultipleExportedDefaultConstructors(*this, Record);
11360   }
11361 }
11362 
11363 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11364   referenceDLLExportedClassMethods();
11365 }
11366 
11367 void Sema::referenceDLLExportedClassMethods() {
11368   if (!DelayedDllExportClasses.empty()) {
11369     // Calling ReferenceDllExportedMembers might cause the current function to
11370     // be called again, so use a local copy of DelayedDllExportClasses.
11371     SmallVector<CXXRecordDecl *, 4> WorkList;
11372     std::swap(DelayedDllExportClasses, WorkList);
11373     for (CXXRecordDecl *Class : WorkList)
11374       ReferenceDllExportedMembers(*this, Class);
11375   }
11376 }
11377 
11378 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11379   assert(getLangOpts().CPlusPlus11 &&
11380          "adjusting dtor exception specs was introduced in c++11");
11381 
11382   if (Destructor->isDependentContext())
11383     return;
11384 
11385   // C++11 [class.dtor]p3:
11386   //   A declaration of a destructor that does not have an exception-
11387   //   specification is implicitly considered to have the same exception-
11388   //   specification as an implicit declaration.
11389   const FunctionProtoType *DtorType = Destructor->getType()->
11390                                         getAs<FunctionProtoType>();
11391   if (DtorType->hasExceptionSpec())
11392     return;
11393 
11394   // Replace the destructor's type, building off the existing one. Fortunately,
11395   // the only thing of interest in the destructor type is its extended info.
11396   // The return and arguments are fixed.
11397   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11398   EPI.ExceptionSpec.Type = EST_Unevaluated;
11399   EPI.ExceptionSpec.SourceDecl = Destructor;
11400   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11401 
11402   // FIXME: If the destructor has a body that could throw, and the newly created
11403   // spec doesn't allow exceptions, we should emit a warning, because this
11404   // change in behavior can break conforming C++03 programs at runtime.
11405   // However, we don't have a body or an exception specification yet, so it
11406   // needs to be done somewhere else.
11407 }
11408 
11409 namespace {
11410 /// An abstract base class for all helper classes used in building the
11411 //  copy/move operators. These classes serve as factory functions and help us
11412 //  avoid using the same Expr* in the AST twice.
11413 class ExprBuilder {
11414   ExprBuilder(const ExprBuilder&) = delete;
11415   ExprBuilder &operator=(const ExprBuilder&) = delete;
11416 
11417 protected:
11418   static Expr *assertNotNull(Expr *E) {
11419     assert(E && "Expression construction must not fail.");
11420     return E;
11421   }
11422 
11423 public:
11424   ExprBuilder() {}
11425   virtual ~ExprBuilder() {}
11426 
11427   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11428 };
11429 
11430 class RefBuilder: public ExprBuilder {
11431   VarDecl *Var;
11432   QualType VarType;
11433 
11434 public:
11435   Expr *build(Sema &S, SourceLocation Loc) const override {
11436     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11437   }
11438 
11439   RefBuilder(VarDecl *Var, QualType VarType)
11440       : Var(Var), VarType(VarType) {}
11441 };
11442 
11443 class ThisBuilder: public ExprBuilder {
11444 public:
11445   Expr *build(Sema &S, SourceLocation Loc) const override {
11446     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11447   }
11448 };
11449 
11450 class CastBuilder: public ExprBuilder {
11451   const ExprBuilder &Builder;
11452   QualType Type;
11453   ExprValueKind Kind;
11454   const CXXCastPath &Path;
11455 
11456 public:
11457   Expr *build(Sema &S, SourceLocation Loc) const override {
11458     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11459                                              CK_UncheckedDerivedToBase, Kind,
11460                                              &Path).get());
11461   }
11462 
11463   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11464               const CXXCastPath &Path)
11465       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11466 };
11467 
11468 class DerefBuilder: public ExprBuilder {
11469   const ExprBuilder &Builder;
11470 
11471 public:
11472   Expr *build(Sema &S, SourceLocation Loc) const override {
11473     return assertNotNull(
11474         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11475   }
11476 
11477   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11478 };
11479 
11480 class MemberBuilder: public ExprBuilder {
11481   const ExprBuilder &Builder;
11482   QualType Type;
11483   CXXScopeSpec SS;
11484   bool IsArrow;
11485   LookupResult &MemberLookup;
11486 
11487 public:
11488   Expr *build(Sema &S, SourceLocation Loc) const override {
11489     return assertNotNull(S.BuildMemberReferenceExpr(
11490         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11491         nullptr, MemberLookup, nullptr, nullptr).get());
11492   }
11493 
11494   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11495                 LookupResult &MemberLookup)
11496       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11497         MemberLookup(MemberLookup) {}
11498 };
11499 
11500 class MoveCastBuilder: public ExprBuilder {
11501   const ExprBuilder &Builder;
11502 
11503 public:
11504   Expr *build(Sema &S, SourceLocation Loc) const override {
11505     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11506   }
11507 
11508   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11509 };
11510 
11511 class LvalueConvBuilder: public ExprBuilder {
11512   const ExprBuilder &Builder;
11513 
11514 public:
11515   Expr *build(Sema &S, SourceLocation Loc) const override {
11516     return assertNotNull(
11517         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11518   }
11519 
11520   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11521 };
11522 
11523 class SubscriptBuilder: public ExprBuilder {
11524   const ExprBuilder &Base;
11525   const ExprBuilder &Index;
11526 
11527 public:
11528   Expr *build(Sema &S, SourceLocation Loc) const override {
11529     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11530         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11531   }
11532 
11533   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11534       : Base(Base), Index(Index) {}
11535 };
11536 
11537 } // end anonymous namespace
11538 
11539 /// When generating a defaulted copy or move assignment operator, if a field
11540 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11541 /// do so. This optimization only applies for arrays of scalars, and for arrays
11542 /// of class type where the selected copy/move-assignment operator is trivial.
11543 static StmtResult
11544 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11545                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11546   // Compute the size of the memory buffer to be copied.
11547   QualType SizeType = S.Context.getSizeType();
11548   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11549                    S.Context.getTypeSizeInChars(T).getQuantity());
11550 
11551   // Take the address of the field references for "from" and "to". We
11552   // directly construct UnaryOperators here because semantic analysis
11553   // does not permit us to take the address of an xvalue.
11554   Expr *From = FromB.build(S, Loc);
11555   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11556                          S.Context.getPointerType(From->getType()),
11557                          VK_RValue, OK_Ordinary, Loc, false);
11558   Expr *To = ToB.build(S, Loc);
11559   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11560                        S.Context.getPointerType(To->getType()),
11561                        VK_RValue, OK_Ordinary, Loc, false);
11562 
11563   const Type *E = T->getBaseElementTypeUnsafe();
11564   bool NeedsCollectableMemCpy =
11565     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11566 
11567   // Create a reference to the __builtin_objc_memmove_collectable function
11568   StringRef MemCpyName = NeedsCollectableMemCpy ?
11569     "__builtin_objc_memmove_collectable" :
11570     "__builtin_memcpy";
11571   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11572                  Sema::LookupOrdinaryName);
11573   S.LookupName(R, S.TUScope, true);
11574 
11575   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11576   if (!MemCpy)
11577     // Something went horribly wrong earlier, and we will have complained
11578     // about it.
11579     return StmtError();
11580 
11581   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11582                                             VK_RValue, Loc, nullptr);
11583   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11584 
11585   Expr *CallArgs[] = {
11586     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11587   };
11588   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11589                                     Loc, CallArgs, Loc);
11590 
11591   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11592   return Call.getAs<Stmt>();
11593 }
11594 
11595 /// Builds a statement that copies/moves the given entity from \p From to
11596 /// \c To.
11597 ///
11598 /// This routine is used to copy/move the members of a class with an
11599 /// implicitly-declared copy/move assignment operator. When the entities being
11600 /// copied are arrays, this routine builds for loops to copy them.
11601 ///
11602 /// \param S The Sema object used for type-checking.
11603 ///
11604 /// \param Loc The location where the implicit copy/move is being generated.
11605 ///
11606 /// \param T The type of the expressions being copied/moved. Both expressions
11607 /// must have this type.
11608 ///
11609 /// \param To The expression we are copying/moving to.
11610 ///
11611 /// \param From The expression we are copying/moving from.
11612 ///
11613 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11614 /// Otherwise, it's a non-static member subobject.
11615 ///
11616 /// \param Copying Whether we're copying or moving.
11617 ///
11618 /// \param Depth Internal parameter recording the depth of the recursion.
11619 ///
11620 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11621 /// if a memcpy should be used instead.
11622 static StmtResult
11623 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11624                                  const ExprBuilder &To, const ExprBuilder &From,
11625                                  bool CopyingBaseSubobject, bool Copying,
11626                                  unsigned Depth = 0) {
11627   // C++11 [class.copy]p28:
11628   //   Each subobject is assigned in the manner appropriate to its type:
11629   //
11630   //     - if the subobject is of class type, as if by a call to operator= with
11631   //       the subobject as the object expression and the corresponding
11632   //       subobject of x as a single function argument (as if by explicit
11633   //       qualification; that is, ignoring any possible virtual overriding
11634   //       functions in more derived classes);
11635   //
11636   // C++03 [class.copy]p13:
11637   //     - if the subobject is of class type, the copy assignment operator for
11638   //       the class is used (as if by explicit qualification; that is,
11639   //       ignoring any possible virtual overriding functions in more derived
11640   //       classes);
11641   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11642     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11643 
11644     // Look for operator=.
11645     DeclarationName Name
11646       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11647     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11648     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11649 
11650     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11651     // operator.
11652     if (!S.getLangOpts().CPlusPlus11) {
11653       LookupResult::Filter F = OpLookup.makeFilter();
11654       while (F.hasNext()) {
11655         NamedDecl *D = F.next();
11656         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11657           if (Method->isCopyAssignmentOperator() ||
11658               (!Copying && Method->isMoveAssignmentOperator()))
11659             continue;
11660 
11661         F.erase();
11662       }
11663       F.done();
11664     }
11665 
11666     // Suppress the protected check (C++ [class.protected]) for each of the
11667     // assignment operators we found. This strange dance is required when
11668     // we're assigning via a base classes's copy-assignment operator. To
11669     // ensure that we're getting the right base class subobject (without
11670     // ambiguities), we need to cast "this" to that subobject type; to
11671     // ensure that we don't go through the virtual call mechanism, we need
11672     // to qualify the operator= name with the base class (see below). However,
11673     // this means that if the base class has a protected copy assignment
11674     // operator, the protected member access check will fail. So, we
11675     // rewrite "protected" access to "public" access in this case, since we
11676     // know by construction that we're calling from a derived class.
11677     if (CopyingBaseSubobject) {
11678       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11679            L != LEnd; ++L) {
11680         if (L.getAccess() == AS_protected)
11681           L.setAccess(AS_public);
11682       }
11683     }
11684 
11685     // Create the nested-name-specifier that will be used to qualify the
11686     // reference to operator=; this is required to suppress the virtual
11687     // call mechanism.
11688     CXXScopeSpec SS;
11689     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11690     SS.MakeTrivial(S.Context,
11691                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11692                                                CanonicalT),
11693                    Loc);
11694 
11695     // Create the reference to operator=.
11696     ExprResult OpEqualRef
11697       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11698                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11699                                    /*FirstQualifierInScope=*/nullptr,
11700                                    OpLookup,
11701                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11702                                    /*SuppressQualifierCheck=*/true);
11703     if (OpEqualRef.isInvalid())
11704       return StmtError();
11705 
11706     // Build the call to the assignment operator.
11707 
11708     Expr *FromInst = From.build(S, Loc);
11709     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11710                                                   OpEqualRef.getAs<Expr>(),
11711                                                   Loc, FromInst, Loc);
11712     if (Call.isInvalid())
11713       return StmtError();
11714 
11715     // If we built a call to a trivial 'operator=' while copying an array,
11716     // bail out. We'll replace the whole shebang with a memcpy.
11717     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11718     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11719       return StmtResult((Stmt*)nullptr);
11720 
11721     // Convert to an expression-statement, and clean up any produced
11722     // temporaries.
11723     return S.ActOnExprStmt(Call);
11724   }
11725 
11726   //     - if the subobject is of scalar type, the built-in assignment
11727   //       operator is used.
11728   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11729   if (!ArrayTy) {
11730     ExprResult Assignment = S.CreateBuiltinBinOp(
11731         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11732     if (Assignment.isInvalid())
11733       return StmtError();
11734     return S.ActOnExprStmt(Assignment);
11735   }
11736 
11737   //     - if the subobject is an array, each element is assigned, in the
11738   //       manner appropriate to the element type;
11739 
11740   // Construct a loop over the array bounds, e.g.,
11741   //
11742   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11743   //
11744   // that will copy each of the array elements.
11745   QualType SizeType = S.Context.getSizeType();
11746 
11747   // Create the iteration variable.
11748   IdentifierInfo *IterationVarName = nullptr;
11749   {
11750     SmallString<8> Str;
11751     llvm::raw_svector_ostream OS(Str);
11752     OS << "__i" << Depth;
11753     IterationVarName = &S.Context.Idents.get(OS.str());
11754   }
11755   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11756                                           IterationVarName, SizeType,
11757                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11758                                           SC_None);
11759 
11760   // Initialize the iteration variable to zero.
11761   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11762   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11763 
11764   // Creates a reference to the iteration variable.
11765   RefBuilder IterationVarRef(IterationVar, SizeType);
11766   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11767 
11768   // Create the DeclStmt that holds the iteration variable.
11769   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11770 
11771   // Subscript the "from" and "to" expressions with the iteration variable.
11772   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11773   MoveCastBuilder FromIndexMove(FromIndexCopy);
11774   const ExprBuilder *FromIndex;
11775   if (Copying)
11776     FromIndex = &FromIndexCopy;
11777   else
11778     FromIndex = &FromIndexMove;
11779 
11780   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11781 
11782   // Build the copy/move for an individual element of the array.
11783   StmtResult Copy =
11784     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11785                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11786                                      Copying, Depth + 1);
11787   // Bail out if copying fails or if we determined that we should use memcpy.
11788   if (Copy.isInvalid() || !Copy.get())
11789     return Copy;
11790 
11791   // Create the comparison against the array bound.
11792   llvm::APInt Upper
11793     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11794   Expr *Comparison
11795     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11796                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11797                                      BO_NE, S.Context.BoolTy,
11798                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11799 
11800   // Create the pre-increment of the iteration variable. We can determine
11801   // whether the increment will overflow based on the value of the array
11802   // bound.
11803   Expr *Increment = new (S.Context)
11804       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11805                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11806 
11807   // Construct the loop that copies all elements of this array.
11808   return S.ActOnForStmt(
11809       Loc, Loc, InitStmt,
11810       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11811       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11812 }
11813 
11814 static StmtResult
11815 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11816                       const ExprBuilder &To, const ExprBuilder &From,
11817                       bool CopyingBaseSubobject, bool Copying) {
11818   // Maybe we should use a memcpy?
11819   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11820       T.isTriviallyCopyableType(S.Context))
11821     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11822 
11823   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11824                                                      CopyingBaseSubobject,
11825                                                      Copying, 0));
11826 
11827   // If we ended up picking a trivial assignment operator for an array of a
11828   // non-trivially-copyable class type, just emit a memcpy.
11829   if (!Result.isInvalid() && !Result.get())
11830     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11831 
11832   return Result;
11833 }
11834 
11835 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11836   // Note: The following rules are largely analoguous to the copy
11837   // constructor rules. Note that virtual bases are not taken into account
11838   // for determining the argument type of the operator. Note also that
11839   // operators taking an object instead of a reference are allowed.
11840   assert(ClassDecl->needsImplicitCopyAssignment());
11841 
11842   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11843   if (DSM.isAlreadyBeingDeclared())
11844     return nullptr;
11845 
11846   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11847   if (Context.getLangOpts().OpenCLCPlusPlus)
11848     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11849   QualType RetType = Context.getLValueReferenceType(ArgType);
11850   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11851   if (Const)
11852     ArgType = ArgType.withConst();
11853 
11854   ArgType = Context.getLValueReferenceType(ArgType);
11855 
11856   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11857                                                      CXXCopyAssignment,
11858                                                      Const);
11859 
11860   //   An implicitly-declared copy assignment operator is an inline public
11861   //   member of its class.
11862   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11863   SourceLocation ClassLoc = ClassDecl->getLocation();
11864   DeclarationNameInfo NameInfo(Name, ClassLoc);
11865   CXXMethodDecl *CopyAssignment =
11866       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11867                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11868                             /*isInline=*/true, Constexpr, SourceLocation());
11869   CopyAssignment->setAccess(AS_public);
11870   CopyAssignment->setDefaulted();
11871   CopyAssignment->setImplicit();
11872 
11873   if (getLangOpts().CUDA) {
11874     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11875                                             CopyAssignment,
11876                                             /* ConstRHS */ Const,
11877                                             /* Diagnose */ false);
11878   }
11879 
11880   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11881 
11882   // Add the parameter to the operator.
11883   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11884                                                ClassLoc, ClassLoc,
11885                                                /*Id=*/nullptr, ArgType,
11886                                                /*TInfo=*/nullptr, SC_None,
11887                                                nullptr);
11888   CopyAssignment->setParams(FromParam);
11889 
11890   CopyAssignment->setTrivial(
11891     ClassDecl->needsOverloadResolutionForCopyAssignment()
11892       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11893       : ClassDecl->hasTrivialCopyAssignment());
11894 
11895   // Note that we have added this copy-assignment operator.
11896   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11897 
11898   Scope *S = getScopeForContext(ClassDecl);
11899   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11900 
11901   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11902     SetDeclDeleted(CopyAssignment, ClassLoc);
11903 
11904   if (S)
11905     PushOnScopeChains(CopyAssignment, S, false);
11906   ClassDecl->addDecl(CopyAssignment);
11907 
11908   return CopyAssignment;
11909 }
11910 
11911 /// Diagnose an implicit copy operation for a class which is odr-used, but
11912 /// which is deprecated because the class has a user-declared copy constructor,
11913 /// copy assignment operator, or destructor.
11914 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11915   assert(CopyOp->isImplicit());
11916 
11917   CXXRecordDecl *RD = CopyOp->getParent();
11918   CXXMethodDecl *UserDeclaredOperation = nullptr;
11919 
11920   // In Microsoft mode, assignment operations don't affect constructors and
11921   // vice versa.
11922   if (RD->hasUserDeclaredDestructor()) {
11923     UserDeclaredOperation = RD->getDestructor();
11924   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11925              RD->hasUserDeclaredCopyConstructor() &&
11926              !S.getLangOpts().MSVCCompat) {
11927     // Find any user-declared copy constructor.
11928     for (auto *I : RD->ctors()) {
11929       if (I->isCopyConstructor()) {
11930         UserDeclaredOperation = I;
11931         break;
11932       }
11933     }
11934     assert(UserDeclaredOperation);
11935   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11936              RD->hasUserDeclaredCopyAssignment() &&
11937              !S.getLangOpts().MSVCCompat) {
11938     // Find any user-declared move assignment operator.
11939     for (auto *I : RD->methods()) {
11940       if (I->isCopyAssignmentOperator()) {
11941         UserDeclaredOperation = I;
11942         break;
11943       }
11944     }
11945     assert(UserDeclaredOperation);
11946   }
11947 
11948   if (UserDeclaredOperation) {
11949     S.Diag(UserDeclaredOperation->getLocation(),
11950          diag::warn_deprecated_copy_operation)
11951       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11952       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11953   }
11954 }
11955 
11956 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11957                                         CXXMethodDecl *CopyAssignOperator) {
11958   assert((CopyAssignOperator->isDefaulted() &&
11959           CopyAssignOperator->isOverloadedOperator() &&
11960           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11961           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11962           !CopyAssignOperator->isDeleted()) &&
11963          "DefineImplicitCopyAssignment called for wrong function");
11964   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11965     return;
11966 
11967   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11968   if (ClassDecl->isInvalidDecl()) {
11969     CopyAssignOperator->setInvalidDecl();
11970     return;
11971   }
11972 
11973   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11974 
11975   // The exception specification is needed because we are defining the
11976   // function.
11977   ResolveExceptionSpec(CurrentLocation,
11978                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11979 
11980   // Add a context note for diagnostics produced after this point.
11981   Scope.addContextNote(CurrentLocation);
11982 
11983   // C++11 [class.copy]p18:
11984   //   The [definition of an implicitly declared copy assignment operator] is
11985   //   deprecated if the class has a user-declared copy constructor or a
11986   //   user-declared destructor.
11987   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11988     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11989 
11990   // C++0x [class.copy]p30:
11991   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11992   //   for a non-union class X performs memberwise copy assignment of its
11993   //   subobjects. The direct base classes of X are assigned first, in the
11994   //   order of their declaration in the base-specifier-list, and then the
11995   //   immediate non-static data members of X are assigned, in the order in
11996   //   which they were declared in the class definition.
11997 
11998   // The statements that form the synthesized function body.
11999   SmallVector<Stmt*, 8> Statements;
12000 
12001   // The parameter for the "other" object, which we are copying from.
12002   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12003   Qualifiers OtherQuals = Other->getType().getQualifiers();
12004   QualType OtherRefType = Other->getType();
12005   if (const LValueReferenceType *OtherRef
12006                                 = OtherRefType->getAs<LValueReferenceType>()) {
12007     OtherRefType = OtherRef->getPointeeType();
12008     OtherQuals = OtherRefType.getQualifiers();
12009   }
12010 
12011   // Our location for everything implicitly-generated.
12012   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12013                            ? CopyAssignOperator->getEndLoc()
12014                            : CopyAssignOperator->getLocation();
12015 
12016   // Builds a DeclRefExpr for the "other" object.
12017   RefBuilder OtherRef(Other, OtherRefType);
12018 
12019   // Builds the "this" pointer.
12020   ThisBuilder This;
12021 
12022   // Assign base classes.
12023   bool Invalid = false;
12024   for (auto &Base : ClassDecl->bases()) {
12025     // Form the assignment:
12026     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12027     QualType BaseType = Base.getType().getUnqualifiedType();
12028     if (!BaseType->isRecordType()) {
12029       Invalid = true;
12030       continue;
12031     }
12032 
12033     CXXCastPath BasePath;
12034     BasePath.push_back(&Base);
12035 
12036     // Construct the "from" expression, which is an implicit cast to the
12037     // appropriately-qualified base type.
12038     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12039                      VK_LValue, BasePath);
12040 
12041     // Dereference "this".
12042     DerefBuilder DerefThis(This);
12043     CastBuilder To(DerefThis,
12044                    Context.getQualifiedType(
12045                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12046                    VK_LValue, BasePath);
12047 
12048     // Build the copy.
12049     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12050                                             To, From,
12051                                             /*CopyingBaseSubobject=*/true,
12052                                             /*Copying=*/true);
12053     if (Copy.isInvalid()) {
12054       CopyAssignOperator->setInvalidDecl();
12055       return;
12056     }
12057 
12058     // Success! Record the copy.
12059     Statements.push_back(Copy.getAs<Expr>());
12060   }
12061 
12062   // Assign non-static members.
12063   for (auto *Field : ClassDecl->fields()) {
12064     // FIXME: We should form some kind of AST representation for the implied
12065     // memcpy in a union copy operation.
12066     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12067       continue;
12068 
12069     if (Field->isInvalidDecl()) {
12070       Invalid = true;
12071       continue;
12072     }
12073 
12074     // Check for members of reference type; we can't copy those.
12075     if (Field->getType()->isReferenceType()) {
12076       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12077         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12078       Diag(Field->getLocation(), diag::note_declared_at);
12079       Invalid = true;
12080       continue;
12081     }
12082 
12083     // Check for members of const-qualified, non-class type.
12084     QualType BaseType = Context.getBaseElementType(Field->getType());
12085     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12086       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12087         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12088       Diag(Field->getLocation(), diag::note_declared_at);
12089       Invalid = true;
12090       continue;
12091     }
12092 
12093     // Suppress assigning zero-width bitfields.
12094     if (Field->isZeroLengthBitField(Context))
12095       continue;
12096 
12097     QualType FieldType = Field->getType().getNonReferenceType();
12098     if (FieldType->isIncompleteArrayType()) {
12099       assert(ClassDecl->hasFlexibleArrayMember() &&
12100              "Incomplete array type is not valid");
12101       continue;
12102     }
12103 
12104     // Build references to the field in the object we're copying from and to.
12105     CXXScopeSpec SS; // Intentionally empty
12106     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12107                               LookupMemberName);
12108     MemberLookup.addDecl(Field);
12109     MemberLookup.resolveKind();
12110 
12111     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12112 
12113     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12114 
12115     // Build the copy of this field.
12116     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12117                                             To, From,
12118                                             /*CopyingBaseSubobject=*/false,
12119                                             /*Copying=*/true);
12120     if (Copy.isInvalid()) {
12121       CopyAssignOperator->setInvalidDecl();
12122       return;
12123     }
12124 
12125     // Success! Record the copy.
12126     Statements.push_back(Copy.getAs<Stmt>());
12127   }
12128 
12129   if (!Invalid) {
12130     // Add a "return *this;"
12131     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12132 
12133     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12134     if (Return.isInvalid())
12135       Invalid = true;
12136     else
12137       Statements.push_back(Return.getAs<Stmt>());
12138   }
12139 
12140   if (Invalid) {
12141     CopyAssignOperator->setInvalidDecl();
12142     return;
12143   }
12144 
12145   StmtResult Body;
12146   {
12147     CompoundScopeRAII CompoundScope(*this);
12148     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12149                              /*isStmtExpr=*/false);
12150     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12151   }
12152   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12153   CopyAssignOperator->markUsed(Context);
12154 
12155   if (ASTMutationListener *L = getASTMutationListener()) {
12156     L->CompletedImplicitDefinition(CopyAssignOperator);
12157   }
12158 }
12159 
12160 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12161   assert(ClassDecl->needsImplicitMoveAssignment());
12162 
12163   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12164   if (DSM.isAlreadyBeingDeclared())
12165     return nullptr;
12166 
12167   // Note: The following rules are largely analoguous to the move
12168   // constructor rules.
12169 
12170   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12171   if (Context.getLangOpts().OpenCLCPlusPlus)
12172     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12173   QualType RetType = Context.getLValueReferenceType(ArgType);
12174   ArgType = Context.getRValueReferenceType(ArgType);
12175 
12176   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12177                                                      CXXMoveAssignment,
12178                                                      false);
12179 
12180   //   An implicitly-declared move assignment operator is an inline public
12181   //   member of its class.
12182   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12183   SourceLocation ClassLoc = ClassDecl->getLocation();
12184   DeclarationNameInfo NameInfo(Name, ClassLoc);
12185   CXXMethodDecl *MoveAssignment =
12186       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12187                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12188                             /*isInline=*/true, Constexpr, SourceLocation());
12189   MoveAssignment->setAccess(AS_public);
12190   MoveAssignment->setDefaulted();
12191   MoveAssignment->setImplicit();
12192 
12193   if (getLangOpts().CUDA) {
12194     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12195                                             MoveAssignment,
12196                                             /* ConstRHS */ false,
12197                                             /* Diagnose */ false);
12198   }
12199 
12200   // Build an exception specification pointing back at this member.
12201   FunctionProtoType::ExtProtoInfo EPI =
12202       getImplicitMethodEPI(*this, MoveAssignment);
12203   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12204 
12205   // Add the parameter to the operator.
12206   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12207                                                ClassLoc, ClassLoc,
12208                                                /*Id=*/nullptr, ArgType,
12209                                                /*TInfo=*/nullptr, SC_None,
12210                                                nullptr);
12211   MoveAssignment->setParams(FromParam);
12212 
12213   MoveAssignment->setTrivial(
12214     ClassDecl->needsOverloadResolutionForMoveAssignment()
12215       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12216       : ClassDecl->hasTrivialMoveAssignment());
12217 
12218   // Note that we have added this copy-assignment operator.
12219   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12220 
12221   Scope *S = getScopeForContext(ClassDecl);
12222   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12223 
12224   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12225     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12226     SetDeclDeleted(MoveAssignment, ClassLoc);
12227   }
12228 
12229   if (S)
12230     PushOnScopeChains(MoveAssignment, S, false);
12231   ClassDecl->addDecl(MoveAssignment);
12232 
12233   return MoveAssignment;
12234 }
12235 
12236 /// Check if we're implicitly defining a move assignment operator for a class
12237 /// with virtual bases. Such a move assignment might move-assign the virtual
12238 /// base multiple times.
12239 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12240                                                SourceLocation CurrentLocation) {
12241   assert(!Class->isDependentContext() && "should not define dependent move");
12242 
12243   // Only a virtual base could get implicitly move-assigned multiple times.
12244   // Only a non-trivial move assignment can observe this. We only want to
12245   // diagnose if we implicitly define an assignment operator that assigns
12246   // two base classes, both of which move-assign the same virtual base.
12247   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12248       Class->getNumBases() < 2)
12249     return;
12250 
12251   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12252   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12253   VBaseMap VBases;
12254 
12255   for (auto &BI : Class->bases()) {
12256     Worklist.push_back(&BI);
12257     while (!Worklist.empty()) {
12258       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12259       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12260 
12261       // If the base has no non-trivial move assignment operators,
12262       // we don't care about moves from it.
12263       if (!Base->hasNonTrivialMoveAssignment())
12264         continue;
12265 
12266       // If there's nothing virtual here, skip it.
12267       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12268         continue;
12269 
12270       // If we're not actually going to call a move assignment for this base,
12271       // or the selected move assignment is trivial, skip it.
12272       Sema::SpecialMemberOverloadResult SMOR =
12273         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12274                               /*ConstArg*/false, /*VolatileArg*/false,
12275                               /*RValueThis*/true, /*ConstThis*/false,
12276                               /*VolatileThis*/false);
12277       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12278           !SMOR.getMethod()->isMoveAssignmentOperator())
12279         continue;
12280 
12281       if (BaseSpec->isVirtual()) {
12282         // We're going to move-assign this virtual base, and its move
12283         // assignment operator is not trivial. If this can happen for
12284         // multiple distinct direct bases of Class, diagnose it. (If it
12285         // only happens in one base, we'll diagnose it when synthesizing
12286         // that base class's move assignment operator.)
12287         CXXBaseSpecifier *&Existing =
12288             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12289                 .first->second;
12290         if (Existing && Existing != &BI) {
12291           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12292             << Class << Base;
12293           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12294               << (Base->getCanonicalDecl() ==
12295                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12296               << Base << Existing->getType() << Existing->getSourceRange();
12297           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12298               << (Base->getCanonicalDecl() ==
12299                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12300               << Base << BI.getType() << BaseSpec->getSourceRange();
12301 
12302           // Only diagnose each vbase once.
12303           Existing = nullptr;
12304         }
12305       } else {
12306         // Only walk over bases that have defaulted move assignment operators.
12307         // We assume that any user-provided move assignment operator handles
12308         // the multiple-moves-of-vbase case itself somehow.
12309         if (!SMOR.getMethod()->isDefaulted())
12310           continue;
12311 
12312         // We're going to move the base classes of Base. Add them to the list.
12313         for (auto &BI : Base->bases())
12314           Worklist.push_back(&BI);
12315       }
12316     }
12317   }
12318 }
12319 
12320 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12321                                         CXXMethodDecl *MoveAssignOperator) {
12322   assert((MoveAssignOperator->isDefaulted() &&
12323           MoveAssignOperator->isOverloadedOperator() &&
12324           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12325           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12326           !MoveAssignOperator->isDeleted()) &&
12327          "DefineImplicitMoveAssignment called for wrong function");
12328   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12329     return;
12330 
12331   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12332   if (ClassDecl->isInvalidDecl()) {
12333     MoveAssignOperator->setInvalidDecl();
12334     return;
12335   }
12336 
12337   // C++0x [class.copy]p28:
12338   //   The implicitly-defined or move assignment operator for a non-union class
12339   //   X performs memberwise move assignment of its subobjects. The direct base
12340   //   classes of X are assigned first, in the order of their declaration in the
12341   //   base-specifier-list, and then the immediate non-static data members of X
12342   //   are assigned, in the order in which they were declared in the class
12343   //   definition.
12344 
12345   // Issue a warning if our implicit move assignment operator will move
12346   // from a virtual base more than once.
12347   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12348 
12349   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12350 
12351   // The exception specification is needed because we are defining the
12352   // function.
12353   ResolveExceptionSpec(CurrentLocation,
12354                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12355 
12356   // Add a context note for diagnostics produced after this point.
12357   Scope.addContextNote(CurrentLocation);
12358 
12359   // The statements that form the synthesized function body.
12360   SmallVector<Stmt*, 8> Statements;
12361 
12362   // The parameter for the "other" object, which we are move from.
12363   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12364   QualType OtherRefType = Other->getType()->
12365       getAs<RValueReferenceType>()->getPointeeType();
12366 
12367   // Our location for everything implicitly-generated.
12368   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12369                            ? MoveAssignOperator->getEndLoc()
12370                            : MoveAssignOperator->getLocation();
12371 
12372   // Builds a reference to the "other" object.
12373   RefBuilder OtherRef(Other, OtherRefType);
12374   // Cast to rvalue.
12375   MoveCastBuilder MoveOther(OtherRef);
12376 
12377   // Builds the "this" pointer.
12378   ThisBuilder This;
12379 
12380   // Assign base classes.
12381   bool Invalid = false;
12382   for (auto &Base : ClassDecl->bases()) {
12383     // C++11 [class.copy]p28:
12384     //   It is unspecified whether subobjects representing virtual base classes
12385     //   are assigned more than once by the implicitly-defined copy assignment
12386     //   operator.
12387     // FIXME: Do not assign to a vbase that will be assigned by some other base
12388     // class. For a move-assignment, this can result in the vbase being moved
12389     // multiple times.
12390 
12391     // Form the assignment:
12392     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12393     QualType BaseType = Base.getType().getUnqualifiedType();
12394     if (!BaseType->isRecordType()) {
12395       Invalid = true;
12396       continue;
12397     }
12398 
12399     CXXCastPath BasePath;
12400     BasePath.push_back(&Base);
12401 
12402     // Construct the "from" expression, which is an implicit cast to the
12403     // appropriately-qualified base type.
12404     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12405 
12406     // Dereference "this".
12407     DerefBuilder DerefThis(This);
12408 
12409     // Implicitly cast "this" to the appropriately-qualified base type.
12410     CastBuilder To(DerefThis,
12411                    Context.getQualifiedType(
12412                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12413                    VK_LValue, BasePath);
12414 
12415     // Build the move.
12416     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12417                                             To, From,
12418                                             /*CopyingBaseSubobject=*/true,
12419                                             /*Copying=*/false);
12420     if (Move.isInvalid()) {
12421       MoveAssignOperator->setInvalidDecl();
12422       return;
12423     }
12424 
12425     // Success! Record the move.
12426     Statements.push_back(Move.getAs<Expr>());
12427   }
12428 
12429   // Assign non-static members.
12430   for (auto *Field : ClassDecl->fields()) {
12431     // FIXME: We should form some kind of AST representation for the implied
12432     // memcpy in a union copy operation.
12433     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12434       continue;
12435 
12436     if (Field->isInvalidDecl()) {
12437       Invalid = true;
12438       continue;
12439     }
12440 
12441     // Check for members of reference type; we can't move those.
12442     if (Field->getType()->isReferenceType()) {
12443       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12444         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12445       Diag(Field->getLocation(), diag::note_declared_at);
12446       Invalid = true;
12447       continue;
12448     }
12449 
12450     // Check for members of const-qualified, non-class type.
12451     QualType BaseType = Context.getBaseElementType(Field->getType());
12452     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12453       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12454         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12455       Diag(Field->getLocation(), diag::note_declared_at);
12456       Invalid = true;
12457       continue;
12458     }
12459 
12460     // Suppress assigning zero-width bitfields.
12461     if (Field->isZeroLengthBitField(Context))
12462       continue;
12463 
12464     QualType FieldType = Field->getType().getNonReferenceType();
12465     if (FieldType->isIncompleteArrayType()) {
12466       assert(ClassDecl->hasFlexibleArrayMember() &&
12467              "Incomplete array type is not valid");
12468       continue;
12469     }
12470 
12471     // Build references to the field in the object we're copying from and to.
12472     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12473                               LookupMemberName);
12474     MemberLookup.addDecl(Field);
12475     MemberLookup.resolveKind();
12476     MemberBuilder From(MoveOther, OtherRefType,
12477                        /*IsArrow=*/false, MemberLookup);
12478     MemberBuilder To(This, getCurrentThisType(),
12479                      /*IsArrow=*/true, MemberLookup);
12480 
12481     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12482         "Member reference with rvalue base must be rvalue except for reference "
12483         "members, which aren't allowed for move assignment.");
12484 
12485     // Build the move of this field.
12486     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12487                                             To, From,
12488                                             /*CopyingBaseSubobject=*/false,
12489                                             /*Copying=*/false);
12490     if (Move.isInvalid()) {
12491       MoveAssignOperator->setInvalidDecl();
12492       return;
12493     }
12494 
12495     // Success! Record the copy.
12496     Statements.push_back(Move.getAs<Stmt>());
12497   }
12498 
12499   if (!Invalid) {
12500     // Add a "return *this;"
12501     ExprResult ThisObj =
12502         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12503 
12504     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12505     if (Return.isInvalid())
12506       Invalid = true;
12507     else
12508       Statements.push_back(Return.getAs<Stmt>());
12509   }
12510 
12511   if (Invalid) {
12512     MoveAssignOperator->setInvalidDecl();
12513     return;
12514   }
12515 
12516   StmtResult Body;
12517   {
12518     CompoundScopeRAII CompoundScope(*this);
12519     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12520                              /*isStmtExpr=*/false);
12521     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12522   }
12523   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12524   MoveAssignOperator->markUsed(Context);
12525 
12526   if (ASTMutationListener *L = getASTMutationListener()) {
12527     L->CompletedImplicitDefinition(MoveAssignOperator);
12528   }
12529 }
12530 
12531 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12532                                                     CXXRecordDecl *ClassDecl) {
12533   // C++ [class.copy]p4:
12534   //   If the class definition does not explicitly declare a copy
12535   //   constructor, one is declared implicitly.
12536   assert(ClassDecl->needsImplicitCopyConstructor());
12537 
12538   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12539   if (DSM.isAlreadyBeingDeclared())
12540     return nullptr;
12541 
12542   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12543   QualType ArgType = ClassType;
12544   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12545   if (Const)
12546     ArgType = ArgType.withConst();
12547 
12548   if (Context.getLangOpts().OpenCLCPlusPlus)
12549     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12550 
12551   ArgType = Context.getLValueReferenceType(ArgType);
12552 
12553   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12554                                                      CXXCopyConstructor,
12555                                                      Const);
12556 
12557   DeclarationName Name
12558     = Context.DeclarationNames.getCXXConstructorName(
12559                                            Context.getCanonicalType(ClassType));
12560   SourceLocation ClassLoc = ClassDecl->getLocation();
12561   DeclarationNameInfo NameInfo(Name, ClassLoc);
12562 
12563   //   An implicitly-declared copy constructor is an inline public
12564   //   member of its class.
12565   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12566       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12567       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12568       Constexpr);
12569   CopyConstructor->setAccess(AS_public);
12570   CopyConstructor->setDefaulted();
12571 
12572   if (getLangOpts().CUDA) {
12573     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12574                                             CopyConstructor,
12575                                             /* ConstRHS */ Const,
12576                                             /* Diagnose */ false);
12577   }
12578 
12579   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12580 
12581   // Add the parameter to the constructor.
12582   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12583                                                ClassLoc, ClassLoc,
12584                                                /*IdentifierInfo=*/nullptr,
12585                                                ArgType, /*TInfo=*/nullptr,
12586                                                SC_None, nullptr);
12587   CopyConstructor->setParams(FromParam);
12588 
12589   CopyConstructor->setTrivial(
12590       ClassDecl->needsOverloadResolutionForCopyConstructor()
12591           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12592           : ClassDecl->hasTrivialCopyConstructor());
12593 
12594   CopyConstructor->setTrivialForCall(
12595       ClassDecl->hasAttr<TrivialABIAttr>() ||
12596       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12597            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12598              TAH_ConsiderTrivialABI)
12599            : ClassDecl->hasTrivialCopyConstructorForCall()));
12600 
12601   // Note that we have declared this constructor.
12602   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12603 
12604   Scope *S = getScopeForContext(ClassDecl);
12605   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12606 
12607   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12608     ClassDecl->setImplicitCopyConstructorIsDeleted();
12609     SetDeclDeleted(CopyConstructor, ClassLoc);
12610   }
12611 
12612   if (S)
12613     PushOnScopeChains(CopyConstructor, S, false);
12614   ClassDecl->addDecl(CopyConstructor);
12615 
12616   return CopyConstructor;
12617 }
12618 
12619 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12620                                          CXXConstructorDecl *CopyConstructor) {
12621   assert((CopyConstructor->isDefaulted() &&
12622           CopyConstructor->isCopyConstructor() &&
12623           !CopyConstructor->doesThisDeclarationHaveABody() &&
12624           !CopyConstructor->isDeleted()) &&
12625          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12626   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12627     return;
12628 
12629   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12630   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12631 
12632   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12633 
12634   // The exception specification is needed because we are defining the
12635   // function.
12636   ResolveExceptionSpec(CurrentLocation,
12637                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12638   MarkVTableUsed(CurrentLocation, ClassDecl);
12639 
12640   // Add a context note for diagnostics produced after this point.
12641   Scope.addContextNote(CurrentLocation);
12642 
12643   // C++11 [class.copy]p7:
12644   //   The [definition of an implicitly declared copy constructor] is
12645   //   deprecated if the class has a user-declared copy assignment operator
12646   //   or a user-declared destructor.
12647   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12648     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12649 
12650   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12651     CopyConstructor->setInvalidDecl();
12652   }  else {
12653     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12654                              ? CopyConstructor->getEndLoc()
12655                              : CopyConstructor->getLocation();
12656     Sema::CompoundScopeRAII CompoundScope(*this);
12657     CopyConstructor->setBody(
12658         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12659     CopyConstructor->markUsed(Context);
12660   }
12661 
12662   if (ASTMutationListener *L = getASTMutationListener()) {
12663     L->CompletedImplicitDefinition(CopyConstructor);
12664   }
12665 }
12666 
12667 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12668                                                     CXXRecordDecl *ClassDecl) {
12669   assert(ClassDecl->needsImplicitMoveConstructor());
12670 
12671   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12672   if (DSM.isAlreadyBeingDeclared())
12673     return nullptr;
12674 
12675   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12676 
12677   QualType ArgType = ClassType;
12678   if (Context.getLangOpts().OpenCLCPlusPlus)
12679     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12680   ArgType = Context.getRValueReferenceType(ArgType);
12681 
12682   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12683                                                      CXXMoveConstructor,
12684                                                      false);
12685 
12686   DeclarationName Name
12687     = Context.DeclarationNames.getCXXConstructorName(
12688                                            Context.getCanonicalType(ClassType));
12689   SourceLocation ClassLoc = ClassDecl->getLocation();
12690   DeclarationNameInfo NameInfo(Name, ClassLoc);
12691 
12692   // C++11 [class.copy]p11:
12693   //   An implicitly-declared copy/move constructor is an inline public
12694   //   member of its class.
12695   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12696       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12697       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12698       Constexpr);
12699   MoveConstructor->setAccess(AS_public);
12700   MoveConstructor->setDefaulted();
12701 
12702   if (getLangOpts().CUDA) {
12703     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12704                                             MoveConstructor,
12705                                             /* ConstRHS */ false,
12706                                             /* Diagnose */ false);
12707   }
12708 
12709   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12710 
12711   // Add the parameter to the constructor.
12712   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12713                                                ClassLoc, ClassLoc,
12714                                                /*IdentifierInfo=*/nullptr,
12715                                                ArgType, /*TInfo=*/nullptr,
12716                                                SC_None, nullptr);
12717   MoveConstructor->setParams(FromParam);
12718 
12719   MoveConstructor->setTrivial(
12720       ClassDecl->needsOverloadResolutionForMoveConstructor()
12721           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12722           : ClassDecl->hasTrivialMoveConstructor());
12723 
12724   MoveConstructor->setTrivialForCall(
12725       ClassDecl->hasAttr<TrivialABIAttr>() ||
12726       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12727            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12728                                     TAH_ConsiderTrivialABI)
12729            : ClassDecl->hasTrivialMoveConstructorForCall()));
12730 
12731   // Note that we have declared this constructor.
12732   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12733 
12734   Scope *S = getScopeForContext(ClassDecl);
12735   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12736 
12737   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12738     ClassDecl->setImplicitMoveConstructorIsDeleted();
12739     SetDeclDeleted(MoveConstructor, ClassLoc);
12740   }
12741 
12742   if (S)
12743     PushOnScopeChains(MoveConstructor, S, false);
12744   ClassDecl->addDecl(MoveConstructor);
12745 
12746   return MoveConstructor;
12747 }
12748 
12749 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12750                                          CXXConstructorDecl *MoveConstructor) {
12751   assert((MoveConstructor->isDefaulted() &&
12752           MoveConstructor->isMoveConstructor() &&
12753           !MoveConstructor->doesThisDeclarationHaveABody() &&
12754           !MoveConstructor->isDeleted()) &&
12755          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12756   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12757     return;
12758 
12759   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12760   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12761 
12762   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12763 
12764   // The exception specification is needed because we are defining the
12765   // function.
12766   ResolveExceptionSpec(CurrentLocation,
12767                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12768   MarkVTableUsed(CurrentLocation, ClassDecl);
12769 
12770   // Add a context note for diagnostics produced after this point.
12771   Scope.addContextNote(CurrentLocation);
12772 
12773   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12774     MoveConstructor->setInvalidDecl();
12775   } else {
12776     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12777                              ? MoveConstructor->getEndLoc()
12778                              : MoveConstructor->getLocation();
12779     Sema::CompoundScopeRAII CompoundScope(*this);
12780     MoveConstructor->setBody(ActOnCompoundStmt(
12781         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12782     MoveConstructor->markUsed(Context);
12783   }
12784 
12785   if (ASTMutationListener *L = getASTMutationListener()) {
12786     L->CompletedImplicitDefinition(MoveConstructor);
12787   }
12788 }
12789 
12790 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12791   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12792 }
12793 
12794 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12795                             SourceLocation CurrentLocation,
12796                             CXXConversionDecl *Conv) {
12797   SynthesizedFunctionScope Scope(*this, Conv);
12798   assert(!Conv->getReturnType()->isUndeducedType());
12799 
12800   CXXRecordDecl *Lambda = Conv->getParent();
12801   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12802   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12803 
12804   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12805     CallOp = InstantiateFunctionDeclaration(
12806         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12807     if (!CallOp)
12808       return;
12809 
12810     Invoker = InstantiateFunctionDeclaration(
12811         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12812     if (!Invoker)
12813       return;
12814   }
12815 
12816   if (CallOp->isInvalidDecl())
12817     return;
12818 
12819   // Mark the call operator referenced (and add to pending instantiations
12820   // if necessary).
12821   // For both the conversion and static-invoker template specializations
12822   // we construct their body's in this function, so no need to add them
12823   // to the PendingInstantiations.
12824   MarkFunctionReferenced(CurrentLocation, CallOp);
12825 
12826   // Fill in the __invoke function with a dummy implementation. IR generation
12827   // will fill in the actual details. Update its type in case it contained
12828   // an 'auto'.
12829   Invoker->markUsed(Context);
12830   Invoker->setReferenced();
12831   Invoker->setType(Conv->getReturnType()->getPointeeType());
12832   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12833 
12834   // Construct the body of the conversion function { return __invoke; }.
12835   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12836                                        VK_LValue, Conv->getLocation()).get();
12837   assert(FunctionRef && "Can't refer to __invoke function?");
12838   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12839   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12840                                      Conv->getLocation()));
12841   Conv->markUsed(Context);
12842   Conv->setReferenced();
12843 
12844   if (ASTMutationListener *L = getASTMutationListener()) {
12845     L->CompletedImplicitDefinition(Conv);
12846     L->CompletedImplicitDefinition(Invoker);
12847   }
12848 }
12849 
12850 
12851 
12852 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12853        SourceLocation CurrentLocation,
12854        CXXConversionDecl *Conv)
12855 {
12856   assert(!Conv->getParent()->isGenericLambda());
12857 
12858   SynthesizedFunctionScope Scope(*this, Conv);
12859 
12860   // Copy-initialize the lambda object as needed to capture it.
12861   Expr *This = ActOnCXXThis(CurrentLocation).get();
12862   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12863 
12864   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12865                                                         Conv->getLocation(),
12866                                                         Conv, DerefThis);
12867 
12868   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12869   // behavior.  Note that only the general conversion function does this
12870   // (since it's unusable otherwise); in the case where we inline the
12871   // block literal, it has block literal lifetime semantics.
12872   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12873     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12874                                           CK_CopyAndAutoreleaseBlockObject,
12875                                           BuildBlock.get(), nullptr, VK_RValue);
12876 
12877   if (BuildBlock.isInvalid()) {
12878     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12879     Conv->setInvalidDecl();
12880     return;
12881   }
12882 
12883   // Create the return statement that returns the block from the conversion
12884   // function.
12885   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12886   if (Return.isInvalid()) {
12887     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12888     Conv->setInvalidDecl();
12889     return;
12890   }
12891 
12892   // Set the body of the conversion function.
12893   Stmt *ReturnS = Return.get();
12894   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12895                                      Conv->getLocation()));
12896   Conv->markUsed(Context);
12897 
12898   // We're done; notify the mutation listener, if any.
12899   if (ASTMutationListener *L = getASTMutationListener()) {
12900     L->CompletedImplicitDefinition(Conv);
12901   }
12902 }
12903 
12904 /// Determine whether the given list arguments contains exactly one
12905 /// "real" (non-default) argument.
12906 static bool hasOneRealArgument(MultiExprArg Args) {
12907   switch (Args.size()) {
12908   case 0:
12909     return false;
12910 
12911   default:
12912     if (!Args[1]->isDefaultArgument())
12913       return false;
12914 
12915     LLVM_FALLTHROUGH;
12916   case 1:
12917     return !Args[0]->isDefaultArgument();
12918   }
12919 
12920   return false;
12921 }
12922 
12923 ExprResult
12924 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12925                             NamedDecl *FoundDecl,
12926                             CXXConstructorDecl *Constructor,
12927                             MultiExprArg ExprArgs,
12928                             bool HadMultipleCandidates,
12929                             bool IsListInitialization,
12930                             bool IsStdInitListInitialization,
12931                             bool RequiresZeroInit,
12932                             unsigned ConstructKind,
12933                             SourceRange ParenRange) {
12934   bool Elidable = false;
12935 
12936   // C++0x [class.copy]p34:
12937   //   When certain criteria are met, an implementation is allowed to
12938   //   omit the copy/move construction of a class object, even if the
12939   //   copy/move constructor and/or destructor for the object have
12940   //   side effects. [...]
12941   //     - when a temporary class object that has not been bound to a
12942   //       reference (12.2) would be copied/moved to a class object
12943   //       with the same cv-unqualified type, the copy/move operation
12944   //       can be omitted by constructing the temporary object
12945   //       directly into the target of the omitted copy/move
12946   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12947       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12948     Expr *SubExpr = ExprArgs[0];
12949     Elidable = SubExpr->isTemporaryObject(
12950         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12951   }
12952 
12953   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12954                                FoundDecl, Constructor,
12955                                Elidable, ExprArgs, HadMultipleCandidates,
12956                                IsListInitialization,
12957                                IsStdInitListInitialization, RequiresZeroInit,
12958                                ConstructKind, ParenRange);
12959 }
12960 
12961 ExprResult
12962 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12963                             NamedDecl *FoundDecl,
12964                             CXXConstructorDecl *Constructor,
12965                             bool Elidable,
12966                             MultiExprArg ExprArgs,
12967                             bool HadMultipleCandidates,
12968                             bool IsListInitialization,
12969                             bool IsStdInitListInitialization,
12970                             bool RequiresZeroInit,
12971                             unsigned ConstructKind,
12972                             SourceRange ParenRange) {
12973   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12974     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12975     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12976       return ExprError();
12977   }
12978 
12979   return BuildCXXConstructExpr(
12980       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12981       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12982       RequiresZeroInit, ConstructKind, ParenRange);
12983 }
12984 
12985 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12986 /// including handling of its default argument expressions.
12987 ExprResult
12988 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12989                             CXXConstructorDecl *Constructor,
12990                             bool Elidable,
12991                             MultiExprArg ExprArgs,
12992                             bool HadMultipleCandidates,
12993                             bool IsListInitialization,
12994                             bool IsStdInitListInitialization,
12995                             bool RequiresZeroInit,
12996                             unsigned ConstructKind,
12997                             SourceRange ParenRange) {
12998   assert(declaresSameEntity(
12999              Constructor->getParent(),
13000              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13001          "given constructor for wrong type");
13002   MarkFunctionReferenced(ConstructLoc, Constructor);
13003   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13004     return ExprError();
13005 
13006   return CXXConstructExpr::Create(
13007       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13008       ExprArgs, HadMultipleCandidates, IsListInitialization,
13009       IsStdInitListInitialization, RequiresZeroInit,
13010       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13011       ParenRange);
13012 }
13013 
13014 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13015   assert(Field->hasInClassInitializer());
13016 
13017   // If we already have the in-class initializer nothing needs to be done.
13018   if (Field->getInClassInitializer())
13019     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13020 
13021   // If we might have already tried and failed to instantiate, don't try again.
13022   if (Field->isInvalidDecl())
13023     return ExprError();
13024 
13025   // Maybe we haven't instantiated the in-class initializer. Go check the
13026   // pattern FieldDecl to see if it has one.
13027   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13028 
13029   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13030     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13031     DeclContext::lookup_result Lookup =
13032         ClassPattern->lookup(Field->getDeclName());
13033 
13034     // Lookup can return at most two results: the pattern for the field, or the
13035     // injected class name of the parent record. No other member can have the
13036     // same name as the field.
13037     // In modules mode, lookup can return multiple results (coming from
13038     // different modules).
13039     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13040            "more than two lookup results for field name");
13041     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13042     if (!Pattern) {
13043       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13044              "cannot have other non-field member with same name");
13045       for (auto L : Lookup)
13046         if (isa<FieldDecl>(L)) {
13047           Pattern = cast<FieldDecl>(L);
13048           break;
13049         }
13050       assert(Pattern && "We must have set the Pattern!");
13051     }
13052 
13053     if (!Pattern->hasInClassInitializer() ||
13054         InstantiateInClassInitializer(Loc, Field, Pattern,
13055                                       getTemplateInstantiationArgs(Field))) {
13056       // Don't diagnose this again.
13057       Field->setInvalidDecl();
13058       return ExprError();
13059     }
13060     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13061   }
13062 
13063   // DR1351:
13064   //   If the brace-or-equal-initializer of a non-static data member
13065   //   invokes a defaulted default constructor of its class or of an
13066   //   enclosing class in a potentially evaluated subexpression, the
13067   //   program is ill-formed.
13068   //
13069   // This resolution is unworkable: the exception specification of the
13070   // default constructor can be needed in an unevaluated context, in
13071   // particular, in the operand of a noexcept-expression, and we can be
13072   // unable to compute an exception specification for an enclosed class.
13073   //
13074   // Any attempt to resolve the exception specification of a defaulted default
13075   // constructor before the initializer is lexically complete will ultimately
13076   // come here at which point we can diagnose it.
13077   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13078   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13079       << OutermostClass << Field;
13080   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13081   // Recover by marking the field invalid, unless we're in a SFINAE context.
13082   if (!isSFINAEContext())
13083     Field->setInvalidDecl();
13084   return ExprError();
13085 }
13086 
13087 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13088   if (VD->isInvalidDecl()) return;
13089 
13090   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13091   if (ClassDecl->isInvalidDecl()) return;
13092   if (ClassDecl->hasIrrelevantDestructor()) return;
13093   if (ClassDecl->isDependentContext()) return;
13094 
13095   if (VD->isNoDestroy(getASTContext()))
13096     return;
13097 
13098   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13099   MarkFunctionReferenced(VD->getLocation(), Destructor);
13100   CheckDestructorAccess(VD->getLocation(), Destructor,
13101                         PDiag(diag::err_access_dtor_var)
13102                         << VD->getDeclName()
13103                         << VD->getType());
13104   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13105 
13106   if (Destructor->isTrivial()) return;
13107   if (!VD->hasGlobalStorage()) return;
13108 
13109   // Emit warning for non-trivial dtor in global scope (a real global,
13110   // class-static, function-static).
13111   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13112 
13113   // TODO: this should be re-enabled for static locals by !CXAAtExit
13114   if (!VD->isStaticLocal())
13115     Diag(VD->getLocation(), diag::warn_global_destructor);
13116 }
13117 
13118 /// Given a constructor and the set of arguments provided for the
13119 /// constructor, convert the arguments and add any required default arguments
13120 /// to form a proper call to this constructor.
13121 ///
13122 /// \returns true if an error occurred, false otherwise.
13123 bool
13124 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13125                               MultiExprArg ArgsPtr,
13126                               SourceLocation Loc,
13127                               SmallVectorImpl<Expr*> &ConvertedArgs,
13128                               bool AllowExplicit,
13129                               bool IsListInitialization) {
13130   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13131   unsigned NumArgs = ArgsPtr.size();
13132   Expr **Args = ArgsPtr.data();
13133 
13134   const FunctionProtoType *Proto
13135     = Constructor->getType()->getAs<FunctionProtoType>();
13136   assert(Proto && "Constructor without a prototype?");
13137   unsigned NumParams = Proto->getNumParams();
13138 
13139   // If too few arguments are available, we'll fill in the rest with defaults.
13140   if (NumArgs < NumParams)
13141     ConvertedArgs.reserve(NumParams);
13142   else
13143     ConvertedArgs.reserve(NumArgs);
13144 
13145   VariadicCallType CallType =
13146     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13147   SmallVector<Expr *, 8> AllArgs;
13148   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13149                                         Proto, 0,
13150                                         llvm::makeArrayRef(Args, NumArgs),
13151                                         AllArgs,
13152                                         CallType, AllowExplicit,
13153                                         IsListInitialization);
13154   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13155 
13156   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13157 
13158   CheckConstructorCall(Constructor,
13159                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13160                        Proto, Loc);
13161 
13162   return Invalid;
13163 }
13164 
13165 static inline bool
13166 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13167                                        const FunctionDecl *FnDecl) {
13168   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13169   if (isa<NamespaceDecl>(DC)) {
13170     return SemaRef.Diag(FnDecl->getLocation(),
13171                         diag::err_operator_new_delete_declared_in_namespace)
13172       << FnDecl->getDeclName();
13173   }
13174 
13175   if (isa<TranslationUnitDecl>(DC) &&
13176       FnDecl->getStorageClass() == SC_Static) {
13177     return SemaRef.Diag(FnDecl->getLocation(),
13178                         diag::err_operator_new_delete_declared_static)
13179       << FnDecl->getDeclName();
13180   }
13181 
13182   return false;
13183 }
13184 
13185 static QualType
13186 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13187   QualType QTy = PtrTy->getPointeeType();
13188   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13189   return SemaRef.Context.getPointerType(QTy);
13190 }
13191 
13192 static inline bool
13193 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13194                             CanQualType ExpectedResultType,
13195                             CanQualType ExpectedFirstParamType,
13196                             unsigned DependentParamTypeDiag,
13197                             unsigned InvalidParamTypeDiag) {
13198   QualType ResultType =
13199       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13200 
13201   // Check that the result type is not dependent.
13202   if (ResultType->isDependentType())
13203     return SemaRef.Diag(FnDecl->getLocation(),
13204                         diag::err_operator_new_delete_dependent_result_type)
13205     << FnDecl->getDeclName() << ExpectedResultType;
13206 
13207   // OpenCL C++: the operator is valid on any address space.
13208   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13209     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13210       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13211     }
13212   }
13213 
13214   // Check that the result type is what we expect.
13215   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13216     return SemaRef.Diag(FnDecl->getLocation(),
13217                         diag::err_operator_new_delete_invalid_result_type)
13218     << FnDecl->getDeclName() << ExpectedResultType;
13219 
13220   // A function template must have at least 2 parameters.
13221   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13222     return SemaRef.Diag(FnDecl->getLocation(),
13223                       diag::err_operator_new_delete_template_too_few_parameters)
13224         << FnDecl->getDeclName();
13225 
13226   // The function decl must have at least 1 parameter.
13227   if (FnDecl->getNumParams() == 0)
13228     return SemaRef.Diag(FnDecl->getLocation(),
13229                         diag::err_operator_new_delete_too_few_parameters)
13230       << FnDecl->getDeclName();
13231 
13232   // Check the first parameter type is not dependent.
13233   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13234   if (FirstParamType->isDependentType())
13235     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13236       << FnDecl->getDeclName() << ExpectedFirstParamType;
13237 
13238   // Check that the first parameter type is what we expect.
13239   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13240     // OpenCL C++: the operator is valid on any address space.
13241     if (auto *PtrTy =
13242             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13243       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13244     }
13245   }
13246   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13247       ExpectedFirstParamType)
13248     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13249     << FnDecl->getDeclName() << ExpectedFirstParamType;
13250 
13251   return false;
13252 }
13253 
13254 static bool
13255 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13256   // C++ [basic.stc.dynamic.allocation]p1:
13257   //   A program is ill-formed if an allocation function is declared in a
13258   //   namespace scope other than global scope or declared static in global
13259   //   scope.
13260   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13261     return true;
13262 
13263   CanQualType SizeTy =
13264     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13265 
13266   // C++ [basic.stc.dynamic.allocation]p1:
13267   //  The return type shall be void*. The first parameter shall have type
13268   //  std::size_t.
13269   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13270                                   SizeTy,
13271                                   diag::err_operator_new_dependent_param_type,
13272                                   diag::err_operator_new_param_type))
13273     return true;
13274 
13275   // C++ [basic.stc.dynamic.allocation]p1:
13276   //  The first parameter shall not have an associated default argument.
13277   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13278     return SemaRef.Diag(FnDecl->getLocation(),
13279                         diag::err_operator_new_default_arg)
13280       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13281 
13282   return false;
13283 }
13284 
13285 static bool
13286 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13287   // C++ [basic.stc.dynamic.deallocation]p1:
13288   //   A program is ill-formed if deallocation functions are declared in a
13289   //   namespace scope other than global scope or declared static in global
13290   //   scope.
13291   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13292     return true;
13293 
13294   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13295 
13296   // C++ P0722:
13297   //   Within a class C, the first parameter of a destroying operator delete
13298   //   shall be of type C *. The first parameter of any other deallocation
13299   //   function shall be of type void *.
13300   CanQualType ExpectedFirstParamType =
13301       MD && MD->isDestroyingOperatorDelete()
13302           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13303                 SemaRef.Context.getRecordType(MD->getParent())))
13304           : SemaRef.Context.VoidPtrTy;
13305 
13306   // C++ [basic.stc.dynamic.deallocation]p2:
13307   //   Each deallocation function shall return void
13308   if (CheckOperatorNewDeleteTypes(
13309           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13310           diag::err_operator_delete_dependent_param_type,
13311           diag::err_operator_delete_param_type))
13312     return true;
13313 
13314   // C++ P0722:
13315   //   A destroying operator delete shall be a usual deallocation function.
13316   if (MD && !MD->getParent()->isDependentContext() &&
13317       MD->isDestroyingOperatorDelete() &&
13318       !SemaRef.isUsualDeallocationFunction(MD)) {
13319     SemaRef.Diag(MD->getLocation(),
13320                  diag::err_destroying_operator_delete_not_usual);
13321     return true;
13322   }
13323 
13324   return false;
13325 }
13326 
13327 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13328 /// of this overloaded operator is well-formed. If so, returns false;
13329 /// otherwise, emits appropriate diagnostics and returns true.
13330 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13331   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13332          "Expected an overloaded operator declaration");
13333 
13334   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13335 
13336   // C++ [over.oper]p5:
13337   //   The allocation and deallocation functions, operator new,
13338   //   operator new[], operator delete and operator delete[], are
13339   //   described completely in 3.7.3. The attributes and restrictions
13340   //   found in the rest of this subclause do not apply to them unless
13341   //   explicitly stated in 3.7.3.
13342   if (Op == OO_Delete || Op == OO_Array_Delete)
13343     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13344 
13345   if (Op == OO_New || Op == OO_Array_New)
13346     return CheckOperatorNewDeclaration(*this, FnDecl);
13347 
13348   // C++ [over.oper]p6:
13349   //   An operator function shall either be a non-static member
13350   //   function or be a non-member function and have at least one
13351   //   parameter whose type is a class, a reference to a class, an
13352   //   enumeration, or a reference to an enumeration.
13353   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13354     if (MethodDecl->isStatic())
13355       return Diag(FnDecl->getLocation(),
13356                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13357   } else {
13358     bool ClassOrEnumParam = false;
13359     for (auto Param : FnDecl->parameters()) {
13360       QualType ParamType = Param->getType().getNonReferenceType();
13361       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13362           ParamType->isEnumeralType()) {
13363         ClassOrEnumParam = true;
13364         break;
13365       }
13366     }
13367 
13368     if (!ClassOrEnumParam)
13369       return Diag(FnDecl->getLocation(),
13370                   diag::err_operator_overload_needs_class_or_enum)
13371         << FnDecl->getDeclName();
13372   }
13373 
13374   // C++ [over.oper]p8:
13375   //   An operator function cannot have default arguments (8.3.6),
13376   //   except where explicitly stated below.
13377   //
13378   // Only the function-call operator allows default arguments
13379   // (C++ [over.call]p1).
13380   if (Op != OO_Call) {
13381     for (auto Param : FnDecl->parameters()) {
13382       if (Param->hasDefaultArg())
13383         return Diag(Param->getLocation(),
13384                     diag::err_operator_overload_default_arg)
13385           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13386     }
13387   }
13388 
13389   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13390     { false, false, false }
13391 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13392     , { Unary, Binary, MemberOnly }
13393 #include "clang/Basic/OperatorKinds.def"
13394   };
13395 
13396   bool CanBeUnaryOperator = OperatorUses[Op][0];
13397   bool CanBeBinaryOperator = OperatorUses[Op][1];
13398   bool MustBeMemberOperator = OperatorUses[Op][2];
13399 
13400   // C++ [over.oper]p8:
13401   //   [...] Operator functions cannot have more or fewer parameters
13402   //   than the number required for the corresponding operator, as
13403   //   described in the rest of this subclause.
13404   unsigned NumParams = FnDecl->getNumParams()
13405                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13406   if (Op != OO_Call &&
13407       ((NumParams == 1 && !CanBeUnaryOperator) ||
13408        (NumParams == 2 && !CanBeBinaryOperator) ||
13409        (NumParams < 1) || (NumParams > 2))) {
13410     // We have the wrong number of parameters.
13411     unsigned ErrorKind;
13412     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13413       ErrorKind = 2;  // 2 -> unary or binary.
13414     } else if (CanBeUnaryOperator) {
13415       ErrorKind = 0;  // 0 -> unary
13416     } else {
13417       assert(CanBeBinaryOperator &&
13418              "All non-call overloaded operators are unary or binary!");
13419       ErrorKind = 1;  // 1 -> binary
13420     }
13421 
13422     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13423       << FnDecl->getDeclName() << NumParams << ErrorKind;
13424   }
13425 
13426   // Overloaded operators other than operator() cannot be variadic.
13427   if (Op != OO_Call &&
13428       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13429     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13430       << FnDecl->getDeclName();
13431   }
13432 
13433   // Some operators must be non-static member functions.
13434   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13435     return Diag(FnDecl->getLocation(),
13436                 diag::err_operator_overload_must_be_member)
13437       << FnDecl->getDeclName();
13438   }
13439 
13440   // C++ [over.inc]p1:
13441   //   The user-defined function called operator++ implements the
13442   //   prefix and postfix ++ operator. If this function is a member
13443   //   function with no parameters, or a non-member function with one
13444   //   parameter of class or enumeration type, it defines the prefix
13445   //   increment operator ++ for objects of that type. If the function
13446   //   is a member function with one parameter (which shall be of type
13447   //   int) or a non-member function with two parameters (the second
13448   //   of which shall be of type int), it defines the postfix
13449   //   increment operator ++ for objects of that type.
13450   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13451     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13452     QualType ParamType = LastParam->getType();
13453 
13454     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13455         !ParamType->isDependentType())
13456       return Diag(LastParam->getLocation(),
13457                   diag::err_operator_overload_post_incdec_must_be_int)
13458         << LastParam->getType() << (Op == OO_MinusMinus);
13459   }
13460 
13461   return false;
13462 }
13463 
13464 static bool
13465 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13466                                           FunctionTemplateDecl *TpDecl) {
13467   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13468 
13469   // Must have one or two template parameters.
13470   if (TemplateParams->size() == 1) {
13471     NonTypeTemplateParmDecl *PmDecl =
13472         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13473 
13474     // The template parameter must be a char parameter pack.
13475     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13476         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13477       return false;
13478 
13479   } else if (TemplateParams->size() == 2) {
13480     TemplateTypeParmDecl *PmType =
13481         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13482     NonTypeTemplateParmDecl *PmArgs =
13483         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13484 
13485     // The second template parameter must be a parameter pack with the
13486     // first template parameter as its type.
13487     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13488         PmArgs->isTemplateParameterPack()) {
13489       const TemplateTypeParmType *TArgs =
13490           PmArgs->getType()->getAs<TemplateTypeParmType>();
13491       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13492           TArgs->getIndex() == PmType->getIndex()) {
13493         if (!SemaRef.inTemplateInstantiation())
13494           SemaRef.Diag(TpDecl->getLocation(),
13495                        diag::ext_string_literal_operator_template);
13496         return false;
13497       }
13498     }
13499   }
13500 
13501   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13502                diag::err_literal_operator_template)
13503       << TpDecl->getTemplateParameters()->getSourceRange();
13504   return true;
13505 }
13506 
13507 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13508 /// of this literal operator function is well-formed. If so, returns
13509 /// false; otherwise, emits appropriate diagnostics and returns true.
13510 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13511   if (isa<CXXMethodDecl>(FnDecl)) {
13512     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13513       << FnDecl->getDeclName();
13514     return true;
13515   }
13516 
13517   if (FnDecl->isExternC()) {
13518     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13519     if (const LinkageSpecDecl *LSD =
13520             FnDecl->getDeclContext()->getExternCContext())
13521       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13522     return true;
13523   }
13524 
13525   // This might be the definition of a literal operator template.
13526   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13527 
13528   // This might be a specialization of a literal operator template.
13529   if (!TpDecl)
13530     TpDecl = FnDecl->getPrimaryTemplate();
13531 
13532   // template <char...> type operator "" name() and
13533   // template <class T, T...> type operator "" name() are the only valid
13534   // template signatures, and the only valid signatures with no parameters.
13535   if (TpDecl) {
13536     if (FnDecl->param_size() != 0) {
13537       Diag(FnDecl->getLocation(),
13538            diag::err_literal_operator_template_with_params);
13539       return true;
13540     }
13541 
13542     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13543       return true;
13544 
13545   } else if (FnDecl->param_size() == 1) {
13546     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13547 
13548     QualType ParamType = Param->getType().getUnqualifiedType();
13549 
13550     // Only unsigned long long int, long double, any character type, and const
13551     // char * are allowed as the only parameters.
13552     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13553         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13554         Context.hasSameType(ParamType, Context.CharTy) ||
13555         Context.hasSameType(ParamType, Context.WideCharTy) ||
13556         Context.hasSameType(ParamType, Context.Char8Ty) ||
13557         Context.hasSameType(ParamType, Context.Char16Ty) ||
13558         Context.hasSameType(ParamType, Context.Char32Ty)) {
13559     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13560       QualType InnerType = Ptr->getPointeeType();
13561 
13562       // Pointer parameter must be a const char *.
13563       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13564                                 Context.CharTy) &&
13565             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13566         Diag(Param->getSourceRange().getBegin(),
13567              diag::err_literal_operator_param)
13568             << ParamType << "'const char *'" << Param->getSourceRange();
13569         return true;
13570       }
13571 
13572     } else if (ParamType->isRealFloatingType()) {
13573       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13574           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13575       return true;
13576 
13577     } else if (ParamType->isIntegerType()) {
13578       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13579           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13580       return true;
13581 
13582     } else {
13583       Diag(Param->getSourceRange().getBegin(),
13584            diag::err_literal_operator_invalid_param)
13585           << ParamType << Param->getSourceRange();
13586       return true;
13587     }
13588 
13589   } else if (FnDecl->param_size() == 2) {
13590     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13591 
13592     // First, verify that the first parameter is correct.
13593 
13594     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13595 
13596     // Two parameter function must have a pointer to const as a
13597     // first parameter; let's strip those qualifiers.
13598     const PointerType *PT = FirstParamType->getAs<PointerType>();
13599 
13600     if (!PT) {
13601       Diag((*Param)->getSourceRange().getBegin(),
13602            diag::err_literal_operator_param)
13603           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13604       return true;
13605     }
13606 
13607     QualType PointeeType = PT->getPointeeType();
13608     // First parameter must be const
13609     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13610       Diag((*Param)->getSourceRange().getBegin(),
13611            diag::err_literal_operator_param)
13612           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13613       return true;
13614     }
13615 
13616     QualType InnerType = PointeeType.getUnqualifiedType();
13617     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13618     // const char32_t* are allowed as the first parameter to a two-parameter
13619     // function
13620     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13621           Context.hasSameType(InnerType, Context.WideCharTy) ||
13622           Context.hasSameType(InnerType, Context.Char8Ty) ||
13623           Context.hasSameType(InnerType, Context.Char16Ty) ||
13624           Context.hasSameType(InnerType, Context.Char32Ty))) {
13625       Diag((*Param)->getSourceRange().getBegin(),
13626            diag::err_literal_operator_param)
13627           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13628       return true;
13629     }
13630 
13631     // Move on to the second and final parameter.
13632     ++Param;
13633 
13634     // The second parameter must be a std::size_t.
13635     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13636     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13637       Diag((*Param)->getSourceRange().getBegin(),
13638            diag::err_literal_operator_param)
13639           << SecondParamType << Context.getSizeType()
13640           << (*Param)->getSourceRange();
13641       return true;
13642     }
13643   } else {
13644     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13645     return true;
13646   }
13647 
13648   // Parameters are good.
13649 
13650   // A parameter-declaration-clause containing a default argument is not
13651   // equivalent to any of the permitted forms.
13652   for (auto Param : FnDecl->parameters()) {
13653     if (Param->hasDefaultArg()) {
13654       Diag(Param->getDefaultArgRange().getBegin(),
13655            diag::err_literal_operator_default_argument)
13656         << Param->getDefaultArgRange();
13657       break;
13658     }
13659   }
13660 
13661   StringRef LiteralName
13662     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13663   if (LiteralName[0] != '_' &&
13664       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13665     // C++11 [usrlit.suffix]p1:
13666     //   Literal suffix identifiers that do not start with an underscore
13667     //   are reserved for future standardization.
13668     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13669       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13670   }
13671 
13672   return false;
13673 }
13674 
13675 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13676 /// linkage specification, including the language and (if present)
13677 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13678 /// language string literal. LBraceLoc, if valid, provides the location of
13679 /// the '{' brace. Otherwise, this linkage specification does not
13680 /// have any braces.
13681 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13682                                            Expr *LangStr,
13683                                            SourceLocation LBraceLoc) {
13684   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13685   if (!Lit->isAscii()) {
13686     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13687       << LangStr->getSourceRange();
13688     return nullptr;
13689   }
13690 
13691   StringRef Lang = Lit->getString();
13692   LinkageSpecDecl::LanguageIDs Language;
13693   if (Lang == "C")
13694     Language = LinkageSpecDecl::lang_c;
13695   else if (Lang == "C++")
13696     Language = LinkageSpecDecl::lang_cxx;
13697   else {
13698     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13699       << LangStr->getSourceRange();
13700     return nullptr;
13701   }
13702 
13703   // FIXME: Add all the various semantics of linkage specifications
13704 
13705   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13706                                                LangStr->getExprLoc(), Language,
13707                                                LBraceLoc.isValid());
13708   CurContext->addDecl(D);
13709   PushDeclContext(S, D);
13710   return D;
13711 }
13712 
13713 /// ActOnFinishLinkageSpecification - Complete the definition of
13714 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13715 /// valid, it's the position of the closing '}' brace in a linkage
13716 /// specification that uses braces.
13717 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13718                                             Decl *LinkageSpec,
13719                                             SourceLocation RBraceLoc) {
13720   if (RBraceLoc.isValid()) {
13721     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13722     LSDecl->setRBraceLoc(RBraceLoc);
13723   }
13724   PopDeclContext();
13725   return LinkageSpec;
13726 }
13727 
13728 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13729                                   const ParsedAttributesView &AttrList,
13730                                   SourceLocation SemiLoc) {
13731   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13732   // Attribute declarations appertain to empty declaration so we handle
13733   // them here.
13734   ProcessDeclAttributeList(S, ED, AttrList);
13735 
13736   CurContext->addDecl(ED);
13737   return ED;
13738 }
13739 
13740 /// Perform semantic analysis for the variable declaration that
13741 /// occurs within a C++ catch clause, returning the newly-created
13742 /// variable.
13743 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13744                                          TypeSourceInfo *TInfo,
13745                                          SourceLocation StartLoc,
13746                                          SourceLocation Loc,
13747                                          IdentifierInfo *Name) {
13748   bool Invalid = false;
13749   QualType ExDeclType = TInfo->getType();
13750 
13751   // Arrays and functions decay.
13752   if (ExDeclType->isArrayType())
13753     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13754   else if (ExDeclType->isFunctionType())
13755     ExDeclType = Context.getPointerType(ExDeclType);
13756 
13757   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13758   // The exception-declaration shall not denote a pointer or reference to an
13759   // incomplete type, other than [cv] void*.
13760   // N2844 forbids rvalue references.
13761   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13762     Diag(Loc, diag::err_catch_rvalue_ref);
13763     Invalid = true;
13764   }
13765 
13766   if (ExDeclType->isVariablyModifiedType()) {
13767     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13768     Invalid = true;
13769   }
13770 
13771   QualType BaseType = ExDeclType;
13772   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13773   unsigned DK = diag::err_catch_incomplete;
13774   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13775     BaseType = Ptr->getPointeeType();
13776     Mode = 1;
13777     DK = diag::err_catch_incomplete_ptr;
13778   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13779     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13780     BaseType = Ref->getPointeeType();
13781     Mode = 2;
13782     DK = diag::err_catch_incomplete_ref;
13783   }
13784   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13785       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13786     Invalid = true;
13787 
13788   if (!Invalid && !ExDeclType->isDependentType() &&
13789       RequireNonAbstractType(Loc, ExDeclType,
13790                              diag::err_abstract_type_in_decl,
13791                              AbstractVariableType))
13792     Invalid = true;
13793 
13794   // Only the non-fragile NeXT runtime currently supports C++ catches
13795   // of ObjC types, and no runtime supports catching ObjC types by value.
13796   if (!Invalid && getLangOpts().ObjC) {
13797     QualType T = ExDeclType;
13798     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13799       T = RT->getPointeeType();
13800 
13801     if (T->isObjCObjectType()) {
13802       Diag(Loc, diag::err_objc_object_catch);
13803       Invalid = true;
13804     } else if (T->isObjCObjectPointerType()) {
13805       // FIXME: should this be a test for macosx-fragile specifically?
13806       if (getLangOpts().ObjCRuntime.isFragile())
13807         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13808     }
13809   }
13810 
13811   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13812                                     ExDeclType, TInfo, SC_None);
13813   ExDecl->setExceptionVariable(true);
13814 
13815   // In ARC, infer 'retaining' for variables of retainable type.
13816   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13817     Invalid = true;
13818 
13819   if (!Invalid && !ExDeclType->isDependentType()) {
13820     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13821       // Insulate this from anything else we might currently be parsing.
13822       EnterExpressionEvaluationContext scope(
13823           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13824 
13825       // C++ [except.handle]p16:
13826       //   The object declared in an exception-declaration or, if the
13827       //   exception-declaration does not specify a name, a temporary (12.2) is
13828       //   copy-initialized (8.5) from the exception object. [...]
13829       //   The object is destroyed when the handler exits, after the destruction
13830       //   of any automatic objects initialized within the handler.
13831       //
13832       // We just pretend to initialize the object with itself, then make sure
13833       // it can be destroyed later.
13834       QualType initType = Context.getExceptionObjectType(ExDeclType);
13835 
13836       InitializedEntity entity =
13837         InitializedEntity::InitializeVariable(ExDecl);
13838       InitializationKind initKind =
13839         InitializationKind::CreateCopy(Loc, SourceLocation());
13840 
13841       Expr *opaqueValue =
13842         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13843       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13844       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13845       if (result.isInvalid())
13846         Invalid = true;
13847       else {
13848         // If the constructor used was non-trivial, set this as the
13849         // "initializer".
13850         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13851         if (!construct->getConstructor()->isTrivial()) {
13852           Expr *init = MaybeCreateExprWithCleanups(construct);
13853           ExDecl->setInit(init);
13854         }
13855 
13856         // And make sure it's destructable.
13857         FinalizeVarWithDestructor(ExDecl, recordType);
13858       }
13859     }
13860   }
13861 
13862   if (Invalid)
13863     ExDecl->setInvalidDecl();
13864 
13865   return ExDecl;
13866 }
13867 
13868 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13869 /// handler.
13870 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13871   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13872   bool Invalid = D.isInvalidType();
13873 
13874   // Check for unexpanded parameter packs.
13875   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13876                                       UPPC_ExceptionType)) {
13877     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13878                                              D.getIdentifierLoc());
13879     Invalid = true;
13880   }
13881 
13882   IdentifierInfo *II = D.getIdentifier();
13883   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13884                                              LookupOrdinaryName,
13885                                              ForVisibleRedeclaration)) {
13886     // The scope should be freshly made just for us. There is just no way
13887     // it contains any previous declaration, except for function parameters in
13888     // a function-try-block's catch statement.
13889     assert(!S->isDeclScope(PrevDecl));
13890     if (isDeclInScope(PrevDecl, CurContext, S)) {
13891       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13892         << D.getIdentifier();
13893       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13894       Invalid = true;
13895     } else if (PrevDecl->isTemplateParameter())
13896       // Maybe we will complain about the shadowed template parameter.
13897       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13898   }
13899 
13900   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13901     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13902       << D.getCXXScopeSpec().getRange();
13903     Invalid = true;
13904   }
13905 
13906   VarDecl *ExDecl = BuildExceptionDeclaration(
13907       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13908   if (Invalid)
13909     ExDecl->setInvalidDecl();
13910 
13911   // Add the exception declaration into this scope.
13912   if (II)
13913     PushOnScopeChains(ExDecl, S);
13914   else
13915     CurContext->addDecl(ExDecl);
13916 
13917   ProcessDeclAttributes(S, ExDecl, D);
13918   return ExDecl;
13919 }
13920 
13921 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13922                                          Expr *AssertExpr,
13923                                          Expr *AssertMessageExpr,
13924                                          SourceLocation RParenLoc) {
13925   StringLiteral *AssertMessage =
13926       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13927 
13928   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13929     return nullptr;
13930 
13931   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13932                                       AssertMessage, RParenLoc, false);
13933 }
13934 
13935 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13936                                          Expr *AssertExpr,
13937                                          StringLiteral *AssertMessage,
13938                                          SourceLocation RParenLoc,
13939                                          bool Failed) {
13940   assert(AssertExpr != nullptr && "Expected non-null condition");
13941   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13942       !Failed) {
13943     // In a static_assert-declaration, the constant-expression shall be a
13944     // constant expression that can be contextually converted to bool.
13945     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13946     if (Converted.isInvalid())
13947       Failed = true;
13948     else
13949       Converted = ConstantExpr::Create(Context, Converted.get());
13950 
13951     llvm::APSInt Cond;
13952     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13953           diag::err_static_assert_expression_is_not_constant,
13954           /*AllowFold=*/false).isInvalid())
13955       Failed = true;
13956 
13957     if (!Failed && !Cond) {
13958       SmallString<256> MsgBuffer;
13959       llvm::raw_svector_ostream Msg(MsgBuffer);
13960       if (AssertMessage)
13961         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13962 
13963       Expr *InnerCond = nullptr;
13964       std::string InnerCondDescription;
13965       std::tie(InnerCond, InnerCondDescription) =
13966         findFailedBooleanCondition(Converted.get());
13967       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13968                     && !isa<IntegerLiteral>(InnerCond)) {
13969         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13970           << InnerCondDescription << !AssertMessage
13971           << Msg.str() << InnerCond->getSourceRange();
13972       } else {
13973         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13974           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13975       }
13976       Failed = true;
13977     }
13978   }
13979 
13980   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13981                                                   /*DiscardedValue*/false,
13982                                                   /*IsConstexpr*/true);
13983   if (FullAssertExpr.isInvalid())
13984     Failed = true;
13985   else
13986     AssertExpr = FullAssertExpr.get();
13987 
13988   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13989                                         AssertExpr, AssertMessage, RParenLoc,
13990                                         Failed);
13991 
13992   CurContext->addDecl(Decl);
13993   return Decl;
13994 }
13995 
13996 /// Perform semantic analysis of the given friend type declaration.
13997 ///
13998 /// \returns A friend declaration that.
13999 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14000                                       SourceLocation FriendLoc,
14001                                       TypeSourceInfo *TSInfo) {
14002   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14003 
14004   QualType T = TSInfo->getType();
14005   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14006 
14007   // C++03 [class.friend]p2:
14008   //   An elaborated-type-specifier shall be used in a friend declaration
14009   //   for a class.*
14010   //
14011   //   * The class-key of the elaborated-type-specifier is required.
14012   if (!CodeSynthesisContexts.empty()) {
14013     // Do not complain about the form of friend template types during any kind
14014     // of code synthesis. For template instantiation, we will have complained
14015     // when the template was defined.
14016   } else {
14017     if (!T->isElaboratedTypeSpecifier()) {
14018       // If we evaluated the type to a record type, suggest putting
14019       // a tag in front.
14020       if (const RecordType *RT = T->getAs<RecordType>()) {
14021         RecordDecl *RD = RT->getDecl();
14022 
14023         SmallString<16> InsertionText(" ");
14024         InsertionText += RD->getKindName();
14025 
14026         Diag(TypeRange.getBegin(),
14027              getLangOpts().CPlusPlus11 ?
14028                diag::warn_cxx98_compat_unelaborated_friend_type :
14029                diag::ext_unelaborated_friend_type)
14030           << (unsigned) RD->getTagKind()
14031           << T
14032           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14033                                         InsertionText);
14034       } else {
14035         Diag(FriendLoc,
14036              getLangOpts().CPlusPlus11 ?
14037                diag::warn_cxx98_compat_nonclass_type_friend :
14038                diag::ext_nonclass_type_friend)
14039           << T
14040           << TypeRange;
14041       }
14042     } else if (T->getAs<EnumType>()) {
14043       Diag(FriendLoc,
14044            getLangOpts().CPlusPlus11 ?
14045              diag::warn_cxx98_compat_enum_friend :
14046              diag::ext_enum_friend)
14047         << T
14048         << TypeRange;
14049     }
14050 
14051     // C++11 [class.friend]p3:
14052     //   A friend declaration that does not declare a function shall have one
14053     //   of the following forms:
14054     //     friend elaborated-type-specifier ;
14055     //     friend simple-type-specifier ;
14056     //     friend typename-specifier ;
14057     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14058       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14059   }
14060 
14061   //   If the type specifier in a friend declaration designates a (possibly
14062   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14063   //   the friend declaration is ignored.
14064   return FriendDecl::Create(Context, CurContext,
14065                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14066                             FriendLoc);
14067 }
14068 
14069 /// Handle a friend tag declaration where the scope specifier was
14070 /// templated.
14071 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14072                                     unsigned TagSpec, SourceLocation TagLoc,
14073                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14074                                     SourceLocation NameLoc,
14075                                     const ParsedAttributesView &Attr,
14076                                     MultiTemplateParamsArg TempParamLists) {
14077   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14078 
14079   bool IsMemberSpecialization = false;
14080   bool Invalid = false;
14081 
14082   if (TemplateParameterList *TemplateParams =
14083           MatchTemplateParametersToScopeSpecifier(
14084               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14085               IsMemberSpecialization, Invalid)) {
14086     if (TemplateParams->size() > 0) {
14087       // This is a declaration of a class template.
14088       if (Invalid)
14089         return nullptr;
14090 
14091       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14092                                 NameLoc, Attr, TemplateParams, AS_public,
14093                                 /*ModulePrivateLoc=*/SourceLocation(),
14094                                 FriendLoc, TempParamLists.size() - 1,
14095                                 TempParamLists.data()).get();
14096     } else {
14097       // The "template<>" header is extraneous.
14098       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14099         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14100       IsMemberSpecialization = true;
14101     }
14102   }
14103 
14104   if (Invalid) return nullptr;
14105 
14106   bool isAllExplicitSpecializations = true;
14107   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14108     if (TempParamLists[I]->size()) {
14109       isAllExplicitSpecializations = false;
14110       break;
14111     }
14112   }
14113 
14114   // FIXME: don't ignore attributes.
14115 
14116   // If it's explicit specializations all the way down, just forget
14117   // about the template header and build an appropriate non-templated
14118   // friend.  TODO: for source fidelity, remember the headers.
14119   if (isAllExplicitSpecializations) {
14120     if (SS.isEmpty()) {
14121       bool Owned = false;
14122       bool IsDependent = false;
14123       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14124                       Attr, AS_public,
14125                       /*ModulePrivateLoc=*/SourceLocation(),
14126                       MultiTemplateParamsArg(), Owned, IsDependent,
14127                       /*ScopedEnumKWLoc=*/SourceLocation(),
14128                       /*ScopedEnumUsesClassTag=*/false,
14129                       /*UnderlyingType=*/TypeResult(),
14130                       /*IsTypeSpecifier=*/false,
14131                       /*IsTemplateParamOrArg=*/false);
14132     }
14133 
14134     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14135     ElaboratedTypeKeyword Keyword
14136       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14137     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14138                                    *Name, NameLoc);
14139     if (T.isNull())
14140       return nullptr;
14141 
14142     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14143     if (isa<DependentNameType>(T)) {
14144       DependentNameTypeLoc TL =
14145           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14146       TL.setElaboratedKeywordLoc(TagLoc);
14147       TL.setQualifierLoc(QualifierLoc);
14148       TL.setNameLoc(NameLoc);
14149     } else {
14150       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14151       TL.setElaboratedKeywordLoc(TagLoc);
14152       TL.setQualifierLoc(QualifierLoc);
14153       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14154     }
14155 
14156     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14157                                             TSI, FriendLoc, TempParamLists);
14158     Friend->setAccess(AS_public);
14159     CurContext->addDecl(Friend);
14160     return Friend;
14161   }
14162 
14163   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14164 
14165 
14166 
14167   // Handle the case of a templated-scope friend class.  e.g.
14168   //   template <class T> class A<T>::B;
14169   // FIXME: we don't support these right now.
14170   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14171     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14172   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14173   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14174   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14175   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14176   TL.setElaboratedKeywordLoc(TagLoc);
14177   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14178   TL.setNameLoc(NameLoc);
14179 
14180   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14181                                           TSI, FriendLoc, TempParamLists);
14182   Friend->setAccess(AS_public);
14183   Friend->setUnsupportedFriend(true);
14184   CurContext->addDecl(Friend);
14185   return Friend;
14186 }
14187 
14188 /// Handle a friend type declaration.  This works in tandem with
14189 /// ActOnTag.
14190 ///
14191 /// Notes on friend class templates:
14192 ///
14193 /// We generally treat friend class declarations as if they were
14194 /// declaring a class.  So, for example, the elaborated type specifier
14195 /// in a friend declaration is required to obey the restrictions of a
14196 /// class-head (i.e. no typedefs in the scope chain), template
14197 /// parameters are required to match up with simple template-ids, &c.
14198 /// However, unlike when declaring a template specialization, it's
14199 /// okay to refer to a template specialization without an empty
14200 /// template parameter declaration, e.g.
14201 ///   friend class A<T>::B<unsigned>;
14202 /// We permit this as a special case; if there are any template
14203 /// parameters present at all, require proper matching, i.e.
14204 ///   template <> template \<class T> friend class A<int>::B;
14205 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14206                                 MultiTemplateParamsArg TempParams) {
14207   SourceLocation Loc = DS.getBeginLoc();
14208 
14209   assert(DS.isFriendSpecified());
14210   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14211 
14212   // C++ [class.friend]p3:
14213   // A friend declaration that does not declare a function shall have one of
14214   // the following forms:
14215   //     friend elaborated-type-specifier ;
14216   //     friend simple-type-specifier ;
14217   //     friend typename-specifier ;
14218   //
14219   // Any declaration with a type qualifier does not have that form. (It's
14220   // legal to specify a qualified type as a friend, you just can't write the
14221   // keywords.)
14222   if (DS.getTypeQualifiers()) {
14223     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14224       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14225     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14226       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14227     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14228       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14229     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14230       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14231     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14232       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14233   }
14234 
14235   // Try to convert the decl specifier to a type.  This works for
14236   // friend templates because ActOnTag never produces a ClassTemplateDecl
14237   // for a TUK_Friend.
14238   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14239   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14240   QualType T = TSI->getType();
14241   if (TheDeclarator.isInvalidType())
14242     return nullptr;
14243 
14244   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14245     return nullptr;
14246 
14247   // This is definitely an error in C++98.  It's probably meant to
14248   // be forbidden in C++0x, too, but the specification is just
14249   // poorly written.
14250   //
14251   // The problem is with declarations like the following:
14252   //   template <T> friend A<T>::foo;
14253   // where deciding whether a class C is a friend or not now hinges
14254   // on whether there exists an instantiation of A that causes
14255   // 'foo' to equal C.  There are restrictions on class-heads
14256   // (which we declare (by fiat) elaborated friend declarations to
14257   // be) that makes this tractable.
14258   //
14259   // FIXME: handle "template <> friend class A<T>;", which
14260   // is possibly well-formed?  Who even knows?
14261   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14262     Diag(Loc, diag::err_tagless_friend_type_template)
14263       << DS.getSourceRange();
14264     return nullptr;
14265   }
14266 
14267   // C++98 [class.friend]p1: A friend of a class is a function
14268   //   or class that is not a member of the class . . .
14269   // This is fixed in DR77, which just barely didn't make the C++03
14270   // deadline.  It's also a very silly restriction that seriously
14271   // affects inner classes and which nobody else seems to implement;
14272   // thus we never diagnose it, not even in -pedantic.
14273   //
14274   // But note that we could warn about it: it's always useless to
14275   // friend one of your own members (it's not, however, worthless to
14276   // friend a member of an arbitrary specialization of your template).
14277 
14278   Decl *D;
14279   if (!TempParams.empty())
14280     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14281                                    TempParams,
14282                                    TSI,
14283                                    DS.getFriendSpecLoc());
14284   else
14285     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14286 
14287   if (!D)
14288     return nullptr;
14289 
14290   D->setAccess(AS_public);
14291   CurContext->addDecl(D);
14292 
14293   return D;
14294 }
14295 
14296 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14297                                         MultiTemplateParamsArg TemplateParams) {
14298   const DeclSpec &DS = D.getDeclSpec();
14299 
14300   assert(DS.isFriendSpecified());
14301   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14302 
14303   SourceLocation Loc = D.getIdentifierLoc();
14304   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14305 
14306   // C++ [class.friend]p1
14307   //   A friend of a class is a function or class....
14308   // Note that this sees through typedefs, which is intended.
14309   // It *doesn't* see through dependent types, which is correct
14310   // according to [temp.arg.type]p3:
14311   //   If a declaration acquires a function type through a
14312   //   type dependent on a template-parameter and this causes
14313   //   a declaration that does not use the syntactic form of a
14314   //   function declarator to have a function type, the program
14315   //   is ill-formed.
14316   if (!TInfo->getType()->isFunctionType()) {
14317     Diag(Loc, diag::err_unexpected_friend);
14318 
14319     // It might be worthwhile to try to recover by creating an
14320     // appropriate declaration.
14321     return nullptr;
14322   }
14323 
14324   // C++ [namespace.memdef]p3
14325   //  - If a friend declaration in a non-local class first declares a
14326   //    class or function, the friend class or function is a member
14327   //    of the innermost enclosing namespace.
14328   //  - The name of the friend is not found by simple name lookup
14329   //    until a matching declaration is provided in that namespace
14330   //    scope (either before or after the class declaration granting
14331   //    friendship).
14332   //  - If a friend function is called, its name may be found by the
14333   //    name lookup that considers functions from namespaces and
14334   //    classes associated with the types of the function arguments.
14335   //  - When looking for a prior declaration of a class or a function
14336   //    declared as a friend, scopes outside the innermost enclosing
14337   //    namespace scope are not considered.
14338 
14339   CXXScopeSpec &SS = D.getCXXScopeSpec();
14340   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14341   assert(NameInfo.getName());
14342 
14343   // Check for unexpanded parameter packs.
14344   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14345       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14346       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14347     return nullptr;
14348 
14349   // The context we found the declaration in, or in which we should
14350   // create the declaration.
14351   DeclContext *DC;
14352   Scope *DCScope = S;
14353   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14354                         ForExternalRedeclaration);
14355 
14356   // There are five cases here.
14357   //   - There's no scope specifier and we're in a local class. Only look
14358   //     for functions declared in the immediately-enclosing block scope.
14359   // We recover from invalid scope qualifiers as if they just weren't there.
14360   FunctionDecl *FunctionContainingLocalClass = nullptr;
14361   if ((SS.isInvalid() || !SS.isSet()) &&
14362       (FunctionContainingLocalClass =
14363            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14364     // C++11 [class.friend]p11:
14365     //   If a friend declaration appears in a local class and the name
14366     //   specified is an unqualified name, a prior declaration is
14367     //   looked up without considering scopes that are outside the
14368     //   innermost enclosing non-class scope. For a friend function
14369     //   declaration, if there is no prior declaration, the program is
14370     //   ill-formed.
14371 
14372     // Find the innermost enclosing non-class scope. This is the block
14373     // scope containing the local class definition (or for a nested class,
14374     // the outer local class).
14375     DCScope = S->getFnParent();
14376 
14377     // Look up the function name in the scope.
14378     Previous.clear(LookupLocalFriendName);
14379     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14380 
14381     if (!Previous.empty()) {
14382       // All possible previous declarations must have the same context:
14383       // either they were declared at block scope or they are members of
14384       // one of the enclosing local classes.
14385       DC = Previous.getRepresentativeDecl()->getDeclContext();
14386     } else {
14387       // This is ill-formed, but provide the context that we would have
14388       // declared the function in, if we were permitted to, for error recovery.
14389       DC = FunctionContainingLocalClass;
14390     }
14391     adjustContextForLocalExternDecl(DC);
14392 
14393     // C++ [class.friend]p6:
14394     //   A function can be defined in a friend declaration of a class if and
14395     //   only if the class is a non-local class (9.8), the function name is
14396     //   unqualified, and the function has namespace scope.
14397     if (D.isFunctionDefinition()) {
14398       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14399     }
14400 
14401   //   - There's no scope specifier, in which case we just go to the
14402   //     appropriate scope and look for a function or function template
14403   //     there as appropriate.
14404   } else if (SS.isInvalid() || !SS.isSet()) {
14405     // C++11 [namespace.memdef]p3:
14406     //   If the name in a friend declaration is neither qualified nor
14407     //   a template-id and the declaration is a function or an
14408     //   elaborated-type-specifier, the lookup to determine whether
14409     //   the entity has been previously declared shall not consider
14410     //   any scopes outside the innermost enclosing namespace.
14411     bool isTemplateId =
14412         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14413 
14414     // Find the appropriate context according to the above.
14415     DC = CurContext;
14416 
14417     // Skip class contexts.  If someone can cite chapter and verse
14418     // for this behavior, that would be nice --- it's what GCC and
14419     // EDG do, and it seems like a reasonable intent, but the spec
14420     // really only says that checks for unqualified existing
14421     // declarations should stop at the nearest enclosing namespace,
14422     // not that they should only consider the nearest enclosing
14423     // namespace.
14424     while (DC->isRecord())
14425       DC = DC->getParent();
14426 
14427     DeclContext *LookupDC = DC;
14428     while (LookupDC->isTransparentContext())
14429       LookupDC = LookupDC->getParent();
14430 
14431     while (true) {
14432       LookupQualifiedName(Previous, LookupDC);
14433 
14434       if (!Previous.empty()) {
14435         DC = LookupDC;
14436         break;
14437       }
14438 
14439       if (isTemplateId) {
14440         if (isa<TranslationUnitDecl>(LookupDC)) break;
14441       } else {
14442         if (LookupDC->isFileContext()) break;
14443       }
14444       LookupDC = LookupDC->getParent();
14445     }
14446 
14447     DCScope = getScopeForDeclContext(S, DC);
14448 
14449   //   - There's a non-dependent scope specifier, in which case we
14450   //     compute it and do a previous lookup there for a function
14451   //     or function template.
14452   } else if (!SS.getScopeRep()->isDependent()) {
14453     DC = computeDeclContext(SS);
14454     if (!DC) return nullptr;
14455 
14456     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14457 
14458     LookupQualifiedName(Previous, DC);
14459 
14460     // C++ [class.friend]p1: A friend of a class is a function or
14461     //   class that is not a member of the class . . .
14462     if (DC->Equals(CurContext))
14463       Diag(DS.getFriendSpecLoc(),
14464            getLangOpts().CPlusPlus11 ?
14465              diag::warn_cxx98_compat_friend_is_member :
14466              diag::err_friend_is_member);
14467 
14468     if (D.isFunctionDefinition()) {
14469       // C++ [class.friend]p6:
14470       //   A function can be defined in a friend declaration of a class if and
14471       //   only if the class is a non-local class (9.8), the function name is
14472       //   unqualified, and the function has namespace scope.
14473       //
14474       // FIXME: We should only do this if the scope specifier names the
14475       // innermost enclosing namespace; otherwise the fixit changes the
14476       // meaning of the code.
14477       SemaDiagnosticBuilder DB
14478         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14479 
14480       DB << SS.getScopeRep();
14481       if (DC->isFileContext())
14482         DB << FixItHint::CreateRemoval(SS.getRange());
14483       SS.clear();
14484     }
14485 
14486   //   - There's a scope specifier that does not match any template
14487   //     parameter lists, in which case we use some arbitrary context,
14488   //     create a method or method template, and wait for instantiation.
14489   //   - There's a scope specifier that does match some template
14490   //     parameter lists, which we don't handle right now.
14491   } else {
14492     if (D.isFunctionDefinition()) {
14493       // C++ [class.friend]p6:
14494       //   A function can be defined in a friend declaration of a class if and
14495       //   only if the class is a non-local class (9.8), the function name is
14496       //   unqualified, and the function has namespace scope.
14497       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14498         << SS.getScopeRep();
14499     }
14500 
14501     DC = CurContext;
14502     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14503   }
14504 
14505   if (!DC->isRecord()) {
14506     int DiagArg = -1;
14507     switch (D.getName().getKind()) {
14508     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14509     case UnqualifiedIdKind::IK_ConstructorName:
14510       DiagArg = 0;
14511       break;
14512     case UnqualifiedIdKind::IK_DestructorName:
14513       DiagArg = 1;
14514       break;
14515     case UnqualifiedIdKind::IK_ConversionFunctionId:
14516       DiagArg = 2;
14517       break;
14518     case UnqualifiedIdKind::IK_DeductionGuideName:
14519       DiagArg = 3;
14520       break;
14521     case UnqualifiedIdKind::IK_Identifier:
14522     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14523     case UnqualifiedIdKind::IK_LiteralOperatorId:
14524     case UnqualifiedIdKind::IK_OperatorFunctionId:
14525     case UnqualifiedIdKind::IK_TemplateId:
14526       break;
14527     }
14528     // This implies that it has to be an operator or function.
14529     if (DiagArg >= 0) {
14530       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14531       return nullptr;
14532     }
14533   }
14534 
14535   // FIXME: This is an egregious hack to cope with cases where the scope stack
14536   // does not contain the declaration context, i.e., in an out-of-line
14537   // definition of a class.
14538   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14539   if (!DCScope) {
14540     FakeDCScope.setEntity(DC);
14541     DCScope = &FakeDCScope;
14542   }
14543 
14544   bool AddToScope = true;
14545   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14546                                           TemplateParams, AddToScope);
14547   if (!ND) return nullptr;
14548 
14549   assert(ND->getLexicalDeclContext() == CurContext);
14550 
14551   // If we performed typo correction, we might have added a scope specifier
14552   // and changed the decl context.
14553   DC = ND->getDeclContext();
14554 
14555   // Add the function declaration to the appropriate lookup tables,
14556   // adjusting the redeclarations list as necessary.  We don't
14557   // want to do this yet if the friending class is dependent.
14558   //
14559   // Also update the scope-based lookup if the target context's
14560   // lookup context is in lexical scope.
14561   if (!CurContext->isDependentContext()) {
14562     DC = DC->getRedeclContext();
14563     DC->makeDeclVisibleInContext(ND);
14564     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14565       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14566   }
14567 
14568   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14569                                        D.getIdentifierLoc(), ND,
14570                                        DS.getFriendSpecLoc());
14571   FrD->setAccess(AS_public);
14572   CurContext->addDecl(FrD);
14573 
14574   if (ND->isInvalidDecl()) {
14575     FrD->setInvalidDecl();
14576   } else {
14577     if (DC->isRecord()) CheckFriendAccess(ND);
14578 
14579     FunctionDecl *FD;
14580     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14581       FD = FTD->getTemplatedDecl();
14582     else
14583       FD = cast<FunctionDecl>(ND);
14584 
14585     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14586     // default argument expression, that declaration shall be a definition
14587     // and shall be the only declaration of the function or function
14588     // template in the translation unit.
14589     if (functionDeclHasDefaultArgument(FD)) {
14590       // We can't look at FD->getPreviousDecl() because it may not have been set
14591       // if we're in a dependent context. If the function is known to be a
14592       // redeclaration, we will have narrowed Previous down to the right decl.
14593       if (D.isRedeclaration()) {
14594         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14595         Diag(Previous.getRepresentativeDecl()->getLocation(),
14596              diag::note_previous_declaration);
14597       } else if (!D.isFunctionDefinition())
14598         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14599     }
14600 
14601     // Mark templated-scope function declarations as unsupported.
14602     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14603       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14604         << SS.getScopeRep() << SS.getRange()
14605         << cast<CXXRecordDecl>(CurContext);
14606       FrD->setUnsupportedFriend(true);
14607     }
14608   }
14609 
14610   return ND;
14611 }
14612 
14613 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14614   AdjustDeclIfTemplate(Dcl);
14615 
14616   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14617   if (!Fn) {
14618     Diag(DelLoc, diag::err_deleted_non_function);
14619     return;
14620   }
14621 
14622   // Deleted function does not have a body.
14623   Fn->setWillHaveBody(false);
14624 
14625   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14626     // Don't consider the implicit declaration we generate for explicit
14627     // specializations. FIXME: Do not generate these implicit declarations.
14628     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14629          Prev->getPreviousDecl()) &&
14630         !Prev->isDefined()) {
14631       Diag(DelLoc, diag::err_deleted_decl_not_first);
14632       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14633            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14634                               : diag::note_previous_declaration);
14635     }
14636     // If the declaration wasn't the first, we delete the function anyway for
14637     // recovery.
14638     Fn = Fn->getCanonicalDecl();
14639   }
14640 
14641   // dllimport/dllexport cannot be deleted.
14642   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14643     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14644     Fn->setInvalidDecl();
14645   }
14646 
14647   if (Fn->isDeleted())
14648     return;
14649 
14650   // See if we're deleting a function which is already known to override a
14651   // non-deleted virtual function.
14652   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14653     bool IssuedDiagnostic = false;
14654     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14655       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14656         if (!IssuedDiagnostic) {
14657           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14658           IssuedDiagnostic = true;
14659         }
14660         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14661       }
14662     }
14663     // If this function was implicitly deleted because it was defaulted,
14664     // explain why it was deleted.
14665     if (IssuedDiagnostic && MD->isDefaulted())
14666       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14667                                 /*Diagnose*/true);
14668   }
14669 
14670   // C++11 [basic.start.main]p3:
14671   //   A program that defines main as deleted [...] is ill-formed.
14672   if (Fn->isMain())
14673     Diag(DelLoc, diag::err_deleted_main);
14674 
14675   // C++11 [dcl.fct.def.delete]p4:
14676   //  A deleted function is implicitly inline.
14677   Fn->setImplicitlyInline();
14678   Fn->setDeletedAsWritten();
14679 }
14680 
14681 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14682   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14683 
14684   if (MD) {
14685     if (MD->getParent()->isDependentType()) {
14686       MD->setDefaulted();
14687       MD->setExplicitlyDefaulted();
14688       return;
14689     }
14690 
14691     CXXSpecialMember Member = getSpecialMember(MD);
14692     if (Member == CXXInvalid) {
14693       if (!MD->isInvalidDecl())
14694         Diag(DefaultLoc, diag::err_default_special_members);
14695       return;
14696     }
14697 
14698     MD->setDefaulted();
14699     MD->setExplicitlyDefaulted();
14700 
14701     // Unset that we will have a body for this function. We might not,
14702     // if it turns out to be trivial, and we don't need this marking now
14703     // that we've marked it as defaulted.
14704     MD->setWillHaveBody(false);
14705 
14706     // If this definition appears within the record, do the checking when
14707     // the record is complete.
14708     const FunctionDecl *Primary = MD;
14709     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14710       // Ask the template instantiation pattern that actually had the
14711       // '= default' on it.
14712       Primary = Pattern;
14713 
14714     // If the method was defaulted on its first declaration, we will have
14715     // already performed the checking in CheckCompletedCXXClass. Such a
14716     // declaration doesn't trigger an implicit definition.
14717     if (Primary->getCanonicalDecl()->isDefaulted())
14718       return;
14719 
14720     CheckExplicitlyDefaultedSpecialMember(MD);
14721 
14722     if (!MD->isInvalidDecl())
14723       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14724   } else {
14725     Diag(DefaultLoc, diag::err_default_special_members);
14726   }
14727 }
14728 
14729 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14730   for (Stmt *SubStmt : S->children()) {
14731     if (!SubStmt)
14732       continue;
14733     if (isa<ReturnStmt>(SubStmt))
14734       Self.Diag(SubStmt->getBeginLoc(),
14735                 diag::err_return_in_constructor_handler);
14736     if (!isa<Expr>(SubStmt))
14737       SearchForReturnInStmt(Self, SubStmt);
14738   }
14739 }
14740 
14741 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14742   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14743     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14744     SearchForReturnInStmt(*this, Handler);
14745   }
14746 }
14747 
14748 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14749                                              const CXXMethodDecl *Old) {
14750   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14751   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14752 
14753   if (OldFT->hasExtParameterInfos()) {
14754     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14755       // A parameter of the overriding method should be annotated with noescape
14756       // if the corresponding parameter of the overridden method is annotated.
14757       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14758           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14759         Diag(New->getParamDecl(I)->getLocation(),
14760              diag::warn_overriding_method_missing_noescape);
14761         Diag(Old->getParamDecl(I)->getLocation(),
14762              diag::note_overridden_marked_noescape);
14763       }
14764   }
14765 
14766   // Virtual overrides must have the same code_seg.
14767   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14768   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14769   if ((NewCSA || OldCSA) &&
14770       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14771     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14772     Diag(Old->getLocation(), diag::note_previous_declaration);
14773     return true;
14774   }
14775 
14776   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14777 
14778   // If the calling conventions match, everything is fine
14779   if (NewCC == OldCC)
14780     return false;
14781 
14782   // If the calling conventions mismatch because the new function is static,
14783   // suppress the calling convention mismatch error; the error about static
14784   // function override (err_static_overrides_virtual from
14785   // Sema::CheckFunctionDeclaration) is more clear.
14786   if (New->getStorageClass() == SC_Static)
14787     return false;
14788 
14789   Diag(New->getLocation(),
14790        diag::err_conflicting_overriding_cc_attributes)
14791     << New->getDeclName() << New->getType() << Old->getType();
14792   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14793   return true;
14794 }
14795 
14796 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14797                                              const CXXMethodDecl *Old) {
14798   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14799   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14800 
14801   if (Context.hasSameType(NewTy, OldTy) ||
14802       NewTy->isDependentType() || OldTy->isDependentType())
14803     return false;
14804 
14805   // Check if the return types are covariant
14806   QualType NewClassTy, OldClassTy;
14807 
14808   /// Both types must be pointers or references to classes.
14809   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14810     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14811       NewClassTy = NewPT->getPointeeType();
14812       OldClassTy = OldPT->getPointeeType();
14813     }
14814   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14815     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14816       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14817         NewClassTy = NewRT->getPointeeType();
14818         OldClassTy = OldRT->getPointeeType();
14819       }
14820     }
14821   }
14822 
14823   // The return types aren't either both pointers or references to a class type.
14824   if (NewClassTy.isNull()) {
14825     Diag(New->getLocation(),
14826          diag::err_different_return_type_for_overriding_virtual_function)
14827         << New->getDeclName() << NewTy << OldTy
14828         << New->getReturnTypeSourceRange();
14829     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14830         << Old->getReturnTypeSourceRange();
14831 
14832     return true;
14833   }
14834 
14835   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14836     // C++14 [class.virtual]p8:
14837     //   If the class type in the covariant return type of D::f differs from
14838     //   that of B::f, the class type in the return type of D::f shall be
14839     //   complete at the point of declaration of D::f or shall be the class
14840     //   type D.
14841     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14842       if (!RT->isBeingDefined() &&
14843           RequireCompleteType(New->getLocation(), NewClassTy,
14844                               diag::err_covariant_return_incomplete,
14845                               New->getDeclName()))
14846         return true;
14847     }
14848 
14849     // Check if the new class derives from the old class.
14850     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14851       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14852           << New->getDeclName() << NewTy << OldTy
14853           << New->getReturnTypeSourceRange();
14854       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14855           << Old->getReturnTypeSourceRange();
14856       return true;
14857     }
14858 
14859     // Check if we the conversion from derived to base is valid.
14860     if (CheckDerivedToBaseConversion(
14861             NewClassTy, OldClassTy,
14862             diag::err_covariant_return_inaccessible_base,
14863             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14864             New->getLocation(), New->getReturnTypeSourceRange(),
14865             New->getDeclName(), nullptr)) {
14866       // FIXME: this note won't trigger for delayed access control
14867       // diagnostics, and it's impossible to get an undelayed error
14868       // here from access control during the original parse because
14869       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14870       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14871           << Old->getReturnTypeSourceRange();
14872       return true;
14873     }
14874   }
14875 
14876   // The qualifiers of the return types must be the same.
14877   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14878     Diag(New->getLocation(),
14879          diag::err_covariant_return_type_different_qualifications)
14880         << New->getDeclName() << NewTy << OldTy
14881         << New->getReturnTypeSourceRange();
14882     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14883         << Old->getReturnTypeSourceRange();
14884     return true;
14885   }
14886 
14887 
14888   // The new class type must have the same or less qualifiers as the old type.
14889   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14890     Diag(New->getLocation(),
14891          diag::err_covariant_return_type_class_type_more_qualified)
14892         << New->getDeclName() << NewTy << OldTy
14893         << New->getReturnTypeSourceRange();
14894     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14895         << Old->getReturnTypeSourceRange();
14896     return true;
14897   }
14898 
14899   return false;
14900 }
14901 
14902 /// Mark the given method pure.
14903 ///
14904 /// \param Method the method to be marked pure.
14905 ///
14906 /// \param InitRange the source range that covers the "0" initializer.
14907 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14908   SourceLocation EndLoc = InitRange.getEnd();
14909   if (EndLoc.isValid())
14910     Method->setRangeEnd(EndLoc);
14911 
14912   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14913     Method->setPure();
14914     return false;
14915   }
14916 
14917   if (!Method->isInvalidDecl())
14918     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14919       << Method->getDeclName() << InitRange;
14920   return true;
14921 }
14922 
14923 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14924   if (D->getFriendObjectKind())
14925     Diag(D->getLocation(), diag::err_pure_friend);
14926   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14927     CheckPureMethod(M, ZeroLoc);
14928   else
14929     Diag(D->getLocation(), diag::err_illegal_initializer);
14930 }
14931 
14932 /// Determine whether the given declaration is a global variable or
14933 /// static data member.
14934 static bool isNonlocalVariable(const Decl *D) {
14935   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14936     return Var->hasGlobalStorage();
14937 
14938   return false;
14939 }
14940 
14941 /// Invoked when we are about to parse an initializer for the declaration
14942 /// 'Dcl'.
14943 ///
14944 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14945 /// static data member of class X, names should be looked up in the scope of
14946 /// class X. If the declaration had a scope specifier, a scope will have
14947 /// been created and passed in for this purpose. Otherwise, S will be null.
14948 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14949   // If there is no declaration, there was an error parsing it.
14950   if (!D || D->isInvalidDecl())
14951     return;
14952 
14953   // We will always have a nested name specifier here, but this declaration
14954   // might not be out of line if the specifier names the current namespace:
14955   //   extern int n;
14956   //   int ::n = 0;
14957   if (S && D->isOutOfLine())
14958     EnterDeclaratorContext(S, D->getDeclContext());
14959 
14960   // If we are parsing the initializer for a static data member, push a
14961   // new expression evaluation context that is associated with this static
14962   // data member.
14963   if (isNonlocalVariable(D))
14964     PushExpressionEvaluationContext(
14965         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14966 }
14967 
14968 /// Invoked after we are finished parsing an initializer for the declaration D.
14969 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14970   // If there is no declaration, there was an error parsing it.
14971   if (!D || D->isInvalidDecl())
14972     return;
14973 
14974   if (isNonlocalVariable(D))
14975     PopExpressionEvaluationContext();
14976 
14977   if (S && D->isOutOfLine())
14978     ExitDeclaratorContext(S);
14979 }
14980 
14981 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14982 /// C++ if/switch/while/for statement.
14983 /// e.g: "if (int x = f()) {...}"
14984 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14985   // C++ 6.4p2:
14986   // The declarator shall not specify a function or an array.
14987   // The type-specifier-seq shall not contain typedef and shall not declare a
14988   // new class or enumeration.
14989   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14990          "Parser allowed 'typedef' as storage class of condition decl.");
14991 
14992   Decl *Dcl = ActOnDeclarator(S, D);
14993   if (!Dcl)
14994     return true;
14995 
14996   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14997     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14998       << D.getSourceRange();
14999     return true;
15000   }
15001 
15002   return Dcl;
15003 }
15004 
15005 void Sema::LoadExternalVTableUses() {
15006   if (!ExternalSource)
15007     return;
15008 
15009   SmallVector<ExternalVTableUse, 4> VTables;
15010   ExternalSource->ReadUsedVTables(VTables);
15011   SmallVector<VTableUse, 4> NewUses;
15012   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15013     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15014       = VTablesUsed.find(VTables[I].Record);
15015     // Even if a definition wasn't required before, it may be required now.
15016     if (Pos != VTablesUsed.end()) {
15017       if (!Pos->second && VTables[I].DefinitionRequired)
15018         Pos->second = true;
15019       continue;
15020     }
15021 
15022     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15023     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15024   }
15025 
15026   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15027 }
15028 
15029 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15030                           bool DefinitionRequired) {
15031   // Ignore any vtable uses in unevaluated operands or for classes that do
15032   // not have a vtable.
15033   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15034       CurContext->isDependentContext() || isUnevaluatedContext())
15035     return;
15036   // Do not mark as used if compiling for the device outside of the target
15037   // region.
15038   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15039       !isInOpenMPDeclareTargetContext() &&
15040       !isInOpenMPTargetExecutionDirective()) {
15041     if (!DefinitionRequired)
15042       MarkVirtualMembersReferenced(Loc, Class);
15043     return;
15044   }
15045 
15046   // Try to insert this class into the map.
15047   LoadExternalVTableUses();
15048   Class = Class->getCanonicalDecl();
15049   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15050     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15051   if (!Pos.second) {
15052     // If we already had an entry, check to see if we are promoting this vtable
15053     // to require a definition. If so, we need to reappend to the VTableUses
15054     // list, since we may have already processed the first entry.
15055     if (DefinitionRequired && !Pos.first->second) {
15056       Pos.first->second = true;
15057     } else {
15058       // Otherwise, we can early exit.
15059       return;
15060     }
15061   } else {
15062     // The Microsoft ABI requires that we perform the destructor body
15063     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15064     // the deleting destructor is emitted with the vtable, not with the
15065     // destructor definition as in the Itanium ABI.
15066     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15067       CXXDestructorDecl *DD = Class->getDestructor();
15068       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15069         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15070           // If this is an out-of-line declaration, marking it referenced will
15071           // not do anything. Manually call CheckDestructor to look up operator
15072           // delete().
15073           ContextRAII SavedContext(*this, DD);
15074           CheckDestructor(DD);
15075         } else {
15076           MarkFunctionReferenced(Loc, Class->getDestructor());
15077         }
15078       }
15079     }
15080   }
15081 
15082   // Local classes need to have their virtual members marked
15083   // immediately. For all other classes, we mark their virtual members
15084   // at the end of the translation unit.
15085   if (Class->isLocalClass())
15086     MarkVirtualMembersReferenced(Loc, Class);
15087   else
15088     VTableUses.push_back(std::make_pair(Class, Loc));
15089 }
15090 
15091 bool Sema::DefineUsedVTables() {
15092   LoadExternalVTableUses();
15093   if (VTableUses.empty())
15094     return false;
15095 
15096   // Note: The VTableUses vector could grow as a result of marking
15097   // the members of a class as "used", so we check the size each
15098   // time through the loop and prefer indices (which are stable) to
15099   // iterators (which are not).
15100   bool DefinedAnything = false;
15101   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15102     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15103     if (!Class)
15104       continue;
15105     TemplateSpecializationKind ClassTSK =
15106         Class->getTemplateSpecializationKind();
15107 
15108     SourceLocation Loc = VTableUses[I].second;
15109 
15110     bool DefineVTable = true;
15111 
15112     // If this class has a key function, but that key function is
15113     // defined in another translation unit, we don't need to emit the
15114     // vtable even though we're using it.
15115     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15116     if (KeyFunction && !KeyFunction->hasBody()) {
15117       // The key function is in another translation unit.
15118       DefineVTable = false;
15119       TemplateSpecializationKind TSK =
15120           KeyFunction->getTemplateSpecializationKind();
15121       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15122              TSK != TSK_ImplicitInstantiation &&
15123              "Instantiations don't have key functions");
15124       (void)TSK;
15125     } else if (!KeyFunction) {
15126       // If we have a class with no key function that is the subject
15127       // of an explicit instantiation declaration, suppress the
15128       // vtable; it will live with the explicit instantiation
15129       // definition.
15130       bool IsExplicitInstantiationDeclaration =
15131           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15132       for (auto R : Class->redecls()) {
15133         TemplateSpecializationKind TSK
15134           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15135         if (TSK == TSK_ExplicitInstantiationDeclaration)
15136           IsExplicitInstantiationDeclaration = true;
15137         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15138           IsExplicitInstantiationDeclaration = false;
15139           break;
15140         }
15141       }
15142 
15143       if (IsExplicitInstantiationDeclaration)
15144         DefineVTable = false;
15145     }
15146 
15147     // The exception specifications for all virtual members may be needed even
15148     // if we are not providing an authoritative form of the vtable in this TU.
15149     // We may choose to emit it available_externally anyway.
15150     if (!DefineVTable) {
15151       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15152       continue;
15153     }
15154 
15155     // Mark all of the virtual members of this class as referenced, so
15156     // that we can build a vtable. Then, tell the AST consumer that a
15157     // vtable for this class is required.
15158     DefinedAnything = true;
15159     MarkVirtualMembersReferenced(Loc, Class);
15160     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15161     if (VTablesUsed[Canonical])
15162       Consumer.HandleVTable(Class);
15163 
15164     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15165     // no key function or the key function is inlined. Don't warn in C++ ABIs
15166     // that lack key functions, since the user won't be able to make one.
15167     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15168         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15169       const FunctionDecl *KeyFunctionDef = nullptr;
15170       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15171                            KeyFunctionDef->isInlined())) {
15172         Diag(Class->getLocation(),
15173              ClassTSK == TSK_ExplicitInstantiationDefinition
15174                  ? diag::warn_weak_template_vtable
15175                  : diag::warn_weak_vtable)
15176             << Class;
15177       }
15178     }
15179   }
15180   VTableUses.clear();
15181 
15182   return DefinedAnything;
15183 }
15184 
15185 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15186                                                  const CXXRecordDecl *RD) {
15187   for (const auto *I : RD->methods())
15188     if (I->isVirtual() && !I->isPure())
15189       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15190 }
15191 
15192 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15193                                         const CXXRecordDecl *RD) {
15194   // Mark all functions which will appear in RD's vtable as used.
15195   CXXFinalOverriderMap FinalOverriders;
15196   RD->getFinalOverriders(FinalOverriders);
15197   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15198                                             E = FinalOverriders.end();
15199        I != E; ++I) {
15200     for (OverridingMethods::const_iterator OI = I->second.begin(),
15201                                            OE = I->second.end();
15202          OI != OE; ++OI) {
15203       assert(OI->second.size() > 0 && "no final overrider");
15204       CXXMethodDecl *Overrider = OI->second.front().Method;
15205 
15206       // C++ [basic.def.odr]p2:
15207       //   [...] A virtual member function is used if it is not pure. [...]
15208       if (!Overrider->isPure())
15209         MarkFunctionReferenced(Loc, Overrider);
15210     }
15211   }
15212 
15213   // Only classes that have virtual bases need a VTT.
15214   if (RD->getNumVBases() == 0)
15215     return;
15216 
15217   for (const auto &I : RD->bases()) {
15218     const CXXRecordDecl *Base =
15219         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15220     if (Base->getNumVBases() == 0)
15221       continue;
15222     MarkVirtualMembersReferenced(Loc, Base);
15223   }
15224 }
15225 
15226 /// SetIvarInitializers - This routine builds initialization ASTs for the
15227 /// Objective-C implementation whose ivars need be initialized.
15228 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15229   if (!getLangOpts().CPlusPlus)
15230     return;
15231   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15232     SmallVector<ObjCIvarDecl*, 8> ivars;
15233     CollectIvarsToConstructOrDestruct(OID, ivars);
15234     if (ivars.empty())
15235       return;
15236     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15237     for (unsigned i = 0; i < ivars.size(); i++) {
15238       FieldDecl *Field = ivars[i];
15239       if (Field->isInvalidDecl())
15240         continue;
15241 
15242       CXXCtorInitializer *Member;
15243       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15244       InitializationKind InitKind =
15245         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15246 
15247       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15248       ExprResult MemberInit =
15249         InitSeq.Perform(*this, InitEntity, InitKind, None);
15250       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15251       // Note, MemberInit could actually come back empty if no initialization
15252       // is required (e.g., because it would call a trivial default constructor)
15253       if (!MemberInit.get() || MemberInit.isInvalid())
15254         continue;
15255 
15256       Member =
15257         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15258                                          SourceLocation(),
15259                                          MemberInit.getAs<Expr>(),
15260                                          SourceLocation());
15261       AllToInit.push_back(Member);
15262 
15263       // Be sure that the destructor is accessible and is marked as referenced.
15264       if (const RecordType *RecordTy =
15265               Context.getBaseElementType(Field->getType())
15266                   ->getAs<RecordType>()) {
15267         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15268         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15269           MarkFunctionReferenced(Field->getLocation(), Destructor);
15270           CheckDestructorAccess(Field->getLocation(), Destructor,
15271                             PDiag(diag::err_access_dtor_ivar)
15272                               << Context.getBaseElementType(Field->getType()));
15273         }
15274       }
15275     }
15276     ObjCImplementation->setIvarInitializers(Context,
15277                                             AllToInit.data(), AllToInit.size());
15278   }
15279 }
15280 
15281 static
15282 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15283                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15284                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15285                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15286                            Sema &S) {
15287   if (Ctor->isInvalidDecl())
15288     return;
15289 
15290   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15291 
15292   // Target may not be determinable yet, for instance if this is a dependent
15293   // call in an uninstantiated template.
15294   if (Target) {
15295     const FunctionDecl *FNTarget = nullptr;
15296     (void)Target->hasBody(FNTarget);
15297     Target = const_cast<CXXConstructorDecl*>(
15298       cast_or_null<CXXConstructorDecl>(FNTarget));
15299   }
15300 
15301   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15302                      // Avoid dereferencing a null pointer here.
15303                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15304 
15305   if (!Current.insert(Canonical).second)
15306     return;
15307 
15308   // We know that beyond here, we aren't chaining into a cycle.
15309   if (!Target || !Target->isDelegatingConstructor() ||
15310       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15311     Valid.insert(Current.begin(), Current.end());
15312     Current.clear();
15313   // We've hit a cycle.
15314   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15315              Current.count(TCanonical)) {
15316     // If we haven't diagnosed this cycle yet, do so now.
15317     if (!Invalid.count(TCanonical)) {
15318       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15319              diag::warn_delegating_ctor_cycle)
15320         << Ctor;
15321 
15322       // Don't add a note for a function delegating directly to itself.
15323       if (TCanonical != Canonical)
15324         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15325 
15326       CXXConstructorDecl *C = Target;
15327       while (C->getCanonicalDecl() != Canonical) {
15328         const FunctionDecl *FNTarget = nullptr;
15329         (void)C->getTargetConstructor()->hasBody(FNTarget);
15330         assert(FNTarget && "Ctor cycle through bodiless function");
15331 
15332         C = const_cast<CXXConstructorDecl*>(
15333           cast<CXXConstructorDecl>(FNTarget));
15334         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15335       }
15336     }
15337 
15338     Invalid.insert(Current.begin(), Current.end());
15339     Current.clear();
15340   } else {
15341     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15342   }
15343 }
15344 
15345 
15346 void Sema::CheckDelegatingCtorCycles() {
15347   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15348 
15349   for (DelegatingCtorDeclsType::iterator
15350          I = DelegatingCtorDecls.begin(ExternalSource),
15351          E = DelegatingCtorDecls.end();
15352        I != E; ++I)
15353     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15354 
15355   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15356     (*CI)->setInvalidDecl();
15357 }
15358 
15359 namespace {
15360   /// AST visitor that finds references to the 'this' expression.
15361   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15362     Sema &S;
15363 
15364   public:
15365     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15366 
15367     bool VisitCXXThisExpr(CXXThisExpr *E) {
15368       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15369         << E->isImplicit();
15370       return false;
15371     }
15372   };
15373 }
15374 
15375 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15376   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15377   if (!TSInfo)
15378     return false;
15379 
15380   TypeLoc TL = TSInfo->getTypeLoc();
15381   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15382   if (!ProtoTL)
15383     return false;
15384 
15385   // C++11 [expr.prim.general]p3:
15386   //   [The expression this] shall not appear before the optional
15387   //   cv-qualifier-seq and it shall not appear within the declaration of a
15388   //   static member function (although its type and value category are defined
15389   //   within a static member function as they are within a non-static member
15390   //   function). [ Note: this is because declaration matching does not occur
15391   //  until the complete declarator is known. - end note ]
15392   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15393   FindCXXThisExpr Finder(*this);
15394 
15395   // If the return type came after the cv-qualifier-seq, check it now.
15396   if (Proto->hasTrailingReturn() &&
15397       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15398     return true;
15399 
15400   // Check the exception specification.
15401   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15402     return true;
15403 
15404   return checkThisInStaticMemberFunctionAttributes(Method);
15405 }
15406 
15407 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15408   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15409   if (!TSInfo)
15410     return false;
15411 
15412   TypeLoc TL = TSInfo->getTypeLoc();
15413   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15414   if (!ProtoTL)
15415     return false;
15416 
15417   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15418   FindCXXThisExpr Finder(*this);
15419 
15420   switch (Proto->getExceptionSpecType()) {
15421   case EST_Unparsed:
15422   case EST_Uninstantiated:
15423   case EST_Unevaluated:
15424   case EST_BasicNoexcept:
15425   case EST_DynamicNone:
15426   case EST_MSAny:
15427   case EST_None:
15428     break;
15429 
15430   case EST_DependentNoexcept:
15431   case EST_NoexceptFalse:
15432   case EST_NoexceptTrue:
15433     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15434       return true;
15435     LLVM_FALLTHROUGH;
15436 
15437   case EST_Dynamic:
15438     for (const auto &E : Proto->exceptions()) {
15439       if (!Finder.TraverseType(E))
15440         return true;
15441     }
15442     break;
15443   }
15444 
15445   return false;
15446 }
15447 
15448 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15449   FindCXXThisExpr Finder(*this);
15450 
15451   // Check attributes.
15452   for (const auto *A : Method->attrs()) {
15453     // FIXME: This should be emitted by tblgen.
15454     Expr *Arg = nullptr;
15455     ArrayRef<Expr *> Args;
15456     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15457       Arg = G->getArg();
15458     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15459       Arg = G->getArg();
15460     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15461       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15462     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15463       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15464     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15465       Arg = ETLF->getSuccessValue();
15466       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15467     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15468       Arg = STLF->getSuccessValue();
15469       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15470     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15471       Arg = LR->getArg();
15472     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15473       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15474     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15475       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15476     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15477       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15478     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15479       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15480     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15481       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15482 
15483     if (Arg && !Finder.TraverseStmt(Arg))
15484       return true;
15485 
15486     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15487       if (!Finder.TraverseStmt(Args[I]))
15488         return true;
15489     }
15490   }
15491 
15492   return false;
15493 }
15494 
15495 void Sema::checkExceptionSpecification(
15496     bool IsTopLevel, ExceptionSpecificationType EST,
15497     ArrayRef<ParsedType> DynamicExceptions,
15498     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15499     SmallVectorImpl<QualType> &Exceptions,
15500     FunctionProtoType::ExceptionSpecInfo &ESI) {
15501   Exceptions.clear();
15502   ESI.Type = EST;
15503   if (EST == EST_Dynamic) {
15504     Exceptions.reserve(DynamicExceptions.size());
15505     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15506       // FIXME: Preserve type source info.
15507       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15508 
15509       if (IsTopLevel) {
15510         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15511         collectUnexpandedParameterPacks(ET, Unexpanded);
15512         if (!Unexpanded.empty()) {
15513           DiagnoseUnexpandedParameterPacks(
15514               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15515               Unexpanded);
15516           continue;
15517         }
15518       }
15519 
15520       // Check that the type is valid for an exception spec, and
15521       // drop it if not.
15522       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15523         Exceptions.push_back(ET);
15524     }
15525     ESI.Exceptions = Exceptions;
15526     return;
15527   }
15528 
15529   if (isComputedNoexcept(EST)) {
15530     assert((NoexceptExpr->isTypeDependent() ||
15531             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15532             Context.BoolTy) &&
15533            "Parser should have made sure that the expression is boolean");
15534     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15535       ESI.Type = EST_BasicNoexcept;
15536       return;
15537     }
15538 
15539     ESI.NoexceptExpr = NoexceptExpr;
15540     return;
15541   }
15542 }
15543 
15544 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15545              ExceptionSpecificationType EST,
15546              SourceRange SpecificationRange,
15547              ArrayRef<ParsedType> DynamicExceptions,
15548              ArrayRef<SourceRange> DynamicExceptionRanges,
15549              Expr *NoexceptExpr) {
15550   if (!MethodD)
15551     return;
15552 
15553   // Dig out the method we're referring to.
15554   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15555     MethodD = FunTmpl->getTemplatedDecl();
15556 
15557   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15558   if (!Method)
15559     return;
15560 
15561   // Check the exception specification.
15562   llvm::SmallVector<QualType, 4> Exceptions;
15563   FunctionProtoType::ExceptionSpecInfo ESI;
15564   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15565                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15566                               ESI);
15567 
15568   // Update the exception specification on the function type.
15569   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15570 
15571   if (Method->isStatic())
15572     checkThisInStaticMemberFunctionExceptionSpec(Method);
15573 
15574   if (Method->isVirtual()) {
15575     // Check overrides, which we previously had to delay.
15576     for (const CXXMethodDecl *O : Method->overridden_methods())
15577       CheckOverridingFunctionExceptionSpec(Method, O);
15578   }
15579 }
15580 
15581 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15582 ///
15583 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15584                                        SourceLocation DeclStart, Declarator &D,
15585                                        Expr *BitWidth,
15586                                        InClassInitStyle InitStyle,
15587                                        AccessSpecifier AS,
15588                                        const ParsedAttr &MSPropertyAttr) {
15589   IdentifierInfo *II = D.getIdentifier();
15590   if (!II) {
15591     Diag(DeclStart, diag::err_anonymous_property);
15592     return nullptr;
15593   }
15594   SourceLocation Loc = D.getIdentifierLoc();
15595 
15596   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15597   QualType T = TInfo->getType();
15598   if (getLangOpts().CPlusPlus) {
15599     CheckExtraCXXDefaultArguments(D);
15600 
15601     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15602                                         UPPC_DataMemberType)) {
15603       D.setInvalidType();
15604       T = Context.IntTy;
15605       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15606     }
15607   }
15608 
15609   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15610 
15611   if (D.getDeclSpec().isInlineSpecified())
15612     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15613         << getLangOpts().CPlusPlus17;
15614   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15615     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15616          diag::err_invalid_thread)
15617       << DeclSpec::getSpecifierName(TSCS);
15618 
15619   // Check to see if this name was declared as a member previously
15620   NamedDecl *PrevDecl = nullptr;
15621   LookupResult Previous(*this, II, Loc, LookupMemberName,
15622                         ForVisibleRedeclaration);
15623   LookupName(Previous, S);
15624   switch (Previous.getResultKind()) {
15625   case LookupResult::Found:
15626   case LookupResult::FoundUnresolvedValue:
15627     PrevDecl = Previous.getAsSingle<NamedDecl>();
15628     break;
15629 
15630   case LookupResult::FoundOverloaded:
15631     PrevDecl = Previous.getRepresentativeDecl();
15632     break;
15633 
15634   case LookupResult::NotFound:
15635   case LookupResult::NotFoundInCurrentInstantiation:
15636   case LookupResult::Ambiguous:
15637     break;
15638   }
15639 
15640   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15641     // Maybe we will complain about the shadowed template parameter.
15642     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15643     // Just pretend that we didn't see the previous declaration.
15644     PrevDecl = nullptr;
15645   }
15646 
15647   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15648     PrevDecl = nullptr;
15649 
15650   SourceLocation TSSL = D.getBeginLoc();
15651   MSPropertyDecl *NewPD =
15652       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15653                              MSPropertyAttr.getPropertyDataGetter(),
15654                              MSPropertyAttr.getPropertyDataSetter());
15655   ProcessDeclAttributes(TUScope, NewPD, D);
15656   NewPD->setAccess(AS);
15657 
15658   if (NewPD->isInvalidDecl())
15659     Record->setInvalidDecl();
15660 
15661   if (D.getDeclSpec().isModulePrivateSpecified())
15662     NewPD->setModulePrivate();
15663 
15664   if (NewPD->isInvalidDecl() && PrevDecl) {
15665     // Don't introduce NewFD into scope; there's already something
15666     // with the same name in the same scope.
15667   } else if (II) {
15668     PushOnScopeChains(NewPD, S);
15669   } else
15670     Record->addDecl(NewPD);
15671 
15672   return NewPD;
15673 }
15674