1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/ComparisonCategories.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <map>
45 #include <set>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55   /// the default argument of a parameter to determine whether it
56   /// contains any ill-formed subexpressions. For example, this will
57   /// diagnose the use of local variables or parameters within the
58   /// default argument expression.
59   class CheckDefaultArgumentVisitor
60     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61     Expr *DefaultArg;
62     Sema *S;
63 
64   public:
65     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66       : DefaultArg(defarg), S(s) {}
67 
68     bool VisitExpr(Expr *Node);
69     bool VisitDeclRefExpr(DeclRefExpr *DRE);
70     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71     bool VisitLambdaExpr(LambdaExpr *Lambda);
72     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73   };
74 
75   /// VisitExpr - Visit all of the children of this expression.
76   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77     bool IsInvalid = false;
78     for (Stmt *SubStmt : Node->children())
79       IsInvalid |= Visit(SubStmt);
80     return IsInvalid;
81   }
82 
83   /// VisitDeclRefExpr - Visit a reference to a declaration, to
84   /// determine whether this declaration can be used in the default
85   /// argument expression.
86   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87     NamedDecl *Decl = DRE->getDecl();
88     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89       // C++ [dcl.fct.default]p9
90       //   Default arguments are evaluated each time the function is
91       //   called. The order of evaluation of function arguments is
92       //   unspecified. Consequently, parameters of a function shall not
93       //   be used in default argument expressions, even if they are not
94       //   evaluated. Parameters of a function declared before a default
95       //   argument expression are in scope and can hide namespace and
96       //   class member names.
97       return S->Diag(DRE->getBeginLoc(),
98                      diag::err_param_default_argument_references_param)
99              << Param->getDeclName() << DefaultArg->getSourceRange();
100     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101       // C++ [dcl.fct.default]p7
102       //   Local variables shall not be used in default argument
103       //   expressions.
104       if (VDecl->isLocalVarDecl())
105         return S->Diag(DRE->getBeginLoc(),
106                        diag::err_param_default_argument_references_local)
107                << VDecl->getDeclName() << DefaultArg->getSourceRange();
108     }
109 
110     return false;
111   }
112 
113   /// VisitCXXThisExpr - Visit a C++ "this" expression.
114   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115     // C++ [dcl.fct.default]p8:
116     //   The keyword this shall not be used in a default argument of a
117     //   member function.
118     return S->Diag(ThisE->getBeginLoc(),
119                    diag::err_param_default_argument_references_this)
120            << ThisE->getSourceRange();
121   }
122 
123   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124     bool Invalid = false;
125     for (PseudoObjectExpr::semantics_iterator
126            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127       Expr *E = *i;
128 
129       // Look through bindings.
130       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131         E = OVE->getSourceExpr();
132         assert(E && "pseudo-object binding without source expression?");
133       }
134 
135       Invalid |= Visit(E);
136     }
137     return Invalid;
138   }
139 
140   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141     // C++11 [expr.lambda.prim]p13:
142     //   A lambda-expression appearing in a default argument shall not
143     //   implicitly or explicitly capture any entity.
144     if (Lambda->capture_begin() == Lambda->capture_end())
145       return false;
146 
147     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171     EST = EST_BasicNoexcept;
172 
173   switch (EST) {
174   case EST_Unparsed:
175   case EST_Uninstantiated:
176   case EST_Unevaluated:
177     llvm_unreachable("should not see unresolved exception specs here");
178 
179   // If this function can throw any exceptions, make a note of that.
180   case EST_MSAny:
181   case EST_None:
182     // FIXME: Whichever we see last of MSAny and None determines our result.
183     // We should make a consistent, order-independent choice here.
184     ClearExceptions();
185     ComputedEST = EST;
186     return;
187   case EST_NoexceptFalse:
188     ClearExceptions();
189     ComputedEST = EST_None;
190     return;
191   // FIXME: If the call to this decl is using any of its default arguments, we
192   // need to search them for potentially-throwing calls.
193   // If this function has a basic noexcept, it doesn't affect the outcome.
194   case EST_BasicNoexcept:
195   case EST_NoexceptTrue:
196     return;
197   // If we're still at noexcept(true) and there's a throw() callee,
198   // change to that specification.
199   case EST_DynamicNone:
200     if (ComputedEST == EST_BasicNoexcept)
201       ComputedEST = EST_DynamicNone;
202     return;
203   case EST_DependentNoexcept:
204     llvm_unreachable(
205         "should not generate implicit declarations for dependent cases");
206   case EST_Dynamic:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficient, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found the right previous declaration.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter unless the new
551       // function is a friend declaration in a template class. In the latter
552       // case the default arguments will be inherited when the friend
553       // declaration will be instantiated.
554       if (New->getFriendObjectKind() == Decl::FOK_None ||
555           !New->getLexicalDeclContext()->isDependentContext()) {
556         // It's important to use getInit() here;  getDefaultArg()
557         // strips off any top-level ExprWithCleanups.
558         NewParam->setHasInheritedDefaultArg();
559         if (OldParam->hasUnparsedDefaultArg())
560           NewParam->setUnparsedDefaultArg();
561         else if (OldParam->hasUninstantiatedDefaultArg())
562           NewParam->setUninstantiatedDefaultArg(
563                                        OldParam->getUninstantiatedDefaultArg());
564         else
565           NewParam->setDefaultArg(OldParam->getInit());
566       }
567     } else if (NewParamHasDfl) {
568       if (New->getDescribedFunctionTemplate()) {
569         // Paragraph 4, quoted above, only applies to non-template functions.
570         Diag(NewParam->getLocation(),
571              diag::err_param_default_argument_template_redecl)
572           << NewParam->getDefaultArgRange();
573         Diag(PrevForDefaultArgs->getLocation(),
574              diag::note_template_prev_declaration)
575             << false;
576       } else if (New->getTemplateSpecializationKind()
577                    != TSK_ImplicitInstantiation &&
578                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
579         // C++ [temp.expr.spec]p21:
580         //   Default function arguments shall not be specified in a declaration
581         //   or a definition for one of the following explicit specializations:
582         //     - the explicit specialization of a function template;
583         //     - the explicit specialization of a member function template;
584         //     - the explicit specialization of a member function of a class
585         //       template where the class template specialization to which the
586         //       member function specialization belongs is implicitly
587         //       instantiated.
588         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590           << New->getDeclName()
591           << NewParam->getDefaultArgRange();
592       } else if (New->getDeclContext()->isDependentContext()) {
593         // C++ [dcl.fct.default]p6 (DR217):
594         //   Default arguments for a member function of a class template shall
595         //   be specified on the initial declaration of the member function
596         //   within the class template.
597         //
598         // Reading the tea leaves a bit in DR217 and its reference to DR205
599         // leads me to the conclusion that one cannot add default function
600         // arguments for an out-of-line definition of a member function of a
601         // dependent type.
602         int WhichKind = 2;
603         if (CXXRecordDecl *Record
604               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605           if (Record->getDescribedClassTemplate())
606             WhichKind = 0;
607           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608             WhichKind = 1;
609           else
610             WhichKind = 2;
611         }
612 
613         Diag(NewParam->getLocation(),
614              diag::err_param_default_argument_member_template_redecl)
615           << WhichKind
616           << NewParam->getDefaultArgRange();
617       }
618     }
619   }
620 
621   // DR1344: If a default argument is added outside a class definition and that
622   // default argument makes the function a special member function, the program
623   // is ill-formed. This can only happen for constructors.
624   if (isa<CXXConstructorDecl>(New) &&
625       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628     if (NewSM != OldSM) {
629       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630       assert(NewParam->hasDefaultArg());
631       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632         << NewParam->getDefaultArgRange() << NewSM;
633       Diag(Old->getLocation(), diag::note_previous_declaration);
634     }
635   }
636 
637   const FunctionDecl *Def;
638   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639   // template has a constexpr specifier then all its declarations shall
640   // contain the constexpr specifier.
641   if (New->isConstexpr() != Old->isConstexpr()) {
642     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643       << New << New->isConstexpr();
644     Diag(Old->getLocation(), diag::note_previous_declaration);
645     Invalid = true;
646   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647              Old->isDefined(Def) &&
648              // If a friend function is inlined but does not have 'inline'
649              // specifier, it is a definition. Do not report attribute conflict
650              // in this case, redefinition will be diagnosed later.
651              (New->isInlineSpecified() ||
652               New->getFriendObjectKind() == Decl::FOK_None)) {
653     // C++11 [dcl.fcn.spec]p4:
654     //   If the definition of a function appears in a translation unit before its
655     //   first declaration as inline, the program is ill-formed.
656     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657     Diag(Def->getLocation(), diag::note_previous_definition);
658     Invalid = true;
659   }
660 
661   // FIXME: It's not clear what should happen if multiple declarations of a
662   // deduction guide have different explicitness. For now at least we simply
663   // reject any case where the explicitness changes.
664   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
665   if (NewGuide && NewGuide->isExplicitSpecified() !=
666                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
667     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
668       << NewGuide->isExplicitSpecified();
669     Diag(Old->getLocation(), diag::note_previous_declaration);
670   }
671 
672   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673   // argument expression, that declaration shall be a definition and shall be
674   // the only declaration of the function or function template in the
675   // translation unit.
676   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677       functionDeclHasDefaultArgument(Old)) {
678     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679     Diag(Old->getLocation(), diag::note_previous_declaration);
680     Invalid = true;
681   }
682 
683   return Invalid;
684 }
685 
686 NamedDecl *
687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688                                    MultiTemplateParamsArg TemplateParamLists) {
689   assert(D.isDecompositionDeclarator());
690   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
691 
692   // The syntax only allows a decomposition declarator as a simple-declaration,
693   // a for-range-declaration, or a condition in Clang, but we parse it in more
694   // cases than that.
695   if (!D.mayHaveDecompositionDeclarator()) {
696     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697       << Decomp.getSourceRange();
698     return nullptr;
699   }
700 
701   if (!TemplateParamLists.empty()) {
702     // FIXME: There's no rule against this, but there are also no rules that
703     // would actually make it usable, so we reject it for now.
704     Diag(TemplateParamLists.front()->getTemplateLoc(),
705          diag::err_decomp_decl_template);
706     return nullptr;
707   }
708 
709   Diag(Decomp.getLSquareLoc(),
710        !getLangOpts().CPlusPlus17
711            ? diag::ext_decomp_decl
712            : D.getContext() == DeclaratorContext::ConditionContext
713                  ? diag::ext_decomp_decl_cond
714                  : diag::warn_cxx14_compat_decomp_decl)
715       << Decomp.getSourceRange();
716 
717   // The semantic context is always just the current context.
718   DeclContext *const DC = CurContext;
719 
720   // C++1z [dcl.dcl]/8:
721   //   The decl-specifier-seq shall contain only the type-specifier auto
722   //   and cv-qualifiers.
723   auto &DS = D.getDeclSpec();
724   {
725     SmallVector<StringRef, 8> BadSpecifiers;
726     SmallVector<SourceLocation, 8> BadSpecifierLocs;
727     if (auto SCS = DS.getStorageClassSpec()) {
728       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
729       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
730     }
731     if (auto TSCS = DS.getThreadStorageClassSpec()) {
732       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
733       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
734     }
735     if (DS.isConstexprSpecified()) {
736       BadSpecifiers.push_back("constexpr");
737       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
738     }
739     if (DS.isInlineSpecified()) {
740       BadSpecifiers.push_back("inline");
741       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
742     }
743     if (!BadSpecifiers.empty()) {
744       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
745       Err << (int)BadSpecifiers.size()
746           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
747       // Don't add FixItHints to remove the specifiers; we do still respect
748       // them when building the underlying variable.
749       for (auto Loc : BadSpecifierLocs)
750         Err << SourceRange(Loc, Loc);
751     }
752     // We can't recover from it being declared as a typedef.
753     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
754       return nullptr;
755   }
756 
757   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
758   QualType R = TInfo->getType();
759 
760   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
761                                       UPPC_DeclarationType))
762     D.setInvalidType();
763 
764   // The syntax only allows a single ref-qualifier prior to the decomposition
765   // declarator. No other declarator chunks are permitted. Also check the type
766   // specifier here.
767   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
768       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
769       (D.getNumTypeObjects() == 1 &&
770        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
771     Diag(Decomp.getLSquareLoc(),
772          (D.hasGroupingParens() ||
773           (D.getNumTypeObjects() &&
774            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
775              ? diag::err_decomp_decl_parens
776              : diag::err_decomp_decl_type)
777         << R;
778 
779     // In most cases, there's no actual problem with an explicitly-specified
780     // type, but a function type won't work here, and ActOnVariableDeclarator
781     // shouldn't be called for such a type.
782     if (R->isFunctionType())
783       D.setInvalidType();
784   }
785 
786   // Build the BindingDecls.
787   SmallVector<BindingDecl*, 8> Bindings;
788 
789   // Build the BindingDecls.
790   for (auto &B : D.getDecompositionDeclarator().bindings()) {
791     // Check for name conflicts.
792     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
793     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
794                           ForVisibleRedeclaration);
795     LookupName(Previous, S,
796                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
797 
798     // It's not permitted to shadow a template parameter name.
799     if (Previous.isSingleResult() &&
800         Previous.getFoundDecl()->isTemplateParameter()) {
801       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
802                                       Previous.getFoundDecl());
803       Previous.clear();
804     }
805 
806     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
807                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
808     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
809                          /*AllowInlineNamespace*/false);
810     if (!Previous.empty()) {
811       auto *Old = Previous.getRepresentativeDecl();
812       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
813       Diag(Old->getLocation(), diag::note_previous_definition);
814     }
815 
816     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
817     PushOnScopeChains(BD, S, true);
818     Bindings.push_back(BD);
819     ParsingInitForAutoVars.insert(BD);
820   }
821 
822   // There are no prior lookup results for the variable itself, because it
823   // is unnamed.
824   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
825                                Decomp.getLSquareLoc());
826   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
827                         ForVisibleRedeclaration);
828 
829   // Build the variable that holds the non-decomposed object.
830   bool AddToScope = true;
831   NamedDecl *New =
832       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
833                               MultiTemplateParamsArg(), AddToScope, Bindings);
834   if (AddToScope) {
835     S->AddDecl(New);
836     CurContext->addHiddenDecl(New);
837   }
838 
839   if (isInOpenMPDeclareTargetContext())
840     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
841 
842   return New;
843 }
844 
845 static bool checkSimpleDecomposition(
846     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
847     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
848     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
849   if ((int64_t)Bindings.size() != NumElems) {
850     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
851         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
852         << (NumElems < Bindings.size());
853     return true;
854   }
855 
856   unsigned I = 0;
857   for (auto *B : Bindings) {
858     SourceLocation Loc = B->getLocation();
859     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
860     if (E.isInvalid())
861       return true;
862     E = GetInit(Loc, E.get(), I++);
863     if (E.isInvalid())
864       return true;
865     B->setBinding(ElemType, E.get());
866   }
867 
868   return false;
869 }
870 
871 static bool checkArrayLikeDecomposition(Sema &S,
872                                         ArrayRef<BindingDecl *> Bindings,
873                                         ValueDecl *Src, QualType DecompType,
874                                         const llvm::APSInt &NumElems,
875                                         QualType ElemType) {
876   return checkSimpleDecomposition(
877       S, Bindings, Src, DecompType, NumElems, ElemType,
878       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
879         ExprResult E = S.ActOnIntegerConstant(Loc, I);
880         if (E.isInvalid())
881           return ExprError();
882         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
883       });
884 }
885 
886 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
887                                     ValueDecl *Src, QualType DecompType,
888                                     const ConstantArrayType *CAT) {
889   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
890                                      llvm::APSInt(CAT->getSize()),
891                                      CAT->getElementType());
892 }
893 
894 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
895                                      ValueDecl *Src, QualType DecompType,
896                                      const VectorType *VT) {
897   return checkArrayLikeDecomposition(
898       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
899       S.Context.getQualifiedType(VT->getElementType(),
900                                  DecompType.getQualifiers()));
901 }
902 
903 static bool checkComplexDecomposition(Sema &S,
904                                       ArrayRef<BindingDecl *> Bindings,
905                                       ValueDecl *Src, QualType DecompType,
906                                       const ComplexType *CT) {
907   return checkSimpleDecomposition(
908       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
909       S.Context.getQualifiedType(CT->getElementType(),
910                                  DecompType.getQualifiers()),
911       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
912         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
913       });
914 }
915 
916 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
917                                      TemplateArgumentListInfo &Args) {
918   SmallString<128> SS;
919   llvm::raw_svector_ostream OS(SS);
920   bool First = true;
921   for (auto &Arg : Args.arguments()) {
922     if (!First)
923       OS << ", ";
924     Arg.getArgument().print(PrintingPolicy, OS);
925     First = false;
926   }
927   return OS.str();
928 }
929 
930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
931                                      SourceLocation Loc, StringRef Trait,
932                                      TemplateArgumentListInfo &Args,
933                                      unsigned DiagID) {
934   auto DiagnoseMissing = [&] {
935     if (DiagID)
936       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
937                                                Args);
938     return true;
939   };
940 
941   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
942   NamespaceDecl *Std = S.getStdNamespace();
943   if (!Std)
944     return DiagnoseMissing();
945 
946   // Look up the trait itself, within namespace std. We can diagnose various
947   // problems with this lookup even if we've been asked to not diagnose a
948   // missing specialization, because this can only fail if the user has been
949   // declaring their own names in namespace std or we don't support the
950   // standard library implementation in use.
951   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
952                       Loc, Sema::LookupOrdinaryName);
953   if (!S.LookupQualifiedName(Result, Std))
954     return DiagnoseMissing();
955   if (Result.isAmbiguous())
956     return true;
957 
958   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
959   if (!TraitTD) {
960     Result.suppressDiagnostics();
961     NamedDecl *Found = *Result.begin();
962     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
963     S.Diag(Found->getLocation(), diag::note_declared_at);
964     return true;
965   }
966 
967   // Build the template-id.
968   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
969   if (TraitTy.isNull())
970     return true;
971   if (!S.isCompleteType(Loc, TraitTy)) {
972     if (DiagID)
973       S.RequireCompleteType(
974           Loc, TraitTy, DiagID,
975           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
976     return true;
977   }
978 
979   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
980   assert(RD && "specialization of class template is not a class?");
981 
982   // Look up the member of the trait type.
983   S.LookupQualifiedName(TraitMemberLookup, RD);
984   return TraitMemberLookup.isAmbiguous();
985 }
986 
987 static TemplateArgumentLoc
988 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
989                                    uint64_t I) {
990   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
991   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
992 }
993 
994 static TemplateArgumentLoc
995 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
996   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
997 }
998 
999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1000 
1001 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1002                                llvm::APSInt &Size) {
1003   EnterExpressionEvaluationContext ContextRAII(
1004       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1005 
1006   DeclarationName Value = S.PP.getIdentifierInfo("value");
1007   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1008 
1009   // Form template argument list for tuple_size<T>.
1010   TemplateArgumentListInfo Args(Loc, Loc);
1011   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1012 
1013   // If there's no tuple_size specialization, it's not tuple-like.
1014   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1015     return IsTupleLike::NotTupleLike;
1016 
1017   // If we get this far, we've committed to the tuple interpretation, but
1018   // we can still fail if there actually isn't a usable ::value.
1019 
1020   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1021     LookupResult &R;
1022     TemplateArgumentListInfo &Args;
1023     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1024         : R(R), Args(Args) {}
1025     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1026       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1027           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1028     }
1029   } Diagnoser(R, Args);
1030 
1031   if (R.empty()) {
1032     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1033     return IsTupleLike::Error;
1034   }
1035 
1036   ExprResult E =
1037       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1038   if (E.isInvalid())
1039     return IsTupleLike::Error;
1040 
1041   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1042   if (E.isInvalid())
1043     return IsTupleLike::Error;
1044 
1045   return IsTupleLike::TupleLike;
1046 }
1047 
1048 /// \return std::tuple_element<I, T>::type.
1049 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1050                                         unsigned I, QualType T) {
1051   // Form template argument list for tuple_element<I, T>.
1052   TemplateArgumentListInfo Args(Loc, Loc);
1053   Args.addArgument(
1054       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1055   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1056 
1057   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1058   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1059   if (lookupStdTypeTraitMember(
1060           S, R, Loc, "tuple_element", Args,
1061           diag::err_decomp_decl_std_tuple_element_not_specialized))
1062     return QualType();
1063 
1064   auto *TD = R.getAsSingle<TypeDecl>();
1065   if (!TD) {
1066     R.suppressDiagnostics();
1067     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1068       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1069     if (!R.empty())
1070       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1071     return QualType();
1072   }
1073 
1074   return S.Context.getTypeDeclType(TD);
1075 }
1076 
1077 namespace {
1078 struct BindingDiagnosticTrap {
1079   Sema &S;
1080   DiagnosticErrorTrap Trap;
1081   BindingDecl *BD;
1082 
1083   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1084       : S(S), Trap(S.Diags), BD(BD) {}
1085   ~BindingDiagnosticTrap() {
1086     if (Trap.hasErrorOccurred())
1087       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1088   }
1089 };
1090 }
1091 
1092 static bool checkTupleLikeDecomposition(Sema &S,
1093                                         ArrayRef<BindingDecl *> Bindings,
1094                                         VarDecl *Src, QualType DecompType,
1095                                         const llvm::APSInt &TupleSize) {
1096   if ((int64_t)Bindings.size() != TupleSize) {
1097     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1098         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1099         << (TupleSize < Bindings.size());
1100     return true;
1101   }
1102 
1103   if (Bindings.empty())
1104     return false;
1105 
1106   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1107 
1108   // [dcl.decomp]p3:
1109   //   The unqualified-id get is looked up in the scope of E by class member
1110   //   access lookup ...
1111   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1112   bool UseMemberGet = false;
1113   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1114     if (auto *RD = DecompType->getAsCXXRecordDecl())
1115       S.LookupQualifiedName(MemberGet, RD);
1116     if (MemberGet.isAmbiguous())
1117       return true;
1118     //   ... and if that finds at least one declaration that is a function
1119     //   template whose first template parameter is a non-type parameter ...
1120     for (NamedDecl *D : MemberGet) {
1121       if (FunctionTemplateDecl *FTD =
1122               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1123         TemplateParameterList *TPL = FTD->getTemplateParameters();
1124         if (TPL->size() != 0 &&
1125             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1126           //   ... the initializer is e.get<i>().
1127           UseMemberGet = true;
1128           break;
1129         }
1130       }
1131     }
1132     S.FilterAcceptableTemplateNames(MemberGet);
1133   }
1134 
1135   unsigned I = 0;
1136   for (auto *B : Bindings) {
1137     BindingDiagnosticTrap Trap(S, B);
1138     SourceLocation Loc = B->getLocation();
1139 
1140     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1141     if (E.isInvalid())
1142       return true;
1143 
1144     //   e is an lvalue if the type of the entity is an lvalue reference and
1145     //   an xvalue otherwise
1146     if (!Src->getType()->isLValueReferenceType())
1147       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1148                                    E.get(), nullptr, VK_XValue);
1149 
1150     TemplateArgumentListInfo Args(Loc, Loc);
1151     Args.addArgument(
1152         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1153 
1154     if (UseMemberGet) {
1155       //   if [lookup of member get] finds at least one declaration, the
1156       //   initializer is e.get<i-1>().
1157       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1158                                      CXXScopeSpec(), SourceLocation(), nullptr,
1159                                      MemberGet, &Args, nullptr);
1160       if (E.isInvalid())
1161         return true;
1162 
1163       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1164     } else {
1165       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1166       //   in the associated namespaces.
1167       Expr *Get = UnresolvedLookupExpr::Create(
1168           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1169           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1170           UnresolvedSetIterator(), UnresolvedSetIterator());
1171 
1172       Expr *Arg = E.get();
1173       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1174     }
1175     if (E.isInvalid())
1176       return true;
1177     Expr *Init = E.get();
1178 
1179     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1180     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1181     if (T.isNull())
1182       return true;
1183 
1184     //   each vi is a variable of type "reference to T" initialized with the
1185     //   initializer, where the reference is an lvalue reference if the
1186     //   initializer is an lvalue and an rvalue reference otherwise
1187     QualType RefType =
1188         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1189     if (RefType.isNull())
1190       return true;
1191     auto *RefVD = VarDecl::Create(
1192         S.Context, Src->getDeclContext(), Loc, Loc,
1193         B->getDeclName().getAsIdentifierInfo(), RefType,
1194         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1195     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1196     RefVD->setTSCSpec(Src->getTSCSpec());
1197     RefVD->setImplicit();
1198     if (Src->isInlineSpecified())
1199       RefVD->setInlineSpecified();
1200     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1201 
1202     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1203     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1204     InitializationSequence Seq(S, Entity, Kind, Init);
1205     E = Seq.Perform(S, Entity, Kind, Init);
1206     if (E.isInvalid())
1207       return true;
1208     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1209     if (E.isInvalid())
1210       return true;
1211     RefVD->setInit(E.get());
1212     RefVD->checkInitIsICE();
1213 
1214     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1215                                    DeclarationNameInfo(B->getDeclName(), Loc),
1216                                    RefVD);
1217     if (E.isInvalid())
1218       return true;
1219 
1220     B->setBinding(T, E.get());
1221     I++;
1222   }
1223 
1224   return false;
1225 }
1226 
1227 /// Find the base class to decompose in a built-in decomposition of a class type.
1228 /// This base class search is, unfortunately, not quite like any other that we
1229 /// perform anywhere else in C++.
1230 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1231                                                 const CXXRecordDecl *RD,
1232                                                 CXXCastPath &BasePath) {
1233   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1234                           CXXBasePath &Path) {
1235     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1236   };
1237 
1238   const CXXRecordDecl *ClassWithFields = nullptr;
1239   AccessSpecifier AS = AS_public;
1240   if (RD->hasDirectFields())
1241     // [dcl.decomp]p4:
1242     //   Otherwise, all of E's non-static data members shall be public direct
1243     //   members of E ...
1244     ClassWithFields = RD;
1245   else {
1246     //   ... or of ...
1247     CXXBasePaths Paths;
1248     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1249     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1250       // If no classes have fields, just decompose RD itself. (This will work
1251       // if and only if zero bindings were provided.)
1252       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1253     }
1254 
1255     CXXBasePath *BestPath = nullptr;
1256     for (auto &P : Paths) {
1257       if (!BestPath)
1258         BestPath = &P;
1259       else if (!S.Context.hasSameType(P.back().Base->getType(),
1260                                       BestPath->back().Base->getType())) {
1261         //   ... the same ...
1262         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1263           << false << RD << BestPath->back().Base->getType()
1264           << P.back().Base->getType();
1265         return DeclAccessPair();
1266       } else if (P.Access < BestPath->Access) {
1267         BestPath = &P;
1268       }
1269     }
1270 
1271     //   ... unambiguous ...
1272     QualType BaseType = BestPath->back().Base->getType();
1273     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1274       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1275         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1276       return DeclAccessPair();
1277     }
1278 
1279     //   ... [accessible, implied by other rules] base class of E.
1280     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1281                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1282     AS = BestPath->Access;
1283 
1284     ClassWithFields = BaseType->getAsCXXRecordDecl();
1285     S.BuildBasePathArray(Paths, BasePath);
1286   }
1287 
1288   // The above search did not check whether the selected class itself has base
1289   // classes with fields, so check that now.
1290   CXXBasePaths Paths;
1291   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293       << (ClassWithFields == RD) << RD << ClassWithFields
1294       << Paths.front().back().Base->getType();
1295     return DeclAccessPair();
1296   }
1297 
1298   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1299 }
1300 
1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302                                      ValueDecl *Src, QualType DecompType,
1303                                      const CXXRecordDecl *OrigRD) {
1304   CXXCastPath BasePath;
1305   DeclAccessPair BasePair =
1306       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1307   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1308   if (!RD)
1309     return true;
1310   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1311                                                  DecompType.getQualifiers());
1312 
1313   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1314     unsigned NumFields =
1315         std::count_if(RD->field_begin(), RD->field_end(),
1316                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1317     assert(Bindings.size() != NumFields);
1318     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1319         << DecompType << (unsigned)Bindings.size() << NumFields
1320         << (NumFields < Bindings.size());
1321     return true;
1322   };
1323 
1324   //   all of E's non-static data members shall be [...] well-formed
1325   //   when named as e.name in the context of the structured binding,
1326   //   E shall not have an anonymous union member, ...
1327   unsigned I = 0;
1328   for (auto *FD : RD->fields()) {
1329     if (FD->isUnnamedBitfield())
1330       continue;
1331 
1332     if (FD->isAnonymousStructOrUnion()) {
1333       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1334         << DecompType << FD->getType()->isUnionType();
1335       S.Diag(FD->getLocation(), diag::note_declared_at);
1336       return true;
1337     }
1338 
1339     // We have a real field to bind.
1340     if (I >= Bindings.size())
1341       return DiagnoseBadNumberOfBindings();
1342     auto *B = Bindings[I++];
1343     SourceLocation Loc = B->getLocation();
1344 
1345     // The field must be accessible in the context of the structured binding.
1346     // We already checked that the base class is accessible.
1347     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1348     // const_cast here.
1349     S.CheckStructuredBindingMemberAccess(
1350         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1351         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1352                                      BasePair.getAccess(), FD->getAccess())));
1353 
1354     // Initialize the binding to Src.FD.
1355     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1356     if (E.isInvalid())
1357       return true;
1358     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1359                             VK_LValue, &BasePath);
1360     if (E.isInvalid())
1361       return true;
1362     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1363                                   CXXScopeSpec(), FD,
1364                                   DeclAccessPair::make(FD, FD->getAccess()),
1365                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1366     if (E.isInvalid())
1367       return true;
1368 
1369     // If the type of the member is T, the referenced type is cv T, where cv is
1370     // the cv-qualification of the decomposition expression.
1371     //
1372     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1373     // 'const' to the type of the field.
1374     Qualifiers Q = DecompType.getQualifiers();
1375     if (FD->isMutable())
1376       Q.removeConst();
1377     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1378   }
1379 
1380   if (I != Bindings.size())
1381     return DiagnoseBadNumberOfBindings();
1382 
1383   return false;
1384 }
1385 
1386 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1387   QualType DecompType = DD->getType();
1388 
1389   // If the type of the decomposition is dependent, then so is the type of
1390   // each binding.
1391   if (DecompType->isDependentType()) {
1392     for (auto *B : DD->bindings())
1393       B->setType(Context.DependentTy);
1394     return;
1395   }
1396 
1397   DecompType = DecompType.getNonReferenceType();
1398   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1399 
1400   // C++1z [dcl.decomp]/2:
1401   //   If E is an array type [...]
1402   // As an extension, we also support decomposition of built-in complex and
1403   // vector types.
1404   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1405     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1406       DD->setInvalidDecl();
1407     return;
1408   }
1409   if (auto *VT = DecompType->getAs<VectorType>()) {
1410     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1411       DD->setInvalidDecl();
1412     return;
1413   }
1414   if (auto *CT = DecompType->getAs<ComplexType>()) {
1415     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1416       DD->setInvalidDecl();
1417     return;
1418   }
1419 
1420   // C++1z [dcl.decomp]/3:
1421   //   if the expression std::tuple_size<E>::value is a well-formed integral
1422   //   constant expression, [...]
1423   llvm::APSInt TupleSize(32);
1424   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1425   case IsTupleLike::Error:
1426     DD->setInvalidDecl();
1427     return;
1428 
1429   case IsTupleLike::TupleLike:
1430     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1431       DD->setInvalidDecl();
1432     return;
1433 
1434   case IsTupleLike::NotTupleLike:
1435     break;
1436   }
1437 
1438   // C++1z [dcl.dcl]/8:
1439   //   [E shall be of array or non-union class type]
1440   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1441   if (!RD || RD->isUnion()) {
1442     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1443         << DD << !RD << DecompType;
1444     DD->setInvalidDecl();
1445     return;
1446   }
1447 
1448   // C++1z [dcl.decomp]/4:
1449   //   all of E's non-static data members shall be [...] direct members of
1450   //   E or of the same unambiguous public base class of E, ...
1451   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1452     DD->setInvalidDecl();
1453 }
1454 
1455 /// Merge the exception specifications of two variable declarations.
1456 ///
1457 /// This is called when there's a redeclaration of a VarDecl. The function
1458 /// checks if the redeclaration might have an exception specification and
1459 /// validates compatibility and merges the specs if necessary.
1460 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1461   // Shortcut if exceptions are disabled.
1462   if (!getLangOpts().CXXExceptions)
1463     return;
1464 
1465   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1466          "Should only be called if types are otherwise the same.");
1467 
1468   QualType NewType = New->getType();
1469   QualType OldType = Old->getType();
1470 
1471   // We're only interested in pointers and references to functions, as well
1472   // as pointers to member functions.
1473   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1474     NewType = R->getPointeeType();
1475     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1476   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1477     NewType = P->getPointeeType();
1478     OldType = OldType->getAs<PointerType>()->getPointeeType();
1479   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1480     NewType = M->getPointeeType();
1481     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1482   }
1483 
1484   if (!NewType->isFunctionProtoType())
1485     return;
1486 
1487   // There's lots of special cases for functions. For function pointers, system
1488   // libraries are hopefully not as broken so that we don't need these
1489   // workarounds.
1490   if (CheckEquivalentExceptionSpec(
1491         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1492         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1493     New->setInvalidDecl();
1494   }
1495 }
1496 
1497 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1498 /// function declaration are well-formed according to C++
1499 /// [dcl.fct.default].
1500 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1501   unsigned NumParams = FD->getNumParams();
1502   unsigned p;
1503 
1504   // Find first parameter with a default argument
1505   for (p = 0; p < NumParams; ++p) {
1506     ParmVarDecl *Param = FD->getParamDecl(p);
1507     if (Param->hasDefaultArg())
1508       break;
1509   }
1510 
1511   // C++11 [dcl.fct.default]p4:
1512   //   In a given function declaration, each parameter subsequent to a parameter
1513   //   with a default argument shall have a default argument supplied in this or
1514   //   a previous declaration or shall be a function parameter pack. A default
1515   //   argument shall not be redefined by a later declaration (not even to the
1516   //   same value).
1517   unsigned LastMissingDefaultArg = 0;
1518   for (; p < NumParams; ++p) {
1519     ParmVarDecl *Param = FD->getParamDecl(p);
1520     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1521       if (Param->isInvalidDecl())
1522         /* We already complained about this parameter. */;
1523       else if (Param->getIdentifier())
1524         Diag(Param->getLocation(),
1525              diag::err_param_default_argument_missing_name)
1526           << Param->getIdentifier();
1527       else
1528         Diag(Param->getLocation(),
1529              diag::err_param_default_argument_missing);
1530 
1531       LastMissingDefaultArg = p;
1532     }
1533   }
1534 
1535   if (LastMissingDefaultArg > 0) {
1536     // Some default arguments were missing. Clear out all of the
1537     // default arguments up to (and including) the last missing
1538     // default argument, so that we leave the function parameters
1539     // in a semantically valid state.
1540     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1541       ParmVarDecl *Param = FD->getParamDecl(p);
1542       if (Param->hasDefaultArg()) {
1543         Param->setDefaultArg(nullptr);
1544       }
1545     }
1546   }
1547 }
1548 
1549 // CheckConstexprParameterTypes - Check whether a function's parameter types
1550 // are all literal types. If so, return true. If not, produce a suitable
1551 // diagnostic and return false.
1552 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1553                                          const FunctionDecl *FD) {
1554   unsigned ArgIndex = 0;
1555   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1556   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1557                                               e = FT->param_type_end();
1558        i != e; ++i, ++ArgIndex) {
1559     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1560     SourceLocation ParamLoc = PD->getLocation();
1561     if (!(*i)->isDependentType() &&
1562         SemaRef.RequireLiteralType(ParamLoc, *i,
1563                                    diag::err_constexpr_non_literal_param,
1564                                    ArgIndex+1, PD->getSourceRange(),
1565                                    isa<CXXConstructorDecl>(FD)))
1566       return false;
1567   }
1568   return true;
1569 }
1570 
1571 /// Get diagnostic %select index for tag kind for
1572 /// record diagnostic message.
1573 /// WARNING: Indexes apply to particular diagnostics only!
1574 ///
1575 /// \returns diagnostic %select index.
1576 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1577   switch (Tag) {
1578   case TTK_Struct: return 0;
1579   case TTK_Interface: return 1;
1580   case TTK_Class:  return 2;
1581   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1582   }
1583 }
1584 
1585 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1586 // the requirements of a constexpr function definition or a constexpr
1587 // constructor definition. If so, return true. If not, produce appropriate
1588 // diagnostics and return false.
1589 //
1590 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1591 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1592   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1593   if (MD && MD->isInstance()) {
1594     // C++11 [dcl.constexpr]p4:
1595     //  The definition of a constexpr constructor shall satisfy the following
1596     //  constraints:
1597     //  - the class shall not have any virtual base classes;
1598     const CXXRecordDecl *RD = MD->getParent();
1599     if (RD->getNumVBases()) {
1600       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1601         << isa<CXXConstructorDecl>(NewFD)
1602         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1603       for (const auto &I : RD->vbases())
1604         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1605             << I.getSourceRange();
1606       return false;
1607     }
1608   }
1609 
1610   if (!isa<CXXConstructorDecl>(NewFD)) {
1611     // C++11 [dcl.constexpr]p3:
1612     //  The definition of a constexpr function shall satisfy the following
1613     //  constraints:
1614     // - it shall not be virtual;
1615     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1616     if (Method && Method->isVirtual()) {
1617       Method = Method->getCanonicalDecl();
1618       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1619 
1620       // If it's not obvious why this function is virtual, find an overridden
1621       // function which uses the 'virtual' keyword.
1622       const CXXMethodDecl *WrittenVirtual = Method;
1623       while (!WrittenVirtual->isVirtualAsWritten())
1624         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1625       if (WrittenVirtual != Method)
1626         Diag(WrittenVirtual->getLocation(),
1627              diag::note_overridden_virtual_function);
1628       return false;
1629     }
1630 
1631     // - its return type shall be a literal type;
1632     QualType RT = NewFD->getReturnType();
1633     if (!RT->isDependentType() &&
1634         RequireLiteralType(NewFD->getLocation(), RT,
1635                            diag::err_constexpr_non_literal_return))
1636       return false;
1637   }
1638 
1639   // - each of its parameter types shall be a literal type;
1640   if (!CheckConstexprParameterTypes(*this, NewFD))
1641     return false;
1642 
1643   return true;
1644 }
1645 
1646 /// Check the given declaration statement is legal within a constexpr function
1647 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1648 ///
1649 /// \return true if the body is OK (maybe only as an extension), false if we
1650 ///         have diagnosed a problem.
1651 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1652                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1653   // C++11 [dcl.constexpr]p3 and p4:
1654   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1655   //  contain only
1656   for (const auto *DclIt : DS->decls()) {
1657     switch (DclIt->getKind()) {
1658     case Decl::StaticAssert:
1659     case Decl::Using:
1660     case Decl::UsingShadow:
1661     case Decl::UsingDirective:
1662     case Decl::UnresolvedUsingTypename:
1663     case Decl::UnresolvedUsingValue:
1664       //   - static_assert-declarations
1665       //   - using-declarations,
1666       //   - using-directives,
1667       continue;
1668 
1669     case Decl::Typedef:
1670     case Decl::TypeAlias: {
1671       //   - typedef declarations and alias-declarations that do not define
1672       //     classes or enumerations,
1673       const auto *TN = cast<TypedefNameDecl>(DclIt);
1674       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1675         // Don't allow variably-modified types in constexpr functions.
1676         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1677         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1678           << TL.getSourceRange() << TL.getType()
1679           << isa<CXXConstructorDecl>(Dcl);
1680         return false;
1681       }
1682       continue;
1683     }
1684 
1685     case Decl::Enum:
1686     case Decl::CXXRecord:
1687       // C++1y allows types to be defined, not just declared.
1688       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1689         SemaRef.Diag(DS->getBeginLoc(),
1690                      SemaRef.getLangOpts().CPlusPlus14
1691                          ? diag::warn_cxx11_compat_constexpr_type_definition
1692                          : diag::ext_constexpr_type_definition)
1693             << isa<CXXConstructorDecl>(Dcl);
1694       continue;
1695 
1696     case Decl::EnumConstant:
1697     case Decl::IndirectField:
1698     case Decl::ParmVar:
1699       // These can only appear with other declarations which are banned in
1700       // C++11 and permitted in C++1y, so ignore them.
1701       continue;
1702 
1703     case Decl::Var:
1704     case Decl::Decomposition: {
1705       // C++1y [dcl.constexpr]p3 allows anything except:
1706       //   a definition of a variable of non-literal type or of static or
1707       //   thread storage duration or for which no initialization is performed.
1708       const auto *VD = cast<VarDecl>(DclIt);
1709       if (VD->isThisDeclarationADefinition()) {
1710         if (VD->isStaticLocal()) {
1711           SemaRef.Diag(VD->getLocation(),
1712                        diag::err_constexpr_local_var_static)
1713             << isa<CXXConstructorDecl>(Dcl)
1714             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1715           return false;
1716         }
1717         if (!VD->getType()->isDependentType() &&
1718             SemaRef.RequireLiteralType(
1719               VD->getLocation(), VD->getType(),
1720               diag::err_constexpr_local_var_non_literal_type,
1721               isa<CXXConstructorDecl>(Dcl)))
1722           return false;
1723         if (!VD->getType()->isDependentType() &&
1724             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1725           SemaRef.Diag(VD->getLocation(),
1726                        diag::err_constexpr_local_var_no_init)
1727             << isa<CXXConstructorDecl>(Dcl);
1728           return false;
1729         }
1730       }
1731       SemaRef.Diag(VD->getLocation(),
1732                    SemaRef.getLangOpts().CPlusPlus14
1733                     ? diag::warn_cxx11_compat_constexpr_local_var
1734                     : diag::ext_constexpr_local_var)
1735         << isa<CXXConstructorDecl>(Dcl);
1736       continue;
1737     }
1738 
1739     case Decl::NamespaceAlias:
1740     case Decl::Function:
1741       // These are disallowed in C++11 and permitted in C++1y. Allow them
1742       // everywhere as an extension.
1743       if (!Cxx1yLoc.isValid())
1744         Cxx1yLoc = DS->getBeginLoc();
1745       continue;
1746 
1747     default:
1748       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1749           << isa<CXXConstructorDecl>(Dcl);
1750       return false;
1751     }
1752   }
1753 
1754   return true;
1755 }
1756 
1757 /// Check that the given field is initialized within a constexpr constructor.
1758 ///
1759 /// \param Dcl The constexpr constructor being checked.
1760 /// \param Field The field being checked. This may be a member of an anonymous
1761 ///        struct or union nested within the class being checked.
1762 /// \param Inits All declarations, including anonymous struct/union members and
1763 ///        indirect members, for which any initialization was provided.
1764 /// \param Diagnosed Set to true if an error is produced.
1765 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1766                                           const FunctionDecl *Dcl,
1767                                           FieldDecl *Field,
1768                                           llvm::SmallSet<Decl*, 16> &Inits,
1769                                           bool &Diagnosed) {
1770   if (Field->isInvalidDecl())
1771     return;
1772 
1773   if (Field->isUnnamedBitfield())
1774     return;
1775 
1776   // Anonymous unions with no variant members and empty anonymous structs do not
1777   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1778   // indirect fields don't need initializing.
1779   if (Field->isAnonymousStructOrUnion() &&
1780       (Field->getType()->isUnionType()
1781            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1782            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1783     return;
1784 
1785   if (!Inits.count(Field)) {
1786     if (!Diagnosed) {
1787       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1788       Diagnosed = true;
1789     }
1790     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1791   } else if (Field->isAnonymousStructOrUnion()) {
1792     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1793     for (auto *I : RD->fields())
1794       // If an anonymous union contains an anonymous struct of which any member
1795       // is initialized, all members must be initialized.
1796       if (!RD->isUnion() || Inits.count(I))
1797         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1798   }
1799 }
1800 
1801 /// Check the provided statement is allowed in a constexpr function
1802 /// definition.
1803 static bool
1804 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1805                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1806                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1807   // - its function-body shall be [...] a compound-statement that contains only
1808   switch (S->getStmtClass()) {
1809   case Stmt::NullStmtClass:
1810     //   - null statements,
1811     return true;
1812 
1813   case Stmt::DeclStmtClass:
1814     //   - static_assert-declarations
1815     //   - using-declarations,
1816     //   - using-directives,
1817     //   - typedef declarations and alias-declarations that do not define
1818     //     classes or enumerations,
1819     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1820       return false;
1821     return true;
1822 
1823   case Stmt::ReturnStmtClass:
1824     //   - and exactly one return statement;
1825     if (isa<CXXConstructorDecl>(Dcl)) {
1826       // C++1y allows return statements in constexpr constructors.
1827       if (!Cxx1yLoc.isValid())
1828         Cxx1yLoc = S->getBeginLoc();
1829       return true;
1830     }
1831 
1832     ReturnStmts.push_back(S->getBeginLoc());
1833     return true;
1834 
1835   case Stmt::CompoundStmtClass: {
1836     // C++1y allows compound-statements.
1837     if (!Cxx1yLoc.isValid())
1838       Cxx1yLoc = S->getBeginLoc();
1839 
1840     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1841     for (auto *BodyIt : CompStmt->body()) {
1842       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1843                                       Cxx1yLoc, Cxx2aLoc))
1844         return false;
1845     }
1846     return true;
1847   }
1848 
1849   case Stmt::AttributedStmtClass:
1850     if (!Cxx1yLoc.isValid())
1851       Cxx1yLoc = S->getBeginLoc();
1852     return true;
1853 
1854   case Stmt::IfStmtClass: {
1855     // C++1y allows if-statements.
1856     if (!Cxx1yLoc.isValid())
1857       Cxx1yLoc = S->getBeginLoc();
1858 
1859     IfStmt *If = cast<IfStmt>(S);
1860     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1861                                     Cxx1yLoc, Cxx2aLoc))
1862       return false;
1863     if (If->getElse() &&
1864         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1865                                     Cxx1yLoc, Cxx2aLoc))
1866       return false;
1867     return true;
1868   }
1869 
1870   case Stmt::WhileStmtClass:
1871   case Stmt::DoStmtClass:
1872   case Stmt::ForStmtClass:
1873   case Stmt::CXXForRangeStmtClass:
1874   case Stmt::ContinueStmtClass:
1875     // C++1y allows all of these. We don't allow them as extensions in C++11,
1876     // because they don't make sense without variable mutation.
1877     if (!SemaRef.getLangOpts().CPlusPlus14)
1878       break;
1879     if (!Cxx1yLoc.isValid())
1880       Cxx1yLoc = S->getBeginLoc();
1881     for (Stmt *SubStmt : S->children())
1882       if (SubStmt &&
1883           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1884                                       Cxx1yLoc, Cxx2aLoc))
1885         return false;
1886     return true;
1887 
1888   case Stmt::SwitchStmtClass:
1889   case Stmt::CaseStmtClass:
1890   case Stmt::DefaultStmtClass:
1891   case Stmt::BreakStmtClass:
1892     // C++1y allows switch-statements, and since they don't need variable
1893     // mutation, we can reasonably allow them in C++11 as an extension.
1894     if (!Cxx1yLoc.isValid())
1895       Cxx1yLoc = S->getBeginLoc();
1896     for (Stmt *SubStmt : S->children())
1897       if (SubStmt &&
1898           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1899                                       Cxx1yLoc, Cxx2aLoc))
1900         return false;
1901     return true;
1902 
1903   case Stmt::CXXTryStmtClass:
1904     if (Cxx2aLoc.isInvalid())
1905       Cxx2aLoc = S->getBeginLoc();
1906     for (Stmt *SubStmt : S->children()) {
1907       if (SubStmt &&
1908           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1909                                       Cxx1yLoc, Cxx2aLoc))
1910         return false;
1911     }
1912     return true;
1913 
1914   case Stmt::CXXCatchStmtClass:
1915     // Do not bother checking the language mode (already covered by the
1916     // try block check).
1917     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1918                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1919                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1920       return false;
1921     return true;
1922 
1923   default:
1924     if (!isa<Expr>(S))
1925       break;
1926 
1927     // C++1y allows expression-statements.
1928     if (!Cxx1yLoc.isValid())
1929       Cxx1yLoc = S->getBeginLoc();
1930     return true;
1931   }
1932 
1933   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1934       << isa<CXXConstructorDecl>(Dcl);
1935   return false;
1936 }
1937 
1938 /// Check the body for the given constexpr function declaration only contains
1939 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1940 ///
1941 /// \return true if the body is OK, false if we have diagnosed a problem.
1942 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1943   SmallVector<SourceLocation, 4> ReturnStmts;
1944 
1945   if (isa<CXXTryStmt>(Body)) {
1946     // C++11 [dcl.constexpr]p3:
1947     //  The definition of a constexpr function shall satisfy the following
1948     //  constraints: [...]
1949     // - its function-body shall be = delete, = default, or a
1950     //   compound-statement
1951     //
1952     // C++11 [dcl.constexpr]p4:
1953     //  In the definition of a constexpr constructor, [...]
1954     // - its function-body shall not be a function-try-block;
1955     //
1956     // This restriction is lifted in C++2a, as long as inner statements also
1957     // apply the general constexpr rules.
1958     Diag(Body->getBeginLoc(),
1959          !getLangOpts().CPlusPlus2a
1960              ? diag::ext_constexpr_function_try_block_cxx2a
1961              : diag::warn_cxx17_compat_constexpr_function_try_block)
1962         << isa<CXXConstructorDecl>(Dcl);
1963   }
1964 
1965   // - its function-body shall be [...] a compound-statement that contains only
1966   //   [... list of cases ...]
1967   //
1968   // Note that walking the children here is enough to properly check for
1969   // CompoundStmt and CXXTryStmt body.
1970   SourceLocation Cxx1yLoc, Cxx2aLoc;
1971   for (Stmt *SubStmt : Body->children()) {
1972     if (SubStmt &&
1973         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1974                                     Cxx1yLoc, Cxx2aLoc))
1975       return false;
1976   }
1977 
1978   if (Cxx2aLoc.isValid())
1979     Diag(Cxx2aLoc,
1980          getLangOpts().CPlusPlus2a
1981            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1982            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1983       << isa<CXXConstructorDecl>(Dcl);
1984   if (Cxx1yLoc.isValid())
1985     Diag(Cxx1yLoc,
1986          getLangOpts().CPlusPlus14
1987            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1988            : diag::ext_constexpr_body_invalid_stmt)
1989       << isa<CXXConstructorDecl>(Dcl);
1990 
1991   if (const CXXConstructorDecl *Constructor
1992         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1993     const CXXRecordDecl *RD = Constructor->getParent();
1994     // DR1359:
1995     // - every non-variant non-static data member and base class sub-object
1996     //   shall be initialized;
1997     // DR1460:
1998     // - if the class is a union having variant members, exactly one of them
1999     //   shall be initialized;
2000     if (RD->isUnion()) {
2001       if (Constructor->getNumCtorInitializers() == 0 &&
2002           RD->hasVariantMembers()) {
2003         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2004         return false;
2005       }
2006     } else if (!Constructor->isDependentContext() &&
2007                !Constructor->isDelegatingConstructor()) {
2008       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2009 
2010       // Skip detailed checking if we have enough initializers, and we would
2011       // allow at most one initializer per member.
2012       bool AnyAnonStructUnionMembers = false;
2013       unsigned Fields = 0;
2014       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2015            E = RD->field_end(); I != E; ++I, ++Fields) {
2016         if (I->isAnonymousStructOrUnion()) {
2017           AnyAnonStructUnionMembers = true;
2018           break;
2019         }
2020       }
2021       // DR1460:
2022       // - if the class is a union-like class, but is not a union, for each of
2023       //   its anonymous union members having variant members, exactly one of
2024       //   them shall be initialized;
2025       if (AnyAnonStructUnionMembers ||
2026           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2027         // Check initialization of non-static data members. Base classes are
2028         // always initialized so do not need to be checked. Dependent bases
2029         // might not have initializers in the member initializer list.
2030         llvm::SmallSet<Decl*, 16> Inits;
2031         for (const auto *I: Constructor->inits()) {
2032           if (FieldDecl *FD = I->getMember())
2033             Inits.insert(FD);
2034           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2035             Inits.insert(ID->chain_begin(), ID->chain_end());
2036         }
2037 
2038         bool Diagnosed = false;
2039         for (auto *I : RD->fields())
2040           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2041         if (Diagnosed)
2042           return false;
2043       }
2044     }
2045   } else {
2046     if (ReturnStmts.empty()) {
2047       // C++1y doesn't require constexpr functions to contain a 'return'
2048       // statement. We still do, unless the return type might be void, because
2049       // otherwise if there's no return statement, the function cannot
2050       // be used in a core constant expression.
2051       bool OK = getLangOpts().CPlusPlus14 &&
2052                 (Dcl->getReturnType()->isVoidType() ||
2053                  Dcl->getReturnType()->isDependentType());
2054       Diag(Dcl->getLocation(),
2055            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2056               : diag::err_constexpr_body_no_return);
2057       if (!OK)
2058         return false;
2059     } else if (ReturnStmts.size() > 1) {
2060       Diag(ReturnStmts.back(),
2061            getLangOpts().CPlusPlus14
2062              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2063              : diag::ext_constexpr_body_multiple_return);
2064       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2065         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2066     }
2067   }
2068 
2069   // C++11 [dcl.constexpr]p5:
2070   //   if no function argument values exist such that the function invocation
2071   //   substitution would produce a constant expression, the program is
2072   //   ill-formed; no diagnostic required.
2073   // C++11 [dcl.constexpr]p3:
2074   //   - every constructor call and implicit conversion used in initializing the
2075   //     return value shall be one of those allowed in a constant expression.
2076   // C++11 [dcl.constexpr]p4:
2077   //   - every constructor involved in initializing non-static data members and
2078   //     base class sub-objects shall be a constexpr constructor.
2079   SmallVector<PartialDiagnosticAt, 8> Diags;
2080   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2081     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2082       << isa<CXXConstructorDecl>(Dcl);
2083     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2084       Diag(Diags[I].first, Diags[I].second);
2085     // Don't return false here: we allow this for compatibility in
2086     // system headers.
2087   }
2088 
2089   return true;
2090 }
2091 
2092 /// Get the class that is directly named by the current context. This is the
2093 /// class for which an unqualified-id in this scope could name a constructor
2094 /// or destructor.
2095 ///
2096 /// If the scope specifier denotes a class, this will be that class.
2097 /// If the scope specifier is empty, this will be the class whose
2098 /// member-specification we are currently within. Otherwise, there
2099 /// is no such class.
2100 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2101   assert(getLangOpts().CPlusPlus && "No class names in C!");
2102 
2103   if (SS && SS->isInvalid())
2104     return nullptr;
2105 
2106   if (SS && SS->isNotEmpty()) {
2107     DeclContext *DC = computeDeclContext(*SS, true);
2108     return dyn_cast_or_null<CXXRecordDecl>(DC);
2109   }
2110 
2111   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2112 }
2113 
2114 /// isCurrentClassName - Determine whether the identifier II is the
2115 /// name of the class type currently being defined. In the case of
2116 /// nested classes, this will only return true if II is the name of
2117 /// the innermost class.
2118 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2119                               const CXXScopeSpec *SS) {
2120   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2121   return CurDecl && &II == CurDecl->getIdentifier();
2122 }
2123 
2124 /// Determine whether the identifier II is a typo for the name of
2125 /// the class type currently being defined. If so, update it to the identifier
2126 /// that should have been used.
2127 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2128   assert(getLangOpts().CPlusPlus && "No class names in C!");
2129 
2130   if (!getLangOpts().SpellChecking)
2131     return false;
2132 
2133   CXXRecordDecl *CurDecl;
2134   if (SS && SS->isSet() && !SS->isInvalid()) {
2135     DeclContext *DC = computeDeclContext(*SS, true);
2136     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2137   } else
2138     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2139 
2140   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2141       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2142           < II->getLength()) {
2143     II = CurDecl->getIdentifier();
2144     return true;
2145   }
2146 
2147   return false;
2148 }
2149 
2150 /// Determine whether the given class is a base class of the given
2151 /// class, including looking at dependent bases.
2152 static bool findCircularInheritance(const CXXRecordDecl *Class,
2153                                     const CXXRecordDecl *Current) {
2154   SmallVector<const CXXRecordDecl*, 8> Queue;
2155 
2156   Class = Class->getCanonicalDecl();
2157   while (true) {
2158     for (const auto &I : Current->bases()) {
2159       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2160       if (!Base)
2161         continue;
2162 
2163       Base = Base->getDefinition();
2164       if (!Base)
2165         continue;
2166 
2167       if (Base->getCanonicalDecl() == Class)
2168         return true;
2169 
2170       Queue.push_back(Base);
2171     }
2172 
2173     if (Queue.empty())
2174       return false;
2175 
2176     Current = Queue.pop_back_val();
2177   }
2178 
2179   return false;
2180 }
2181 
2182 /// Check the validity of a C++ base class specifier.
2183 ///
2184 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2185 /// and returns NULL otherwise.
2186 CXXBaseSpecifier *
2187 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2188                          SourceRange SpecifierRange,
2189                          bool Virtual, AccessSpecifier Access,
2190                          TypeSourceInfo *TInfo,
2191                          SourceLocation EllipsisLoc) {
2192   QualType BaseType = TInfo->getType();
2193 
2194   // C++ [class.union]p1:
2195   //   A union shall not have base classes.
2196   if (Class->isUnion()) {
2197     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2198       << SpecifierRange;
2199     return nullptr;
2200   }
2201 
2202   if (EllipsisLoc.isValid() &&
2203       !TInfo->getType()->containsUnexpandedParameterPack()) {
2204     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2205       << TInfo->getTypeLoc().getSourceRange();
2206     EllipsisLoc = SourceLocation();
2207   }
2208 
2209   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2210 
2211   if (BaseType->isDependentType()) {
2212     // Make sure that we don't have circular inheritance among our dependent
2213     // bases. For non-dependent bases, the check for completeness below handles
2214     // this.
2215     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2216       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2217           ((BaseDecl = BaseDecl->getDefinition()) &&
2218            findCircularInheritance(Class, BaseDecl))) {
2219         Diag(BaseLoc, diag::err_circular_inheritance)
2220           << BaseType << Context.getTypeDeclType(Class);
2221 
2222         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2223           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2224             << BaseType;
2225 
2226         return nullptr;
2227       }
2228     }
2229 
2230     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2231                                           Class->getTagKind() == TTK_Class,
2232                                           Access, TInfo, EllipsisLoc);
2233   }
2234 
2235   // Base specifiers must be record types.
2236   if (!BaseType->isRecordType()) {
2237     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2238     return nullptr;
2239   }
2240 
2241   // C++ [class.union]p1:
2242   //   A union shall not be used as a base class.
2243   if (BaseType->isUnionType()) {
2244     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2245     return nullptr;
2246   }
2247 
2248   // For the MS ABI, propagate DLL attributes to base class templates.
2249   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2250     if (Attr *ClassAttr = getDLLAttr(Class)) {
2251       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2252               BaseType->getAsCXXRecordDecl())) {
2253         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2254                                             BaseLoc);
2255       }
2256     }
2257   }
2258 
2259   // C++ [class.derived]p2:
2260   //   The class-name in a base-specifier shall not be an incompletely
2261   //   defined class.
2262   if (RequireCompleteType(BaseLoc, BaseType,
2263                           diag::err_incomplete_base_class, SpecifierRange)) {
2264     Class->setInvalidDecl();
2265     return nullptr;
2266   }
2267 
2268   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2269   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2270   assert(BaseDecl && "Record type has no declaration");
2271   BaseDecl = BaseDecl->getDefinition();
2272   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2273   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2274   assert(CXXBaseDecl && "Base type is not a C++ type");
2275 
2276   // Microsoft docs say:
2277   // "If a base-class has a code_seg attribute, derived classes must have the
2278   // same attribute."
2279   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2280   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2281   if ((DerivedCSA || BaseCSA) &&
2282       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2283     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2284     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2285       << CXXBaseDecl;
2286     return nullptr;
2287   }
2288 
2289   // A class which contains a flexible array member is not suitable for use as a
2290   // base class:
2291   //   - If the layout determines that a base comes before another base,
2292   //     the flexible array member would index into the subsequent base.
2293   //   - If the layout determines that base comes before the derived class,
2294   //     the flexible array member would index into the derived class.
2295   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2296     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2297       << CXXBaseDecl->getDeclName();
2298     return nullptr;
2299   }
2300 
2301   // C++ [class]p3:
2302   //   If a class is marked final and it appears as a base-type-specifier in
2303   //   base-clause, the program is ill-formed.
2304   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2305     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2306       << CXXBaseDecl->getDeclName()
2307       << FA->isSpelledAsSealed();
2308     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2309         << CXXBaseDecl->getDeclName() << FA->getRange();
2310     return nullptr;
2311   }
2312 
2313   if (BaseDecl->isInvalidDecl())
2314     Class->setInvalidDecl();
2315 
2316   // Create the base specifier.
2317   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2318                                         Class->getTagKind() == TTK_Class,
2319                                         Access, TInfo, EllipsisLoc);
2320 }
2321 
2322 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2323 /// one entry in the base class list of a class specifier, for
2324 /// example:
2325 ///    class foo : public bar, virtual private baz {
2326 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2327 BaseResult
2328 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2329                          ParsedAttributes &Attributes,
2330                          bool Virtual, AccessSpecifier Access,
2331                          ParsedType basetype, SourceLocation BaseLoc,
2332                          SourceLocation EllipsisLoc) {
2333   if (!classdecl)
2334     return true;
2335 
2336   AdjustDeclIfTemplate(classdecl);
2337   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2338   if (!Class)
2339     return true;
2340 
2341   // We haven't yet attached the base specifiers.
2342   Class->setIsParsingBaseSpecifiers();
2343 
2344   // We do not support any C++11 attributes on base-specifiers yet.
2345   // Diagnose any attributes we see.
2346   for (const ParsedAttr &AL : Attributes) {
2347     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2348       continue;
2349     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2350                           ? (unsigned)diag::warn_unknown_attribute_ignored
2351                           : (unsigned)diag::err_base_specifier_attribute)
2352         << AL.getName();
2353   }
2354 
2355   TypeSourceInfo *TInfo = nullptr;
2356   GetTypeFromParser(basetype, &TInfo);
2357 
2358   if (EllipsisLoc.isInvalid() &&
2359       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2360                                       UPPC_BaseType))
2361     return true;
2362 
2363   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2364                                                       Virtual, Access, TInfo,
2365                                                       EllipsisLoc))
2366     return BaseSpec;
2367   else
2368     Class->setInvalidDecl();
2369 
2370   return true;
2371 }
2372 
2373 /// Use small set to collect indirect bases.  As this is only used
2374 /// locally, there's no need to abstract the small size parameter.
2375 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2376 
2377 /// Recursively add the bases of Type.  Don't add Type itself.
2378 static void
2379 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2380                   const QualType &Type)
2381 {
2382   // Even though the incoming type is a base, it might not be
2383   // a class -- it could be a template parm, for instance.
2384   if (auto Rec = Type->getAs<RecordType>()) {
2385     auto Decl = Rec->getAsCXXRecordDecl();
2386 
2387     // Iterate over its bases.
2388     for (const auto &BaseSpec : Decl->bases()) {
2389       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2390         .getUnqualifiedType();
2391       if (Set.insert(Base).second)
2392         // If we've not already seen it, recurse.
2393         NoteIndirectBases(Context, Set, Base);
2394     }
2395   }
2396 }
2397 
2398 /// Performs the actual work of attaching the given base class
2399 /// specifiers to a C++ class.
2400 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2401                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2402  if (Bases.empty())
2403     return false;
2404 
2405   // Used to keep track of which base types we have already seen, so
2406   // that we can properly diagnose redundant direct base types. Note
2407   // that the key is always the unqualified canonical type of the base
2408   // class.
2409   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2410 
2411   // Used to track indirect bases so we can see if a direct base is
2412   // ambiguous.
2413   IndirectBaseSet IndirectBaseTypes;
2414 
2415   // Copy non-redundant base specifiers into permanent storage.
2416   unsigned NumGoodBases = 0;
2417   bool Invalid = false;
2418   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2419     QualType NewBaseType
2420       = Context.getCanonicalType(Bases[idx]->getType());
2421     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2422 
2423     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2424     if (KnownBase) {
2425       // C++ [class.mi]p3:
2426       //   A class shall not be specified as a direct base class of a
2427       //   derived class more than once.
2428       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2429           << KnownBase->getType() << Bases[idx]->getSourceRange();
2430 
2431       // Delete the duplicate base class specifier; we're going to
2432       // overwrite its pointer later.
2433       Context.Deallocate(Bases[idx]);
2434 
2435       Invalid = true;
2436     } else {
2437       // Okay, add this new base class.
2438       KnownBase = Bases[idx];
2439       Bases[NumGoodBases++] = Bases[idx];
2440 
2441       // Note this base's direct & indirect bases, if there could be ambiguity.
2442       if (Bases.size() > 1)
2443         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2444 
2445       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2446         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2447         if (Class->isInterface() &&
2448               (!RD->isInterfaceLike() ||
2449                KnownBase->getAccessSpecifier() != AS_public)) {
2450           // The Microsoft extension __interface does not permit bases that
2451           // are not themselves public interfaces.
2452           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2453               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2454               << RD->getSourceRange();
2455           Invalid = true;
2456         }
2457         if (RD->hasAttr<WeakAttr>())
2458           Class->addAttr(WeakAttr::CreateImplicit(Context));
2459       }
2460     }
2461   }
2462 
2463   // Attach the remaining base class specifiers to the derived class.
2464   Class->setBases(Bases.data(), NumGoodBases);
2465 
2466   // Check that the only base classes that are duplicate are virtual.
2467   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2468     // Check whether this direct base is inaccessible due to ambiguity.
2469     QualType BaseType = Bases[idx]->getType();
2470 
2471     // Skip all dependent types in templates being used as base specifiers.
2472     // Checks below assume that the base specifier is a CXXRecord.
2473     if (BaseType->isDependentType())
2474       continue;
2475 
2476     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2477       .getUnqualifiedType();
2478 
2479     if (IndirectBaseTypes.count(CanonicalBase)) {
2480       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2481                          /*DetectVirtual=*/true);
2482       bool found
2483         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2484       assert(found);
2485       (void)found;
2486 
2487       if (Paths.isAmbiguous(CanonicalBase))
2488         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2489             << BaseType << getAmbiguousPathsDisplayString(Paths)
2490             << Bases[idx]->getSourceRange();
2491       else
2492         assert(Bases[idx]->isVirtual());
2493     }
2494 
2495     // Delete the base class specifier, since its data has been copied
2496     // into the CXXRecordDecl.
2497     Context.Deallocate(Bases[idx]);
2498   }
2499 
2500   return Invalid;
2501 }
2502 
2503 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2504 /// class, after checking whether there are any duplicate base
2505 /// classes.
2506 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2507                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2508   if (!ClassDecl || Bases.empty())
2509     return;
2510 
2511   AdjustDeclIfTemplate(ClassDecl);
2512   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2513 }
2514 
2515 /// Determine whether the type \p Derived is a C++ class that is
2516 /// derived from the type \p Base.
2517 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2518   if (!getLangOpts().CPlusPlus)
2519     return false;
2520 
2521   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2522   if (!DerivedRD)
2523     return false;
2524 
2525   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2526   if (!BaseRD)
2527     return false;
2528 
2529   // If either the base or the derived type is invalid, don't try to
2530   // check whether one is derived from the other.
2531   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2532     return false;
2533 
2534   // FIXME: In a modules build, do we need the entire path to be visible for us
2535   // to be able to use the inheritance relationship?
2536   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2537     return false;
2538 
2539   return DerivedRD->isDerivedFrom(BaseRD);
2540 }
2541 
2542 /// Determine whether the type \p Derived is a C++ class that is
2543 /// derived from the type \p Base.
2544 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2545                          CXXBasePaths &Paths) {
2546   if (!getLangOpts().CPlusPlus)
2547     return false;
2548 
2549   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2550   if (!DerivedRD)
2551     return false;
2552 
2553   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2554   if (!BaseRD)
2555     return false;
2556 
2557   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2558     return false;
2559 
2560   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2561 }
2562 
2563 static void BuildBasePathArray(const CXXBasePath &Path,
2564                                CXXCastPath &BasePathArray) {
2565   // We first go backward and check if we have a virtual base.
2566   // FIXME: It would be better if CXXBasePath had the base specifier for
2567   // the nearest virtual base.
2568   unsigned Start = 0;
2569   for (unsigned I = Path.size(); I != 0; --I) {
2570     if (Path[I - 1].Base->isVirtual()) {
2571       Start = I - 1;
2572       break;
2573     }
2574   }
2575 
2576   // Now add all bases.
2577   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2578     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2579 }
2580 
2581 
2582 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2583                               CXXCastPath &BasePathArray) {
2584   assert(BasePathArray.empty() && "Base path array must be empty!");
2585   assert(Paths.isRecordingPaths() && "Must record paths!");
2586   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2587 }
2588 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2589 /// conversion (where Derived and Base are class types) is
2590 /// well-formed, meaning that the conversion is unambiguous (and
2591 /// that all of the base classes are accessible). Returns true
2592 /// and emits a diagnostic if the code is ill-formed, returns false
2593 /// otherwise. Loc is the location where this routine should point to
2594 /// if there is an error, and Range is the source range to highlight
2595 /// if there is an error.
2596 ///
2597 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2598 /// diagnostic for the respective type of error will be suppressed, but the
2599 /// check for ill-formed code will still be performed.
2600 bool
2601 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2602                                    unsigned InaccessibleBaseID,
2603                                    unsigned AmbigiousBaseConvID,
2604                                    SourceLocation Loc, SourceRange Range,
2605                                    DeclarationName Name,
2606                                    CXXCastPath *BasePath,
2607                                    bool IgnoreAccess) {
2608   // First, determine whether the path from Derived to Base is
2609   // ambiguous. This is slightly more expensive than checking whether
2610   // the Derived to Base conversion exists, because here we need to
2611   // explore multiple paths to determine if there is an ambiguity.
2612   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2613                      /*DetectVirtual=*/false);
2614   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2615   if (!DerivationOkay)
2616     return true;
2617 
2618   const CXXBasePath *Path = nullptr;
2619   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2620     Path = &Paths.front();
2621 
2622   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2623   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2624   // user to access such bases.
2625   if (!Path && getLangOpts().MSVCCompat) {
2626     for (const CXXBasePath &PossiblePath : Paths) {
2627       if (PossiblePath.size() == 1) {
2628         Path = &PossiblePath;
2629         if (AmbigiousBaseConvID)
2630           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2631               << Base << Derived << Range;
2632         break;
2633       }
2634     }
2635   }
2636 
2637   if (Path) {
2638     if (!IgnoreAccess) {
2639       // Check that the base class can be accessed.
2640       switch (
2641           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2642       case AR_inaccessible:
2643         return true;
2644       case AR_accessible:
2645       case AR_dependent:
2646       case AR_delayed:
2647         break;
2648       }
2649     }
2650 
2651     // Build a base path if necessary.
2652     if (BasePath)
2653       ::BuildBasePathArray(*Path, *BasePath);
2654     return false;
2655   }
2656 
2657   if (AmbigiousBaseConvID) {
2658     // We know that the derived-to-base conversion is ambiguous, and
2659     // we're going to produce a diagnostic. Perform the derived-to-base
2660     // search just one more time to compute all of the possible paths so
2661     // that we can print them out. This is more expensive than any of
2662     // the previous derived-to-base checks we've done, but at this point
2663     // performance isn't as much of an issue.
2664     Paths.clear();
2665     Paths.setRecordingPaths(true);
2666     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2667     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2668     (void)StillOkay;
2669 
2670     // Build up a textual representation of the ambiguous paths, e.g.,
2671     // D -> B -> A, that will be used to illustrate the ambiguous
2672     // conversions in the diagnostic. We only print one of the paths
2673     // to each base class subobject.
2674     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2675 
2676     Diag(Loc, AmbigiousBaseConvID)
2677     << Derived << Base << PathDisplayStr << Range << Name;
2678   }
2679   return true;
2680 }
2681 
2682 bool
2683 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2684                                    SourceLocation Loc, SourceRange Range,
2685                                    CXXCastPath *BasePath,
2686                                    bool IgnoreAccess) {
2687   return CheckDerivedToBaseConversion(
2688       Derived, Base, diag::err_upcast_to_inaccessible_base,
2689       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2690       BasePath, IgnoreAccess);
2691 }
2692 
2693 
2694 /// Builds a string representing ambiguous paths from a
2695 /// specific derived class to different subobjects of the same base
2696 /// class.
2697 ///
2698 /// This function builds a string that can be used in error messages
2699 /// to show the different paths that one can take through the
2700 /// inheritance hierarchy to go from the derived class to different
2701 /// subobjects of a base class. The result looks something like this:
2702 /// @code
2703 /// struct D -> struct B -> struct A
2704 /// struct D -> struct C -> struct A
2705 /// @endcode
2706 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2707   std::string PathDisplayStr;
2708   std::set<unsigned> DisplayedPaths;
2709   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2710        Path != Paths.end(); ++Path) {
2711     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2712       // We haven't displayed a path to this particular base
2713       // class subobject yet.
2714       PathDisplayStr += "\n    ";
2715       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2716       for (CXXBasePath::const_iterator Element = Path->begin();
2717            Element != Path->end(); ++Element)
2718         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2719     }
2720   }
2721 
2722   return PathDisplayStr;
2723 }
2724 
2725 //===----------------------------------------------------------------------===//
2726 // C++ class member Handling
2727 //===----------------------------------------------------------------------===//
2728 
2729 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2730 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2731                                 SourceLocation ColonLoc,
2732                                 const ParsedAttributesView &Attrs) {
2733   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2734   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2735                                                   ASLoc, ColonLoc);
2736   CurContext->addHiddenDecl(ASDecl);
2737   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2738 }
2739 
2740 /// CheckOverrideControl - Check C++11 override control semantics.
2741 void Sema::CheckOverrideControl(NamedDecl *D) {
2742   if (D->isInvalidDecl())
2743     return;
2744 
2745   // We only care about "override" and "final" declarations.
2746   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2747     return;
2748 
2749   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2750 
2751   // We can't check dependent instance methods.
2752   if (MD && MD->isInstance() &&
2753       (MD->getParent()->hasAnyDependentBases() ||
2754        MD->getType()->isDependentType()))
2755     return;
2756 
2757   if (MD && !MD->isVirtual()) {
2758     // If we have a non-virtual method, check if if hides a virtual method.
2759     // (In that case, it's most likely the method has the wrong type.)
2760     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2761     FindHiddenVirtualMethods(MD, OverloadedMethods);
2762 
2763     if (!OverloadedMethods.empty()) {
2764       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2765         Diag(OA->getLocation(),
2766              diag::override_keyword_hides_virtual_member_function)
2767           << "override" << (OverloadedMethods.size() > 1);
2768       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2769         Diag(FA->getLocation(),
2770              diag::override_keyword_hides_virtual_member_function)
2771           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2772           << (OverloadedMethods.size() > 1);
2773       }
2774       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2775       MD->setInvalidDecl();
2776       return;
2777     }
2778     // Fall through into the general case diagnostic.
2779     // FIXME: We might want to attempt typo correction here.
2780   }
2781 
2782   if (!MD || !MD->isVirtual()) {
2783     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2784       Diag(OA->getLocation(),
2785            diag::override_keyword_only_allowed_on_virtual_member_functions)
2786         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2787       D->dropAttr<OverrideAttr>();
2788     }
2789     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2790       Diag(FA->getLocation(),
2791            diag::override_keyword_only_allowed_on_virtual_member_functions)
2792         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2793         << FixItHint::CreateRemoval(FA->getLocation());
2794       D->dropAttr<FinalAttr>();
2795     }
2796     return;
2797   }
2798 
2799   // C++11 [class.virtual]p5:
2800   //   If a function is marked with the virt-specifier override and
2801   //   does not override a member function of a base class, the program is
2802   //   ill-formed.
2803   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2804   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2805     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2806       << MD->getDeclName();
2807 }
2808 
2809 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2810   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2811     return;
2812   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2813   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2814     return;
2815 
2816   SourceLocation Loc = MD->getLocation();
2817   SourceLocation SpellingLoc = Loc;
2818   if (getSourceManager().isMacroArgExpansion(Loc))
2819     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2820   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2821   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2822       return;
2823 
2824   if (MD->size_overridden_methods() > 0) {
2825     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2826                           ? diag::warn_destructor_marked_not_override_overriding
2827                           : diag::warn_function_marked_not_override_overriding;
2828     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2829     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2830     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2831   }
2832 }
2833 
2834 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2835 /// function overrides a virtual member function marked 'final', according to
2836 /// C++11 [class.virtual]p4.
2837 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2838                                                   const CXXMethodDecl *Old) {
2839   FinalAttr *FA = Old->getAttr<FinalAttr>();
2840   if (!FA)
2841     return false;
2842 
2843   Diag(New->getLocation(), diag::err_final_function_overridden)
2844     << New->getDeclName()
2845     << FA->isSpelledAsSealed();
2846   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2847   return true;
2848 }
2849 
2850 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2851   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2852   // FIXME: Destruction of ObjC lifetime types has side-effects.
2853   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2854     return !RD->isCompleteDefinition() ||
2855            !RD->hasTrivialDefaultConstructor() ||
2856            !RD->hasTrivialDestructor();
2857   return false;
2858 }
2859 
2860 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2861   ParsedAttributesView::const_iterator Itr =
2862       llvm::find_if(list, [](const ParsedAttr &AL) {
2863         return AL.isDeclspecPropertyAttribute();
2864       });
2865   if (Itr != list.end())
2866     return &*Itr;
2867   return nullptr;
2868 }
2869 
2870 // Check if there is a field shadowing.
2871 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2872                                       DeclarationName FieldName,
2873                                       const CXXRecordDecl *RD,
2874                                       bool DeclIsField) {
2875   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2876     return;
2877 
2878   // To record a shadowed field in a base
2879   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2880   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2881                            CXXBasePath &Path) {
2882     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2883     // Record an ambiguous path directly
2884     if (Bases.find(Base) != Bases.end())
2885       return true;
2886     for (const auto Field : Base->lookup(FieldName)) {
2887       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2888           Field->getAccess() != AS_private) {
2889         assert(Field->getAccess() != AS_none);
2890         assert(Bases.find(Base) == Bases.end());
2891         Bases[Base] = Field;
2892         return true;
2893       }
2894     }
2895     return false;
2896   };
2897 
2898   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2899                      /*DetectVirtual=*/true);
2900   if (!RD->lookupInBases(FieldShadowed, Paths))
2901     return;
2902 
2903   for (const auto &P : Paths) {
2904     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2905     auto It = Bases.find(Base);
2906     // Skip duplicated bases
2907     if (It == Bases.end())
2908       continue;
2909     auto BaseField = It->second;
2910     assert(BaseField->getAccess() != AS_private);
2911     if (AS_none !=
2912         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2913       Diag(Loc, diag::warn_shadow_field)
2914         << FieldName << RD << Base << DeclIsField;
2915       Diag(BaseField->getLocation(), diag::note_shadow_field);
2916       Bases.erase(It);
2917     }
2918   }
2919 }
2920 
2921 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2922 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2923 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2924 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2925 /// present (but parsing it has been deferred).
2926 NamedDecl *
2927 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2928                                MultiTemplateParamsArg TemplateParameterLists,
2929                                Expr *BW, const VirtSpecifiers &VS,
2930                                InClassInitStyle InitStyle) {
2931   const DeclSpec &DS = D.getDeclSpec();
2932   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2933   DeclarationName Name = NameInfo.getName();
2934   SourceLocation Loc = NameInfo.getLoc();
2935 
2936   // For anonymous bitfields, the location should point to the type.
2937   if (Loc.isInvalid())
2938     Loc = D.getBeginLoc();
2939 
2940   Expr *BitWidth = static_cast<Expr*>(BW);
2941 
2942   assert(isa<CXXRecordDecl>(CurContext));
2943   assert(!DS.isFriendSpecified());
2944 
2945   bool isFunc = D.isDeclarationOfFunction();
2946   const ParsedAttr *MSPropertyAttr =
2947       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2948 
2949   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2950     // The Microsoft extension __interface only permits public member functions
2951     // and prohibits constructors, destructors, operators, non-public member
2952     // functions, static methods and data members.
2953     unsigned InvalidDecl;
2954     bool ShowDeclName = true;
2955     if (!isFunc &&
2956         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2957       InvalidDecl = 0;
2958     else if (!isFunc)
2959       InvalidDecl = 1;
2960     else if (AS != AS_public)
2961       InvalidDecl = 2;
2962     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2963       InvalidDecl = 3;
2964     else switch (Name.getNameKind()) {
2965       case DeclarationName::CXXConstructorName:
2966         InvalidDecl = 4;
2967         ShowDeclName = false;
2968         break;
2969 
2970       case DeclarationName::CXXDestructorName:
2971         InvalidDecl = 5;
2972         ShowDeclName = false;
2973         break;
2974 
2975       case DeclarationName::CXXOperatorName:
2976       case DeclarationName::CXXConversionFunctionName:
2977         InvalidDecl = 6;
2978         break;
2979 
2980       default:
2981         InvalidDecl = 0;
2982         break;
2983     }
2984 
2985     if (InvalidDecl) {
2986       if (ShowDeclName)
2987         Diag(Loc, diag::err_invalid_member_in_interface)
2988           << (InvalidDecl-1) << Name;
2989       else
2990         Diag(Loc, diag::err_invalid_member_in_interface)
2991           << (InvalidDecl-1) << "";
2992       return nullptr;
2993     }
2994   }
2995 
2996   // C++ 9.2p6: A member shall not be declared to have automatic storage
2997   // duration (auto, register) or with the extern storage-class-specifier.
2998   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2999   // data members and cannot be applied to names declared const or static,
3000   // and cannot be applied to reference members.
3001   switch (DS.getStorageClassSpec()) {
3002   case DeclSpec::SCS_unspecified:
3003   case DeclSpec::SCS_typedef:
3004   case DeclSpec::SCS_static:
3005     break;
3006   case DeclSpec::SCS_mutable:
3007     if (isFunc) {
3008       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3009 
3010       // FIXME: It would be nicer if the keyword was ignored only for this
3011       // declarator. Otherwise we could get follow-up errors.
3012       D.getMutableDeclSpec().ClearStorageClassSpecs();
3013     }
3014     break;
3015   default:
3016     Diag(DS.getStorageClassSpecLoc(),
3017          diag::err_storageclass_invalid_for_member);
3018     D.getMutableDeclSpec().ClearStorageClassSpecs();
3019     break;
3020   }
3021 
3022   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3023                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3024                       !isFunc);
3025 
3026   if (DS.isConstexprSpecified() && isInstField) {
3027     SemaDiagnosticBuilder B =
3028         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3029     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3030     if (InitStyle == ICIS_NoInit) {
3031       B << 0 << 0;
3032       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3033         B << FixItHint::CreateRemoval(ConstexprLoc);
3034       else {
3035         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3036         D.getMutableDeclSpec().ClearConstexprSpec();
3037         const char *PrevSpec;
3038         unsigned DiagID;
3039         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3040             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3041         (void)Failed;
3042         assert(!Failed && "Making a constexpr member const shouldn't fail");
3043       }
3044     } else {
3045       B << 1;
3046       const char *PrevSpec;
3047       unsigned DiagID;
3048       if (D.getMutableDeclSpec().SetStorageClassSpec(
3049           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3050           Context.getPrintingPolicy())) {
3051         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3052                "This is the only DeclSpec that should fail to be applied");
3053         B << 1;
3054       } else {
3055         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3056         isInstField = false;
3057       }
3058     }
3059   }
3060 
3061   NamedDecl *Member;
3062   if (isInstField) {
3063     CXXScopeSpec &SS = D.getCXXScopeSpec();
3064 
3065     // Data members must have identifiers for names.
3066     if (!Name.isIdentifier()) {
3067       Diag(Loc, diag::err_bad_variable_name)
3068         << Name;
3069       return nullptr;
3070     }
3071 
3072     IdentifierInfo *II = Name.getAsIdentifierInfo();
3073 
3074     // Member field could not be with "template" keyword.
3075     // So TemplateParameterLists should be empty in this case.
3076     if (TemplateParameterLists.size()) {
3077       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3078       if (TemplateParams->size()) {
3079         // There is no such thing as a member field template.
3080         Diag(D.getIdentifierLoc(), diag::err_template_member)
3081             << II
3082             << SourceRange(TemplateParams->getTemplateLoc(),
3083                 TemplateParams->getRAngleLoc());
3084       } else {
3085         // There is an extraneous 'template<>' for this member.
3086         Diag(TemplateParams->getTemplateLoc(),
3087             diag::err_template_member_noparams)
3088             << II
3089             << SourceRange(TemplateParams->getTemplateLoc(),
3090                 TemplateParams->getRAngleLoc());
3091       }
3092       return nullptr;
3093     }
3094 
3095     if (SS.isSet() && !SS.isInvalid()) {
3096       // The user provided a superfluous scope specifier inside a class
3097       // definition:
3098       //
3099       // class X {
3100       //   int X::member;
3101       // };
3102       if (DeclContext *DC = computeDeclContext(SS, false))
3103         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3104                                      D.getName().getKind() ==
3105                                          UnqualifiedIdKind::IK_TemplateId);
3106       else
3107         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3108           << Name << SS.getRange();
3109 
3110       SS.clear();
3111     }
3112 
3113     if (MSPropertyAttr) {
3114       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3115                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3116       if (!Member)
3117         return nullptr;
3118       isInstField = false;
3119     } else {
3120       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3121                                 BitWidth, InitStyle, AS);
3122       if (!Member)
3123         return nullptr;
3124     }
3125 
3126     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3127   } else {
3128     Member = HandleDeclarator(S, D, TemplateParameterLists);
3129     if (!Member)
3130       return nullptr;
3131 
3132     // Non-instance-fields can't have a bitfield.
3133     if (BitWidth) {
3134       if (Member->isInvalidDecl()) {
3135         // don't emit another diagnostic.
3136       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3137         // C++ 9.6p3: A bit-field shall not be a static member.
3138         // "static member 'A' cannot be a bit-field"
3139         Diag(Loc, diag::err_static_not_bitfield)
3140           << Name << BitWidth->getSourceRange();
3141       } else if (isa<TypedefDecl>(Member)) {
3142         // "typedef member 'x' cannot be a bit-field"
3143         Diag(Loc, diag::err_typedef_not_bitfield)
3144           << Name << BitWidth->getSourceRange();
3145       } else {
3146         // A function typedef ("typedef int f(); f a;").
3147         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3148         Diag(Loc, diag::err_not_integral_type_bitfield)
3149           << Name << cast<ValueDecl>(Member)->getType()
3150           << BitWidth->getSourceRange();
3151       }
3152 
3153       BitWidth = nullptr;
3154       Member->setInvalidDecl();
3155     }
3156 
3157     NamedDecl *NonTemplateMember = Member;
3158     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3159       NonTemplateMember = FunTmpl->getTemplatedDecl();
3160     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3161       NonTemplateMember = VarTmpl->getTemplatedDecl();
3162 
3163     Member->setAccess(AS);
3164 
3165     // If we have declared a member function template or static data member
3166     // template, set the access of the templated declaration as well.
3167     if (NonTemplateMember != Member)
3168       NonTemplateMember->setAccess(AS);
3169 
3170     // C++ [temp.deduct.guide]p3:
3171     //   A deduction guide [...] for a member class template [shall be
3172     //   declared] with the same access [as the template].
3173     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3174       auto *TD = DG->getDeducedTemplate();
3175       if (AS != TD->getAccess()) {
3176         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3177         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3178             << TD->getAccess();
3179         const AccessSpecDecl *LastAccessSpec = nullptr;
3180         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3181           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3182             LastAccessSpec = AccessSpec;
3183         }
3184         assert(LastAccessSpec && "differing access with no access specifier");
3185         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3186             << AS;
3187       }
3188     }
3189   }
3190 
3191   if (VS.isOverrideSpecified())
3192     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3193   if (VS.isFinalSpecified())
3194     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3195                                             VS.isFinalSpelledSealed()));
3196 
3197   if (VS.getLastLocation().isValid()) {
3198     // Update the end location of a method that has a virt-specifiers.
3199     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3200       MD->setRangeEnd(VS.getLastLocation());
3201   }
3202 
3203   CheckOverrideControl(Member);
3204 
3205   assert((Name || isInstField) && "No identifier for non-field ?");
3206 
3207   if (isInstField) {
3208     FieldDecl *FD = cast<FieldDecl>(Member);
3209     FieldCollector->Add(FD);
3210 
3211     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3212       // Remember all explicit private FieldDecls that have a name, no side
3213       // effects and are not part of a dependent type declaration.
3214       if (!FD->isImplicit() && FD->getDeclName() &&
3215           FD->getAccess() == AS_private &&
3216           !FD->hasAttr<UnusedAttr>() &&
3217           !FD->getParent()->isDependentContext() &&
3218           !InitializationHasSideEffects(*FD))
3219         UnusedPrivateFields.insert(FD);
3220     }
3221   }
3222 
3223   return Member;
3224 }
3225 
3226 namespace {
3227   class UninitializedFieldVisitor
3228       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3229     Sema &S;
3230     // List of Decls to generate a warning on.  Also remove Decls that become
3231     // initialized.
3232     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3233     // List of base classes of the record.  Classes are removed after their
3234     // initializers.
3235     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3236     // Vector of decls to be removed from the Decl set prior to visiting the
3237     // nodes.  These Decls may have been initialized in the prior initializer.
3238     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3239     // If non-null, add a note to the warning pointing back to the constructor.
3240     const CXXConstructorDecl *Constructor;
3241     // Variables to hold state when processing an initializer list.  When
3242     // InitList is true, special case initialization of FieldDecls matching
3243     // InitListFieldDecl.
3244     bool InitList;
3245     FieldDecl *InitListFieldDecl;
3246     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3247 
3248   public:
3249     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3250     UninitializedFieldVisitor(Sema &S,
3251                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3252                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3253       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3254         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3255 
3256     // Returns true if the use of ME is not an uninitialized use.
3257     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3258                                          bool CheckReferenceOnly) {
3259       llvm::SmallVector<FieldDecl*, 4> Fields;
3260       bool ReferenceField = false;
3261       while (ME) {
3262         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3263         if (!FD)
3264           return false;
3265         Fields.push_back(FD);
3266         if (FD->getType()->isReferenceType())
3267           ReferenceField = true;
3268         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3269       }
3270 
3271       // Binding a reference to an uninitialized field is not an
3272       // uninitialized use.
3273       if (CheckReferenceOnly && !ReferenceField)
3274         return true;
3275 
3276       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3277       // Discard the first field since it is the field decl that is being
3278       // initialized.
3279       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3280         UsedFieldIndex.push_back((*I)->getFieldIndex());
3281       }
3282 
3283       for (auto UsedIter = UsedFieldIndex.begin(),
3284                 UsedEnd = UsedFieldIndex.end(),
3285                 OrigIter = InitFieldIndex.begin(),
3286                 OrigEnd = InitFieldIndex.end();
3287            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3288         if (*UsedIter < *OrigIter)
3289           return true;
3290         if (*UsedIter > *OrigIter)
3291           break;
3292       }
3293 
3294       return false;
3295     }
3296 
3297     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3298                           bool AddressOf) {
3299       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3300         return;
3301 
3302       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3303       // or union.
3304       MemberExpr *FieldME = ME;
3305 
3306       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3307 
3308       Expr *Base = ME;
3309       while (MemberExpr *SubME =
3310                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3311 
3312         if (isa<VarDecl>(SubME->getMemberDecl()))
3313           return;
3314 
3315         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3316           if (!FD->isAnonymousStructOrUnion())
3317             FieldME = SubME;
3318 
3319         if (!FieldME->getType().isPODType(S.Context))
3320           AllPODFields = false;
3321 
3322         Base = SubME->getBase();
3323       }
3324 
3325       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3326         return;
3327 
3328       if (AddressOf && AllPODFields)
3329         return;
3330 
3331       ValueDecl* FoundVD = FieldME->getMemberDecl();
3332 
3333       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3334         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3335           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3336         }
3337 
3338         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3339           QualType T = BaseCast->getType();
3340           if (T->isPointerType() &&
3341               BaseClasses.count(T->getPointeeType())) {
3342             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3343                 << T->getPointeeType() << FoundVD;
3344           }
3345         }
3346       }
3347 
3348       if (!Decls.count(FoundVD))
3349         return;
3350 
3351       const bool IsReference = FoundVD->getType()->isReferenceType();
3352 
3353       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3354         // Special checking for initializer lists.
3355         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3356           return;
3357         }
3358       } else {
3359         // Prevent double warnings on use of unbounded references.
3360         if (CheckReferenceOnly && !IsReference)
3361           return;
3362       }
3363 
3364       unsigned diag = IsReference
3365           ? diag::warn_reference_field_is_uninit
3366           : diag::warn_field_is_uninit;
3367       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3368       if (Constructor)
3369         S.Diag(Constructor->getLocation(),
3370                diag::note_uninit_in_this_constructor)
3371           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3372 
3373     }
3374 
3375     void HandleValue(Expr *E, bool AddressOf) {
3376       E = E->IgnoreParens();
3377 
3378       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3379         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3380                          AddressOf /*AddressOf*/);
3381         return;
3382       }
3383 
3384       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3385         Visit(CO->getCond());
3386         HandleValue(CO->getTrueExpr(), AddressOf);
3387         HandleValue(CO->getFalseExpr(), AddressOf);
3388         return;
3389       }
3390 
3391       if (BinaryConditionalOperator *BCO =
3392               dyn_cast<BinaryConditionalOperator>(E)) {
3393         Visit(BCO->getCond());
3394         HandleValue(BCO->getFalseExpr(), AddressOf);
3395         return;
3396       }
3397 
3398       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3399         HandleValue(OVE->getSourceExpr(), AddressOf);
3400         return;
3401       }
3402 
3403       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3404         switch (BO->getOpcode()) {
3405         default:
3406           break;
3407         case(BO_PtrMemD):
3408         case(BO_PtrMemI):
3409           HandleValue(BO->getLHS(), AddressOf);
3410           Visit(BO->getRHS());
3411           return;
3412         case(BO_Comma):
3413           Visit(BO->getLHS());
3414           HandleValue(BO->getRHS(), AddressOf);
3415           return;
3416         }
3417       }
3418 
3419       Visit(E);
3420     }
3421 
3422     void CheckInitListExpr(InitListExpr *ILE) {
3423       InitFieldIndex.push_back(0);
3424       for (auto Child : ILE->children()) {
3425         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3426           CheckInitListExpr(SubList);
3427         } else {
3428           Visit(Child);
3429         }
3430         ++InitFieldIndex.back();
3431       }
3432       InitFieldIndex.pop_back();
3433     }
3434 
3435     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3436                           FieldDecl *Field, const Type *BaseClass) {
3437       // Remove Decls that may have been initialized in the previous
3438       // initializer.
3439       for (ValueDecl* VD : DeclsToRemove)
3440         Decls.erase(VD);
3441       DeclsToRemove.clear();
3442 
3443       Constructor = FieldConstructor;
3444       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3445 
3446       if (ILE && Field) {
3447         InitList = true;
3448         InitListFieldDecl = Field;
3449         InitFieldIndex.clear();
3450         CheckInitListExpr(ILE);
3451       } else {
3452         InitList = false;
3453         Visit(E);
3454       }
3455 
3456       if (Field)
3457         Decls.erase(Field);
3458       if (BaseClass)
3459         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3460     }
3461 
3462     void VisitMemberExpr(MemberExpr *ME) {
3463       // All uses of unbounded reference fields will warn.
3464       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3465     }
3466 
3467     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3468       if (E->getCastKind() == CK_LValueToRValue) {
3469         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3470         return;
3471       }
3472 
3473       Inherited::VisitImplicitCastExpr(E);
3474     }
3475 
3476     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3477       if (E->getConstructor()->isCopyConstructor()) {
3478         Expr *ArgExpr = E->getArg(0);
3479         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3480           if (ILE->getNumInits() == 1)
3481             ArgExpr = ILE->getInit(0);
3482         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3483           if (ICE->getCastKind() == CK_NoOp)
3484             ArgExpr = ICE->getSubExpr();
3485         HandleValue(ArgExpr, false /*AddressOf*/);
3486         return;
3487       }
3488       Inherited::VisitCXXConstructExpr(E);
3489     }
3490 
3491     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3492       Expr *Callee = E->getCallee();
3493       if (isa<MemberExpr>(Callee)) {
3494         HandleValue(Callee, false /*AddressOf*/);
3495         for (auto Arg : E->arguments())
3496           Visit(Arg);
3497         return;
3498       }
3499 
3500       Inherited::VisitCXXMemberCallExpr(E);
3501     }
3502 
3503     void VisitCallExpr(CallExpr *E) {
3504       // Treat std::move as a use.
3505       if (E->isCallToStdMove()) {
3506         HandleValue(E->getArg(0), /*AddressOf=*/false);
3507         return;
3508       }
3509 
3510       Inherited::VisitCallExpr(E);
3511     }
3512 
3513     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3514       Expr *Callee = E->getCallee();
3515 
3516       if (isa<UnresolvedLookupExpr>(Callee))
3517         return Inherited::VisitCXXOperatorCallExpr(E);
3518 
3519       Visit(Callee);
3520       for (auto Arg : E->arguments())
3521         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3522     }
3523 
3524     void VisitBinaryOperator(BinaryOperator *E) {
3525       // If a field assignment is detected, remove the field from the
3526       // uninitiailized field set.
3527       if (E->getOpcode() == BO_Assign)
3528         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3529           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3530             if (!FD->getType()->isReferenceType())
3531               DeclsToRemove.push_back(FD);
3532 
3533       if (E->isCompoundAssignmentOp()) {
3534         HandleValue(E->getLHS(), false /*AddressOf*/);
3535         Visit(E->getRHS());
3536         return;
3537       }
3538 
3539       Inherited::VisitBinaryOperator(E);
3540     }
3541 
3542     void VisitUnaryOperator(UnaryOperator *E) {
3543       if (E->isIncrementDecrementOp()) {
3544         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3545         return;
3546       }
3547       if (E->getOpcode() == UO_AddrOf) {
3548         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3549           HandleValue(ME->getBase(), true /*AddressOf*/);
3550           return;
3551         }
3552       }
3553 
3554       Inherited::VisitUnaryOperator(E);
3555     }
3556   };
3557 
3558   // Diagnose value-uses of fields to initialize themselves, e.g.
3559   //   foo(foo)
3560   // where foo is not also a parameter to the constructor.
3561   // Also diagnose across field uninitialized use such as
3562   //   x(y), y(x)
3563   // TODO: implement -Wuninitialized and fold this into that framework.
3564   static void DiagnoseUninitializedFields(
3565       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3566 
3567     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3568                                            Constructor->getLocation())) {
3569       return;
3570     }
3571 
3572     if (Constructor->isInvalidDecl())
3573       return;
3574 
3575     const CXXRecordDecl *RD = Constructor->getParent();
3576 
3577     if (RD->getDescribedClassTemplate())
3578       return;
3579 
3580     // Holds fields that are uninitialized.
3581     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3582 
3583     // At the beginning, all fields are uninitialized.
3584     for (auto *I : RD->decls()) {
3585       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3586         UninitializedFields.insert(FD);
3587       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3588         UninitializedFields.insert(IFD->getAnonField());
3589       }
3590     }
3591 
3592     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3593     for (auto I : RD->bases())
3594       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3595 
3596     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3597       return;
3598 
3599     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3600                                                    UninitializedFields,
3601                                                    UninitializedBaseClasses);
3602 
3603     for (const auto *FieldInit : Constructor->inits()) {
3604       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3605         break;
3606 
3607       Expr *InitExpr = FieldInit->getInit();
3608       if (!InitExpr)
3609         continue;
3610 
3611       if (CXXDefaultInitExpr *Default =
3612               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3613         InitExpr = Default->getExpr();
3614         if (!InitExpr)
3615           continue;
3616         // In class initializers will point to the constructor.
3617         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3618                                               FieldInit->getAnyMember(),
3619                                               FieldInit->getBaseClass());
3620       } else {
3621         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3622                                               FieldInit->getAnyMember(),
3623                                               FieldInit->getBaseClass());
3624       }
3625     }
3626   }
3627 } // namespace
3628 
3629 /// Enter a new C++ default initializer scope. After calling this, the
3630 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3631 /// parsing or instantiating the initializer failed.
3632 void Sema::ActOnStartCXXInClassMemberInitializer() {
3633   // Create a synthetic function scope to represent the call to the constructor
3634   // that notionally surrounds a use of this initializer.
3635   PushFunctionScope();
3636 }
3637 
3638 /// This is invoked after parsing an in-class initializer for a
3639 /// non-static C++ class member, and after instantiating an in-class initializer
3640 /// in a class template. Such actions are deferred until the class is complete.
3641 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3642                                                   SourceLocation InitLoc,
3643                                                   Expr *InitExpr) {
3644   // Pop the notional constructor scope we created earlier.
3645   PopFunctionScopeInfo(nullptr, D);
3646 
3647   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3648   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3649          "must set init style when field is created");
3650 
3651   if (!InitExpr) {
3652     D->setInvalidDecl();
3653     if (FD)
3654       FD->removeInClassInitializer();
3655     return;
3656   }
3657 
3658   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3659     FD->setInvalidDecl();
3660     FD->removeInClassInitializer();
3661     return;
3662   }
3663 
3664   ExprResult Init = InitExpr;
3665   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3666     InitializedEntity Entity =
3667         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3668     InitializationKind Kind =
3669         FD->getInClassInitStyle() == ICIS_ListInit
3670             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3671                                                    InitExpr->getBeginLoc(),
3672                                                    InitExpr->getEndLoc())
3673             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3674     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3675     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3676     if (Init.isInvalid()) {
3677       FD->setInvalidDecl();
3678       return;
3679     }
3680   }
3681 
3682   // C++11 [class.base.init]p7:
3683   //   The initialization of each base and member constitutes a
3684   //   full-expression.
3685   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3686   if (Init.isInvalid()) {
3687     FD->setInvalidDecl();
3688     return;
3689   }
3690 
3691   InitExpr = Init.get();
3692 
3693   FD->setInClassInitializer(InitExpr);
3694 }
3695 
3696 /// Find the direct and/or virtual base specifiers that
3697 /// correspond to the given base type, for use in base initialization
3698 /// within a constructor.
3699 static bool FindBaseInitializer(Sema &SemaRef,
3700                                 CXXRecordDecl *ClassDecl,
3701                                 QualType BaseType,
3702                                 const CXXBaseSpecifier *&DirectBaseSpec,
3703                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3704   // First, check for a direct base class.
3705   DirectBaseSpec = nullptr;
3706   for (const auto &Base : ClassDecl->bases()) {
3707     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3708       // We found a direct base of this type. That's what we're
3709       // initializing.
3710       DirectBaseSpec = &Base;
3711       break;
3712     }
3713   }
3714 
3715   // Check for a virtual base class.
3716   // FIXME: We might be able to short-circuit this if we know in advance that
3717   // there are no virtual bases.
3718   VirtualBaseSpec = nullptr;
3719   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3720     // We haven't found a base yet; search the class hierarchy for a
3721     // virtual base class.
3722     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3723                        /*DetectVirtual=*/false);
3724     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3725                               SemaRef.Context.getTypeDeclType(ClassDecl),
3726                               BaseType, Paths)) {
3727       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3728            Path != Paths.end(); ++Path) {
3729         if (Path->back().Base->isVirtual()) {
3730           VirtualBaseSpec = Path->back().Base;
3731           break;
3732         }
3733       }
3734     }
3735   }
3736 
3737   return DirectBaseSpec || VirtualBaseSpec;
3738 }
3739 
3740 /// Handle a C++ member initializer using braced-init-list syntax.
3741 MemInitResult
3742 Sema::ActOnMemInitializer(Decl *ConstructorD,
3743                           Scope *S,
3744                           CXXScopeSpec &SS,
3745                           IdentifierInfo *MemberOrBase,
3746                           ParsedType TemplateTypeTy,
3747                           const DeclSpec &DS,
3748                           SourceLocation IdLoc,
3749                           Expr *InitList,
3750                           SourceLocation EllipsisLoc) {
3751   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3752                              DS, IdLoc, InitList,
3753                              EllipsisLoc);
3754 }
3755 
3756 /// Handle a C++ member initializer using parentheses syntax.
3757 MemInitResult
3758 Sema::ActOnMemInitializer(Decl *ConstructorD,
3759                           Scope *S,
3760                           CXXScopeSpec &SS,
3761                           IdentifierInfo *MemberOrBase,
3762                           ParsedType TemplateTypeTy,
3763                           const DeclSpec &DS,
3764                           SourceLocation IdLoc,
3765                           SourceLocation LParenLoc,
3766                           ArrayRef<Expr *> Args,
3767                           SourceLocation RParenLoc,
3768                           SourceLocation EllipsisLoc) {
3769   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3770   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3771                              DS, IdLoc, List, EllipsisLoc);
3772 }
3773 
3774 namespace {
3775 
3776 // Callback to only accept typo corrections that can be a valid C++ member
3777 // intializer: either a non-static field member or a base class.
3778 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3779 public:
3780   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3781       : ClassDecl(ClassDecl) {}
3782 
3783   bool ValidateCandidate(const TypoCorrection &candidate) override {
3784     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3785       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3786         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3787       return isa<TypeDecl>(ND);
3788     }
3789     return false;
3790   }
3791 
3792 private:
3793   CXXRecordDecl *ClassDecl;
3794 };
3795 
3796 }
3797 
3798 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3799                                              CXXScopeSpec &SS,
3800                                              ParsedType TemplateTypeTy,
3801                                              IdentifierInfo *MemberOrBase) {
3802   if (SS.getScopeRep() || TemplateTypeTy)
3803     return nullptr;
3804   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3805   if (Result.empty())
3806     return nullptr;
3807   ValueDecl *Member;
3808   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3809       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3810     return Member;
3811   return nullptr;
3812 }
3813 
3814 /// Handle a C++ member initializer.
3815 MemInitResult
3816 Sema::BuildMemInitializer(Decl *ConstructorD,
3817                           Scope *S,
3818                           CXXScopeSpec &SS,
3819                           IdentifierInfo *MemberOrBase,
3820                           ParsedType TemplateTypeTy,
3821                           const DeclSpec &DS,
3822                           SourceLocation IdLoc,
3823                           Expr *Init,
3824                           SourceLocation EllipsisLoc) {
3825   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3826   if (!Res.isUsable())
3827     return true;
3828   Init = Res.get();
3829 
3830   if (!ConstructorD)
3831     return true;
3832 
3833   AdjustDeclIfTemplate(ConstructorD);
3834 
3835   CXXConstructorDecl *Constructor
3836     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3837   if (!Constructor) {
3838     // The user wrote a constructor initializer on a function that is
3839     // not a C++ constructor. Ignore the error for now, because we may
3840     // have more member initializers coming; we'll diagnose it just
3841     // once in ActOnMemInitializers.
3842     return true;
3843   }
3844 
3845   CXXRecordDecl *ClassDecl = Constructor->getParent();
3846 
3847   // C++ [class.base.init]p2:
3848   //   Names in a mem-initializer-id are looked up in the scope of the
3849   //   constructor's class and, if not found in that scope, are looked
3850   //   up in the scope containing the constructor's definition.
3851   //   [Note: if the constructor's class contains a member with the
3852   //   same name as a direct or virtual base class of the class, a
3853   //   mem-initializer-id naming the member or base class and composed
3854   //   of a single identifier refers to the class member. A
3855   //   mem-initializer-id for the hidden base class may be specified
3856   //   using a qualified name. ]
3857 
3858   // Look for a member, first.
3859   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3860           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3861     if (EllipsisLoc.isValid())
3862       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3863           << MemberOrBase
3864           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3865 
3866     return BuildMemberInitializer(Member, Init, IdLoc);
3867   }
3868   // It didn't name a member, so see if it names a class.
3869   QualType BaseType;
3870   TypeSourceInfo *TInfo = nullptr;
3871 
3872   if (TemplateTypeTy) {
3873     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3874   } else if (DS.getTypeSpecType() == TST_decltype) {
3875     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3876   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3877     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3878     return true;
3879   } else {
3880     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3881     LookupParsedName(R, S, &SS);
3882 
3883     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3884     if (!TyD) {
3885       if (R.isAmbiguous()) return true;
3886 
3887       // We don't want access-control diagnostics here.
3888       R.suppressDiagnostics();
3889 
3890       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3891         bool NotUnknownSpecialization = false;
3892         DeclContext *DC = computeDeclContext(SS, false);
3893         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3894           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3895 
3896         if (!NotUnknownSpecialization) {
3897           // When the scope specifier can refer to a member of an unknown
3898           // specialization, we take it as a type name.
3899           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3900                                        SS.getWithLocInContext(Context),
3901                                        *MemberOrBase, IdLoc);
3902           if (BaseType.isNull())
3903             return true;
3904 
3905           TInfo = Context.CreateTypeSourceInfo(BaseType);
3906           DependentNameTypeLoc TL =
3907               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3908           if (!TL.isNull()) {
3909             TL.setNameLoc(IdLoc);
3910             TL.setElaboratedKeywordLoc(SourceLocation());
3911             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3912           }
3913 
3914           R.clear();
3915           R.setLookupName(MemberOrBase);
3916         }
3917       }
3918 
3919       // If no results were found, try to correct typos.
3920       TypoCorrection Corr;
3921       if (R.empty() && BaseType.isNull() &&
3922           (Corr = CorrectTypo(
3923                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3924                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3925                CTK_ErrorRecovery, ClassDecl))) {
3926         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3927           // We have found a non-static data member with a similar
3928           // name to what was typed; complain and initialize that
3929           // member.
3930           diagnoseTypo(Corr,
3931                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3932                          << MemberOrBase << true);
3933           return BuildMemberInitializer(Member, Init, IdLoc);
3934         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3935           const CXXBaseSpecifier *DirectBaseSpec;
3936           const CXXBaseSpecifier *VirtualBaseSpec;
3937           if (FindBaseInitializer(*this, ClassDecl,
3938                                   Context.getTypeDeclType(Type),
3939                                   DirectBaseSpec, VirtualBaseSpec)) {
3940             // We have found a direct or virtual base class with a
3941             // similar name to what was typed; complain and initialize
3942             // that base class.
3943             diagnoseTypo(Corr,
3944                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3945                            << MemberOrBase << false,
3946                          PDiag() /*Suppress note, we provide our own.*/);
3947 
3948             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3949                                                               : VirtualBaseSpec;
3950             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3951                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3952 
3953             TyD = Type;
3954           }
3955         }
3956       }
3957 
3958       if (!TyD && BaseType.isNull()) {
3959         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3960           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3961         return true;
3962       }
3963     }
3964 
3965     if (BaseType.isNull()) {
3966       BaseType = Context.getTypeDeclType(TyD);
3967       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3968       if (SS.isSet()) {
3969         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3970                                              BaseType);
3971         TInfo = Context.CreateTypeSourceInfo(BaseType);
3972         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3973         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3974         TL.setElaboratedKeywordLoc(SourceLocation());
3975         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3976       }
3977     }
3978   }
3979 
3980   if (!TInfo)
3981     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3982 
3983   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3984 }
3985 
3986 MemInitResult
3987 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3988                              SourceLocation IdLoc) {
3989   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3990   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3991   assert((DirectMember || IndirectMember) &&
3992          "Member must be a FieldDecl or IndirectFieldDecl");
3993 
3994   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3995     return true;
3996 
3997   if (Member->isInvalidDecl())
3998     return true;
3999 
4000   MultiExprArg Args;
4001   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4002     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4003   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4004     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4005   } else {
4006     // Template instantiation doesn't reconstruct ParenListExprs for us.
4007     Args = Init;
4008   }
4009 
4010   SourceRange InitRange = Init->getSourceRange();
4011 
4012   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4013     // Can't check initialization for a member of dependent type or when
4014     // any of the arguments are type-dependent expressions.
4015     DiscardCleanupsInEvaluationContext();
4016   } else {
4017     bool InitList = false;
4018     if (isa<InitListExpr>(Init)) {
4019       InitList = true;
4020       Args = Init;
4021     }
4022 
4023     // Initialize the member.
4024     InitializedEntity MemberEntity =
4025       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4026                    : InitializedEntity::InitializeMember(IndirectMember,
4027                                                          nullptr);
4028     InitializationKind Kind =
4029         InitList ? InitializationKind::CreateDirectList(
4030                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4031                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4032                                                     InitRange.getEnd());
4033 
4034     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4035     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4036                                             nullptr);
4037     if (MemberInit.isInvalid())
4038       return true;
4039 
4040     // C++11 [class.base.init]p7:
4041     //   The initialization of each base and member constitutes a
4042     //   full-expression.
4043     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4044                                      /*DiscardedValue*/ false);
4045     if (MemberInit.isInvalid())
4046       return true;
4047 
4048     Init = MemberInit.get();
4049   }
4050 
4051   if (DirectMember) {
4052     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4053                                             InitRange.getBegin(), Init,
4054                                             InitRange.getEnd());
4055   } else {
4056     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4057                                             InitRange.getBegin(), Init,
4058                                             InitRange.getEnd());
4059   }
4060 }
4061 
4062 MemInitResult
4063 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4064                                  CXXRecordDecl *ClassDecl) {
4065   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4066   if (!LangOpts.CPlusPlus11)
4067     return Diag(NameLoc, diag::err_delegating_ctor)
4068       << TInfo->getTypeLoc().getLocalSourceRange();
4069   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4070 
4071   bool InitList = true;
4072   MultiExprArg Args = Init;
4073   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4074     InitList = false;
4075     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4076   }
4077 
4078   SourceRange InitRange = Init->getSourceRange();
4079   // Initialize the object.
4080   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4081                                      QualType(ClassDecl->getTypeForDecl(), 0));
4082   InitializationKind Kind =
4083       InitList ? InitializationKind::CreateDirectList(
4084                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4085                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4086                                                   InitRange.getEnd());
4087   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4088   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4089                                               Args, nullptr);
4090   if (DelegationInit.isInvalid())
4091     return true;
4092 
4093   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4094          "Delegating constructor with no target?");
4095 
4096   // C++11 [class.base.init]p7:
4097   //   The initialization of each base and member constitutes a
4098   //   full-expression.
4099   DelegationInit = ActOnFinishFullExpr(
4100       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4101   if (DelegationInit.isInvalid())
4102     return true;
4103 
4104   // If we are in a dependent context, template instantiation will
4105   // perform this type-checking again. Just save the arguments that we
4106   // received in a ParenListExpr.
4107   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4108   // of the information that we have about the base
4109   // initializer. However, deconstructing the ASTs is a dicey process,
4110   // and this approach is far more likely to get the corner cases right.
4111   if (CurContext->isDependentContext())
4112     DelegationInit = Init;
4113 
4114   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4115                                           DelegationInit.getAs<Expr>(),
4116                                           InitRange.getEnd());
4117 }
4118 
4119 MemInitResult
4120 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4121                            Expr *Init, CXXRecordDecl *ClassDecl,
4122                            SourceLocation EllipsisLoc) {
4123   SourceLocation BaseLoc
4124     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4125 
4126   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4127     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4128              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4129 
4130   // C++ [class.base.init]p2:
4131   //   [...] Unless the mem-initializer-id names a nonstatic data
4132   //   member of the constructor's class or a direct or virtual base
4133   //   of that class, the mem-initializer is ill-formed. A
4134   //   mem-initializer-list can initialize a base class using any
4135   //   name that denotes that base class type.
4136   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4137 
4138   SourceRange InitRange = Init->getSourceRange();
4139   if (EllipsisLoc.isValid()) {
4140     // This is a pack expansion.
4141     if (!BaseType->containsUnexpandedParameterPack())  {
4142       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4143         << SourceRange(BaseLoc, InitRange.getEnd());
4144 
4145       EllipsisLoc = SourceLocation();
4146     }
4147   } else {
4148     // Check for any unexpanded parameter packs.
4149     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4150       return true;
4151 
4152     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4153       return true;
4154   }
4155 
4156   // Check for direct and virtual base classes.
4157   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4158   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4159   if (!Dependent) {
4160     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4161                                        BaseType))
4162       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4163 
4164     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4165                         VirtualBaseSpec);
4166 
4167     // C++ [base.class.init]p2:
4168     // Unless the mem-initializer-id names a nonstatic data member of the
4169     // constructor's class or a direct or virtual base of that class, the
4170     // mem-initializer is ill-formed.
4171     if (!DirectBaseSpec && !VirtualBaseSpec) {
4172       // If the class has any dependent bases, then it's possible that
4173       // one of those types will resolve to the same type as
4174       // BaseType. Therefore, just treat this as a dependent base
4175       // class initialization.  FIXME: Should we try to check the
4176       // initialization anyway? It seems odd.
4177       if (ClassDecl->hasAnyDependentBases())
4178         Dependent = true;
4179       else
4180         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4181           << BaseType << Context.getTypeDeclType(ClassDecl)
4182           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4183     }
4184   }
4185 
4186   if (Dependent) {
4187     DiscardCleanupsInEvaluationContext();
4188 
4189     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4190                                             /*IsVirtual=*/false,
4191                                             InitRange.getBegin(), Init,
4192                                             InitRange.getEnd(), EllipsisLoc);
4193   }
4194 
4195   // C++ [base.class.init]p2:
4196   //   If a mem-initializer-id is ambiguous because it designates both
4197   //   a direct non-virtual base class and an inherited virtual base
4198   //   class, the mem-initializer is ill-formed.
4199   if (DirectBaseSpec && VirtualBaseSpec)
4200     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4201       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4202 
4203   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4204   if (!BaseSpec)
4205     BaseSpec = VirtualBaseSpec;
4206 
4207   // Initialize the base.
4208   bool InitList = true;
4209   MultiExprArg Args = Init;
4210   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4211     InitList = false;
4212     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4213   }
4214 
4215   InitializedEntity BaseEntity =
4216     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4217   InitializationKind Kind =
4218       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4219                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4220                                                   InitRange.getEnd());
4221   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4222   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4223   if (BaseInit.isInvalid())
4224     return true;
4225 
4226   // C++11 [class.base.init]p7:
4227   //   The initialization of each base and member constitutes a
4228   //   full-expression.
4229   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4230                                  /*DiscardedValue*/ false);
4231   if (BaseInit.isInvalid())
4232     return true;
4233 
4234   // If we are in a dependent context, template instantiation will
4235   // perform this type-checking again. Just save the arguments that we
4236   // received in a ParenListExpr.
4237   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4238   // of the information that we have about the base
4239   // initializer. However, deconstructing the ASTs is a dicey process,
4240   // and this approach is far more likely to get the corner cases right.
4241   if (CurContext->isDependentContext())
4242     BaseInit = Init;
4243 
4244   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4245                                           BaseSpec->isVirtual(),
4246                                           InitRange.getBegin(),
4247                                           BaseInit.getAs<Expr>(),
4248                                           InitRange.getEnd(), EllipsisLoc);
4249 }
4250 
4251 // Create a static_cast\<T&&>(expr).
4252 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4253   if (T.isNull()) T = E->getType();
4254   QualType TargetType = SemaRef.BuildReferenceType(
4255       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4256   SourceLocation ExprLoc = E->getBeginLoc();
4257   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4258       TargetType, ExprLoc);
4259 
4260   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4261                                    SourceRange(ExprLoc, ExprLoc),
4262                                    E->getSourceRange()).get();
4263 }
4264 
4265 /// ImplicitInitializerKind - How an implicit base or member initializer should
4266 /// initialize its base or member.
4267 enum ImplicitInitializerKind {
4268   IIK_Default,
4269   IIK_Copy,
4270   IIK_Move,
4271   IIK_Inherit
4272 };
4273 
4274 static bool
4275 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4276                              ImplicitInitializerKind ImplicitInitKind,
4277                              CXXBaseSpecifier *BaseSpec,
4278                              bool IsInheritedVirtualBase,
4279                              CXXCtorInitializer *&CXXBaseInit) {
4280   InitializedEntity InitEntity
4281     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4282                                         IsInheritedVirtualBase);
4283 
4284   ExprResult BaseInit;
4285 
4286   switch (ImplicitInitKind) {
4287   case IIK_Inherit:
4288   case IIK_Default: {
4289     InitializationKind InitKind
4290       = InitializationKind::CreateDefault(Constructor->getLocation());
4291     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4292     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4293     break;
4294   }
4295 
4296   case IIK_Move:
4297   case IIK_Copy: {
4298     bool Moving = ImplicitInitKind == IIK_Move;
4299     ParmVarDecl *Param = Constructor->getParamDecl(0);
4300     QualType ParamType = Param->getType().getNonReferenceType();
4301 
4302     Expr *CopyCtorArg =
4303       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4304                           SourceLocation(), Param, false,
4305                           Constructor->getLocation(), ParamType,
4306                           VK_LValue, nullptr);
4307 
4308     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4309 
4310     // Cast to the base class to avoid ambiguities.
4311     QualType ArgTy =
4312       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4313                                        ParamType.getQualifiers());
4314 
4315     if (Moving) {
4316       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4317     }
4318 
4319     CXXCastPath BasePath;
4320     BasePath.push_back(BaseSpec);
4321     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4322                                             CK_UncheckedDerivedToBase,
4323                                             Moving ? VK_XValue : VK_LValue,
4324                                             &BasePath).get();
4325 
4326     InitializationKind InitKind
4327       = InitializationKind::CreateDirect(Constructor->getLocation(),
4328                                          SourceLocation(), SourceLocation());
4329     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4330     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4331     break;
4332   }
4333   }
4334 
4335   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4336   if (BaseInit.isInvalid())
4337     return true;
4338 
4339   CXXBaseInit =
4340     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4341                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4342                                                         SourceLocation()),
4343                                              BaseSpec->isVirtual(),
4344                                              SourceLocation(),
4345                                              BaseInit.getAs<Expr>(),
4346                                              SourceLocation(),
4347                                              SourceLocation());
4348 
4349   return false;
4350 }
4351 
4352 static bool RefersToRValueRef(Expr *MemRef) {
4353   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4354   return Referenced->getType()->isRValueReferenceType();
4355 }
4356 
4357 static bool
4358 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4359                                ImplicitInitializerKind ImplicitInitKind,
4360                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4361                                CXXCtorInitializer *&CXXMemberInit) {
4362   if (Field->isInvalidDecl())
4363     return true;
4364 
4365   SourceLocation Loc = Constructor->getLocation();
4366 
4367   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4368     bool Moving = ImplicitInitKind == IIK_Move;
4369     ParmVarDecl *Param = Constructor->getParamDecl(0);
4370     QualType ParamType = Param->getType().getNonReferenceType();
4371 
4372     // Suppress copying zero-width bitfields.
4373     if (Field->isZeroLengthBitField(SemaRef.Context))
4374       return false;
4375 
4376     Expr *MemberExprBase =
4377       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4378                           SourceLocation(), Param, false,
4379                           Loc, ParamType, VK_LValue, nullptr);
4380 
4381     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4382 
4383     if (Moving) {
4384       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4385     }
4386 
4387     // Build a reference to this field within the parameter.
4388     CXXScopeSpec SS;
4389     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4390                               Sema::LookupMemberName);
4391     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4392                                   : cast<ValueDecl>(Field), AS_public);
4393     MemberLookup.resolveKind();
4394     ExprResult CtorArg
4395       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4396                                          ParamType, Loc,
4397                                          /*IsArrow=*/false,
4398                                          SS,
4399                                          /*TemplateKWLoc=*/SourceLocation(),
4400                                          /*FirstQualifierInScope=*/nullptr,
4401                                          MemberLookup,
4402                                          /*TemplateArgs=*/nullptr,
4403                                          /*S*/nullptr);
4404     if (CtorArg.isInvalid())
4405       return true;
4406 
4407     // C++11 [class.copy]p15:
4408     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4409     //     with static_cast<T&&>(x.m);
4410     if (RefersToRValueRef(CtorArg.get())) {
4411       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4412     }
4413 
4414     InitializedEntity Entity =
4415         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4416                                                        /*Implicit*/ true)
4417                  : InitializedEntity::InitializeMember(Field, nullptr,
4418                                                        /*Implicit*/ true);
4419 
4420     // Direct-initialize to use the copy constructor.
4421     InitializationKind InitKind =
4422       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4423 
4424     Expr *CtorArgE = CtorArg.getAs<Expr>();
4425     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4426     ExprResult MemberInit =
4427         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4428     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4429     if (MemberInit.isInvalid())
4430       return true;
4431 
4432     if (Indirect)
4433       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4434           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4435     else
4436       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4437           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4438     return false;
4439   }
4440 
4441   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4442          "Unhandled implicit init kind!");
4443 
4444   QualType FieldBaseElementType =
4445     SemaRef.Context.getBaseElementType(Field->getType());
4446 
4447   if (FieldBaseElementType->isRecordType()) {
4448     InitializedEntity InitEntity =
4449         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4450                                                        /*Implicit*/ true)
4451                  : InitializedEntity::InitializeMember(Field, nullptr,
4452                                                        /*Implicit*/ true);
4453     InitializationKind InitKind =
4454       InitializationKind::CreateDefault(Loc);
4455 
4456     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4457     ExprResult MemberInit =
4458       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4459 
4460     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4461     if (MemberInit.isInvalid())
4462       return true;
4463 
4464     if (Indirect)
4465       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4466                                                                Indirect, Loc,
4467                                                                Loc,
4468                                                                MemberInit.get(),
4469                                                                Loc);
4470     else
4471       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4472                                                                Field, Loc, Loc,
4473                                                                MemberInit.get(),
4474                                                                Loc);
4475     return false;
4476   }
4477 
4478   if (!Field->getParent()->isUnion()) {
4479     if (FieldBaseElementType->isReferenceType()) {
4480       SemaRef.Diag(Constructor->getLocation(),
4481                    diag::err_uninitialized_member_in_ctor)
4482       << (int)Constructor->isImplicit()
4483       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4484       << 0 << Field->getDeclName();
4485       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4486       return true;
4487     }
4488 
4489     if (FieldBaseElementType.isConstQualified()) {
4490       SemaRef.Diag(Constructor->getLocation(),
4491                    diag::err_uninitialized_member_in_ctor)
4492       << (int)Constructor->isImplicit()
4493       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4494       << 1 << Field->getDeclName();
4495       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4496       return true;
4497     }
4498   }
4499 
4500   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4501     // ARC and Weak:
4502     //   Default-initialize Objective-C pointers to NULL.
4503     CXXMemberInit
4504       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4505                                                  Loc, Loc,
4506                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4507                                                  Loc);
4508     return false;
4509   }
4510 
4511   // Nothing to initialize.
4512   CXXMemberInit = nullptr;
4513   return false;
4514 }
4515 
4516 namespace {
4517 struct BaseAndFieldInfo {
4518   Sema &S;
4519   CXXConstructorDecl *Ctor;
4520   bool AnyErrorsInInits;
4521   ImplicitInitializerKind IIK;
4522   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4523   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4524   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4525 
4526   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4527     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4528     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4529     if (Ctor->getInheritedConstructor())
4530       IIK = IIK_Inherit;
4531     else if (Generated && Ctor->isCopyConstructor())
4532       IIK = IIK_Copy;
4533     else if (Generated && Ctor->isMoveConstructor())
4534       IIK = IIK_Move;
4535     else
4536       IIK = IIK_Default;
4537   }
4538 
4539   bool isImplicitCopyOrMove() const {
4540     switch (IIK) {
4541     case IIK_Copy:
4542     case IIK_Move:
4543       return true;
4544 
4545     case IIK_Default:
4546     case IIK_Inherit:
4547       return false;
4548     }
4549 
4550     llvm_unreachable("Invalid ImplicitInitializerKind!");
4551   }
4552 
4553   bool addFieldInitializer(CXXCtorInitializer *Init) {
4554     AllToInit.push_back(Init);
4555 
4556     // Check whether this initializer makes the field "used".
4557     if (Init->getInit()->HasSideEffects(S.Context))
4558       S.UnusedPrivateFields.remove(Init->getAnyMember());
4559 
4560     return false;
4561   }
4562 
4563   bool isInactiveUnionMember(FieldDecl *Field) {
4564     RecordDecl *Record = Field->getParent();
4565     if (!Record->isUnion())
4566       return false;
4567 
4568     if (FieldDecl *Active =
4569             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4570       return Active != Field->getCanonicalDecl();
4571 
4572     // In an implicit copy or move constructor, ignore any in-class initializer.
4573     if (isImplicitCopyOrMove())
4574       return true;
4575 
4576     // If there's no explicit initialization, the field is active only if it
4577     // has an in-class initializer...
4578     if (Field->hasInClassInitializer())
4579       return false;
4580     // ... or it's an anonymous struct or union whose class has an in-class
4581     // initializer.
4582     if (!Field->isAnonymousStructOrUnion())
4583       return true;
4584     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4585     return !FieldRD->hasInClassInitializer();
4586   }
4587 
4588   /// Determine whether the given field is, or is within, a union member
4589   /// that is inactive (because there was an initializer given for a different
4590   /// member of the union, or because the union was not initialized at all).
4591   bool isWithinInactiveUnionMember(FieldDecl *Field,
4592                                    IndirectFieldDecl *Indirect) {
4593     if (!Indirect)
4594       return isInactiveUnionMember(Field);
4595 
4596     for (auto *C : Indirect->chain()) {
4597       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4598       if (Field && isInactiveUnionMember(Field))
4599         return true;
4600     }
4601     return false;
4602   }
4603 };
4604 }
4605 
4606 /// Determine whether the given type is an incomplete or zero-lenfgth
4607 /// array type.
4608 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4609   if (T->isIncompleteArrayType())
4610     return true;
4611 
4612   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4613     if (!ArrayT->getSize())
4614       return true;
4615 
4616     T = ArrayT->getElementType();
4617   }
4618 
4619   return false;
4620 }
4621 
4622 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4623                                     FieldDecl *Field,
4624                                     IndirectFieldDecl *Indirect = nullptr) {
4625   if (Field->isInvalidDecl())
4626     return false;
4627 
4628   // Overwhelmingly common case: we have a direct initializer for this field.
4629   if (CXXCtorInitializer *Init =
4630           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4631     return Info.addFieldInitializer(Init);
4632 
4633   // C++11 [class.base.init]p8:
4634   //   if the entity is a non-static data member that has a
4635   //   brace-or-equal-initializer and either
4636   //   -- the constructor's class is a union and no other variant member of that
4637   //      union is designated by a mem-initializer-id or
4638   //   -- the constructor's class is not a union, and, if the entity is a member
4639   //      of an anonymous union, no other member of that union is designated by
4640   //      a mem-initializer-id,
4641   //   the entity is initialized as specified in [dcl.init].
4642   //
4643   // We also apply the same rules to handle anonymous structs within anonymous
4644   // unions.
4645   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4646     return false;
4647 
4648   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4649     ExprResult DIE =
4650         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4651     if (DIE.isInvalid())
4652       return true;
4653 
4654     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4655     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4656 
4657     CXXCtorInitializer *Init;
4658     if (Indirect)
4659       Init = new (SemaRef.Context)
4660           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4661                              SourceLocation(), DIE.get(), SourceLocation());
4662     else
4663       Init = new (SemaRef.Context)
4664           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4665                              SourceLocation(), DIE.get(), SourceLocation());
4666     return Info.addFieldInitializer(Init);
4667   }
4668 
4669   // Don't initialize incomplete or zero-length arrays.
4670   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4671     return false;
4672 
4673   // Don't try to build an implicit initializer if there were semantic
4674   // errors in any of the initializers (and therefore we might be
4675   // missing some that the user actually wrote).
4676   if (Info.AnyErrorsInInits)
4677     return false;
4678 
4679   CXXCtorInitializer *Init = nullptr;
4680   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4681                                      Indirect, Init))
4682     return true;
4683 
4684   if (!Init)
4685     return false;
4686 
4687   return Info.addFieldInitializer(Init);
4688 }
4689 
4690 bool
4691 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4692                                CXXCtorInitializer *Initializer) {
4693   assert(Initializer->isDelegatingInitializer());
4694   Constructor->setNumCtorInitializers(1);
4695   CXXCtorInitializer **initializer =
4696     new (Context) CXXCtorInitializer*[1];
4697   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4698   Constructor->setCtorInitializers(initializer);
4699 
4700   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4701     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4702     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4703   }
4704 
4705   DelegatingCtorDecls.push_back(Constructor);
4706 
4707   DiagnoseUninitializedFields(*this, Constructor);
4708 
4709   return false;
4710 }
4711 
4712 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4713                                ArrayRef<CXXCtorInitializer *> Initializers) {
4714   if (Constructor->isDependentContext()) {
4715     // Just store the initializers as written, they will be checked during
4716     // instantiation.
4717     if (!Initializers.empty()) {
4718       Constructor->setNumCtorInitializers(Initializers.size());
4719       CXXCtorInitializer **baseOrMemberInitializers =
4720         new (Context) CXXCtorInitializer*[Initializers.size()];
4721       memcpy(baseOrMemberInitializers, Initializers.data(),
4722              Initializers.size() * sizeof(CXXCtorInitializer*));
4723       Constructor->setCtorInitializers(baseOrMemberInitializers);
4724     }
4725 
4726     // Let template instantiation know whether we had errors.
4727     if (AnyErrors)
4728       Constructor->setInvalidDecl();
4729 
4730     return false;
4731   }
4732 
4733   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4734 
4735   // We need to build the initializer AST according to order of construction
4736   // and not what user specified in the Initializers list.
4737   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4738   if (!ClassDecl)
4739     return true;
4740 
4741   bool HadError = false;
4742 
4743   for (unsigned i = 0; i < Initializers.size(); i++) {
4744     CXXCtorInitializer *Member = Initializers[i];
4745 
4746     if (Member->isBaseInitializer())
4747       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4748     else {
4749       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4750 
4751       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4752         for (auto *C : F->chain()) {
4753           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4754           if (FD && FD->getParent()->isUnion())
4755             Info.ActiveUnionMember.insert(std::make_pair(
4756                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4757         }
4758       } else if (FieldDecl *FD = Member->getMember()) {
4759         if (FD->getParent()->isUnion())
4760           Info.ActiveUnionMember.insert(std::make_pair(
4761               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4762       }
4763     }
4764   }
4765 
4766   // Keep track of the direct virtual bases.
4767   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4768   for (auto &I : ClassDecl->bases()) {
4769     if (I.isVirtual())
4770       DirectVBases.insert(&I);
4771   }
4772 
4773   // Push virtual bases before others.
4774   for (auto &VBase : ClassDecl->vbases()) {
4775     if (CXXCtorInitializer *Value
4776         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4777       // [class.base.init]p7, per DR257:
4778       //   A mem-initializer where the mem-initializer-id names a virtual base
4779       //   class is ignored during execution of a constructor of any class that
4780       //   is not the most derived class.
4781       if (ClassDecl->isAbstract()) {
4782         // FIXME: Provide a fixit to remove the base specifier. This requires
4783         // tracking the location of the associated comma for a base specifier.
4784         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4785           << VBase.getType() << ClassDecl;
4786         DiagnoseAbstractType(ClassDecl);
4787       }
4788 
4789       Info.AllToInit.push_back(Value);
4790     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4791       // [class.base.init]p8, per DR257:
4792       //   If a given [...] base class is not named by a mem-initializer-id
4793       //   [...] and the entity is not a virtual base class of an abstract
4794       //   class, then [...] the entity is default-initialized.
4795       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4796       CXXCtorInitializer *CXXBaseInit;
4797       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4798                                        &VBase, IsInheritedVirtualBase,
4799                                        CXXBaseInit)) {
4800         HadError = true;
4801         continue;
4802       }
4803 
4804       Info.AllToInit.push_back(CXXBaseInit);
4805     }
4806   }
4807 
4808   // Non-virtual bases.
4809   for (auto &Base : ClassDecl->bases()) {
4810     // Virtuals are in the virtual base list and already constructed.
4811     if (Base.isVirtual())
4812       continue;
4813 
4814     if (CXXCtorInitializer *Value
4815           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4816       Info.AllToInit.push_back(Value);
4817     } else if (!AnyErrors) {
4818       CXXCtorInitializer *CXXBaseInit;
4819       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4820                                        &Base, /*IsInheritedVirtualBase=*/false,
4821                                        CXXBaseInit)) {
4822         HadError = true;
4823         continue;
4824       }
4825 
4826       Info.AllToInit.push_back(CXXBaseInit);
4827     }
4828   }
4829 
4830   // Fields.
4831   for (auto *Mem : ClassDecl->decls()) {
4832     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4833       // C++ [class.bit]p2:
4834       //   A declaration for a bit-field that omits the identifier declares an
4835       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4836       //   initialized.
4837       if (F->isUnnamedBitfield())
4838         continue;
4839 
4840       // If we're not generating the implicit copy/move constructor, then we'll
4841       // handle anonymous struct/union fields based on their individual
4842       // indirect fields.
4843       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4844         continue;
4845 
4846       if (CollectFieldInitializer(*this, Info, F))
4847         HadError = true;
4848       continue;
4849     }
4850 
4851     // Beyond this point, we only consider default initialization.
4852     if (Info.isImplicitCopyOrMove())
4853       continue;
4854 
4855     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4856       if (F->getType()->isIncompleteArrayType()) {
4857         assert(ClassDecl->hasFlexibleArrayMember() &&
4858                "Incomplete array type is not valid");
4859         continue;
4860       }
4861 
4862       // Initialize each field of an anonymous struct individually.
4863       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4864         HadError = true;
4865 
4866       continue;
4867     }
4868   }
4869 
4870   unsigned NumInitializers = Info.AllToInit.size();
4871   if (NumInitializers > 0) {
4872     Constructor->setNumCtorInitializers(NumInitializers);
4873     CXXCtorInitializer **baseOrMemberInitializers =
4874       new (Context) CXXCtorInitializer*[NumInitializers];
4875     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4876            NumInitializers * sizeof(CXXCtorInitializer*));
4877     Constructor->setCtorInitializers(baseOrMemberInitializers);
4878 
4879     // Constructors implicitly reference the base and member
4880     // destructors.
4881     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4882                                            Constructor->getParent());
4883   }
4884 
4885   return HadError;
4886 }
4887 
4888 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4889   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4890     const RecordDecl *RD = RT->getDecl();
4891     if (RD->isAnonymousStructOrUnion()) {
4892       for (auto *Field : RD->fields())
4893         PopulateKeysForFields(Field, IdealInits);
4894       return;
4895     }
4896   }
4897   IdealInits.push_back(Field->getCanonicalDecl());
4898 }
4899 
4900 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4901   return Context.getCanonicalType(BaseType).getTypePtr();
4902 }
4903 
4904 static const void *GetKeyForMember(ASTContext &Context,
4905                                    CXXCtorInitializer *Member) {
4906   if (!Member->isAnyMemberInitializer())
4907     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4908 
4909   return Member->getAnyMember()->getCanonicalDecl();
4910 }
4911 
4912 static void DiagnoseBaseOrMemInitializerOrder(
4913     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4914     ArrayRef<CXXCtorInitializer *> Inits) {
4915   if (Constructor->getDeclContext()->isDependentContext())
4916     return;
4917 
4918   // Don't check initializers order unless the warning is enabled at the
4919   // location of at least one initializer.
4920   bool ShouldCheckOrder = false;
4921   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4922     CXXCtorInitializer *Init = Inits[InitIndex];
4923     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4924                                  Init->getSourceLocation())) {
4925       ShouldCheckOrder = true;
4926       break;
4927     }
4928   }
4929   if (!ShouldCheckOrder)
4930     return;
4931 
4932   // Build the list of bases and members in the order that they'll
4933   // actually be initialized.  The explicit initializers should be in
4934   // this same order but may be missing things.
4935   SmallVector<const void*, 32> IdealInitKeys;
4936 
4937   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4938 
4939   // 1. Virtual bases.
4940   for (const auto &VBase : ClassDecl->vbases())
4941     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4942 
4943   // 2. Non-virtual bases.
4944   for (const auto &Base : ClassDecl->bases()) {
4945     if (Base.isVirtual())
4946       continue;
4947     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4948   }
4949 
4950   // 3. Direct fields.
4951   for (auto *Field : ClassDecl->fields()) {
4952     if (Field->isUnnamedBitfield())
4953       continue;
4954 
4955     PopulateKeysForFields(Field, IdealInitKeys);
4956   }
4957 
4958   unsigned NumIdealInits = IdealInitKeys.size();
4959   unsigned IdealIndex = 0;
4960 
4961   CXXCtorInitializer *PrevInit = nullptr;
4962   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4963     CXXCtorInitializer *Init = Inits[InitIndex];
4964     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4965 
4966     // Scan forward to try to find this initializer in the idealized
4967     // initializers list.
4968     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4969       if (InitKey == IdealInitKeys[IdealIndex])
4970         break;
4971 
4972     // If we didn't find this initializer, it must be because we
4973     // scanned past it on a previous iteration.  That can only
4974     // happen if we're out of order;  emit a warning.
4975     if (IdealIndex == NumIdealInits && PrevInit) {
4976       Sema::SemaDiagnosticBuilder D =
4977         SemaRef.Diag(PrevInit->getSourceLocation(),
4978                      diag::warn_initializer_out_of_order);
4979 
4980       if (PrevInit->isAnyMemberInitializer())
4981         D << 0 << PrevInit->getAnyMember()->getDeclName();
4982       else
4983         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4984 
4985       if (Init->isAnyMemberInitializer())
4986         D << 0 << Init->getAnyMember()->getDeclName();
4987       else
4988         D << 1 << Init->getTypeSourceInfo()->getType();
4989 
4990       // Move back to the initializer's location in the ideal list.
4991       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4992         if (InitKey == IdealInitKeys[IdealIndex])
4993           break;
4994 
4995       assert(IdealIndex < NumIdealInits &&
4996              "initializer not found in initializer list");
4997     }
4998 
4999     PrevInit = Init;
5000   }
5001 }
5002 
5003 namespace {
5004 bool CheckRedundantInit(Sema &S,
5005                         CXXCtorInitializer *Init,
5006                         CXXCtorInitializer *&PrevInit) {
5007   if (!PrevInit) {
5008     PrevInit = Init;
5009     return false;
5010   }
5011 
5012   if (FieldDecl *Field = Init->getAnyMember())
5013     S.Diag(Init->getSourceLocation(),
5014            diag::err_multiple_mem_initialization)
5015       << Field->getDeclName()
5016       << Init->getSourceRange();
5017   else {
5018     const Type *BaseClass = Init->getBaseClass();
5019     assert(BaseClass && "neither field nor base");
5020     S.Diag(Init->getSourceLocation(),
5021            diag::err_multiple_base_initialization)
5022       << QualType(BaseClass, 0)
5023       << Init->getSourceRange();
5024   }
5025   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5026     << 0 << PrevInit->getSourceRange();
5027 
5028   return true;
5029 }
5030 
5031 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5032 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5033 
5034 bool CheckRedundantUnionInit(Sema &S,
5035                              CXXCtorInitializer *Init,
5036                              RedundantUnionMap &Unions) {
5037   FieldDecl *Field = Init->getAnyMember();
5038   RecordDecl *Parent = Field->getParent();
5039   NamedDecl *Child = Field;
5040 
5041   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5042     if (Parent->isUnion()) {
5043       UnionEntry &En = Unions[Parent];
5044       if (En.first && En.first != Child) {
5045         S.Diag(Init->getSourceLocation(),
5046                diag::err_multiple_mem_union_initialization)
5047           << Field->getDeclName()
5048           << Init->getSourceRange();
5049         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5050           << 0 << En.second->getSourceRange();
5051         return true;
5052       }
5053       if (!En.first) {
5054         En.first = Child;
5055         En.second = Init;
5056       }
5057       if (!Parent->isAnonymousStructOrUnion())
5058         return false;
5059     }
5060 
5061     Child = Parent;
5062     Parent = cast<RecordDecl>(Parent->getDeclContext());
5063   }
5064 
5065   return false;
5066 }
5067 }
5068 
5069 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5070 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5071                                 SourceLocation ColonLoc,
5072                                 ArrayRef<CXXCtorInitializer*> MemInits,
5073                                 bool AnyErrors) {
5074   if (!ConstructorDecl)
5075     return;
5076 
5077   AdjustDeclIfTemplate(ConstructorDecl);
5078 
5079   CXXConstructorDecl *Constructor
5080     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5081 
5082   if (!Constructor) {
5083     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5084     return;
5085   }
5086 
5087   // Mapping for the duplicate initializers check.
5088   // For member initializers, this is keyed with a FieldDecl*.
5089   // For base initializers, this is keyed with a Type*.
5090   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5091 
5092   // Mapping for the inconsistent anonymous-union initializers check.
5093   RedundantUnionMap MemberUnions;
5094 
5095   bool HadError = false;
5096   for (unsigned i = 0; i < MemInits.size(); i++) {
5097     CXXCtorInitializer *Init = MemInits[i];
5098 
5099     // Set the source order index.
5100     Init->setSourceOrder(i);
5101 
5102     if (Init->isAnyMemberInitializer()) {
5103       const void *Key = GetKeyForMember(Context, Init);
5104       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5105           CheckRedundantUnionInit(*this, Init, MemberUnions))
5106         HadError = true;
5107     } else if (Init->isBaseInitializer()) {
5108       const void *Key = GetKeyForMember(Context, Init);
5109       if (CheckRedundantInit(*this, Init, Members[Key]))
5110         HadError = true;
5111     } else {
5112       assert(Init->isDelegatingInitializer());
5113       // This must be the only initializer
5114       if (MemInits.size() != 1) {
5115         Diag(Init->getSourceLocation(),
5116              diag::err_delegating_initializer_alone)
5117           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5118         // We will treat this as being the only initializer.
5119       }
5120       SetDelegatingInitializer(Constructor, MemInits[i]);
5121       // Return immediately as the initializer is set.
5122       return;
5123     }
5124   }
5125 
5126   if (HadError)
5127     return;
5128 
5129   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5130 
5131   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5132 
5133   DiagnoseUninitializedFields(*this, Constructor);
5134 }
5135 
5136 void
5137 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5138                                              CXXRecordDecl *ClassDecl) {
5139   // Ignore dependent contexts. Also ignore unions, since their members never
5140   // have destructors implicitly called.
5141   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5142     return;
5143 
5144   // FIXME: all the access-control diagnostics are positioned on the
5145   // field/base declaration.  That's probably good; that said, the
5146   // user might reasonably want to know why the destructor is being
5147   // emitted, and we currently don't say.
5148 
5149   // Non-static data members.
5150   for (auto *Field : ClassDecl->fields()) {
5151     if (Field->isInvalidDecl())
5152       continue;
5153 
5154     // Don't destroy incomplete or zero-length arrays.
5155     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5156       continue;
5157 
5158     QualType FieldType = Context.getBaseElementType(Field->getType());
5159 
5160     const RecordType* RT = FieldType->getAs<RecordType>();
5161     if (!RT)
5162       continue;
5163 
5164     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5165     if (FieldClassDecl->isInvalidDecl())
5166       continue;
5167     if (FieldClassDecl->hasIrrelevantDestructor())
5168       continue;
5169     // The destructor for an implicit anonymous union member is never invoked.
5170     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5171       continue;
5172 
5173     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5174     assert(Dtor && "No dtor found for FieldClassDecl!");
5175     CheckDestructorAccess(Field->getLocation(), Dtor,
5176                           PDiag(diag::err_access_dtor_field)
5177                             << Field->getDeclName()
5178                             << FieldType);
5179 
5180     MarkFunctionReferenced(Location, Dtor);
5181     DiagnoseUseOfDecl(Dtor, Location);
5182   }
5183 
5184   // We only potentially invoke the destructors of potentially constructed
5185   // subobjects.
5186   bool VisitVirtualBases = !ClassDecl->isAbstract();
5187 
5188   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5189 
5190   // Bases.
5191   for (const auto &Base : ClassDecl->bases()) {
5192     // Bases are always records in a well-formed non-dependent class.
5193     const RecordType *RT = Base.getType()->getAs<RecordType>();
5194 
5195     // Remember direct virtual bases.
5196     if (Base.isVirtual()) {
5197       if (!VisitVirtualBases)
5198         continue;
5199       DirectVirtualBases.insert(RT);
5200     }
5201 
5202     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5203     // If our base class is invalid, we probably can't get its dtor anyway.
5204     if (BaseClassDecl->isInvalidDecl())
5205       continue;
5206     if (BaseClassDecl->hasIrrelevantDestructor())
5207       continue;
5208 
5209     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5210     assert(Dtor && "No dtor found for BaseClassDecl!");
5211 
5212     // FIXME: caret should be on the start of the class name
5213     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5214                           PDiag(diag::err_access_dtor_base)
5215                               << Base.getType() << Base.getSourceRange(),
5216                           Context.getTypeDeclType(ClassDecl));
5217 
5218     MarkFunctionReferenced(Location, Dtor);
5219     DiagnoseUseOfDecl(Dtor, Location);
5220   }
5221 
5222   if (!VisitVirtualBases)
5223     return;
5224 
5225   // Virtual bases.
5226   for (const auto &VBase : ClassDecl->vbases()) {
5227     // Bases are always records in a well-formed non-dependent class.
5228     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5229 
5230     // Ignore direct virtual bases.
5231     if (DirectVirtualBases.count(RT))
5232       continue;
5233 
5234     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5235     // If our base class is invalid, we probably can't get its dtor anyway.
5236     if (BaseClassDecl->isInvalidDecl())
5237       continue;
5238     if (BaseClassDecl->hasIrrelevantDestructor())
5239       continue;
5240 
5241     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5242     assert(Dtor && "No dtor found for BaseClassDecl!");
5243     if (CheckDestructorAccess(
5244             ClassDecl->getLocation(), Dtor,
5245             PDiag(diag::err_access_dtor_vbase)
5246                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5247             Context.getTypeDeclType(ClassDecl)) ==
5248         AR_accessible) {
5249       CheckDerivedToBaseConversion(
5250           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5251           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5252           SourceRange(), DeclarationName(), nullptr);
5253     }
5254 
5255     MarkFunctionReferenced(Location, Dtor);
5256     DiagnoseUseOfDecl(Dtor, Location);
5257   }
5258 }
5259 
5260 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5261   if (!CDtorDecl)
5262     return;
5263 
5264   if (CXXConstructorDecl *Constructor
5265       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5266     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5267     DiagnoseUninitializedFields(*this, Constructor);
5268   }
5269 }
5270 
5271 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5272   if (!getLangOpts().CPlusPlus)
5273     return false;
5274 
5275   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5276   if (!RD)
5277     return false;
5278 
5279   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5280   // class template specialization here, but doing so breaks a lot of code.
5281 
5282   // We can't answer whether something is abstract until it has a
5283   // definition. If it's currently being defined, we'll walk back
5284   // over all the declarations when we have a full definition.
5285   const CXXRecordDecl *Def = RD->getDefinition();
5286   if (!Def || Def->isBeingDefined())
5287     return false;
5288 
5289   return RD->isAbstract();
5290 }
5291 
5292 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5293                                   TypeDiagnoser &Diagnoser) {
5294   if (!isAbstractType(Loc, T))
5295     return false;
5296 
5297   T = Context.getBaseElementType(T);
5298   Diagnoser.diagnose(*this, Loc, T);
5299   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5300   return true;
5301 }
5302 
5303 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5304   // Check if we've already emitted the list of pure virtual functions
5305   // for this class.
5306   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5307     return;
5308 
5309   // If the diagnostic is suppressed, don't emit the notes. We're only
5310   // going to emit them once, so try to attach them to a diagnostic we're
5311   // actually going to show.
5312   if (Diags.isLastDiagnosticIgnored())
5313     return;
5314 
5315   CXXFinalOverriderMap FinalOverriders;
5316   RD->getFinalOverriders(FinalOverriders);
5317 
5318   // Keep a set of seen pure methods so we won't diagnose the same method
5319   // more than once.
5320   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5321 
5322   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5323                                    MEnd = FinalOverriders.end();
5324        M != MEnd;
5325        ++M) {
5326     for (OverridingMethods::iterator SO = M->second.begin(),
5327                                   SOEnd = M->second.end();
5328          SO != SOEnd; ++SO) {
5329       // C++ [class.abstract]p4:
5330       //   A class is abstract if it contains or inherits at least one
5331       //   pure virtual function for which the final overrider is pure
5332       //   virtual.
5333 
5334       //
5335       if (SO->second.size() != 1)
5336         continue;
5337 
5338       if (!SO->second.front().Method->isPure())
5339         continue;
5340 
5341       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5342         continue;
5343 
5344       Diag(SO->second.front().Method->getLocation(),
5345            diag::note_pure_virtual_function)
5346         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5347     }
5348   }
5349 
5350   if (!PureVirtualClassDiagSet)
5351     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5352   PureVirtualClassDiagSet->insert(RD);
5353 }
5354 
5355 namespace {
5356 struct AbstractUsageInfo {
5357   Sema &S;
5358   CXXRecordDecl *Record;
5359   CanQualType AbstractType;
5360   bool Invalid;
5361 
5362   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5363     : S(S), Record(Record),
5364       AbstractType(S.Context.getCanonicalType(
5365                    S.Context.getTypeDeclType(Record))),
5366       Invalid(false) {}
5367 
5368   void DiagnoseAbstractType() {
5369     if (Invalid) return;
5370     S.DiagnoseAbstractType(Record);
5371     Invalid = true;
5372   }
5373 
5374   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5375 };
5376 
5377 struct CheckAbstractUsage {
5378   AbstractUsageInfo &Info;
5379   const NamedDecl *Ctx;
5380 
5381   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5382     : Info(Info), Ctx(Ctx) {}
5383 
5384   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5385     switch (TL.getTypeLocClass()) {
5386 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5387 #define TYPELOC(CLASS, PARENT) \
5388     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5389 #include "clang/AST/TypeLocNodes.def"
5390     }
5391   }
5392 
5393   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5394     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5395     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5396       if (!TL.getParam(I))
5397         continue;
5398 
5399       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5400       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5401     }
5402   }
5403 
5404   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5405     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5406   }
5407 
5408   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5409     // Visit the type parameters from a permissive context.
5410     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5411       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5412       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5413         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5414           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5415       // TODO: other template argument types?
5416     }
5417   }
5418 
5419   // Visit pointee types from a permissive context.
5420 #define CheckPolymorphic(Type) \
5421   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5422     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5423   }
5424   CheckPolymorphic(PointerTypeLoc)
5425   CheckPolymorphic(ReferenceTypeLoc)
5426   CheckPolymorphic(MemberPointerTypeLoc)
5427   CheckPolymorphic(BlockPointerTypeLoc)
5428   CheckPolymorphic(AtomicTypeLoc)
5429 
5430   /// Handle all the types we haven't given a more specific
5431   /// implementation for above.
5432   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5433     // Every other kind of type that we haven't called out already
5434     // that has an inner type is either (1) sugar or (2) contains that
5435     // inner type in some way as a subobject.
5436     if (TypeLoc Next = TL.getNextTypeLoc())
5437       return Visit(Next, Sel);
5438 
5439     // If there's no inner type and we're in a permissive context,
5440     // don't diagnose.
5441     if (Sel == Sema::AbstractNone) return;
5442 
5443     // Check whether the type matches the abstract type.
5444     QualType T = TL.getType();
5445     if (T->isArrayType()) {
5446       Sel = Sema::AbstractArrayType;
5447       T = Info.S.Context.getBaseElementType(T);
5448     }
5449     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5450     if (CT != Info.AbstractType) return;
5451 
5452     // It matched; do some magic.
5453     if (Sel == Sema::AbstractArrayType) {
5454       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5455         << T << TL.getSourceRange();
5456     } else {
5457       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5458         << Sel << T << TL.getSourceRange();
5459     }
5460     Info.DiagnoseAbstractType();
5461   }
5462 };
5463 
5464 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5465                                   Sema::AbstractDiagSelID Sel) {
5466   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5467 }
5468 
5469 }
5470 
5471 /// Check for invalid uses of an abstract type in a method declaration.
5472 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5473                                     CXXMethodDecl *MD) {
5474   // No need to do the check on definitions, which require that
5475   // the return/param types be complete.
5476   if (MD->doesThisDeclarationHaveABody())
5477     return;
5478 
5479   // For safety's sake, just ignore it if we don't have type source
5480   // information.  This should never happen for non-implicit methods,
5481   // but...
5482   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5483     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5484 }
5485 
5486 /// Check for invalid uses of an abstract type within a class definition.
5487 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5488                                     CXXRecordDecl *RD) {
5489   for (auto *D : RD->decls()) {
5490     if (D->isImplicit()) continue;
5491 
5492     // Methods and method templates.
5493     if (isa<CXXMethodDecl>(D)) {
5494       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5495     } else if (isa<FunctionTemplateDecl>(D)) {
5496       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5497       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5498 
5499     // Fields and static variables.
5500     } else if (isa<FieldDecl>(D)) {
5501       FieldDecl *FD = cast<FieldDecl>(D);
5502       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5503         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5504     } else if (isa<VarDecl>(D)) {
5505       VarDecl *VD = cast<VarDecl>(D);
5506       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5507         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5508 
5509     // Nested classes and class templates.
5510     } else if (isa<CXXRecordDecl>(D)) {
5511       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5512     } else if (isa<ClassTemplateDecl>(D)) {
5513       CheckAbstractClassUsage(Info,
5514                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5515     }
5516   }
5517 }
5518 
5519 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5520   Attr *ClassAttr = getDLLAttr(Class);
5521   if (!ClassAttr)
5522     return;
5523 
5524   assert(ClassAttr->getKind() == attr::DLLExport);
5525 
5526   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5527 
5528   if (TSK == TSK_ExplicitInstantiationDeclaration)
5529     // Don't go any further if this is just an explicit instantiation
5530     // declaration.
5531     return;
5532 
5533   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5534     S.MarkVTableUsed(Class->getLocation(), Class, true);
5535 
5536   for (Decl *Member : Class->decls()) {
5537     // Defined static variables that are members of an exported base
5538     // class must be marked export too.
5539     auto *VD = dyn_cast<VarDecl>(Member);
5540     if (VD && Member->getAttr<DLLExportAttr>() &&
5541         VD->getStorageClass() == SC_Static &&
5542         TSK == TSK_ImplicitInstantiation)
5543       S.MarkVariableReferenced(VD->getLocation(), VD);
5544 
5545     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5546     if (!MD)
5547       continue;
5548 
5549     if (Member->getAttr<DLLExportAttr>()) {
5550       if (MD->isUserProvided()) {
5551         // Instantiate non-default class member functions ...
5552 
5553         // .. except for certain kinds of template specializations.
5554         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5555           continue;
5556 
5557         S.MarkFunctionReferenced(Class->getLocation(), MD);
5558 
5559         // The function will be passed to the consumer when its definition is
5560         // encountered.
5561       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5562                  MD->isCopyAssignmentOperator() ||
5563                  MD->isMoveAssignmentOperator()) {
5564         // Synthesize and instantiate non-trivial implicit methods, explicitly
5565         // defaulted methods, and the copy and move assignment operators. The
5566         // latter are exported even if they are trivial, because the address of
5567         // an operator can be taken and should compare equal across libraries.
5568         DiagnosticErrorTrap Trap(S.Diags);
5569         S.MarkFunctionReferenced(Class->getLocation(), MD);
5570         if (Trap.hasErrorOccurred()) {
5571           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5572               << Class << !S.getLangOpts().CPlusPlus11;
5573           break;
5574         }
5575 
5576         // There is no later point when we will see the definition of this
5577         // function, so pass it to the consumer now.
5578         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5579       }
5580     }
5581   }
5582 }
5583 
5584 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5585                                                         CXXRecordDecl *Class) {
5586   // Only the MS ABI has default constructor closures, so we don't need to do
5587   // this semantic checking anywhere else.
5588   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5589     return;
5590 
5591   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5592   for (Decl *Member : Class->decls()) {
5593     // Look for exported default constructors.
5594     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5595     if (!CD || !CD->isDefaultConstructor())
5596       continue;
5597     auto *Attr = CD->getAttr<DLLExportAttr>();
5598     if (!Attr)
5599       continue;
5600 
5601     // If the class is non-dependent, mark the default arguments as ODR-used so
5602     // that we can properly codegen the constructor closure.
5603     if (!Class->isDependentContext()) {
5604       for (ParmVarDecl *PD : CD->parameters()) {
5605         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5606         S.DiscardCleanupsInEvaluationContext();
5607       }
5608     }
5609 
5610     if (LastExportedDefaultCtor) {
5611       S.Diag(LastExportedDefaultCtor->getLocation(),
5612              diag::err_attribute_dll_ambiguous_default_ctor)
5613           << Class;
5614       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5615           << CD->getDeclName();
5616       return;
5617     }
5618     LastExportedDefaultCtor = CD;
5619   }
5620 }
5621 
5622 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5623   // Mark any compiler-generated routines with the implicit code_seg attribute.
5624   for (auto *Method : Class->methods()) {
5625     if (Method->isUserProvided())
5626       continue;
5627     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5628       Method->addAttr(A);
5629   }
5630 }
5631 
5632 /// Check class-level dllimport/dllexport attribute.
5633 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5634   Attr *ClassAttr = getDLLAttr(Class);
5635 
5636   // MSVC inherits DLL attributes to partial class template specializations.
5637   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5638     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5639       if (Attr *TemplateAttr =
5640               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5641         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5642         A->setInherited(true);
5643         ClassAttr = A;
5644       }
5645     }
5646   }
5647 
5648   if (!ClassAttr)
5649     return;
5650 
5651   if (!Class->isExternallyVisible()) {
5652     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5653         << Class << ClassAttr;
5654     return;
5655   }
5656 
5657   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5658       !ClassAttr->isInherited()) {
5659     // Diagnose dll attributes on members of class with dll attribute.
5660     for (Decl *Member : Class->decls()) {
5661       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5662         continue;
5663       InheritableAttr *MemberAttr = getDLLAttr(Member);
5664       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5665         continue;
5666 
5667       Diag(MemberAttr->getLocation(),
5668              diag::err_attribute_dll_member_of_dll_class)
5669           << MemberAttr << ClassAttr;
5670       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5671       Member->setInvalidDecl();
5672     }
5673   }
5674 
5675   if (Class->getDescribedClassTemplate())
5676     // Don't inherit dll attribute until the template is instantiated.
5677     return;
5678 
5679   // The class is either imported or exported.
5680   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5681 
5682   // Check if this was a dllimport attribute propagated from a derived class to
5683   // a base class template specialization. We don't apply these attributes to
5684   // static data members.
5685   const bool PropagatedImport =
5686       !ClassExported &&
5687       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5688 
5689   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5690 
5691   // Ignore explicit dllexport on explicit class template instantiation declarations.
5692   if (ClassExported && !ClassAttr->isInherited() &&
5693       TSK == TSK_ExplicitInstantiationDeclaration) {
5694     Class->dropAttr<DLLExportAttr>();
5695     return;
5696   }
5697 
5698   // Force declaration of implicit members so they can inherit the attribute.
5699   ForceDeclarationOfImplicitMembers(Class);
5700 
5701   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5702   // seem to be true in practice?
5703 
5704   for (Decl *Member : Class->decls()) {
5705     VarDecl *VD = dyn_cast<VarDecl>(Member);
5706     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5707 
5708     // Only methods and static fields inherit the attributes.
5709     if (!VD && !MD)
5710       continue;
5711 
5712     if (MD) {
5713       // Don't process deleted methods.
5714       if (MD->isDeleted())
5715         continue;
5716 
5717       if (MD->isInlined()) {
5718         // MinGW does not import or export inline methods.
5719         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5720             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5721           continue;
5722 
5723         // MSVC versions before 2015 don't export the move assignment operators
5724         // and move constructor, so don't attempt to import/export them if
5725         // we have a definition.
5726         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5727         if ((MD->isMoveAssignmentOperator() ||
5728              (Ctor && Ctor->isMoveConstructor())) &&
5729             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5730           continue;
5731 
5732         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5733         // operator is exported anyway.
5734         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5735             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5736           continue;
5737       }
5738     }
5739 
5740     // Don't apply dllimport attributes to static data members of class template
5741     // instantiations when the attribute is propagated from a derived class.
5742     if (VD && PropagatedImport)
5743       continue;
5744 
5745     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5746       continue;
5747 
5748     if (!getDLLAttr(Member)) {
5749       InheritableAttr *NewAttr = nullptr;
5750 
5751       // Do not export/import inline function when -fno-dllexport-inlines is
5752       // passed. But add attribute for later local static var check.
5753       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5754           TSK != TSK_ExplicitInstantiationDeclaration &&
5755           TSK != TSK_ExplicitInstantiationDefinition) {
5756         if (ClassExported) {
5757           NewAttr = ::new (getASTContext())
5758             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5759                                      getASTContext(),
5760                                      ClassAttr->getSpellingListIndex());
5761         } else {
5762           NewAttr = ::new (getASTContext())
5763             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5764                                      getASTContext(),
5765                                      ClassAttr->getSpellingListIndex());
5766         }
5767       } else {
5768         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5769       }
5770 
5771       NewAttr->setInherited(true);
5772       Member->addAttr(NewAttr);
5773 
5774       if (MD) {
5775         // Propagate DLLAttr to friend re-declarations of MD that have already
5776         // been constructed.
5777         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5778              FD = FD->getPreviousDecl()) {
5779           if (FD->getFriendObjectKind() == Decl::FOK_None)
5780             continue;
5781           assert(!getDLLAttr(FD) &&
5782                  "friend re-decl should not already have a DLLAttr");
5783           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5784           NewAttr->setInherited(true);
5785           FD->addAttr(NewAttr);
5786         }
5787       }
5788     }
5789   }
5790 
5791   if (ClassExported)
5792     DelayedDllExportClasses.push_back(Class);
5793 }
5794 
5795 /// Perform propagation of DLL attributes from a derived class to a
5796 /// templated base class for MS compatibility.
5797 void Sema::propagateDLLAttrToBaseClassTemplate(
5798     CXXRecordDecl *Class, Attr *ClassAttr,
5799     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5800   if (getDLLAttr(
5801           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5802     // If the base class template has a DLL attribute, don't try to change it.
5803     return;
5804   }
5805 
5806   auto TSK = BaseTemplateSpec->getSpecializationKind();
5807   if (!getDLLAttr(BaseTemplateSpec) &&
5808       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5809        TSK == TSK_ImplicitInstantiation)) {
5810     // The template hasn't been instantiated yet (or it has, but only as an
5811     // explicit instantiation declaration or implicit instantiation, which means
5812     // we haven't codegenned any members yet), so propagate the attribute.
5813     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5814     NewAttr->setInherited(true);
5815     BaseTemplateSpec->addAttr(NewAttr);
5816 
5817     // If this was an import, mark that we propagated it from a derived class to
5818     // a base class template specialization.
5819     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5820       ImportAttr->setPropagatedToBaseTemplate();
5821 
5822     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5823     // needs to be run again to work see the new attribute. Otherwise this will
5824     // get run whenever the template is instantiated.
5825     if (TSK != TSK_Undeclared)
5826       checkClassLevelDLLAttribute(BaseTemplateSpec);
5827 
5828     return;
5829   }
5830 
5831   if (getDLLAttr(BaseTemplateSpec)) {
5832     // The template has already been specialized or instantiated with an
5833     // attribute, explicitly or through propagation. We should not try to change
5834     // it.
5835     return;
5836   }
5837 
5838   // The template was previously instantiated or explicitly specialized without
5839   // a dll attribute, It's too late for us to add an attribute, so warn that
5840   // this is unsupported.
5841   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5842       << BaseTemplateSpec->isExplicitSpecialization();
5843   Diag(ClassAttr->getLocation(), diag::note_attribute);
5844   if (BaseTemplateSpec->isExplicitSpecialization()) {
5845     Diag(BaseTemplateSpec->getLocation(),
5846            diag::note_template_class_explicit_specialization_was_here)
5847         << BaseTemplateSpec;
5848   } else {
5849     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5850            diag::note_template_class_instantiation_was_here)
5851         << BaseTemplateSpec;
5852   }
5853 }
5854 
5855 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5856                                         SourceLocation DefaultLoc) {
5857   switch (S.getSpecialMember(MD)) {
5858   case Sema::CXXDefaultConstructor:
5859     S.DefineImplicitDefaultConstructor(DefaultLoc,
5860                                        cast<CXXConstructorDecl>(MD));
5861     break;
5862   case Sema::CXXCopyConstructor:
5863     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5864     break;
5865   case Sema::CXXCopyAssignment:
5866     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5867     break;
5868   case Sema::CXXDestructor:
5869     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5870     break;
5871   case Sema::CXXMoveConstructor:
5872     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5873     break;
5874   case Sema::CXXMoveAssignment:
5875     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5876     break;
5877   case Sema::CXXInvalid:
5878     llvm_unreachable("Invalid special member.");
5879   }
5880 }
5881 
5882 /// Determine whether a type is permitted to be passed or returned in
5883 /// registers, per C++ [class.temporary]p3.
5884 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5885                                TargetInfo::CallingConvKind CCK) {
5886   if (D->isDependentType() || D->isInvalidDecl())
5887     return false;
5888 
5889   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5890   // The PS4 platform ABI follows the behavior of Clang 3.2.
5891   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5892     return !D->hasNonTrivialDestructorForCall() &&
5893            !D->hasNonTrivialCopyConstructorForCall();
5894 
5895   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5896     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5897     bool DtorIsTrivialForCall = false;
5898 
5899     // If a class has at least one non-deleted, trivial copy constructor, it
5900     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5901     //
5902     // Note: This permits classes with non-trivial copy or move ctors to be
5903     // passed in registers, so long as they *also* have a trivial copy ctor,
5904     // which is non-conforming.
5905     if (D->needsImplicitCopyConstructor()) {
5906       if (!D->defaultedCopyConstructorIsDeleted()) {
5907         if (D->hasTrivialCopyConstructor())
5908           CopyCtorIsTrivial = true;
5909         if (D->hasTrivialCopyConstructorForCall())
5910           CopyCtorIsTrivialForCall = true;
5911       }
5912     } else {
5913       for (const CXXConstructorDecl *CD : D->ctors()) {
5914         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5915           if (CD->isTrivial())
5916             CopyCtorIsTrivial = true;
5917           if (CD->isTrivialForCall())
5918             CopyCtorIsTrivialForCall = true;
5919         }
5920       }
5921     }
5922 
5923     if (D->needsImplicitDestructor()) {
5924       if (!D->defaultedDestructorIsDeleted() &&
5925           D->hasTrivialDestructorForCall())
5926         DtorIsTrivialForCall = true;
5927     } else if (const auto *DD = D->getDestructor()) {
5928       if (!DD->isDeleted() && DD->isTrivialForCall())
5929         DtorIsTrivialForCall = true;
5930     }
5931 
5932     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5933     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5934       return true;
5935 
5936     // If a class has a destructor, we'd really like to pass it indirectly
5937     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5938     // impossible for small types, which it will pass in a single register or
5939     // stack slot. Most objects with dtors are large-ish, so handle that early.
5940     // We can't call out all large objects as being indirect because there are
5941     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5942     // how we pass large POD types.
5943 
5944     // Note: This permits small classes with nontrivial destructors to be
5945     // passed in registers, which is non-conforming.
5946     if (CopyCtorIsTrivial &&
5947         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5948       return true;
5949     return false;
5950   }
5951 
5952   // Per C++ [class.temporary]p3, the relevant condition is:
5953   //   each copy constructor, move constructor, and destructor of X is
5954   //   either trivial or deleted, and X has at least one non-deleted copy
5955   //   or move constructor
5956   bool HasNonDeletedCopyOrMove = false;
5957 
5958   if (D->needsImplicitCopyConstructor() &&
5959       !D->defaultedCopyConstructorIsDeleted()) {
5960     if (!D->hasTrivialCopyConstructorForCall())
5961       return false;
5962     HasNonDeletedCopyOrMove = true;
5963   }
5964 
5965   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5966       !D->defaultedMoveConstructorIsDeleted()) {
5967     if (!D->hasTrivialMoveConstructorForCall())
5968       return false;
5969     HasNonDeletedCopyOrMove = true;
5970   }
5971 
5972   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5973       !D->hasTrivialDestructorForCall())
5974     return false;
5975 
5976   for (const CXXMethodDecl *MD : D->methods()) {
5977     if (MD->isDeleted())
5978       continue;
5979 
5980     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5981     if (CD && CD->isCopyOrMoveConstructor())
5982       HasNonDeletedCopyOrMove = true;
5983     else if (!isa<CXXDestructorDecl>(MD))
5984       continue;
5985 
5986     if (!MD->isTrivialForCall())
5987       return false;
5988   }
5989 
5990   return HasNonDeletedCopyOrMove;
5991 }
5992 
5993 /// Perform semantic checks on a class definition that has been
5994 /// completing, introducing implicitly-declared members, checking for
5995 /// abstract types, etc.
5996 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5997   if (!Record)
5998     return;
5999 
6000   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6001     AbstractUsageInfo Info(*this, Record);
6002     CheckAbstractClassUsage(Info, Record);
6003   }
6004 
6005   // If this is not an aggregate type and has no user-declared constructor,
6006   // complain about any non-static data members of reference or const scalar
6007   // type, since they will never get initializers.
6008   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6009       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6010       !Record->isLambda()) {
6011     bool Complained = false;
6012     for (const auto *F : Record->fields()) {
6013       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6014         continue;
6015 
6016       if (F->getType()->isReferenceType() ||
6017           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6018         if (!Complained) {
6019           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6020             << Record->getTagKind() << Record;
6021           Complained = true;
6022         }
6023 
6024         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6025           << F->getType()->isReferenceType()
6026           << F->getDeclName();
6027       }
6028     }
6029   }
6030 
6031   if (Record->getIdentifier()) {
6032     // C++ [class.mem]p13:
6033     //   If T is the name of a class, then each of the following shall have a
6034     //   name different from T:
6035     //     - every member of every anonymous union that is a member of class T.
6036     //
6037     // C++ [class.mem]p14:
6038     //   In addition, if class T has a user-declared constructor (12.1), every
6039     //   non-static data member of class T shall have a name different from T.
6040     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6041     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6042          ++I) {
6043       NamedDecl *D = (*I)->getUnderlyingDecl();
6044       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6045            Record->hasUserDeclaredConstructor()) ||
6046           isa<IndirectFieldDecl>(D)) {
6047         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6048           << D->getDeclName();
6049         break;
6050       }
6051     }
6052   }
6053 
6054   // Warn if the class has virtual methods but non-virtual public destructor.
6055   if (Record->isPolymorphic() && !Record->isDependentType()) {
6056     CXXDestructorDecl *dtor = Record->getDestructor();
6057     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6058         !Record->hasAttr<FinalAttr>())
6059       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6060            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6061   }
6062 
6063   if (Record->isAbstract()) {
6064     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6065       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6066         << FA->isSpelledAsSealed();
6067       DiagnoseAbstractType(Record);
6068     }
6069   }
6070 
6071   // See if trivial_abi has to be dropped.
6072   if (Record->hasAttr<TrivialABIAttr>())
6073     checkIllFormedTrivialABIStruct(*Record);
6074 
6075   // Set HasTrivialSpecialMemberForCall if the record has attribute
6076   // "trivial_abi".
6077   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6078 
6079   if (HasTrivialABI)
6080     Record->setHasTrivialSpecialMemberForCall();
6081 
6082   bool HasMethodWithOverrideControl = false,
6083        HasOverridingMethodWithoutOverrideControl = false;
6084   if (!Record->isDependentType()) {
6085     for (auto *M : Record->methods()) {
6086       // See if a method overloads virtual methods in a base
6087       // class without overriding any.
6088       if (!M->isStatic())
6089         DiagnoseHiddenVirtualMethods(M);
6090       if (M->hasAttr<OverrideAttr>())
6091         HasMethodWithOverrideControl = true;
6092       else if (M->size_overridden_methods() > 0)
6093         HasOverridingMethodWithoutOverrideControl = true;
6094       // Check whether the explicitly-defaulted special members are valid.
6095       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6096         CheckExplicitlyDefaultedSpecialMember(M);
6097 
6098       // For an explicitly defaulted or deleted special member, we defer
6099       // determining triviality until the class is complete. That time is now!
6100       CXXSpecialMember CSM = getSpecialMember(M);
6101       if (!M->isImplicit() && !M->isUserProvided()) {
6102         if (CSM != CXXInvalid) {
6103           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6104           // Inform the class that we've finished declaring this member.
6105           Record->finishedDefaultedOrDeletedMember(M);
6106           M->setTrivialForCall(
6107               HasTrivialABI ||
6108               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6109           Record->setTrivialForCallFlags(M);
6110         }
6111       }
6112 
6113       // Set triviality for the purpose of calls if this is a user-provided
6114       // copy/move constructor or destructor.
6115       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6116            CSM == CXXDestructor) && M->isUserProvided()) {
6117         M->setTrivialForCall(HasTrivialABI);
6118         Record->setTrivialForCallFlags(M);
6119       }
6120 
6121       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6122           M->hasAttr<DLLExportAttr>()) {
6123         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6124             M->isTrivial() &&
6125             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6126              CSM == CXXDestructor))
6127           M->dropAttr<DLLExportAttr>();
6128 
6129         if (M->hasAttr<DLLExportAttr>()) {
6130           DefineImplicitSpecialMember(*this, M, M->getLocation());
6131           ActOnFinishInlineFunctionDef(M);
6132         }
6133       }
6134     }
6135   }
6136 
6137   if (HasMethodWithOverrideControl &&
6138       HasOverridingMethodWithoutOverrideControl) {
6139     // At least one method has the 'override' control declared.
6140     // Diagnose all other overridden methods which do not have 'override' specified on them.
6141     for (auto *M : Record->methods())
6142       DiagnoseAbsenceOfOverrideControl(M);
6143   }
6144 
6145   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6146   // whether this class uses any C++ features that are implemented
6147   // completely differently in MSVC, and if so, emit a diagnostic.
6148   // That diagnostic defaults to an error, but we allow projects to
6149   // map it down to a warning (or ignore it).  It's a fairly common
6150   // practice among users of the ms_struct pragma to mass-annotate
6151   // headers, sweeping up a bunch of types that the project doesn't
6152   // really rely on MSVC-compatible layout for.  We must therefore
6153   // support "ms_struct except for C++ stuff" as a secondary ABI.
6154   if (Record->isMsStruct(Context) &&
6155       (Record->isPolymorphic() || Record->getNumBases())) {
6156     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6157   }
6158 
6159   checkClassLevelDLLAttribute(Record);
6160   checkClassLevelCodeSegAttribute(Record);
6161 
6162   bool ClangABICompat4 =
6163       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6164   TargetInfo::CallingConvKind CCK =
6165       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6166   bool CanPass = canPassInRegisters(*this, Record, CCK);
6167 
6168   // Do not change ArgPassingRestrictions if it has already been set to
6169   // APK_CanNeverPassInRegs.
6170   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6171     Record->setArgPassingRestrictions(CanPass
6172                                           ? RecordDecl::APK_CanPassInRegs
6173                                           : RecordDecl::APK_CannotPassInRegs);
6174 
6175   // If canPassInRegisters returns true despite the record having a non-trivial
6176   // destructor, the record is destructed in the callee. This happens only when
6177   // the record or one of its subobjects has a field annotated with trivial_abi
6178   // or a field qualified with ObjC __strong/__weak.
6179   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6180     Record->setParamDestroyedInCallee(true);
6181   else if (Record->hasNonTrivialDestructor())
6182     Record->setParamDestroyedInCallee(CanPass);
6183 
6184   if (getLangOpts().ForceEmitVTables) {
6185     // If we want to emit all the vtables, we need to mark it as used.  This
6186     // is especially required for cases like vtable assumption loads.
6187     MarkVTableUsed(Record->getInnerLocStart(), Record);
6188   }
6189 }
6190 
6191 /// Look up the special member function that would be called by a special
6192 /// member function for a subobject of class type.
6193 ///
6194 /// \param Class The class type of the subobject.
6195 /// \param CSM The kind of special member function.
6196 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6197 /// \param ConstRHS True if this is a copy operation with a const object
6198 ///        on its RHS, that is, if the argument to the outer special member
6199 ///        function is 'const' and this is not a field marked 'mutable'.
6200 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6201     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6202     unsigned FieldQuals, bool ConstRHS) {
6203   unsigned LHSQuals = 0;
6204   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6205     LHSQuals = FieldQuals;
6206 
6207   unsigned RHSQuals = FieldQuals;
6208   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6209     RHSQuals = 0;
6210   else if (ConstRHS)
6211     RHSQuals |= Qualifiers::Const;
6212 
6213   return S.LookupSpecialMember(Class, CSM,
6214                                RHSQuals & Qualifiers::Const,
6215                                RHSQuals & Qualifiers::Volatile,
6216                                false,
6217                                LHSQuals & Qualifiers::Const,
6218                                LHSQuals & Qualifiers::Volatile);
6219 }
6220 
6221 class Sema::InheritedConstructorInfo {
6222   Sema &S;
6223   SourceLocation UseLoc;
6224 
6225   /// A mapping from the base classes through which the constructor was
6226   /// inherited to the using shadow declaration in that base class (or a null
6227   /// pointer if the constructor was declared in that base class).
6228   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6229       InheritedFromBases;
6230 
6231 public:
6232   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6233                            ConstructorUsingShadowDecl *Shadow)
6234       : S(S), UseLoc(UseLoc) {
6235     bool DiagnosedMultipleConstructedBases = false;
6236     CXXRecordDecl *ConstructedBase = nullptr;
6237     UsingDecl *ConstructedBaseUsing = nullptr;
6238 
6239     // Find the set of such base class subobjects and check that there's a
6240     // unique constructed subobject.
6241     for (auto *D : Shadow->redecls()) {
6242       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6243       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6244       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6245 
6246       InheritedFromBases.insert(
6247           std::make_pair(DNominatedBase->getCanonicalDecl(),
6248                          DShadow->getNominatedBaseClassShadowDecl()));
6249       if (DShadow->constructsVirtualBase())
6250         InheritedFromBases.insert(
6251             std::make_pair(DConstructedBase->getCanonicalDecl(),
6252                            DShadow->getConstructedBaseClassShadowDecl()));
6253       else
6254         assert(DNominatedBase == DConstructedBase);
6255 
6256       // [class.inhctor.init]p2:
6257       //   If the constructor was inherited from multiple base class subobjects
6258       //   of type B, the program is ill-formed.
6259       if (!ConstructedBase) {
6260         ConstructedBase = DConstructedBase;
6261         ConstructedBaseUsing = D->getUsingDecl();
6262       } else if (ConstructedBase != DConstructedBase &&
6263                  !Shadow->isInvalidDecl()) {
6264         if (!DiagnosedMultipleConstructedBases) {
6265           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6266               << Shadow->getTargetDecl();
6267           S.Diag(ConstructedBaseUsing->getLocation(),
6268                diag::note_ambiguous_inherited_constructor_using)
6269               << ConstructedBase;
6270           DiagnosedMultipleConstructedBases = true;
6271         }
6272         S.Diag(D->getUsingDecl()->getLocation(),
6273                diag::note_ambiguous_inherited_constructor_using)
6274             << DConstructedBase;
6275       }
6276     }
6277 
6278     if (DiagnosedMultipleConstructedBases)
6279       Shadow->setInvalidDecl();
6280   }
6281 
6282   /// Find the constructor to use for inherited construction of a base class,
6283   /// and whether that base class constructor inherits the constructor from a
6284   /// virtual base class (in which case it won't actually invoke it).
6285   std::pair<CXXConstructorDecl *, bool>
6286   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6287     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6288     if (It == InheritedFromBases.end())
6289       return std::make_pair(nullptr, false);
6290 
6291     // This is an intermediary class.
6292     if (It->second)
6293       return std::make_pair(
6294           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6295           It->second->constructsVirtualBase());
6296 
6297     // This is the base class from which the constructor was inherited.
6298     return std::make_pair(Ctor, false);
6299   }
6300 };
6301 
6302 /// Is the special member function which would be selected to perform the
6303 /// specified operation on the specified class type a constexpr constructor?
6304 static bool
6305 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6306                          Sema::CXXSpecialMember CSM, unsigned Quals,
6307                          bool ConstRHS,
6308                          CXXConstructorDecl *InheritedCtor = nullptr,
6309                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6310   // If we're inheriting a constructor, see if we need to call it for this base
6311   // class.
6312   if (InheritedCtor) {
6313     assert(CSM == Sema::CXXDefaultConstructor);
6314     auto BaseCtor =
6315         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6316     if (BaseCtor)
6317       return BaseCtor->isConstexpr();
6318   }
6319 
6320   if (CSM == Sema::CXXDefaultConstructor)
6321     return ClassDecl->hasConstexprDefaultConstructor();
6322 
6323   Sema::SpecialMemberOverloadResult SMOR =
6324       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6325   if (!SMOR.getMethod())
6326     // A constructor we wouldn't select can't be "involved in initializing"
6327     // anything.
6328     return true;
6329   return SMOR.getMethod()->isConstexpr();
6330 }
6331 
6332 /// Determine whether the specified special member function would be constexpr
6333 /// if it were implicitly defined.
6334 static bool defaultedSpecialMemberIsConstexpr(
6335     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6336     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6337     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6338   if (!S.getLangOpts().CPlusPlus11)
6339     return false;
6340 
6341   // C++11 [dcl.constexpr]p4:
6342   // In the definition of a constexpr constructor [...]
6343   bool Ctor = true;
6344   switch (CSM) {
6345   case Sema::CXXDefaultConstructor:
6346     if (Inherited)
6347       break;
6348     // Since default constructor lookup is essentially trivial (and cannot
6349     // involve, for instance, template instantiation), we compute whether a
6350     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6351     //
6352     // This is important for performance; we need to know whether the default
6353     // constructor is constexpr to determine whether the type is a literal type.
6354     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6355 
6356   case Sema::CXXCopyConstructor:
6357   case Sema::CXXMoveConstructor:
6358     // For copy or move constructors, we need to perform overload resolution.
6359     break;
6360 
6361   case Sema::CXXCopyAssignment:
6362   case Sema::CXXMoveAssignment:
6363     if (!S.getLangOpts().CPlusPlus14)
6364       return false;
6365     // In C++1y, we need to perform overload resolution.
6366     Ctor = false;
6367     break;
6368 
6369   case Sema::CXXDestructor:
6370   case Sema::CXXInvalid:
6371     return false;
6372   }
6373 
6374   //   -- if the class is a non-empty union, or for each non-empty anonymous
6375   //      union member of a non-union class, exactly one non-static data member
6376   //      shall be initialized; [DR1359]
6377   //
6378   // If we squint, this is guaranteed, since exactly one non-static data member
6379   // will be initialized (if the constructor isn't deleted), we just don't know
6380   // which one.
6381   if (Ctor && ClassDecl->isUnion())
6382     return CSM == Sema::CXXDefaultConstructor
6383                ? ClassDecl->hasInClassInitializer() ||
6384                      !ClassDecl->hasVariantMembers()
6385                : true;
6386 
6387   //   -- the class shall not have any virtual base classes;
6388   if (Ctor && ClassDecl->getNumVBases())
6389     return false;
6390 
6391   // C++1y [class.copy]p26:
6392   //   -- [the class] is a literal type, and
6393   if (!Ctor && !ClassDecl->isLiteral())
6394     return false;
6395 
6396   //   -- every constructor involved in initializing [...] base class
6397   //      sub-objects shall be a constexpr constructor;
6398   //   -- the assignment operator selected to copy/move each direct base
6399   //      class is a constexpr function, and
6400   for (const auto &B : ClassDecl->bases()) {
6401     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6402     if (!BaseType) continue;
6403 
6404     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6405     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6406                                   InheritedCtor, Inherited))
6407       return false;
6408   }
6409 
6410   //   -- every constructor involved in initializing non-static data members
6411   //      [...] shall be a constexpr constructor;
6412   //   -- every non-static data member and base class sub-object shall be
6413   //      initialized
6414   //   -- for each non-static data member of X that is of class type (or array
6415   //      thereof), the assignment operator selected to copy/move that member is
6416   //      a constexpr function
6417   for (const auto *F : ClassDecl->fields()) {
6418     if (F->isInvalidDecl())
6419       continue;
6420     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6421       continue;
6422     QualType BaseType = S.Context.getBaseElementType(F->getType());
6423     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6424       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6425       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6426                                     BaseType.getCVRQualifiers(),
6427                                     ConstArg && !F->isMutable()))
6428         return false;
6429     } else if (CSM == Sema::CXXDefaultConstructor) {
6430       return false;
6431     }
6432   }
6433 
6434   // All OK, it's constexpr!
6435   return true;
6436 }
6437 
6438 static Sema::ImplicitExceptionSpecification
6439 ComputeDefaultedSpecialMemberExceptionSpec(
6440     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6441     Sema::InheritedConstructorInfo *ICI);
6442 
6443 static Sema::ImplicitExceptionSpecification
6444 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6445   auto CSM = S.getSpecialMember(MD);
6446   if (CSM != Sema::CXXInvalid)
6447     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6448 
6449   auto *CD = cast<CXXConstructorDecl>(MD);
6450   assert(CD->getInheritedConstructor() &&
6451          "only special members have implicit exception specs");
6452   Sema::InheritedConstructorInfo ICI(
6453       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6454   return ComputeDefaultedSpecialMemberExceptionSpec(
6455       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6456 }
6457 
6458 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6459                                                             CXXMethodDecl *MD) {
6460   FunctionProtoType::ExtProtoInfo EPI;
6461 
6462   // Build an exception specification pointing back at this member.
6463   EPI.ExceptionSpec.Type = EST_Unevaluated;
6464   EPI.ExceptionSpec.SourceDecl = MD;
6465 
6466   // Set the calling convention to the default for C++ instance methods.
6467   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6468       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6469                                             /*IsCXXMethod=*/true));
6470   return EPI;
6471 }
6472 
6473 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6474   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6475   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6476     return;
6477 
6478   // Evaluate the exception specification.
6479   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6480   auto ESI = IES.getExceptionSpec();
6481 
6482   // Update the type of the special member to use it.
6483   UpdateExceptionSpec(MD, ESI);
6484 
6485   // A user-provided destructor can be defined outside the class. When that
6486   // happens, be sure to update the exception specification on both
6487   // declarations.
6488   const FunctionProtoType *CanonicalFPT =
6489     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6490   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6491     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6492 }
6493 
6494 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6495   CXXRecordDecl *RD = MD->getParent();
6496   CXXSpecialMember CSM = getSpecialMember(MD);
6497 
6498   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6499          "not an explicitly-defaulted special member");
6500 
6501   // Whether this was the first-declared instance of the constructor.
6502   // This affects whether we implicitly add an exception spec and constexpr.
6503   bool First = MD == MD->getCanonicalDecl();
6504 
6505   bool HadError = false;
6506 
6507   // C++11 [dcl.fct.def.default]p1:
6508   //   A function that is explicitly defaulted shall
6509   //     -- be a special member function (checked elsewhere),
6510   //     -- have the same type (except for ref-qualifiers, and except that a
6511   //        copy operation can take a non-const reference) as an implicit
6512   //        declaration, and
6513   //     -- not have default arguments.
6514   // C++2a changes the second bullet to instead delete the function if it's
6515   // defaulted on its first declaration, unless it's "an assignment operator,
6516   // and its return type differs or its parameter type is not a reference".
6517   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6518   bool ShouldDeleteForTypeMismatch = false;
6519   unsigned ExpectedParams = 1;
6520   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6521     ExpectedParams = 0;
6522   if (MD->getNumParams() != ExpectedParams) {
6523     // This checks for default arguments: a copy or move constructor with a
6524     // default argument is classified as a default constructor, and assignment
6525     // operations and destructors can't have default arguments.
6526     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6527       << CSM << MD->getSourceRange();
6528     HadError = true;
6529   } else if (MD->isVariadic()) {
6530     if (DeleteOnTypeMismatch)
6531       ShouldDeleteForTypeMismatch = true;
6532     else {
6533       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6534         << CSM << MD->getSourceRange();
6535       HadError = true;
6536     }
6537   }
6538 
6539   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6540 
6541   bool CanHaveConstParam = false;
6542   if (CSM == CXXCopyConstructor)
6543     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6544   else if (CSM == CXXCopyAssignment)
6545     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6546 
6547   QualType ReturnType = Context.VoidTy;
6548   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6549     // Check for return type matching.
6550     ReturnType = Type->getReturnType();
6551     QualType ExpectedReturnType =
6552         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6553     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6554       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6555         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6556       HadError = true;
6557     }
6558 
6559     // A defaulted special member cannot have cv-qualifiers.
6560     if (Type->getTypeQuals()) {
6561       if (DeleteOnTypeMismatch)
6562         ShouldDeleteForTypeMismatch = true;
6563       else {
6564         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6565           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6566         HadError = true;
6567       }
6568     }
6569   }
6570 
6571   // Check for parameter type matching.
6572   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6573   bool HasConstParam = false;
6574   if (ExpectedParams && ArgType->isReferenceType()) {
6575     // Argument must be reference to possibly-const T.
6576     QualType ReferentType = ArgType->getPointeeType();
6577     HasConstParam = ReferentType.isConstQualified();
6578 
6579     if (ReferentType.isVolatileQualified()) {
6580       if (DeleteOnTypeMismatch)
6581         ShouldDeleteForTypeMismatch = true;
6582       else {
6583         Diag(MD->getLocation(),
6584              diag::err_defaulted_special_member_volatile_param) << CSM;
6585         HadError = true;
6586       }
6587     }
6588 
6589     if (HasConstParam && !CanHaveConstParam) {
6590       if (DeleteOnTypeMismatch)
6591         ShouldDeleteForTypeMismatch = true;
6592       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6593         Diag(MD->getLocation(),
6594              diag::err_defaulted_special_member_copy_const_param)
6595           << (CSM == CXXCopyAssignment);
6596         // FIXME: Explain why this special member can't be const.
6597         HadError = true;
6598       } else {
6599         Diag(MD->getLocation(),
6600              diag::err_defaulted_special_member_move_const_param)
6601           << (CSM == CXXMoveAssignment);
6602         HadError = true;
6603       }
6604     }
6605   } else if (ExpectedParams) {
6606     // A copy assignment operator can take its argument by value, but a
6607     // defaulted one cannot.
6608     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6609     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6610     HadError = true;
6611   }
6612 
6613   // C++11 [dcl.fct.def.default]p2:
6614   //   An explicitly-defaulted function may be declared constexpr only if it
6615   //   would have been implicitly declared as constexpr,
6616   // Do not apply this rule to members of class templates, since core issue 1358
6617   // makes such functions always instantiate to constexpr functions. For
6618   // functions which cannot be constexpr (for non-constructors in C++11 and for
6619   // destructors in C++1y), this is checked elsewhere.
6620   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6621                                                      HasConstParam);
6622   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6623                                  : isa<CXXConstructorDecl>(MD)) &&
6624       MD->isConstexpr() && !Constexpr &&
6625       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6626     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6627     // FIXME: Explain why the special member can't be constexpr.
6628     HadError = true;
6629   }
6630 
6631   //   and may have an explicit exception-specification only if it is compatible
6632   //   with the exception-specification on the implicit declaration.
6633   if (Type->hasExceptionSpec()) {
6634     // Delay the check if this is the first declaration of the special member,
6635     // since we may not have parsed some necessary in-class initializers yet.
6636     if (First) {
6637       // If the exception specification needs to be instantiated, do so now,
6638       // before we clobber it with an EST_Unevaluated specification below.
6639       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6640         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6641         Type = MD->getType()->getAs<FunctionProtoType>();
6642       }
6643       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6644     } else
6645       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6646   }
6647 
6648   //   If a function is explicitly defaulted on its first declaration,
6649   if (First) {
6650     //  -- it is implicitly considered to be constexpr if the implicit
6651     //     definition would be,
6652     MD->setConstexpr(Constexpr);
6653 
6654     //  -- it is implicitly considered to have the same exception-specification
6655     //     as if it had been implicitly declared,
6656     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6657     EPI.ExceptionSpec.Type = EST_Unevaluated;
6658     EPI.ExceptionSpec.SourceDecl = MD;
6659     MD->setType(Context.getFunctionType(ReturnType,
6660                                         llvm::makeArrayRef(&ArgType,
6661                                                            ExpectedParams),
6662                                         EPI));
6663   }
6664 
6665   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6666     if (First) {
6667       SetDeclDeleted(MD, MD->getLocation());
6668       if (!inTemplateInstantiation() && !HadError) {
6669         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6670         if (ShouldDeleteForTypeMismatch) {
6671           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6672         } else {
6673           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6674         }
6675       }
6676       if (ShouldDeleteForTypeMismatch && !HadError) {
6677         Diag(MD->getLocation(),
6678              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6679       }
6680     } else {
6681       // C++11 [dcl.fct.def.default]p4:
6682       //   [For a] user-provided explicitly-defaulted function [...] if such a
6683       //   function is implicitly defined as deleted, the program is ill-formed.
6684       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6685       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6686       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6687       HadError = true;
6688     }
6689   }
6690 
6691   if (HadError)
6692     MD->setInvalidDecl();
6693 }
6694 
6695 /// Check whether the exception specification provided for an
6696 /// explicitly-defaulted special member matches the exception specification
6697 /// that would have been generated for an implicit special member, per
6698 /// C++11 [dcl.fct.def.default]p2.
6699 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6700     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6701   // If the exception specification was explicitly specified but hadn't been
6702   // parsed when the method was defaulted, grab it now.
6703   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6704     SpecifiedType =
6705         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6706 
6707   // Compute the implicit exception specification.
6708   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6709                                                        /*IsCXXMethod=*/true);
6710   FunctionProtoType::ExtProtoInfo EPI(CC);
6711   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6712   EPI.ExceptionSpec = IES.getExceptionSpec();
6713   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6714     Context.getFunctionType(Context.VoidTy, None, EPI));
6715 
6716   // Ensure that it matches.
6717   CheckEquivalentExceptionSpec(
6718     PDiag(diag::err_incorrect_defaulted_exception_spec)
6719       << getSpecialMember(MD), PDiag(),
6720     ImplicitType, SourceLocation(),
6721     SpecifiedType, MD->getLocation());
6722 }
6723 
6724 void Sema::CheckDelayedMemberExceptionSpecs() {
6725   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6726   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6727   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6728 
6729   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6730   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6731   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6732 
6733   // Perform any deferred checking of exception specifications for virtual
6734   // destructors.
6735   for (auto &Check : Overriding)
6736     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6737 
6738   // Perform any deferred checking of exception specifications for befriended
6739   // special members.
6740   for (auto &Check : Equivalent)
6741     CheckEquivalentExceptionSpec(Check.second, Check.first);
6742 
6743   // Check that any explicitly-defaulted methods have exception specifications
6744   // compatible with their implicit exception specifications.
6745   for (auto &Spec : Defaulted)
6746     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6747 }
6748 
6749 namespace {
6750 /// CRTP base class for visiting operations performed by a special member
6751 /// function (or inherited constructor).
6752 template<typename Derived>
6753 struct SpecialMemberVisitor {
6754   Sema &S;
6755   CXXMethodDecl *MD;
6756   Sema::CXXSpecialMember CSM;
6757   Sema::InheritedConstructorInfo *ICI;
6758 
6759   // Properties of the special member, computed for convenience.
6760   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6761 
6762   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6763                        Sema::InheritedConstructorInfo *ICI)
6764       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6765     switch (CSM) {
6766     case Sema::CXXDefaultConstructor:
6767     case Sema::CXXCopyConstructor:
6768     case Sema::CXXMoveConstructor:
6769       IsConstructor = true;
6770       break;
6771     case Sema::CXXCopyAssignment:
6772     case Sema::CXXMoveAssignment:
6773       IsAssignment = true;
6774       break;
6775     case Sema::CXXDestructor:
6776       break;
6777     case Sema::CXXInvalid:
6778       llvm_unreachable("invalid special member kind");
6779     }
6780 
6781     if (MD->getNumParams()) {
6782       if (const ReferenceType *RT =
6783               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6784         ConstArg = RT->getPointeeType().isConstQualified();
6785     }
6786   }
6787 
6788   Derived &getDerived() { return static_cast<Derived&>(*this); }
6789 
6790   /// Is this a "move" special member?
6791   bool isMove() const {
6792     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6793   }
6794 
6795   /// Look up the corresponding special member in the given class.
6796   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6797                                              unsigned Quals, bool IsMutable) {
6798     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6799                                        ConstArg && !IsMutable);
6800   }
6801 
6802   /// Look up the constructor for the specified base class to see if it's
6803   /// overridden due to this being an inherited constructor.
6804   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6805     if (!ICI)
6806       return {};
6807     assert(CSM == Sema::CXXDefaultConstructor);
6808     auto *BaseCtor =
6809       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6810     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6811       return MD;
6812     return {};
6813   }
6814 
6815   /// A base or member subobject.
6816   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6817 
6818   /// Get the location to use for a subobject in diagnostics.
6819   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6820     // FIXME: For an indirect virtual base, the direct base leading to
6821     // the indirect virtual base would be a more useful choice.
6822     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6823       return B->getBaseTypeLoc();
6824     else
6825       return Subobj.get<FieldDecl*>()->getLocation();
6826   }
6827 
6828   enum BasesToVisit {
6829     /// Visit all non-virtual (direct) bases.
6830     VisitNonVirtualBases,
6831     /// Visit all direct bases, virtual or not.
6832     VisitDirectBases,
6833     /// Visit all non-virtual bases, and all virtual bases if the class
6834     /// is not abstract.
6835     VisitPotentiallyConstructedBases,
6836     /// Visit all direct or virtual bases.
6837     VisitAllBases
6838   };
6839 
6840   // Visit the bases and members of the class.
6841   bool visit(BasesToVisit Bases) {
6842     CXXRecordDecl *RD = MD->getParent();
6843 
6844     if (Bases == VisitPotentiallyConstructedBases)
6845       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6846 
6847     for (auto &B : RD->bases())
6848       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6849           getDerived().visitBase(&B))
6850         return true;
6851 
6852     if (Bases == VisitAllBases)
6853       for (auto &B : RD->vbases())
6854         if (getDerived().visitBase(&B))
6855           return true;
6856 
6857     for (auto *F : RD->fields())
6858       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6859           getDerived().visitField(F))
6860         return true;
6861 
6862     return false;
6863   }
6864 };
6865 }
6866 
6867 namespace {
6868 struct SpecialMemberDeletionInfo
6869     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6870   bool Diagnose;
6871 
6872   SourceLocation Loc;
6873 
6874   bool AllFieldsAreConst;
6875 
6876   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6877                             Sema::CXXSpecialMember CSM,
6878                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6879       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6880         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6881 
6882   bool inUnion() const { return MD->getParent()->isUnion(); }
6883 
6884   Sema::CXXSpecialMember getEffectiveCSM() {
6885     return ICI ? Sema::CXXInvalid : CSM;
6886   }
6887 
6888   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6889   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6890 
6891   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6892   bool shouldDeleteForField(FieldDecl *FD);
6893   bool shouldDeleteForAllConstMembers();
6894 
6895   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6896                                      unsigned Quals);
6897   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6898                                     Sema::SpecialMemberOverloadResult SMOR,
6899                                     bool IsDtorCallInCtor);
6900 
6901   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6902 };
6903 }
6904 
6905 /// Is the given special member inaccessible when used on the given
6906 /// sub-object.
6907 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6908                                              CXXMethodDecl *target) {
6909   /// If we're operating on a base class, the object type is the
6910   /// type of this special member.
6911   QualType objectTy;
6912   AccessSpecifier access = target->getAccess();
6913   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6914     objectTy = S.Context.getTypeDeclType(MD->getParent());
6915     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6916 
6917   // If we're operating on a field, the object type is the type of the field.
6918   } else {
6919     objectTy = S.Context.getTypeDeclType(target->getParent());
6920   }
6921 
6922   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6923 }
6924 
6925 /// Check whether we should delete a special member due to the implicit
6926 /// definition containing a call to a special member of a subobject.
6927 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6928     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6929     bool IsDtorCallInCtor) {
6930   CXXMethodDecl *Decl = SMOR.getMethod();
6931   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6932 
6933   int DiagKind = -1;
6934 
6935   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6936     DiagKind = !Decl ? 0 : 1;
6937   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6938     DiagKind = 2;
6939   else if (!isAccessible(Subobj, Decl))
6940     DiagKind = 3;
6941   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6942            !Decl->isTrivial()) {
6943     // A member of a union must have a trivial corresponding special member.
6944     // As a weird special case, a destructor call from a union's constructor
6945     // must be accessible and non-deleted, but need not be trivial. Such a
6946     // destructor is never actually called, but is semantically checked as
6947     // if it were.
6948     DiagKind = 4;
6949   }
6950 
6951   if (DiagKind == -1)
6952     return false;
6953 
6954   if (Diagnose) {
6955     if (Field) {
6956       S.Diag(Field->getLocation(),
6957              diag::note_deleted_special_member_class_subobject)
6958         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6959         << Field << DiagKind << IsDtorCallInCtor;
6960     } else {
6961       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6962       S.Diag(Base->getBeginLoc(),
6963              diag::note_deleted_special_member_class_subobject)
6964           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6965           << Base->getType() << DiagKind << IsDtorCallInCtor;
6966     }
6967 
6968     if (DiagKind == 1)
6969       S.NoteDeletedFunction(Decl);
6970     // FIXME: Explain inaccessibility if DiagKind == 3.
6971   }
6972 
6973   return true;
6974 }
6975 
6976 /// Check whether we should delete a special member function due to having a
6977 /// direct or virtual base class or non-static data member of class type M.
6978 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6979     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6980   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6981   bool IsMutable = Field && Field->isMutable();
6982 
6983   // C++11 [class.ctor]p5:
6984   // -- any direct or virtual base class, or non-static data member with no
6985   //    brace-or-equal-initializer, has class type M (or array thereof) and
6986   //    either M has no default constructor or overload resolution as applied
6987   //    to M's default constructor results in an ambiguity or in a function
6988   //    that is deleted or inaccessible
6989   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6990   // -- a direct or virtual base class B that cannot be copied/moved because
6991   //    overload resolution, as applied to B's corresponding special member,
6992   //    results in an ambiguity or a function that is deleted or inaccessible
6993   //    from the defaulted special member
6994   // C++11 [class.dtor]p5:
6995   // -- any direct or virtual base class [...] has a type with a destructor
6996   //    that is deleted or inaccessible
6997   if (!(CSM == Sema::CXXDefaultConstructor &&
6998         Field && Field->hasInClassInitializer()) &&
6999       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7000                                    false))
7001     return true;
7002 
7003   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7004   // -- any direct or virtual base class or non-static data member has a
7005   //    type with a destructor that is deleted or inaccessible
7006   if (IsConstructor) {
7007     Sema::SpecialMemberOverloadResult SMOR =
7008         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7009                               false, false, false, false, false);
7010     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7011       return true;
7012   }
7013 
7014   return false;
7015 }
7016 
7017 /// Check whether we should delete a special member function due to the class
7018 /// having a particular direct or virtual base class.
7019 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7020   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7021   // If program is correct, BaseClass cannot be null, but if it is, the error
7022   // must be reported elsewhere.
7023   if (!BaseClass)
7024     return false;
7025   // If we have an inheriting constructor, check whether we're calling an
7026   // inherited constructor instead of a default constructor.
7027   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7028   if (auto *BaseCtor = SMOR.getMethod()) {
7029     // Note that we do not check access along this path; other than that,
7030     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7031     // FIXME: Check that the base has a usable destructor! Sink this into
7032     // shouldDeleteForClassSubobject.
7033     if (BaseCtor->isDeleted() && Diagnose) {
7034       S.Diag(Base->getBeginLoc(),
7035              diag::note_deleted_special_member_class_subobject)
7036           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7037           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
7038       S.NoteDeletedFunction(BaseCtor);
7039     }
7040     return BaseCtor->isDeleted();
7041   }
7042   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7043 }
7044 
7045 /// Check whether we should delete a special member function due to the class
7046 /// having a particular non-static data member.
7047 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7048   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7049   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7050 
7051   if (CSM == Sema::CXXDefaultConstructor) {
7052     // For a default constructor, all references must be initialized in-class
7053     // and, if a union, it must have a non-const member.
7054     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7055       if (Diagnose)
7056         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7057           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7058       return true;
7059     }
7060     // C++11 [class.ctor]p5: any non-variant non-static data member of
7061     // const-qualified type (or array thereof) with no
7062     // brace-or-equal-initializer does not have a user-provided default
7063     // constructor.
7064     if (!inUnion() && FieldType.isConstQualified() &&
7065         !FD->hasInClassInitializer() &&
7066         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7067       if (Diagnose)
7068         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7069           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7070       return true;
7071     }
7072 
7073     if (inUnion() && !FieldType.isConstQualified())
7074       AllFieldsAreConst = false;
7075   } else if (CSM == Sema::CXXCopyConstructor) {
7076     // For a copy constructor, data members must not be of rvalue reference
7077     // type.
7078     if (FieldType->isRValueReferenceType()) {
7079       if (Diagnose)
7080         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7081           << MD->getParent() << FD << FieldType;
7082       return true;
7083     }
7084   } else if (IsAssignment) {
7085     // For an assignment operator, data members must not be of reference type.
7086     if (FieldType->isReferenceType()) {
7087       if (Diagnose)
7088         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7089           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7090       return true;
7091     }
7092     if (!FieldRecord && FieldType.isConstQualified()) {
7093       // C++11 [class.copy]p23:
7094       // -- a non-static data member of const non-class type (or array thereof)
7095       if (Diagnose)
7096         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7097           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7098       return true;
7099     }
7100   }
7101 
7102   if (FieldRecord) {
7103     // Some additional restrictions exist on the variant members.
7104     if (!inUnion() && FieldRecord->isUnion() &&
7105         FieldRecord->isAnonymousStructOrUnion()) {
7106       bool AllVariantFieldsAreConst = true;
7107 
7108       // FIXME: Handle anonymous unions declared within anonymous unions.
7109       for (auto *UI : FieldRecord->fields()) {
7110         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7111 
7112         if (!UnionFieldType.isConstQualified())
7113           AllVariantFieldsAreConst = false;
7114 
7115         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7116         if (UnionFieldRecord &&
7117             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7118                                           UnionFieldType.getCVRQualifiers()))
7119           return true;
7120       }
7121 
7122       // At least one member in each anonymous union must be non-const
7123       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7124           !FieldRecord->field_empty()) {
7125         if (Diagnose)
7126           S.Diag(FieldRecord->getLocation(),
7127                  diag::note_deleted_default_ctor_all_const)
7128             << !!ICI << MD->getParent() << /*anonymous union*/1;
7129         return true;
7130       }
7131 
7132       // Don't check the implicit member of the anonymous union type.
7133       // This is technically non-conformant, but sanity demands it.
7134       return false;
7135     }
7136 
7137     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7138                                       FieldType.getCVRQualifiers()))
7139       return true;
7140   }
7141 
7142   return false;
7143 }
7144 
7145 /// C++11 [class.ctor] p5:
7146 ///   A defaulted default constructor for a class X is defined as deleted if
7147 /// X is a union and all of its variant members are of const-qualified type.
7148 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7149   // This is a silly definition, because it gives an empty union a deleted
7150   // default constructor. Don't do that.
7151   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7152     bool AnyFields = false;
7153     for (auto *F : MD->getParent()->fields())
7154       if ((AnyFields = !F->isUnnamedBitfield()))
7155         break;
7156     if (!AnyFields)
7157       return false;
7158     if (Diagnose)
7159       S.Diag(MD->getParent()->getLocation(),
7160              diag::note_deleted_default_ctor_all_const)
7161         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7162     return true;
7163   }
7164   return false;
7165 }
7166 
7167 /// Determine whether a defaulted special member function should be defined as
7168 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7169 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7170 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7171                                      InheritedConstructorInfo *ICI,
7172                                      bool Diagnose) {
7173   if (MD->isInvalidDecl())
7174     return false;
7175   CXXRecordDecl *RD = MD->getParent();
7176   assert(!RD->isDependentType() && "do deletion after instantiation");
7177   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7178     return false;
7179 
7180   // C++11 [expr.lambda.prim]p19:
7181   //   The closure type associated with a lambda-expression has a
7182   //   deleted (8.4.3) default constructor and a deleted copy
7183   //   assignment operator.
7184   // C++2a adds back these operators if the lambda has no capture-default.
7185   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7186       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7187     if (Diagnose)
7188       Diag(RD->getLocation(), diag::note_lambda_decl);
7189     return true;
7190   }
7191 
7192   // For an anonymous struct or union, the copy and assignment special members
7193   // will never be used, so skip the check. For an anonymous union declared at
7194   // namespace scope, the constructor and destructor are used.
7195   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7196       RD->isAnonymousStructOrUnion())
7197     return false;
7198 
7199   // C++11 [class.copy]p7, p18:
7200   //   If the class definition declares a move constructor or move assignment
7201   //   operator, an implicitly declared copy constructor or copy assignment
7202   //   operator is defined as deleted.
7203   if (MD->isImplicit() &&
7204       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7205     CXXMethodDecl *UserDeclaredMove = nullptr;
7206 
7207     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7208     // deletion of the corresponding copy operation, not both copy operations.
7209     // MSVC 2015 has adopted the standards conforming behavior.
7210     bool DeletesOnlyMatchingCopy =
7211         getLangOpts().MSVCCompat &&
7212         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7213 
7214     if (RD->hasUserDeclaredMoveConstructor() &&
7215         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7216       if (!Diagnose) return true;
7217 
7218       // Find any user-declared move constructor.
7219       for (auto *I : RD->ctors()) {
7220         if (I->isMoveConstructor()) {
7221           UserDeclaredMove = I;
7222           break;
7223         }
7224       }
7225       assert(UserDeclaredMove);
7226     } else if (RD->hasUserDeclaredMoveAssignment() &&
7227                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7228       if (!Diagnose) return true;
7229 
7230       // Find any user-declared move assignment operator.
7231       for (auto *I : RD->methods()) {
7232         if (I->isMoveAssignmentOperator()) {
7233           UserDeclaredMove = I;
7234           break;
7235         }
7236       }
7237       assert(UserDeclaredMove);
7238     }
7239 
7240     if (UserDeclaredMove) {
7241       Diag(UserDeclaredMove->getLocation(),
7242            diag::note_deleted_copy_user_declared_move)
7243         << (CSM == CXXCopyAssignment) << RD
7244         << UserDeclaredMove->isMoveAssignmentOperator();
7245       return true;
7246     }
7247   }
7248 
7249   // Do access control from the special member function
7250   ContextRAII MethodContext(*this, MD);
7251 
7252   // C++11 [class.dtor]p5:
7253   // -- for a virtual destructor, lookup of the non-array deallocation function
7254   //    results in an ambiguity or in a function that is deleted or inaccessible
7255   if (CSM == CXXDestructor && MD->isVirtual()) {
7256     FunctionDecl *OperatorDelete = nullptr;
7257     DeclarationName Name =
7258       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7259     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7260                                  OperatorDelete, /*Diagnose*/false)) {
7261       if (Diagnose)
7262         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7263       return true;
7264     }
7265   }
7266 
7267   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7268 
7269   // Per DR1611, do not consider virtual bases of constructors of abstract
7270   // classes, since we are not going to construct them.
7271   // Per DR1658, do not consider virtual bases of destructors of abstract
7272   // classes either.
7273   // Per DR2180, for assignment operators we only assign (and thus only
7274   // consider) direct bases.
7275   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7276                                  : SMI.VisitPotentiallyConstructedBases))
7277     return true;
7278 
7279   if (SMI.shouldDeleteForAllConstMembers())
7280     return true;
7281 
7282   if (getLangOpts().CUDA) {
7283     // We should delete the special member in CUDA mode if target inference
7284     // failed.
7285     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7286     // is treated as certain special member, which may not reflect what special
7287     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7288     // expects CSM to match MD, therefore recalculate CSM.
7289     assert(ICI || CSM == getSpecialMember(MD));
7290     auto RealCSM = CSM;
7291     if (ICI)
7292       RealCSM = getSpecialMember(MD);
7293 
7294     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7295                                                    SMI.ConstArg, Diagnose);
7296   }
7297 
7298   return false;
7299 }
7300 
7301 /// Perform lookup for a special member of the specified kind, and determine
7302 /// whether it is trivial. If the triviality can be determined without the
7303 /// lookup, skip it. This is intended for use when determining whether a
7304 /// special member of a containing object is trivial, and thus does not ever
7305 /// perform overload resolution for default constructors.
7306 ///
7307 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7308 /// member that was most likely to be intended to be trivial, if any.
7309 ///
7310 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7311 /// determine whether the special member is trivial.
7312 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7313                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7314                                      bool ConstRHS,
7315                                      Sema::TrivialABIHandling TAH,
7316                                      CXXMethodDecl **Selected) {
7317   if (Selected)
7318     *Selected = nullptr;
7319 
7320   switch (CSM) {
7321   case Sema::CXXInvalid:
7322     llvm_unreachable("not a special member");
7323 
7324   case Sema::CXXDefaultConstructor:
7325     // C++11 [class.ctor]p5:
7326     //   A default constructor is trivial if:
7327     //    - all the [direct subobjects] have trivial default constructors
7328     //
7329     // Note, no overload resolution is performed in this case.
7330     if (RD->hasTrivialDefaultConstructor())
7331       return true;
7332 
7333     if (Selected) {
7334       // If there's a default constructor which could have been trivial, dig it
7335       // out. Otherwise, if there's any user-provided default constructor, point
7336       // to that as an example of why there's not a trivial one.
7337       CXXConstructorDecl *DefCtor = nullptr;
7338       if (RD->needsImplicitDefaultConstructor())
7339         S.DeclareImplicitDefaultConstructor(RD);
7340       for (auto *CI : RD->ctors()) {
7341         if (!CI->isDefaultConstructor())
7342           continue;
7343         DefCtor = CI;
7344         if (!DefCtor->isUserProvided())
7345           break;
7346       }
7347 
7348       *Selected = DefCtor;
7349     }
7350 
7351     return false;
7352 
7353   case Sema::CXXDestructor:
7354     // C++11 [class.dtor]p5:
7355     //   A destructor is trivial if:
7356     //    - all the direct [subobjects] have trivial destructors
7357     if (RD->hasTrivialDestructor() ||
7358         (TAH == Sema::TAH_ConsiderTrivialABI &&
7359          RD->hasTrivialDestructorForCall()))
7360       return true;
7361 
7362     if (Selected) {
7363       if (RD->needsImplicitDestructor())
7364         S.DeclareImplicitDestructor(RD);
7365       *Selected = RD->getDestructor();
7366     }
7367 
7368     return false;
7369 
7370   case Sema::CXXCopyConstructor:
7371     // C++11 [class.copy]p12:
7372     //   A copy constructor is trivial if:
7373     //    - the constructor selected to copy each direct [subobject] is trivial
7374     if (RD->hasTrivialCopyConstructor() ||
7375         (TAH == Sema::TAH_ConsiderTrivialABI &&
7376          RD->hasTrivialCopyConstructorForCall())) {
7377       if (Quals == Qualifiers::Const)
7378         // We must either select the trivial copy constructor or reach an
7379         // ambiguity; no need to actually perform overload resolution.
7380         return true;
7381     } else if (!Selected) {
7382       return false;
7383     }
7384     // In C++98, we are not supposed to perform overload resolution here, but we
7385     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7386     // cases like B as having a non-trivial copy constructor:
7387     //   struct A { template<typename T> A(T&); };
7388     //   struct B { mutable A a; };
7389     goto NeedOverloadResolution;
7390 
7391   case Sema::CXXCopyAssignment:
7392     // C++11 [class.copy]p25:
7393     //   A copy assignment operator is trivial if:
7394     //    - the assignment operator selected to copy each direct [subobject] is
7395     //      trivial
7396     if (RD->hasTrivialCopyAssignment()) {
7397       if (Quals == Qualifiers::Const)
7398         return true;
7399     } else if (!Selected) {
7400       return false;
7401     }
7402     // In C++98, we are not supposed to perform overload resolution here, but we
7403     // treat that as a language defect.
7404     goto NeedOverloadResolution;
7405 
7406   case Sema::CXXMoveConstructor:
7407   case Sema::CXXMoveAssignment:
7408   NeedOverloadResolution:
7409     Sema::SpecialMemberOverloadResult SMOR =
7410         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7411 
7412     // The standard doesn't describe how to behave if the lookup is ambiguous.
7413     // We treat it as not making the member non-trivial, just like the standard
7414     // mandates for the default constructor. This should rarely matter, because
7415     // the member will also be deleted.
7416     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7417       return true;
7418 
7419     if (!SMOR.getMethod()) {
7420       assert(SMOR.getKind() ==
7421              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7422       return false;
7423     }
7424 
7425     // We deliberately don't check if we found a deleted special member. We're
7426     // not supposed to!
7427     if (Selected)
7428       *Selected = SMOR.getMethod();
7429 
7430     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7431         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7432       return SMOR.getMethod()->isTrivialForCall();
7433     return SMOR.getMethod()->isTrivial();
7434   }
7435 
7436   llvm_unreachable("unknown special method kind");
7437 }
7438 
7439 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7440   for (auto *CI : RD->ctors())
7441     if (!CI->isImplicit())
7442       return CI;
7443 
7444   // Look for constructor templates.
7445   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7446   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7447     if (CXXConstructorDecl *CD =
7448           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7449       return CD;
7450   }
7451 
7452   return nullptr;
7453 }
7454 
7455 /// The kind of subobject we are checking for triviality. The values of this
7456 /// enumeration are used in diagnostics.
7457 enum TrivialSubobjectKind {
7458   /// The subobject is a base class.
7459   TSK_BaseClass,
7460   /// The subobject is a non-static data member.
7461   TSK_Field,
7462   /// The object is actually the complete object.
7463   TSK_CompleteObject
7464 };
7465 
7466 /// Check whether the special member selected for a given type would be trivial.
7467 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7468                                       QualType SubType, bool ConstRHS,
7469                                       Sema::CXXSpecialMember CSM,
7470                                       TrivialSubobjectKind Kind,
7471                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7472   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7473   if (!SubRD)
7474     return true;
7475 
7476   CXXMethodDecl *Selected;
7477   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7478                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7479     return true;
7480 
7481   if (Diagnose) {
7482     if (ConstRHS)
7483       SubType.addConst();
7484 
7485     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7486       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7487         << Kind << SubType.getUnqualifiedType();
7488       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7489         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7490     } else if (!Selected)
7491       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7492         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7493     else if (Selected->isUserProvided()) {
7494       if (Kind == TSK_CompleteObject)
7495         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7496           << Kind << SubType.getUnqualifiedType() << CSM;
7497       else {
7498         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7499           << Kind << SubType.getUnqualifiedType() << CSM;
7500         S.Diag(Selected->getLocation(), diag::note_declared_at);
7501       }
7502     } else {
7503       if (Kind != TSK_CompleteObject)
7504         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7505           << Kind << SubType.getUnqualifiedType() << CSM;
7506 
7507       // Explain why the defaulted or deleted special member isn't trivial.
7508       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7509                                Diagnose);
7510     }
7511   }
7512 
7513   return false;
7514 }
7515 
7516 /// Check whether the members of a class type allow a special member to be
7517 /// trivial.
7518 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7519                                      Sema::CXXSpecialMember CSM,
7520                                      bool ConstArg,
7521                                      Sema::TrivialABIHandling TAH,
7522                                      bool Diagnose) {
7523   for (const auto *FI : RD->fields()) {
7524     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7525       continue;
7526 
7527     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7528 
7529     // Pretend anonymous struct or union members are members of this class.
7530     if (FI->isAnonymousStructOrUnion()) {
7531       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7532                                     CSM, ConstArg, TAH, Diagnose))
7533         return false;
7534       continue;
7535     }
7536 
7537     // C++11 [class.ctor]p5:
7538     //   A default constructor is trivial if [...]
7539     //    -- no non-static data member of its class has a
7540     //       brace-or-equal-initializer
7541     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7542       if (Diagnose)
7543         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7544       return false;
7545     }
7546 
7547     // Objective C ARC 4.3.5:
7548     //   [...] nontrivally ownership-qualified types are [...] not trivially
7549     //   default constructible, copy constructible, move constructible, copy
7550     //   assignable, move assignable, or destructible [...]
7551     if (FieldType.hasNonTrivialObjCLifetime()) {
7552       if (Diagnose)
7553         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7554           << RD << FieldType.getObjCLifetime();
7555       return false;
7556     }
7557 
7558     bool ConstRHS = ConstArg && !FI->isMutable();
7559     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7560                                    CSM, TSK_Field, TAH, Diagnose))
7561       return false;
7562   }
7563 
7564   return true;
7565 }
7566 
7567 /// Diagnose why the specified class does not have a trivial special member of
7568 /// the given kind.
7569 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7570   QualType Ty = Context.getRecordType(RD);
7571 
7572   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7573   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7574                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7575                             /*Diagnose*/true);
7576 }
7577 
7578 /// Determine whether a defaulted or deleted special member function is trivial,
7579 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7580 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7581 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7582                                   TrivialABIHandling TAH, bool Diagnose) {
7583   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7584 
7585   CXXRecordDecl *RD = MD->getParent();
7586 
7587   bool ConstArg = false;
7588 
7589   // C++11 [class.copy]p12, p25: [DR1593]
7590   //   A [special member] is trivial if [...] its parameter-type-list is
7591   //   equivalent to the parameter-type-list of an implicit declaration [...]
7592   switch (CSM) {
7593   case CXXDefaultConstructor:
7594   case CXXDestructor:
7595     // Trivial default constructors and destructors cannot have parameters.
7596     break;
7597 
7598   case CXXCopyConstructor:
7599   case CXXCopyAssignment: {
7600     // Trivial copy operations always have const, non-volatile parameter types.
7601     ConstArg = true;
7602     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7603     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7604     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7605       if (Diagnose)
7606         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7607           << Param0->getSourceRange() << Param0->getType()
7608           << Context.getLValueReferenceType(
7609                Context.getRecordType(RD).withConst());
7610       return false;
7611     }
7612     break;
7613   }
7614 
7615   case CXXMoveConstructor:
7616   case CXXMoveAssignment: {
7617     // Trivial move operations always have non-cv-qualified parameters.
7618     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7619     const RValueReferenceType *RT =
7620       Param0->getType()->getAs<RValueReferenceType>();
7621     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7622       if (Diagnose)
7623         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7624           << Param0->getSourceRange() << Param0->getType()
7625           << Context.getRValueReferenceType(Context.getRecordType(RD));
7626       return false;
7627     }
7628     break;
7629   }
7630 
7631   case CXXInvalid:
7632     llvm_unreachable("not a special member");
7633   }
7634 
7635   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7636     if (Diagnose)
7637       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7638            diag::note_nontrivial_default_arg)
7639         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7640     return false;
7641   }
7642   if (MD->isVariadic()) {
7643     if (Diagnose)
7644       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7645     return false;
7646   }
7647 
7648   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7649   //   A copy/move [constructor or assignment operator] is trivial if
7650   //    -- the [member] selected to copy/move each direct base class subobject
7651   //       is trivial
7652   //
7653   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7654   //   A [default constructor or destructor] is trivial if
7655   //    -- all the direct base classes have trivial [default constructors or
7656   //       destructors]
7657   for (const auto &BI : RD->bases())
7658     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7659                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7660       return false;
7661 
7662   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7663   //   A copy/move [constructor or assignment operator] for a class X is
7664   //   trivial if
7665   //    -- for each non-static data member of X that is of class type (or array
7666   //       thereof), the constructor selected to copy/move that member is
7667   //       trivial
7668   //
7669   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7670   //   A [default constructor or destructor] is trivial if
7671   //    -- for all of the non-static data members of its class that are of class
7672   //       type (or array thereof), each such class has a trivial [default
7673   //       constructor or destructor]
7674   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7675     return false;
7676 
7677   // C++11 [class.dtor]p5:
7678   //   A destructor is trivial if [...]
7679   //    -- the destructor is not virtual
7680   if (CSM == CXXDestructor && MD->isVirtual()) {
7681     if (Diagnose)
7682       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7683     return false;
7684   }
7685 
7686   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7687   //   A [special member] for class X is trivial if [...]
7688   //    -- class X has no virtual functions and no virtual base classes
7689   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7690     if (!Diagnose)
7691       return false;
7692 
7693     if (RD->getNumVBases()) {
7694       // Check for virtual bases. We already know that the corresponding
7695       // member in all bases is trivial, so vbases must all be direct.
7696       CXXBaseSpecifier &BS = *RD->vbases_begin();
7697       assert(BS.isVirtual());
7698       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7699       return false;
7700     }
7701 
7702     // Must have a virtual method.
7703     for (const auto *MI : RD->methods()) {
7704       if (MI->isVirtual()) {
7705         SourceLocation MLoc = MI->getBeginLoc();
7706         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7707         return false;
7708       }
7709     }
7710 
7711     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7712   }
7713 
7714   // Looks like it's trivial!
7715   return true;
7716 }
7717 
7718 namespace {
7719 struct FindHiddenVirtualMethod {
7720   Sema *S;
7721   CXXMethodDecl *Method;
7722   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7723   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7724 
7725 private:
7726   /// Check whether any most overridden method from MD in Methods
7727   static bool CheckMostOverridenMethods(
7728       const CXXMethodDecl *MD,
7729       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7730     if (MD->size_overridden_methods() == 0)
7731       return Methods.count(MD->getCanonicalDecl());
7732     for (const CXXMethodDecl *O : MD->overridden_methods())
7733       if (CheckMostOverridenMethods(O, Methods))
7734         return true;
7735     return false;
7736   }
7737 
7738 public:
7739   /// Member lookup function that determines whether a given C++
7740   /// method overloads virtual methods in a base class without overriding any,
7741   /// to be used with CXXRecordDecl::lookupInBases().
7742   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7743     RecordDecl *BaseRecord =
7744         Specifier->getType()->getAs<RecordType>()->getDecl();
7745 
7746     DeclarationName Name = Method->getDeclName();
7747     assert(Name.getNameKind() == DeclarationName::Identifier);
7748 
7749     bool foundSameNameMethod = false;
7750     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7751     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7752          Path.Decls = Path.Decls.slice(1)) {
7753       NamedDecl *D = Path.Decls.front();
7754       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7755         MD = MD->getCanonicalDecl();
7756         foundSameNameMethod = true;
7757         // Interested only in hidden virtual methods.
7758         if (!MD->isVirtual())
7759           continue;
7760         // If the method we are checking overrides a method from its base
7761         // don't warn about the other overloaded methods. Clang deviates from
7762         // GCC by only diagnosing overloads of inherited virtual functions that
7763         // do not override any other virtual functions in the base. GCC's
7764         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7765         // function from a base class. These cases may be better served by a
7766         // warning (not specific to virtual functions) on call sites when the
7767         // call would select a different function from the base class, were it
7768         // visible.
7769         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7770         if (!S->IsOverload(Method, MD, false))
7771           return true;
7772         // Collect the overload only if its hidden.
7773         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7774           overloadedMethods.push_back(MD);
7775       }
7776     }
7777 
7778     if (foundSameNameMethod)
7779       OverloadedMethods.append(overloadedMethods.begin(),
7780                                overloadedMethods.end());
7781     return foundSameNameMethod;
7782   }
7783 };
7784 } // end anonymous namespace
7785 
7786 /// Add the most overriden methods from MD to Methods
7787 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7788                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7789   if (MD->size_overridden_methods() == 0)
7790     Methods.insert(MD->getCanonicalDecl());
7791   else
7792     for (const CXXMethodDecl *O : MD->overridden_methods())
7793       AddMostOverridenMethods(O, Methods);
7794 }
7795 
7796 /// Check if a method overloads virtual methods in a base class without
7797 /// overriding any.
7798 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7799                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7800   if (!MD->getDeclName().isIdentifier())
7801     return;
7802 
7803   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7804                      /*bool RecordPaths=*/false,
7805                      /*bool DetectVirtual=*/false);
7806   FindHiddenVirtualMethod FHVM;
7807   FHVM.Method = MD;
7808   FHVM.S = this;
7809 
7810   // Keep the base methods that were overridden or introduced in the subclass
7811   // by 'using' in a set. A base method not in this set is hidden.
7812   CXXRecordDecl *DC = MD->getParent();
7813   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7814   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7815     NamedDecl *ND = *I;
7816     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7817       ND = shad->getTargetDecl();
7818     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7819       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7820   }
7821 
7822   if (DC->lookupInBases(FHVM, Paths))
7823     OverloadedMethods = FHVM.OverloadedMethods;
7824 }
7825 
7826 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7827                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7828   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7829     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7830     PartialDiagnostic PD = PDiag(
7831          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7832     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7833     Diag(overloadedMD->getLocation(), PD);
7834   }
7835 }
7836 
7837 /// Diagnose methods which overload virtual methods in a base class
7838 /// without overriding any.
7839 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7840   if (MD->isInvalidDecl())
7841     return;
7842 
7843   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7844     return;
7845 
7846   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7847   FindHiddenVirtualMethods(MD, OverloadedMethods);
7848   if (!OverloadedMethods.empty()) {
7849     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7850       << MD << (OverloadedMethods.size() > 1);
7851 
7852     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7853   }
7854 }
7855 
7856 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7857   auto PrintDiagAndRemoveAttr = [&]() {
7858     // No diagnostics if this is a template instantiation.
7859     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7860       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7861            diag::ext_cannot_use_trivial_abi) << &RD;
7862     RD.dropAttr<TrivialABIAttr>();
7863   };
7864 
7865   // Ill-formed if the struct has virtual functions.
7866   if (RD.isPolymorphic()) {
7867     PrintDiagAndRemoveAttr();
7868     return;
7869   }
7870 
7871   for (const auto &B : RD.bases()) {
7872     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7873     // virtual base.
7874     if ((!B.getType()->isDependentType() &&
7875          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7876         B.isVirtual()) {
7877       PrintDiagAndRemoveAttr();
7878       return;
7879     }
7880   }
7881 
7882   for (const auto *FD : RD.fields()) {
7883     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7884     // non-trivial for the purpose of calls.
7885     QualType FT = FD->getType();
7886     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7887       PrintDiagAndRemoveAttr();
7888       return;
7889     }
7890 
7891     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7892       if (!RT->isDependentType() &&
7893           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7894         PrintDiagAndRemoveAttr();
7895         return;
7896       }
7897   }
7898 }
7899 
7900 void Sema::ActOnFinishCXXMemberSpecification(
7901     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7902     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7903   if (!TagDecl)
7904     return;
7905 
7906   AdjustDeclIfTemplate(TagDecl);
7907 
7908   for (const ParsedAttr &AL : AttrList) {
7909     if (AL.getKind() != ParsedAttr::AT_Visibility)
7910       continue;
7911     AL.setInvalid();
7912     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7913         << AL.getName();
7914   }
7915 
7916   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7917               // strict aliasing violation!
7918               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7919               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7920 
7921   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7922 }
7923 
7924 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7925 /// special functions, such as the default constructor, copy
7926 /// constructor, or destructor, to the given C++ class (C++
7927 /// [special]p1).  This routine can only be executed just before the
7928 /// definition of the class is complete.
7929 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7930   if (ClassDecl->needsImplicitDefaultConstructor()) {
7931     ++ASTContext::NumImplicitDefaultConstructors;
7932 
7933     if (ClassDecl->hasInheritedConstructor())
7934       DeclareImplicitDefaultConstructor(ClassDecl);
7935   }
7936 
7937   if (ClassDecl->needsImplicitCopyConstructor()) {
7938     ++ASTContext::NumImplicitCopyConstructors;
7939 
7940     // If the properties or semantics of the copy constructor couldn't be
7941     // determined while the class was being declared, force a declaration
7942     // of it now.
7943     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7944         ClassDecl->hasInheritedConstructor())
7945       DeclareImplicitCopyConstructor(ClassDecl);
7946     // For the MS ABI we need to know whether the copy ctor is deleted. A
7947     // prerequisite for deleting the implicit copy ctor is that the class has a
7948     // move ctor or move assignment that is either user-declared or whose
7949     // semantics are inherited from a subobject. FIXME: We should provide a more
7950     // direct way for CodeGen to ask whether the constructor was deleted.
7951     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7952              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7953               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7954               ClassDecl->hasUserDeclaredMoveAssignment() ||
7955               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7956       DeclareImplicitCopyConstructor(ClassDecl);
7957   }
7958 
7959   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7960     ++ASTContext::NumImplicitMoveConstructors;
7961 
7962     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7963         ClassDecl->hasInheritedConstructor())
7964       DeclareImplicitMoveConstructor(ClassDecl);
7965   }
7966 
7967   if (ClassDecl->needsImplicitCopyAssignment()) {
7968     ++ASTContext::NumImplicitCopyAssignmentOperators;
7969 
7970     // If we have a dynamic class, then the copy assignment operator may be
7971     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7972     // it shows up in the right place in the vtable and that we diagnose
7973     // problems with the implicit exception specification.
7974     if (ClassDecl->isDynamicClass() ||
7975         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7976         ClassDecl->hasInheritedAssignment())
7977       DeclareImplicitCopyAssignment(ClassDecl);
7978   }
7979 
7980   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7981     ++ASTContext::NumImplicitMoveAssignmentOperators;
7982 
7983     // Likewise for the move assignment operator.
7984     if (ClassDecl->isDynamicClass() ||
7985         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7986         ClassDecl->hasInheritedAssignment())
7987       DeclareImplicitMoveAssignment(ClassDecl);
7988   }
7989 
7990   if (ClassDecl->needsImplicitDestructor()) {
7991     ++ASTContext::NumImplicitDestructors;
7992 
7993     // If we have a dynamic class, then the destructor may be virtual, so we
7994     // have to declare the destructor immediately. This ensures that, e.g., it
7995     // shows up in the right place in the vtable and that we diagnose problems
7996     // with the implicit exception specification.
7997     if (ClassDecl->isDynamicClass() ||
7998         ClassDecl->needsOverloadResolutionForDestructor())
7999       DeclareImplicitDestructor(ClassDecl);
8000   }
8001 }
8002 
8003 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8004   if (!D)
8005     return 0;
8006 
8007   // The order of template parameters is not important here. All names
8008   // get added to the same scope.
8009   SmallVector<TemplateParameterList *, 4> ParameterLists;
8010 
8011   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8012     D = TD->getTemplatedDecl();
8013 
8014   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8015     ParameterLists.push_back(PSD->getTemplateParameters());
8016 
8017   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8018     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8019       ParameterLists.push_back(DD->getTemplateParameterList(i));
8020 
8021     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8022       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8023         ParameterLists.push_back(FTD->getTemplateParameters());
8024     }
8025   }
8026 
8027   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8028     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8029       ParameterLists.push_back(TD->getTemplateParameterList(i));
8030 
8031     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8032       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8033         ParameterLists.push_back(CTD->getTemplateParameters());
8034     }
8035   }
8036 
8037   unsigned Count = 0;
8038   for (TemplateParameterList *Params : ParameterLists) {
8039     if (Params->size() > 0)
8040       // Ignore explicit specializations; they don't contribute to the template
8041       // depth.
8042       ++Count;
8043     for (NamedDecl *Param : *Params) {
8044       if (Param->getDeclName()) {
8045         S->AddDecl(Param);
8046         IdResolver.AddDecl(Param);
8047       }
8048     }
8049   }
8050 
8051   return Count;
8052 }
8053 
8054 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8055   if (!RecordD) return;
8056   AdjustDeclIfTemplate(RecordD);
8057   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8058   PushDeclContext(S, Record);
8059 }
8060 
8061 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8062   if (!RecordD) return;
8063   PopDeclContext();
8064 }
8065 
8066 /// This is used to implement the constant expression evaluation part of the
8067 /// attribute enable_if extension. There is nothing in standard C++ which would
8068 /// require reentering parameters.
8069 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8070   if (!Param)
8071     return;
8072 
8073   S->AddDecl(Param);
8074   if (Param->getDeclName())
8075     IdResolver.AddDecl(Param);
8076 }
8077 
8078 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8079 /// parsing a top-level (non-nested) C++ class, and we are now
8080 /// parsing those parts of the given Method declaration that could
8081 /// not be parsed earlier (C++ [class.mem]p2), such as default
8082 /// arguments. This action should enter the scope of the given
8083 /// Method declaration as if we had just parsed the qualified method
8084 /// name. However, it should not bring the parameters into scope;
8085 /// that will be performed by ActOnDelayedCXXMethodParameter.
8086 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8087 }
8088 
8089 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8090 /// C++ method declaration. We're (re-)introducing the given
8091 /// function parameter into scope for use in parsing later parts of
8092 /// the method declaration. For example, we could see an
8093 /// ActOnParamDefaultArgument event for this parameter.
8094 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8095   if (!ParamD)
8096     return;
8097 
8098   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8099 
8100   // If this parameter has an unparsed default argument, clear it out
8101   // to make way for the parsed default argument.
8102   if (Param->hasUnparsedDefaultArg())
8103     Param->setDefaultArg(nullptr);
8104 
8105   S->AddDecl(Param);
8106   if (Param->getDeclName())
8107     IdResolver.AddDecl(Param);
8108 }
8109 
8110 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8111 /// processing the delayed method declaration for Method. The method
8112 /// declaration is now considered finished. There may be a separate
8113 /// ActOnStartOfFunctionDef action later (not necessarily
8114 /// immediately!) for this method, if it was also defined inside the
8115 /// class body.
8116 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8117   if (!MethodD)
8118     return;
8119 
8120   AdjustDeclIfTemplate(MethodD);
8121 
8122   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8123 
8124   // Now that we have our default arguments, check the constructor
8125   // again. It could produce additional diagnostics or affect whether
8126   // the class has implicitly-declared destructors, among other
8127   // things.
8128   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8129     CheckConstructor(Constructor);
8130 
8131   // Check the default arguments, which we may have added.
8132   if (!Method->isInvalidDecl())
8133     CheckCXXDefaultArguments(Method);
8134 }
8135 
8136 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8137 /// the well-formedness of the constructor declarator @p D with type @p
8138 /// R. If there are any errors in the declarator, this routine will
8139 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8140 /// will be updated to reflect a well-formed type for the constructor and
8141 /// returned.
8142 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8143                                           StorageClass &SC) {
8144   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8145 
8146   // C++ [class.ctor]p3:
8147   //   A constructor shall not be virtual (10.3) or static (9.4). A
8148   //   constructor can be invoked for a const, volatile or const
8149   //   volatile object. A constructor shall not be declared const,
8150   //   volatile, or const volatile (9.3.2).
8151   if (isVirtual) {
8152     if (!D.isInvalidType())
8153       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8154         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8155         << SourceRange(D.getIdentifierLoc());
8156     D.setInvalidType();
8157   }
8158   if (SC == SC_Static) {
8159     if (!D.isInvalidType())
8160       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8161         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8162         << SourceRange(D.getIdentifierLoc());
8163     D.setInvalidType();
8164     SC = SC_None;
8165   }
8166 
8167   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8168     diagnoseIgnoredQualifiers(
8169         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8170         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8171         D.getDeclSpec().getRestrictSpecLoc(),
8172         D.getDeclSpec().getAtomicSpecLoc());
8173     D.setInvalidType();
8174   }
8175 
8176   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8177   if (FTI.TypeQuals != 0) {
8178     if (FTI.TypeQuals & Qualifiers::Const)
8179       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8180         << "const" << SourceRange(D.getIdentifierLoc());
8181     if (FTI.TypeQuals & Qualifiers::Volatile)
8182       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8183         << "volatile" << SourceRange(D.getIdentifierLoc());
8184     if (FTI.TypeQuals & Qualifiers::Restrict)
8185       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8186         << "restrict" << SourceRange(D.getIdentifierLoc());
8187     D.setInvalidType();
8188   }
8189 
8190   // C++0x [class.ctor]p4:
8191   //   A constructor shall not be declared with a ref-qualifier.
8192   if (FTI.hasRefQualifier()) {
8193     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8194       << FTI.RefQualifierIsLValueRef
8195       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8196     D.setInvalidType();
8197   }
8198 
8199   // Rebuild the function type "R" without any type qualifiers (in
8200   // case any of the errors above fired) and with "void" as the
8201   // return type, since constructors don't have return types.
8202   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8203   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8204     return R;
8205 
8206   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8207   EPI.TypeQuals = Qualifiers();
8208   EPI.RefQualifier = RQ_None;
8209 
8210   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8211 }
8212 
8213 /// CheckConstructor - Checks a fully-formed constructor for
8214 /// well-formedness, issuing any diagnostics required. Returns true if
8215 /// the constructor declarator is invalid.
8216 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8217   CXXRecordDecl *ClassDecl
8218     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8219   if (!ClassDecl)
8220     return Constructor->setInvalidDecl();
8221 
8222   // C++ [class.copy]p3:
8223   //   A declaration of a constructor for a class X is ill-formed if
8224   //   its first parameter is of type (optionally cv-qualified) X and
8225   //   either there are no other parameters or else all other
8226   //   parameters have default arguments.
8227   if (!Constructor->isInvalidDecl() &&
8228       ((Constructor->getNumParams() == 1) ||
8229        (Constructor->getNumParams() > 1 &&
8230         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8231       Constructor->getTemplateSpecializationKind()
8232                                               != TSK_ImplicitInstantiation) {
8233     QualType ParamType = Constructor->getParamDecl(0)->getType();
8234     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8235     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8236       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8237       const char *ConstRef
8238         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8239                                                         : " const &";
8240       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8241         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8242 
8243       // FIXME: Rather that making the constructor invalid, we should endeavor
8244       // to fix the type.
8245       Constructor->setInvalidDecl();
8246     }
8247   }
8248 }
8249 
8250 /// CheckDestructor - Checks a fully-formed destructor definition for
8251 /// well-formedness, issuing any diagnostics required.  Returns true
8252 /// on error.
8253 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8254   CXXRecordDecl *RD = Destructor->getParent();
8255 
8256   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8257     SourceLocation Loc;
8258 
8259     if (!Destructor->isImplicit())
8260       Loc = Destructor->getLocation();
8261     else
8262       Loc = RD->getLocation();
8263 
8264     // If we have a virtual destructor, look up the deallocation function
8265     if (FunctionDecl *OperatorDelete =
8266             FindDeallocationFunctionForDestructor(Loc, RD)) {
8267       Expr *ThisArg = nullptr;
8268 
8269       // If the notional 'delete this' expression requires a non-trivial
8270       // conversion from 'this' to the type of a destroying operator delete's
8271       // first parameter, perform that conversion now.
8272       if (OperatorDelete->isDestroyingOperatorDelete()) {
8273         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8274         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8275           // C++ [class.dtor]p13:
8276           //   ... as if for the expression 'delete this' appearing in a
8277           //   non-virtual destructor of the destructor's class.
8278           ContextRAII SwitchContext(*this, Destructor);
8279           ExprResult This =
8280               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8281           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8282           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8283           if (This.isInvalid()) {
8284             // FIXME: Register this as a context note so that it comes out
8285             // in the right order.
8286             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8287             return true;
8288           }
8289           ThisArg = This.get();
8290         }
8291       }
8292 
8293       DiagnoseUseOfDecl(OperatorDelete, Loc);
8294       MarkFunctionReferenced(Loc, OperatorDelete);
8295       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8296     }
8297   }
8298 
8299   return false;
8300 }
8301 
8302 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8303 /// the well-formednes of the destructor declarator @p D with type @p
8304 /// R. If there are any errors in the declarator, this routine will
8305 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8306 /// will be updated to reflect a well-formed type for the destructor and
8307 /// returned.
8308 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8309                                          StorageClass& SC) {
8310   // C++ [class.dtor]p1:
8311   //   [...] A typedef-name that names a class is a class-name
8312   //   (7.1.3); however, a typedef-name that names a class shall not
8313   //   be used as the identifier in the declarator for a destructor
8314   //   declaration.
8315   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8316   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8317     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8318       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8319   else if (const TemplateSpecializationType *TST =
8320              DeclaratorType->getAs<TemplateSpecializationType>())
8321     if (TST->isTypeAlias())
8322       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8323         << DeclaratorType << 1;
8324 
8325   // C++ [class.dtor]p2:
8326   //   A destructor is used to destroy objects of its class type. A
8327   //   destructor takes no parameters, and no return type can be
8328   //   specified for it (not even void). The address of a destructor
8329   //   shall not be taken. A destructor shall not be static. A
8330   //   destructor can be invoked for a const, volatile or const
8331   //   volatile object. A destructor shall not be declared const,
8332   //   volatile or const volatile (9.3.2).
8333   if (SC == SC_Static) {
8334     if (!D.isInvalidType())
8335       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8336         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8337         << SourceRange(D.getIdentifierLoc())
8338         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8339 
8340     SC = SC_None;
8341   }
8342   if (!D.isInvalidType()) {
8343     // Destructors don't have return types, but the parser will
8344     // happily parse something like:
8345     //
8346     //   class X {
8347     //     float ~X();
8348     //   };
8349     //
8350     // The return type will be eliminated later.
8351     if (D.getDeclSpec().hasTypeSpecifier())
8352       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8353         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8354         << SourceRange(D.getIdentifierLoc());
8355     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8356       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8357                                 SourceLocation(),
8358                                 D.getDeclSpec().getConstSpecLoc(),
8359                                 D.getDeclSpec().getVolatileSpecLoc(),
8360                                 D.getDeclSpec().getRestrictSpecLoc(),
8361                                 D.getDeclSpec().getAtomicSpecLoc());
8362       D.setInvalidType();
8363     }
8364   }
8365 
8366   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8367   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8368     if (FTI.TypeQuals & Qualifiers::Const)
8369       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8370         << "const" << SourceRange(D.getIdentifierLoc());
8371     if (FTI.TypeQuals & Qualifiers::Volatile)
8372       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8373         << "volatile" << SourceRange(D.getIdentifierLoc());
8374     if (FTI.TypeQuals & Qualifiers::Restrict)
8375       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8376         << "restrict" << SourceRange(D.getIdentifierLoc());
8377     D.setInvalidType();
8378   }
8379 
8380   // C++0x [class.dtor]p2:
8381   //   A destructor shall not be declared with a ref-qualifier.
8382   if (FTI.hasRefQualifier()) {
8383     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8384       << FTI.RefQualifierIsLValueRef
8385       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8386     D.setInvalidType();
8387   }
8388 
8389   // Make sure we don't have any parameters.
8390   if (FTIHasNonVoidParameters(FTI)) {
8391     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8392 
8393     // Delete the parameters.
8394     FTI.freeParams();
8395     D.setInvalidType();
8396   }
8397 
8398   // Make sure the destructor isn't variadic.
8399   if (FTI.isVariadic) {
8400     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8401     D.setInvalidType();
8402   }
8403 
8404   // Rebuild the function type "R" without any type qualifiers or
8405   // parameters (in case any of the errors above fired) and with
8406   // "void" as the return type, since destructors don't have return
8407   // types.
8408   if (!D.isInvalidType())
8409     return R;
8410 
8411   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8412   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8413   EPI.Variadic = false;
8414   EPI.TypeQuals = Qualifiers();
8415   EPI.RefQualifier = RQ_None;
8416   return Context.getFunctionType(Context.VoidTy, None, EPI);
8417 }
8418 
8419 static void extendLeft(SourceRange &R, SourceRange Before) {
8420   if (Before.isInvalid())
8421     return;
8422   R.setBegin(Before.getBegin());
8423   if (R.getEnd().isInvalid())
8424     R.setEnd(Before.getEnd());
8425 }
8426 
8427 static void extendRight(SourceRange &R, SourceRange After) {
8428   if (After.isInvalid())
8429     return;
8430   if (R.getBegin().isInvalid())
8431     R.setBegin(After.getBegin());
8432   R.setEnd(After.getEnd());
8433 }
8434 
8435 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8436 /// well-formednes of the conversion function declarator @p D with
8437 /// type @p R. If there are any errors in the declarator, this routine
8438 /// will emit diagnostics and return true. Otherwise, it will return
8439 /// false. Either way, the type @p R will be updated to reflect a
8440 /// well-formed type for the conversion operator.
8441 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8442                                      StorageClass& SC) {
8443   // C++ [class.conv.fct]p1:
8444   //   Neither parameter types nor return type can be specified. The
8445   //   type of a conversion function (8.3.5) is "function taking no
8446   //   parameter returning conversion-type-id."
8447   if (SC == SC_Static) {
8448     if (!D.isInvalidType())
8449       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8450         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8451         << D.getName().getSourceRange();
8452     D.setInvalidType();
8453     SC = SC_None;
8454   }
8455 
8456   TypeSourceInfo *ConvTSI = nullptr;
8457   QualType ConvType =
8458       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8459 
8460   const DeclSpec &DS = D.getDeclSpec();
8461   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8462     // Conversion functions don't have return types, but the parser will
8463     // happily parse something like:
8464     //
8465     //   class X {
8466     //     float operator bool();
8467     //   };
8468     //
8469     // The return type will be changed later anyway.
8470     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8471       << SourceRange(DS.getTypeSpecTypeLoc())
8472       << SourceRange(D.getIdentifierLoc());
8473     D.setInvalidType();
8474   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8475     // It's also plausible that the user writes type qualifiers in the wrong
8476     // place, such as:
8477     //   struct S { const operator int(); };
8478     // FIXME: we could provide a fixit to move the qualifiers onto the
8479     // conversion type.
8480     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8481         << SourceRange(D.getIdentifierLoc()) << 0;
8482     D.setInvalidType();
8483   }
8484 
8485   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8486 
8487   // Make sure we don't have any parameters.
8488   if (Proto->getNumParams() > 0) {
8489     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8490 
8491     // Delete the parameters.
8492     D.getFunctionTypeInfo().freeParams();
8493     D.setInvalidType();
8494   } else if (Proto->isVariadic()) {
8495     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8496     D.setInvalidType();
8497   }
8498 
8499   // Diagnose "&operator bool()" and other such nonsense.  This
8500   // is actually a gcc extension which we don't support.
8501   if (Proto->getReturnType() != ConvType) {
8502     bool NeedsTypedef = false;
8503     SourceRange Before, After;
8504 
8505     // Walk the chunks and extract information on them for our diagnostic.
8506     bool PastFunctionChunk = false;
8507     for (auto &Chunk : D.type_objects()) {
8508       switch (Chunk.Kind) {
8509       case DeclaratorChunk::Function:
8510         if (!PastFunctionChunk) {
8511           if (Chunk.Fun.HasTrailingReturnType) {
8512             TypeSourceInfo *TRT = nullptr;
8513             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8514             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8515           }
8516           PastFunctionChunk = true;
8517           break;
8518         }
8519         LLVM_FALLTHROUGH;
8520       case DeclaratorChunk::Array:
8521         NeedsTypedef = true;
8522         extendRight(After, Chunk.getSourceRange());
8523         break;
8524 
8525       case DeclaratorChunk::Pointer:
8526       case DeclaratorChunk::BlockPointer:
8527       case DeclaratorChunk::Reference:
8528       case DeclaratorChunk::MemberPointer:
8529       case DeclaratorChunk::Pipe:
8530         extendLeft(Before, Chunk.getSourceRange());
8531         break;
8532 
8533       case DeclaratorChunk::Paren:
8534         extendLeft(Before, Chunk.Loc);
8535         extendRight(After, Chunk.EndLoc);
8536         break;
8537       }
8538     }
8539 
8540     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8541                          After.isValid()  ? After.getBegin() :
8542                                             D.getIdentifierLoc();
8543     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8544     DB << Before << After;
8545 
8546     if (!NeedsTypedef) {
8547       DB << /*don't need a typedef*/0;
8548 
8549       // If we can provide a correct fix-it hint, do so.
8550       if (After.isInvalid() && ConvTSI) {
8551         SourceLocation InsertLoc =
8552             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8553         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8554            << FixItHint::CreateInsertionFromRange(
8555                   InsertLoc, CharSourceRange::getTokenRange(Before))
8556            << FixItHint::CreateRemoval(Before);
8557       }
8558     } else if (!Proto->getReturnType()->isDependentType()) {
8559       DB << /*typedef*/1 << Proto->getReturnType();
8560     } else if (getLangOpts().CPlusPlus11) {
8561       DB << /*alias template*/2 << Proto->getReturnType();
8562     } else {
8563       DB << /*might not be fixable*/3;
8564     }
8565 
8566     // Recover by incorporating the other type chunks into the result type.
8567     // Note, this does *not* change the name of the function. This is compatible
8568     // with the GCC extension:
8569     //   struct S { &operator int(); } s;
8570     //   int &r = s.operator int(); // ok in GCC
8571     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8572     ConvType = Proto->getReturnType();
8573   }
8574 
8575   // C++ [class.conv.fct]p4:
8576   //   The conversion-type-id shall not represent a function type nor
8577   //   an array type.
8578   if (ConvType->isArrayType()) {
8579     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8580     ConvType = Context.getPointerType(ConvType);
8581     D.setInvalidType();
8582   } else if (ConvType->isFunctionType()) {
8583     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8584     ConvType = Context.getPointerType(ConvType);
8585     D.setInvalidType();
8586   }
8587 
8588   // Rebuild the function type "R" without any parameters (in case any
8589   // of the errors above fired) and with the conversion type as the
8590   // return type.
8591   if (D.isInvalidType())
8592     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8593 
8594   // C++0x explicit conversion operators.
8595   if (DS.isExplicitSpecified())
8596     Diag(DS.getExplicitSpecLoc(),
8597          getLangOpts().CPlusPlus11
8598              ? diag::warn_cxx98_compat_explicit_conversion_functions
8599              : diag::ext_explicit_conversion_functions)
8600         << SourceRange(DS.getExplicitSpecLoc());
8601 }
8602 
8603 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8604 /// the declaration of the given C++ conversion function. This routine
8605 /// is responsible for recording the conversion function in the C++
8606 /// class, if possible.
8607 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8608   assert(Conversion && "Expected to receive a conversion function declaration");
8609 
8610   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8611 
8612   // Make sure we aren't redeclaring the conversion function.
8613   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8614 
8615   // C++ [class.conv.fct]p1:
8616   //   [...] A conversion function is never used to convert a
8617   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8618   //   same object type (or a reference to it), to a (possibly
8619   //   cv-qualified) base class of that type (or a reference to it),
8620   //   or to (possibly cv-qualified) void.
8621   // FIXME: Suppress this warning if the conversion function ends up being a
8622   // virtual function that overrides a virtual function in a base class.
8623   QualType ClassType
8624     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8625   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8626     ConvType = ConvTypeRef->getPointeeType();
8627   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8628       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8629     /* Suppress diagnostics for instantiations. */;
8630   else if (ConvType->isRecordType()) {
8631     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8632     if (ConvType == ClassType)
8633       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8634         << ClassType;
8635     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8636       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8637         <<  ClassType << ConvType;
8638   } else if (ConvType->isVoidType()) {
8639     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8640       << ClassType << ConvType;
8641   }
8642 
8643   if (FunctionTemplateDecl *ConversionTemplate
8644                                 = Conversion->getDescribedFunctionTemplate())
8645     return ConversionTemplate;
8646 
8647   return Conversion;
8648 }
8649 
8650 namespace {
8651 /// Utility class to accumulate and print a diagnostic listing the invalid
8652 /// specifier(s) on a declaration.
8653 struct BadSpecifierDiagnoser {
8654   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8655       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8656   ~BadSpecifierDiagnoser() {
8657     Diagnostic << Specifiers;
8658   }
8659 
8660   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8661     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8662   }
8663   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8664     return check(SpecLoc,
8665                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8666   }
8667   void check(SourceLocation SpecLoc, const char *Spec) {
8668     if (SpecLoc.isInvalid()) return;
8669     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8670     if (!Specifiers.empty()) Specifiers += " ";
8671     Specifiers += Spec;
8672   }
8673 
8674   Sema &S;
8675   Sema::SemaDiagnosticBuilder Diagnostic;
8676   std::string Specifiers;
8677 };
8678 }
8679 
8680 /// Check the validity of a declarator that we parsed for a deduction-guide.
8681 /// These aren't actually declarators in the grammar, so we need to check that
8682 /// the user didn't specify any pieces that are not part of the deduction-guide
8683 /// grammar.
8684 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8685                                          StorageClass &SC) {
8686   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8687   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8688   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8689 
8690   // C++ [temp.deduct.guide]p3:
8691   //   A deduction-gide shall be declared in the same scope as the
8692   //   corresponding class template.
8693   if (!CurContext->getRedeclContext()->Equals(
8694           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8695     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8696       << GuidedTemplateDecl;
8697     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8698   }
8699 
8700   auto &DS = D.getMutableDeclSpec();
8701   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8702   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8703       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8704       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8705     BadSpecifierDiagnoser Diagnoser(
8706         *this, D.getIdentifierLoc(),
8707         diag::err_deduction_guide_invalid_specifier);
8708 
8709     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8710     DS.ClearStorageClassSpecs();
8711     SC = SC_None;
8712 
8713     // 'explicit' is permitted.
8714     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8715     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8716     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8717     DS.ClearConstexprSpec();
8718 
8719     Diagnoser.check(DS.getConstSpecLoc(), "const");
8720     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8721     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8722     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8723     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8724     DS.ClearTypeQualifiers();
8725 
8726     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8727     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8728     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8729     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8730     DS.ClearTypeSpecType();
8731   }
8732 
8733   if (D.isInvalidType())
8734     return;
8735 
8736   // Check the declarator is simple enough.
8737   bool FoundFunction = false;
8738   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8739     if (Chunk.Kind == DeclaratorChunk::Paren)
8740       continue;
8741     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8742       Diag(D.getDeclSpec().getBeginLoc(),
8743            diag::err_deduction_guide_with_complex_decl)
8744           << D.getSourceRange();
8745       break;
8746     }
8747     if (!Chunk.Fun.hasTrailingReturnType()) {
8748       Diag(D.getName().getBeginLoc(),
8749            diag::err_deduction_guide_no_trailing_return_type);
8750       break;
8751     }
8752 
8753     // Check that the return type is written as a specialization of
8754     // the template specified as the deduction-guide's name.
8755     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8756     TypeSourceInfo *TSI = nullptr;
8757     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8758     assert(TSI && "deduction guide has valid type but invalid return type?");
8759     bool AcceptableReturnType = false;
8760     bool MightInstantiateToSpecialization = false;
8761     if (auto RetTST =
8762             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8763       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8764       bool TemplateMatches =
8765           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8766       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8767         AcceptableReturnType = true;
8768       else {
8769         // This could still instantiate to the right type, unless we know it
8770         // names the wrong class template.
8771         auto *TD = SpecifiedName.getAsTemplateDecl();
8772         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8773                                              !TemplateMatches);
8774       }
8775     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8776       MightInstantiateToSpecialization = true;
8777     }
8778 
8779     if (!AcceptableReturnType) {
8780       Diag(TSI->getTypeLoc().getBeginLoc(),
8781            diag::err_deduction_guide_bad_trailing_return_type)
8782           << GuidedTemplate << TSI->getType()
8783           << MightInstantiateToSpecialization
8784           << TSI->getTypeLoc().getSourceRange();
8785     }
8786 
8787     // Keep going to check that we don't have any inner declarator pieces (we
8788     // could still have a function returning a pointer to a function).
8789     FoundFunction = true;
8790   }
8791 
8792   if (D.isFunctionDefinition())
8793     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8794 }
8795 
8796 //===----------------------------------------------------------------------===//
8797 // Namespace Handling
8798 //===----------------------------------------------------------------------===//
8799 
8800 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8801 /// reopened.
8802 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8803                                             SourceLocation Loc,
8804                                             IdentifierInfo *II, bool *IsInline,
8805                                             NamespaceDecl *PrevNS) {
8806   assert(*IsInline != PrevNS->isInline());
8807 
8808   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8809   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8810   // inline namespaces, with the intention of bringing names into namespace std.
8811   //
8812   // We support this just well enough to get that case working; this is not
8813   // sufficient to support reopening namespaces as inline in general.
8814   if (*IsInline && II && II->getName().startswith("__atomic") &&
8815       S.getSourceManager().isInSystemHeader(Loc)) {
8816     // Mark all prior declarations of the namespace as inline.
8817     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8818          NS = NS->getPreviousDecl())
8819       NS->setInline(*IsInline);
8820     // Patch up the lookup table for the containing namespace. This isn't really
8821     // correct, but it's good enough for this particular case.
8822     for (auto *I : PrevNS->decls())
8823       if (auto *ND = dyn_cast<NamedDecl>(I))
8824         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8825     return;
8826   }
8827 
8828   if (PrevNS->isInline())
8829     // The user probably just forgot the 'inline', so suggest that it
8830     // be added back.
8831     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8832       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8833   else
8834     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8835 
8836   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8837   *IsInline = PrevNS->isInline();
8838 }
8839 
8840 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8841 /// definition.
8842 Decl *Sema::ActOnStartNamespaceDef(
8843     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8844     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8845     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8846   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8847   // For anonymous namespace, take the location of the left brace.
8848   SourceLocation Loc = II ? IdentLoc : LBrace;
8849   bool IsInline = InlineLoc.isValid();
8850   bool IsInvalid = false;
8851   bool IsStd = false;
8852   bool AddToKnown = false;
8853   Scope *DeclRegionScope = NamespcScope->getParent();
8854 
8855   NamespaceDecl *PrevNS = nullptr;
8856   if (II) {
8857     // C++ [namespace.def]p2:
8858     //   The identifier in an original-namespace-definition shall not
8859     //   have been previously defined in the declarative region in
8860     //   which the original-namespace-definition appears. The
8861     //   identifier in an original-namespace-definition is the name of
8862     //   the namespace. Subsequently in that declarative region, it is
8863     //   treated as an original-namespace-name.
8864     //
8865     // Since namespace names are unique in their scope, and we don't
8866     // look through using directives, just look for any ordinary names
8867     // as if by qualified name lookup.
8868     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8869                    ForExternalRedeclaration);
8870     LookupQualifiedName(R, CurContext->getRedeclContext());
8871     NamedDecl *PrevDecl =
8872         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8873     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8874 
8875     if (PrevNS) {
8876       // This is an extended namespace definition.
8877       if (IsInline != PrevNS->isInline())
8878         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8879                                         &IsInline, PrevNS);
8880     } else if (PrevDecl) {
8881       // This is an invalid name redefinition.
8882       Diag(Loc, diag::err_redefinition_different_kind)
8883         << II;
8884       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8885       IsInvalid = true;
8886       // Continue on to push Namespc as current DeclContext and return it.
8887     } else if (II->isStr("std") &&
8888                CurContext->getRedeclContext()->isTranslationUnit()) {
8889       // This is the first "real" definition of the namespace "std", so update
8890       // our cache of the "std" namespace to point at this definition.
8891       PrevNS = getStdNamespace();
8892       IsStd = true;
8893       AddToKnown = !IsInline;
8894     } else {
8895       // We've seen this namespace for the first time.
8896       AddToKnown = !IsInline;
8897     }
8898   } else {
8899     // Anonymous namespaces.
8900 
8901     // Determine whether the parent already has an anonymous namespace.
8902     DeclContext *Parent = CurContext->getRedeclContext();
8903     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8904       PrevNS = TU->getAnonymousNamespace();
8905     } else {
8906       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8907       PrevNS = ND->getAnonymousNamespace();
8908     }
8909 
8910     if (PrevNS && IsInline != PrevNS->isInline())
8911       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8912                                       &IsInline, PrevNS);
8913   }
8914 
8915   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8916                                                  StartLoc, Loc, II, PrevNS);
8917   if (IsInvalid)
8918     Namespc->setInvalidDecl();
8919 
8920   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8921   AddPragmaAttributes(DeclRegionScope, Namespc);
8922 
8923   // FIXME: Should we be merging attributes?
8924   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8925     PushNamespaceVisibilityAttr(Attr, Loc);
8926 
8927   if (IsStd)
8928     StdNamespace = Namespc;
8929   if (AddToKnown)
8930     KnownNamespaces[Namespc] = false;
8931 
8932   if (II) {
8933     PushOnScopeChains(Namespc, DeclRegionScope);
8934   } else {
8935     // Link the anonymous namespace into its parent.
8936     DeclContext *Parent = CurContext->getRedeclContext();
8937     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8938       TU->setAnonymousNamespace(Namespc);
8939     } else {
8940       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8941     }
8942 
8943     CurContext->addDecl(Namespc);
8944 
8945     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8946     //   behaves as if it were replaced by
8947     //     namespace unique { /* empty body */ }
8948     //     using namespace unique;
8949     //     namespace unique { namespace-body }
8950     //   where all occurrences of 'unique' in a translation unit are
8951     //   replaced by the same identifier and this identifier differs
8952     //   from all other identifiers in the entire program.
8953 
8954     // We just create the namespace with an empty name and then add an
8955     // implicit using declaration, just like the standard suggests.
8956     //
8957     // CodeGen enforces the "universally unique" aspect by giving all
8958     // declarations semantically contained within an anonymous
8959     // namespace internal linkage.
8960 
8961     if (!PrevNS) {
8962       UD = UsingDirectiveDecl::Create(Context, Parent,
8963                                       /* 'using' */ LBrace,
8964                                       /* 'namespace' */ SourceLocation(),
8965                                       /* qualifier */ NestedNameSpecifierLoc(),
8966                                       /* identifier */ SourceLocation(),
8967                                       Namespc,
8968                                       /* Ancestor */ Parent);
8969       UD->setImplicit();
8970       Parent->addDecl(UD);
8971     }
8972   }
8973 
8974   ActOnDocumentableDecl(Namespc);
8975 
8976   // Although we could have an invalid decl (i.e. the namespace name is a
8977   // redefinition), push it as current DeclContext and try to continue parsing.
8978   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8979   // for the namespace has the declarations that showed up in that particular
8980   // namespace definition.
8981   PushDeclContext(NamespcScope, Namespc);
8982   return Namespc;
8983 }
8984 
8985 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8986 /// is a namespace alias, returns the namespace it points to.
8987 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8988   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8989     return AD->getNamespace();
8990   return dyn_cast_or_null<NamespaceDecl>(D);
8991 }
8992 
8993 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8994 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8995 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8996   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8997   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8998   Namespc->setRBraceLoc(RBrace);
8999   PopDeclContext();
9000   if (Namespc->hasAttr<VisibilityAttr>())
9001     PopPragmaVisibility(true, RBrace);
9002 }
9003 
9004 CXXRecordDecl *Sema::getStdBadAlloc() const {
9005   return cast_or_null<CXXRecordDecl>(
9006                                   StdBadAlloc.get(Context.getExternalSource()));
9007 }
9008 
9009 EnumDecl *Sema::getStdAlignValT() const {
9010   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9011 }
9012 
9013 NamespaceDecl *Sema::getStdNamespace() const {
9014   return cast_or_null<NamespaceDecl>(
9015                                  StdNamespace.get(Context.getExternalSource()));
9016 }
9017 
9018 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9019   if (!StdExperimentalNamespaceCache) {
9020     if (auto Std = getStdNamespace()) {
9021       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9022                           SourceLocation(), LookupNamespaceName);
9023       if (!LookupQualifiedName(Result, Std) ||
9024           !(StdExperimentalNamespaceCache =
9025                 Result.getAsSingle<NamespaceDecl>()))
9026         Result.suppressDiagnostics();
9027     }
9028   }
9029   return StdExperimentalNamespaceCache;
9030 }
9031 
9032 namespace {
9033 
9034 enum UnsupportedSTLSelect {
9035   USS_InvalidMember,
9036   USS_MissingMember,
9037   USS_NonTrivial,
9038   USS_Other
9039 };
9040 
9041 struct InvalidSTLDiagnoser {
9042   Sema &S;
9043   SourceLocation Loc;
9044   QualType TyForDiags;
9045 
9046   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9047                       const VarDecl *VD = nullptr) {
9048     {
9049       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9050                << TyForDiags << ((int)Sel);
9051       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9052         assert(!Name.empty());
9053         D << Name;
9054       }
9055     }
9056     if (Sel == USS_InvalidMember) {
9057       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9058           << VD << VD->getSourceRange();
9059     }
9060     return QualType();
9061   }
9062 };
9063 } // namespace
9064 
9065 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9066                                            SourceLocation Loc) {
9067   assert(getLangOpts().CPlusPlus &&
9068          "Looking for comparison category type outside of C++.");
9069 
9070   // Check if we've already successfully checked the comparison category type
9071   // before. If so, skip checking it again.
9072   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9073   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9074     return Info->getType();
9075 
9076   // If lookup failed
9077   if (!Info) {
9078     std::string NameForDiags = "std::";
9079     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9080     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9081         << NameForDiags;
9082     return QualType();
9083   }
9084 
9085   assert(Info->Kind == Kind);
9086   assert(Info->Record);
9087 
9088   // Update the Record decl in case we encountered a forward declaration on our
9089   // first pass. FIXME: This is a bit of a hack.
9090   if (Info->Record->hasDefinition())
9091     Info->Record = Info->Record->getDefinition();
9092 
9093   // Use an elaborated type for diagnostics which has a name containing the
9094   // prepended 'std' namespace but not any inline namespace names.
9095   QualType TyForDiags = [&]() {
9096     auto *NNS =
9097         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9098     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9099   }();
9100 
9101   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9102     return QualType();
9103 
9104   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9105 
9106   if (!Info->Record->isTriviallyCopyable())
9107     return UnsupportedSTLError(USS_NonTrivial);
9108 
9109   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9110     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9111     // Tolerate empty base classes.
9112     if (Base->isEmpty())
9113       continue;
9114     // Reject STL implementations which have at least one non-empty base.
9115     return UnsupportedSTLError();
9116   }
9117 
9118   // Check that the STL has implemented the types using a single integer field.
9119   // This expectation allows better codegen for builtin operators. We require:
9120   //   (1) The class has exactly one field.
9121   //   (2) The field is an integral or enumeration type.
9122   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9123   if (std::distance(FIt, FEnd) != 1 ||
9124       !FIt->getType()->isIntegralOrEnumerationType()) {
9125     return UnsupportedSTLError();
9126   }
9127 
9128   // Build each of the require values and store them in Info.
9129   for (ComparisonCategoryResult CCR :
9130        ComparisonCategories::getPossibleResultsForType(Kind)) {
9131     StringRef MemName = ComparisonCategories::getResultString(CCR);
9132     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9133 
9134     if (!ValInfo)
9135       return UnsupportedSTLError(USS_MissingMember, MemName);
9136 
9137     VarDecl *VD = ValInfo->VD;
9138     assert(VD && "should not be null!");
9139 
9140     // Attempt to diagnose reasons why the STL definition of this type
9141     // might be foobar, including it failing to be a constant expression.
9142     // TODO Handle more ways the lookup or result can be invalid.
9143     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9144         !VD->checkInitIsICE())
9145       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9146 
9147     // Attempt to evaluate the var decl as a constant expression and extract
9148     // the value of its first field as a ICE. If this fails, the STL
9149     // implementation is not supported.
9150     if (!ValInfo->hasValidIntValue())
9151       return UnsupportedSTLError();
9152 
9153     MarkVariableReferenced(Loc, VD);
9154   }
9155 
9156   // We've successfully built the required types and expressions. Update
9157   // the cache and return the newly cached value.
9158   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9159   return Info->getType();
9160 }
9161 
9162 /// Retrieve the special "std" namespace, which may require us to
9163 /// implicitly define the namespace.
9164 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9165   if (!StdNamespace) {
9166     // The "std" namespace has not yet been defined, so build one implicitly.
9167     StdNamespace = NamespaceDecl::Create(Context,
9168                                          Context.getTranslationUnitDecl(),
9169                                          /*Inline=*/false,
9170                                          SourceLocation(), SourceLocation(),
9171                                          &PP.getIdentifierTable().get("std"),
9172                                          /*PrevDecl=*/nullptr);
9173     getStdNamespace()->setImplicit(true);
9174   }
9175 
9176   return getStdNamespace();
9177 }
9178 
9179 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9180   assert(getLangOpts().CPlusPlus &&
9181          "Looking for std::initializer_list outside of C++.");
9182 
9183   // We're looking for implicit instantiations of
9184   // template <typename E> class std::initializer_list.
9185 
9186   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9187     return false;
9188 
9189   ClassTemplateDecl *Template = nullptr;
9190   const TemplateArgument *Arguments = nullptr;
9191 
9192   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9193 
9194     ClassTemplateSpecializationDecl *Specialization =
9195         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9196     if (!Specialization)
9197       return false;
9198 
9199     Template = Specialization->getSpecializedTemplate();
9200     Arguments = Specialization->getTemplateArgs().data();
9201   } else if (const TemplateSpecializationType *TST =
9202                  Ty->getAs<TemplateSpecializationType>()) {
9203     Template = dyn_cast_or_null<ClassTemplateDecl>(
9204         TST->getTemplateName().getAsTemplateDecl());
9205     Arguments = TST->getArgs();
9206   }
9207   if (!Template)
9208     return false;
9209 
9210   if (!StdInitializerList) {
9211     // Haven't recognized std::initializer_list yet, maybe this is it.
9212     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9213     if (TemplateClass->getIdentifier() !=
9214             &PP.getIdentifierTable().get("initializer_list") ||
9215         !getStdNamespace()->InEnclosingNamespaceSetOf(
9216             TemplateClass->getDeclContext()))
9217       return false;
9218     // This is a template called std::initializer_list, but is it the right
9219     // template?
9220     TemplateParameterList *Params = Template->getTemplateParameters();
9221     if (Params->getMinRequiredArguments() != 1)
9222       return false;
9223     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9224       return false;
9225 
9226     // It's the right template.
9227     StdInitializerList = Template;
9228   }
9229 
9230   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9231     return false;
9232 
9233   // This is an instance of std::initializer_list. Find the argument type.
9234   if (Element)
9235     *Element = Arguments[0].getAsType();
9236   return true;
9237 }
9238 
9239 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9240   NamespaceDecl *Std = S.getStdNamespace();
9241   if (!Std) {
9242     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9243     return nullptr;
9244   }
9245 
9246   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9247                       Loc, Sema::LookupOrdinaryName);
9248   if (!S.LookupQualifiedName(Result, Std)) {
9249     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9250     return nullptr;
9251   }
9252   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9253   if (!Template) {
9254     Result.suppressDiagnostics();
9255     // We found something weird. Complain about the first thing we found.
9256     NamedDecl *Found = *Result.begin();
9257     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9258     return nullptr;
9259   }
9260 
9261   // We found some template called std::initializer_list. Now verify that it's
9262   // correct.
9263   TemplateParameterList *Params = Template->getTemplateParameters();
9264   if (Params->getMinRequiredArguments() != 1 ||
9265       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9266     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9267     return nullptr;
9268   }
9269 
9270   return Template;
9271 }
9272 
9273 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9274   if (!StdInitializerList) {
9275     StdInitializerList = LookupStdInitializerList(*this, Loc);
9276     if (!StdInitializerList)
9277       return QualType();
9278   }
9279 
9280   TemplateArgumentListInfo Args(Loc, Loc);
9281   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9282                                        Context.getTrivialTypeSourceInfo(Element,
9283                                                                         Loc)));
9284   return Context.getCanonicalType(
9285       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9286 }
9287 
9288 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9289   // C++ [dcl.init.list]p2:
9290   //   A constructor is an initializer-list constructor if its first parameter
9291   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9292   //   std::initializer_list<E> for some type E, and either there are no other
9293   //   parameters or else all other parameters have default arguments.
9294   if (Ctor->getNumParams() < 1 ||
9295       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9296     return false;
9297 
9298   QualType ArgType = Ctor->getParamDecl(0)->getType();
9299   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9300     ArgType = RT->getPointeeType().getUnqualifiedType();
9301 
9302   return isStdInitializerList(ArgType, nullptr);
9303 }
9304 
9305 /// Determine whether a using statement is in a context where it will be
9306 /// apply in all contexts.
9307 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9308   switch (CurContext->getDeclKind()) {
9309     case Decl::TranslationUnit:
9310       return true;
9311     case Decl::LinkageSpec:
9312       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9313     default:
9314       return false;
9315   }
9316 }
9317 
9318 namespace {
9319 
9320 // Callback to only accept typo corrections that are namespaces.
9321 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9322 public:
9323   bool ValidateCandidate(const TypoCorrection &candidate) override {
9324     if (NamedDecl *ND = candidate.getCorrectionDecl())
9325       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9326     return false;
9327   }
9328 };
9329 
9330 }
9331 
9332 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9333                                        CXXScopeSpec &SS,
9334                                        SourceLocation IdentLoc,
9335                                        IdentifierInfo *Ident) {
9336   R.clear();
9337   if (TypoCorrection Corrected =
9338           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9339                         llvm::make_unique<NamespaceValidatorCCC>(),
9340                         Sema::CTK_ErrorRecovery)) {
9341     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9342       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9343       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9344                               Ident->getName().equals(CorrectedStr);
9345       S.diagnoseTypo(Corrected,
9346                      S.PDiag(diag::err_using_directive_member_suggest)
9347                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9348                      S.PDiag(diag::note_namespace_defined_here));
9349     } else {
9350       S.diagnoseTypo(Corrected,
9351                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9352                      S.PDiag(diag::note_namespace_defined_here));
9353     }
9354     R.addDecl(Corrected.getFoundDecl());
9355     return true;
9356   }
9357   return false;
9358 }
9359 
9360 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9361                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9362                                 SourceLocation IdentLoc,
9363                                 IdentifierInfo *NamespcName,
9364                                 const ParsedAttributesView &AttrList) {
9365   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9366   assert(NamespcName && "Invalid NamespcName.");
9367   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9368 
9369   // This can only happen along a recovery path.
9370   while (S->isTemplateParamScope())
9371     S = S->getParent();
9372   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9373 
9374   UsingDirectiveDecl *UDir = nullptr;
9375   NestedNameSpecifier *Qualifier = nullptr;
9376   if (SS.isSet())
9377     Qualifier = SS.getScopeRep();
9378 
9379   // Lookup namespace name.
9380   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9381   LookupParsedName(R, S, &SS);
9382   if (R.isAmbiguous())
9383     return nullptr;
9384 
9385   if (R.empty()) {
9386     R.clear();
9387     // Allow "using namespace std;" or "using namespace ::std;" even if
9388     // "std" hasn't been defined yet, for GCC compatibility.
9389     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9390         NamespcName->isStr("std")) {
9391       Diag(IdentLoc, diag::ext_using_undefined_std);
9392       R.addDecl(getOrCreateStdNamespace());
9393       R.resolveKind();
9394     }
9395     // Otherwise, attempt typo correction.
9396     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9397   }
9398 
9399   if (!R.empty()) {
9400     NamedDecl *Named = R.getRepresentativeDecl();
9401     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9402     assert(NS && "expected namespace decl");
9403 
9404     // The use of a nested name specifier may trigger deprecation warnings.
9405     DiagnoseUseOfDecl(Named, IdentLoc);
9406 
9407     // C++ [namespace.udir]p1:
9408     //   A using-directive specifies that the names in the nominated
9409     //   namespace can be used in the scope in which the
9410     //   using-directive appears after the using-directive. During
9411     //   unqualified name lookup (3.4.1), the names appear as if they
9412     //   were declared in the nearest enclosing namespace which
9413     //   contains both the using-directive and the nominated
9414     //   namespace. [Note: in this context, "contains" means "contains
9415     //   directly or indirectly". ]
9416 
9417     // Find enclosing context containing both using-directive and
9418     // nominated namespace.
9419     DeclContext *CommonAncestor = NS;
9420     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9421       CommonAncestor = CommonAncestor->getParent();
9422 
9423     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9424                                       SS.getWithLocInContext(Context),
9425                                       IdentLoc, Named, CommonAncestor);
9426 
9427     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9428         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9429       Diag(IdentLoc, diag::warn_using_directive_in_header);
9430     }
9431 
9432     PushUsingDirective(S, UDir);
9433   } else {
9434     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9435   }
9436 
9437   if (UDir)
9438     ProcessDeclAttributeList(S, UDir, AttrList);
9439 
9440   return UDir;
9441 }
9442 
9443 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9444   // If the scope has an associated entity and the using directive is at
9445   // namespace or translation unit scope, add the UsingDirectiveDecl into
9446   // its lookup structure so qualified name lookup can find it.
9447   DeclContext *Ctx = S->getEntity();
9448   if (Ctx && !Ctx->isFunctionOrMethod())
9449     Ctx->addDecl(UDir);
9450   else
9451     // Otherwise, it is at block scope. The using-directives will affect lookup
9452     // only to the end of the scope.
9453     S->PushUsingDirective(UDir);
9454 }
9455 
9456 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9457                                   SourceLocation UsingLoc,
9458                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9459                                   UnqualifiedId &Name,
9460                                   SourceLocation EllipsisLoc,
9461                                   const ParsedAttributesView &AttrList) {
9462   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9463 
9464   if (SS.isEmpty()) {
9465     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9466     return nullptr;
9467   }
9468 
9469   switch (Name.getKind()) {
9470   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9471   case UnqualifiedIdKind::IK_Identifier:
9472   case UnqualifiedIdKind::IK_OperatorFunctionId:
9473   case UnqualifiedIdKind::IK_LiteralOperatorId:
9474   case UnqualifiedIdKind::IK_ConversionFunctionId:
9475     break;
9476 
9477   case UnqualifiedIdKind::IK_ConstructorName:
9478   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9479     // C++11 inheriting constructors.
9480     Diag(Name.getBeginLoc(),
9481          getLangOpts().CPlusPlus11
9482              ? diag::warn_cxx98_compat_using_decl_constructor
9483              : diag::err_using_decl_constructor)
9484         << SS.getRange();
9485 
9486     if (getLangOpts().CPlusPlus11) break;
9487 
9488     return nullptr;
9489 
9490   case UnqualifiedIdKind::IK_DestructorName:
9491     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9492     return nullptr;
9493 
9494   case UnqualifiedIdKind::IK_TemplateId:
9495     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9496         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9497     return nullptr;
9498 
9499   case UnqualifiedIdKind::IK_DeductionGuideName:
9500     llvm_unreachable("cannot parse qualified deduction guide name");
9501   }
9502 
9503   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9504   DeclarationName TargetName = TargetNameInfo.getName();
9505   if (!TargetName)
9506     return nullptr;
9507 
9508   // Warn about access declarations.
9509   if (UsingLoc.isInvalid()) {
9510     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9511                                  ? diag::err_access_decl
9512                                  : diag::warn_access_decl_deprecated)
9513         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9514   }
9515 
9516   if (EllipsisLoc.isInvalid()) {
9517     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9518         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9519       return nullptr;
9520   } else {
9521     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9522         !TargetNameInfo.containsUnexpandedParameterPack()) {
9523       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9524         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9525       EllipsisLoc = SourceLocation();
9526     }
9527   }
9528 
9529   NamedDecl *UD =
9530       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9531                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9532                             /*IsInstantiation*/false);
9533   if (UD)
9534     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9535 
9536   return UD;
9537 }
9538 
9539 /// Determine whether a using declaration considers the given
9540 /// declarations as "equivalent", e.g., if they are redeclarations of
9541 /// the same entity or are both typedefs of the same type.
9542 static bool
9543 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9544   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9545     return true;
9546 
9547   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9548     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9549       return Context.hasSameType(TD1->getUnderlyingType(),
9550                                  TD2->getUnderlyingType());
9551 
9552   return false;
9553 }
9554 
9555 
9556 /// Determines whether to create a using shadow decl for a particular
9557 /// decl, given the set of decls existing prior to this using lookup.
9558 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9559                                 const LookupResult &Previous,
9560                                 UsingShadowDecl *&PrevShadow) {
9561   // Diagnose finding a decl which is not from a base class of the
9562   // current class.  We do this now because there are cases where this
9563   // function will silently decide not to build a shadow decl, which
9564   // will pre-empt further diagnostics.
9565   //
9566   // We don't need to do this in C++11 because we do the check once on
9567   // the qualifier.
9568   //
9569   // FIXME: diagnose the following if we care enough:
9570   //   struct A { int foo; };
9571   //   struct B : A { using A::foo; };
9572   //   template <class T> struct C : A {};
9573   //   template <class T> struct D : C<T> { using B::foo; } // <---
9574   // This is invalid (during instantiation) in C++03 because B::foo
9575   // resolves to the using decl in B, which is not a base class of D<T>.
9576   // We can't diagnose it immediately because C<T> is an unknown
9577   // specialization.  The UsingShadowDecl in D<T> then points directly
9578   // to A::foo, which will look well-formed when we instantiate.
9579   // The right solution is to not collapse the shadow-decl chain.
9580   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9581     DeclContext *OrigDC = Orig->getDeclContext();
9582 
9583     // Handle enums and anonymous structs.
9584     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9585     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9586     while (OrigRec->isAnonymousStructOrUnion())
9587       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9588 
9589     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9590       if (OrigDC == CurContext) {
9591         Diag(Using->getLocation(),
9592              diag::err_using_decl_nested_name_specifier_is_current_class)
9593           << Using->getQualifierLoc().getSourceRange();
9594         Diag(Orig->getLocation(), diag::note_using_decl_target);
9595         Using->setInvalidDecl();
9596         return true;
9597       }
9598 
9599       Diag(Using->getQualifierLoc().getBeginLoc(),
9600            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9601         << Using->getQualifier()
9602         << cast<CXXRecordDecl>(CurContext)
9603         << Using->getQualifierLoc().getSourceRange();
9604       Diag(Orig->getLocation(), diag::note_using_decl_target);
9605       Using->setInvalidDecl();
9606       return true;
9607     }
9608   }
9609 
9610   if (Previous.empty()) return false;
9611 
9612   NamedDecl *Target = Orig;
9613   if (isa<UsingShadowDecl>(Target))
9614     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9615 
9616   // If the target happens to be one of the previous declarations, we
9617   // don't have a conflict.
9618   //
9619   // FIXME: but we might be increasing its access, in which case we
9620   // should redeclare it.
9621   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9622   bool FoundEquivalentDecl = false;
9623   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9624          I != E; ++I) {
9625     NamedDecl *D = (*I)->getUnderlyingDecl();
9626     // We can have UsingDecls in our Previous results because we use the same
9627     // LookupResult for checking whether the UsingDecl itself is a valid
9628     // redeclaration.
9629     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9630       continue;
9631 
9632     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9633       // C++ [class.mem]p19:
9634       //   If T is the name of a class, then [every named member other than
9635       //   a non-static data member] shall have a name different from T
9636       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9637           !isa<IndirectFieldDecl>(Target) &&
9638           !isa<UnresolvedUsingValueDecl>(Target) &&
9639           DiagnoseClassNameShadow(
9640               CurContext,
9641               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9642         return true;
9643     }
9644 
9645     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9646       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9647         PrevShadow = Shadow;
9648       FoundEquivalentDecl = true;
9649     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9650       // We don't conflict with an existing using shadow decl of an equivalent
9651       // declaration, but we're not a redeclaration of it.
9652       FoundEquivalentDecl = true;
9653     }
9654 
9655     if (isVisible(D))
9656       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9657   }
9658 
9659   if (FoundEquivalentDecl)
9660     return false;
9661 
9662   if (FunctionDecl *FD = Target->getAsFunction()) {
9663     NamedDecl *OldDecl = nullptr;
9664     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9665                           /*IsForUsingDecl*/ true)) {
9666     case Ovl_Overload:
9667       return false;
9668 
9669     case Ovl_NonFunction:
9670       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9671       break;
9672 
9673     // We found a decl with the exact signature.
9674     case Ovl_Match:
9675       // If we're in a record, we want to hide the target, so we
9676       // return true (without a diagnostic) to tell the caller not to
9677       // build a shadow decl.
9678       if (CurContext->isRecord())
9679         return true;
9680 
9681       // If we're not in a record, this is an error.
9682       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9683       break;
9684     }
9685 
9686     Diag(Target->getLocation(), diag::note_using_decl_target);
9687     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9688     Using->setInvalidDecl();
9689     return true;
9690   }
9691 
9692   // Target is not a function.
9693 
9694   if (isa<TagDecl>(Target)) {
9695     // No conflict between a tag and a non-tag.
9696     if (!Tag) return false;
9697 
9698     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9699     Diag(Target->getLocation(), diag::note_using_decl_target);
9700     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9701     Using->setInvalidDecl();
9702     return true;
9703   }
9704 
9705   // No conflict between a tag and a non-tag.
9706   if (!NonTag) return false;
9707 
9708   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9709   Diag(Target->getLocation(), diag::note_using_decl_target);
9710   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9711   Using->setInvalidDecl();
9712   return true;
9713 }
9714 
9715 /// Determine whether a direct base class is a virtual base class.
9716 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9717   if (!Derived->getNumVBases())
9718     return false;
9719   for (auto &B : Derived->bases())
9720     if (B.getType()->getAsCXXRecordDecl() == Base)
9721       return B.isVirtual();
9722   llvm_unreachable("not a direct base class");
9723 }
9724 
9725 /// Builds a shadow declaration corresponding to a 'using' declaration.
9726 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9727                                             UsingDecl *UD,
9728                                             NamedDecl *Orig,
9729                                             UsingShadowDecl *PrevDecl) {
9730   // If we resolved to another shadow declaration, just coalesce them.
9731   NamedDecl *Target = Orig;
9732   if (isa<UsingShadowDecl>(Target)) {
9733     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9734     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9735   }
9736 
9737   NamedDecl *NonTemplateTarget = Target;
9738   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9739     NonTemplateTarget = TargetTD->getTemplatedDecl();
9740 
9741   UsingShadowDecl *Shadow;
9742   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9743     bool IsVirtualBase =
9744         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9745                             UD->getQualifier()->getAsRecordDecl());
9746     Shadow = ConstructorUsingShadowDecl::Create(
9747         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9748   } else {
9749     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9750                                      Target);
9751   }
9752   UD->addShadowDecl(Shadow);
9753 
9754   Shadow->setAccess(UD->getAccess());
9755   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9756     Shadow->setInvalidDecl();
9757 
9758   Shadow->setPreviousDecl(PrevDecl);
9759 
9760   if (S)
9761     PushOnScopeChains(Shadow, S);
9762   else
9763     CurContext->addDecl(Shadow);
9764 
9765 
9766   return Shadow;
9767 }
9768 
9769 /// Hides a using shadow declaration.  This is required by the current
9770 /// using-decl implementation when a resolvable using declaration in a
9771 /// class is followed by a declaration which would hide or override
9772 /// one or more of the using decl's targets; for example:
9773 ///
9774 ///   struct Base { void foo(int); };
9775 ///   struct Derived : Base {
9776 ///     using Base::foo;
9777 ///     void foo(int);
9778 ///   };
9779 ///
9780 /// The governing language is C++03 [namespace.udecl]p12:
9781 ///
9782 ///   When a using-declaration brings names from a base class into a
9783 ///   derived class scope, member functions in the derived class
9784 ///   override and/or hide member functions with the same name and
9785 ///   parameter types in a base class (rather than conflicting).
9786 ///
9787 /// There are two ways to implement this:
9788 ///   (1) optimistically create shadow decls when they're not hidden
9789 ///       by existing declarations, or
9790 ///   (2) don't create any shadow decls (or at least don't make them
9791 ///       visible) until we've fully parsed/instantiated the class.
9792 /// The problem with (1) is that we might have to retroactively remove
9793 /// a shadow decl, which requires several O(n) operations because the
9794 /// decl structures are (very reasonably) not designed for removal.
9795 /// (2) avoids this but is very fiddly and phase-dependent.
9796 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9797   if (Shadow->getDeclName().getNameKind() ==
9798         DeclarationName::CXXConversionFunctionName)
9799     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9800 
9801   // Remove it from the DeclContext...
9802   Shadow->getDeclContext()->removeDecl(Shadow);
9803 
9804   // ...and the scope, if applicable...
9805   if (S) {
9806     S->RemoveDecl(Shadow);
9807     IdResolver.RemoveDecl(Shadow);
9808   }
9809 
9810   // ...and the using decl.
9811   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9812 
9813   // TODO: complain somehow if Shadow was used.  It shouldn't
9814   // be possible for this to happen, because...?
9815 }
9816 
9817 /// Find the base specifier for a base class with the given type.
9818 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9819                                                 QualType DesiredBase,
9820                                                 bool &AnyDependentBases) {
9821   // Check whether the named type is a direct base class.
9822   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9823   for (auto &Base : Derived->bases()) {
9824     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9825     if (CanonicalDesiredBase == BaseType)
9826       return &Base;
9827     if (BaseType->isDependentType())
9828       AnyDependentBases = true;
9829   }
9830   return nullptr;
9831 }
9832 
9833 namespace {
9834 class UsingValidatorCCC : public CorrectionCandidateCallback {
9835 public:
9836   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9837                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9838       : HasTypenameKeyword(HasTypenameKeyword),
9839         IsInstantiation(IsInstantiation), OldNNS(NNS),
9840         RequireMemberOf(RequireMemberOf) {}
9841 
9842   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9843     NamedDecl *ND = Candidate.getCorrectionDecl();
9844 
9845     // Keywords are not valid here.
9846     if (!ND || isa<NamespaceDecl>(ND))
9847       return false;
9848 
9849     // Completely unqualified names are invalid for a 'using' declaration.
9850     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9851       return false;
9852 
9853     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9854     // reject.
9855 
9856     if (RequireMemberOf) {
9857       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9858       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9859         // No-one ever wants a using-declaration to name an injected-class-name
9860         // of a base class, unless they're declaring an inheriting constructor.
9861         ASTContext &Ctx = ND->getASTContext();
9862         if (!Ctx.getLangOpts().CPlusPlus11)
9863           return false;
9864         QualType FoundType = Ctx.getRecordType(FoundRecord);
9865 
9866         // Check that the injected-class-name is named as a member of its own
9867         // type; we don't want to suggest 'using Derived::Base;', since that
9868         // means something else.
9869         NestedNameSpecifier *Specifier =
9870             Candidate.WillReplaceSpecifier()
9871                 ? Candidate.getCorrectionSpecifier()
9872                 : OldNNS;
9873         if (!Specifier->getAsType() ||
9874             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9875           return false;
9876 
9877         // Check that this inheriting constructor declaration actually names a
9878         // direct base class of the current class.
9879         bool AnyDependentBases = false;
9880         if (!findDirectBaseWithType(RequireMemberOf,
9881                                     Ctx.getRecordType(FoundRecord),
9882                                     AnyDependentBases) &&
9883             !AnyDependentBases)
9884           return false;
9885       } else {
9886         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9887         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9888           return false;
9889 
9890         // FIXME: Check that the base class member is accessible?
9891       }
9892     } else {
9893       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9894       if (FoundRecord && FoundRecord->isInjectedClassName())
9895         return false;
9896     }
9897 
9898     if (isa<TypeDecl>(ND))
9899       return HasTypenameKeyword || !IsInstantiation;
9900 
9901     return !HasTypenameKeyword;
9902   }
9903 
9904 private:
9905   bool HasTypenameKeyword;
9906   bool IsInstantiation;
9907   NestedNameSpecifier *OldNNS;
9908   CXXRecordDecl *RequireMemberOf;
9909 };
9910 } // end anonymous namespace
9911 
9912 /// Builds a using declaration.
9913 ///
9914 /// \param IsInstantiation - Whether this call arises from an
9915 ///   instantiation of an unresolved using declaration.  We treat
9916 ///   the lookup differently for these declarations.
9917 NamedDecl *Sema::BuildUsingDeclaration(
9918     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9919     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9920     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9921     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9922   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9923   SourceLocation IdentLoc = NameInfo.getLoc();
9924   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9925 
9926   // FIXME: We ignore attributes for now.
9927 
9928   // For an inheriting constructor declaration, the name of the using
9929   // declaration is the name of a constructor in this class, not in the
9930   // base class.
9931   DeclarationNameInfo UsingName = NameInfo;
9932   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9933     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9934       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9935           Context.getCanonicalType(Context.getRecordType(RD))));
9936 
9937   // Do the redeclaration lookup in the current scope.
9938   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9939                         ForVisibleRedeclaration);
9940   Previous.setHideTags(false);
9941   if (S) {
9942     LookupName(Previous, S);
9943 
9944     // It is really dumb that we have to do this.
9945     LookupResult::Filter F = Previous.makeFilter();
9946     while (F.hasNext()) {
9947       NamedDecl *D = F.next();
9948       if (!isDeclInScope(D, CurContext, S))
9949         F.erase();
9950       // If we found a local extern declaration that's not ordinarily visible,
9951       // and this declaration is being added to a non-block scope, ignore it.
9952       // We're only checking for scope conflicts here, not also for violations
9953       // of the linkage rules.
9954       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9955                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9956         F.erase();
9957     }
9958     F.done();
9959   } else {
9960     assert(IsInstantiation && "no scope in non-instantiation");
9961     if (CurContext->isRecord())
9962       LookupQualifiedName(Previous, CurContext);
9963     else {
9964       // No redeclaration check is needed here; in non-member contexts we
9965       // diagnosed all possible conflicts with other using-declarations when
9966       // building the template:
9967       //
9968       // For a dependent non-type using declaration, the only valid case is
9969       // if we instantiate to a single enumerator. We check for conflicts
9970       // between shadow declarations we introduce, and we check in the template
9971       // definition for conflicts between a non-type using declaration and any
9972       // other declaration, which together covers all cases.
9973       //
9974       // A dependent typename using declaration will never successfully
9975       // instantiate, since it will always name a class member, so we reject
9976       // that in the template definition.
9977     }
9978   }
9979 
9980   // Check for invalid redeclarations.
9981   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9982                                   SS, IdentLoc, Previous))
9983     return nullptr;
9984 
9985   // Check for bad qualifiers.
9986   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9987                               IdentLoc))
9988     return nullptr;
9989 
9990   DeclContext *LookupContext = computeDeclContext(SS);
9991   NamedDecl *D;
9992   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9993   if (!LookupContext || EllipsisLoc.isValid()) {
9994     if (HasTypenameKeyword) {
9995       // FIXME: not all declaration name kinds are legal here
9996       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9997                                               UsingLoc, TypenameLoc,
9998                                               QualifierLoc,
9999                                               IdentLoc, NameInfo.getName(),
10000                                               EllipsisLoc);
10001     } else {
10002       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10003                                            QualifierLoc, NameInfo, EllipsisLoc);
10004     }
10005     D->setAccess(AS);
10006     CurContext->addDecl(D);
10007     return D;
10008   }
10009 
10010   auto Build = [&](bool Invalid) {
10011     UsingDecl *UD =
10012         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10013                           UsingName, HasTypenameKeyword);
10014     UD->setAccess(AS);
10015     CurContext->addDecl(UD);
10016     UD->setInvalidDecl(Invalid);
10017     return UD;
10018   };
10019   auto BuildInvalid = [&]{ return Build(true); };
10020   auto BuildValid = [&]{ return Build(false); };
10021 
10022   if (RequireCompleteDeclContext(SS, LookupContext))
10023     return BuildInvalid();
10024 
10025   // Look up the target name.
10026   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10027 
10028   // Unlike most lookups, we don't always want to hide tag
10029   // declarations: tag names are visible through the using declaration
10030   // even if hidden by ordinary names, *except* in a dependent context
10031   // where it's important for the sanity of two-phase lookup.
10032   if (!IsInstantiation)
10033     R.setHideTags(false);
10034 
10035   // For the purposes of this lookup, we have a base object type
10036   // equal to that of the current context.
10037   if (CurContext->isRecord()) {
10038     R.setBaseObjectType(
10039                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10040   }
10041 
10042   LookupQualifiedName(R, LookupContext);
10043 
10044   // Try to correct typos if possible. If constructor name lookup finds no
10045   // results, that means the named class has no explicit constructors, and we
10046   // suppressed declaring implicit ones (probably because it's dependent or
10047   // invalid).
10048   if (R.empty() &&
10049       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10050     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10051     // it will believe that glibc provides a ::gets in cases where it does not,
10052     // and will try to pull it into namespace std with a using-declaration.
10053     // Just ignore the using-declaration in that case.
10054     auto *II = NameInfo.getName().getAsIdentifierInfo();
10055     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10056         CurContext->isStdNamespace() &&
10057         isa<TranslationUnitDecl>(LookupContext) &&
10058         getSourceManager().isInSystemHeader(UsingLoc))
10059       return nullptr;
10060     if (TypoCorrection Corrected = CorrectTypo(
10061             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10062             llvm::make_unique<UsingValidatorCCC>(
10063                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10064                 dyn_cast<CXXRecordDecl>(CurContext)),
10065             CTK_ErrorRecovery)) {
10066       // We reject candidates where DroppedSpecifier == true, hence the
10067       // literal '0' below.
10068       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10069                                 << NameInfo.getName() << LookupContext << 0
10070                                 << SS.getRange());
10071 
10072       // If we picked a correction with no attached Decl we can't do anything
10073       // useful with it, bail out.
10074       NamedDecl *ND = Corrected.getCorrectionDecl();
10075       if (!ND)
10076         return BuildInvalid();
10077 
10078       // If we corrected to an inheriting constructor, handle it as one.
10079       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10080       if (RD && RD->isInjectedClassName()) {
10081         // The parent of the injected class name is the class itself.
10082         RD = cast<CXXRecordDecl>(RD->getParent());
10083 
10084         // Fix up the information we'll use to build the using declaration.
10085         if (Corrected.WillReplaceSpecifier()) {
10086           NestedNameSpecifierLocBuilder Builder;
10087           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10088                               QualifierLoc.getSourceRange());
10089           QualifierLoc = Builder.getWithLocInContext(Context);
10090         }
10091 
10092         // In this case, the name we introduce is the name of a derived class
10093         // constructor.
10094         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10095         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10096             Context.getCanonicalType(Context.getRecordType(CurClass))));
10097         UsingName.setNamedTypeInfo(nullptr);
10098         for (auto *Ctor : LookupConstructors(RD))
10099           R.addDecl(Ctor);
10100         R.resolveKind();
10101       } else {
10102         // FIXME: Pick up all the declarations if we found an overloaded
10103         // function.
10104         UsingName.setName(ND->getDeclName());
10105         R.addDecl(ND);
10106       }
10107     } else {
10108       Diag(IdentLoc, diag::err_no_member)
10109         << NameInfo.getName() << LookupContext << SS.getRange();
10110       return BuildInvalid();
10111     }
10112   }
10113 
10114   if (R.isAmbiguous())
10115     return BuildInvalid();
10116 
10117   if (HasTypenameKeyword) {
10118     // If we asked for a typename and got a non-type decl, error out.
10119     if (!R.getAsSingle<TypeDecl>()) {
10120       Diag(IdentLoc, diag::err_using_typename_non_type);
10121       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10122         Diag((*I)->getUnderlyingDecl()->getLocation(),
10123              diag::note_using_decl_target);
10124       return BuildInvalid();
10125     }
10126   } else {
10127     // If we asked for a non-typename and we got a type, error out,
10128     // but only if this is an instantiation of an unresolved using
10129     // decl.  Otherwise just silently find the type name.
10130     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10131       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10132       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10133       return BuildInvalid();
10134     }
10135   }
10136 
10137   // C++14 [namespace.udecl]p6:
10138   // A using-declaration shall not name a namespace.
10139   if (R.getAsSingle<NamespaceDecl>()) {
10140     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10141       << SS.getRange();
10142     return BuildInvalid();
10143   }
10144 
10145   // C++14 [namespace.udecl]p7:
10146   // A using-declaration shall not name a scoped enumerator.
10147   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10148     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10149       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10150         << SS.getRange();
10151       return BuildInvalid();
10152     }
10153   }
10154 
10155   UsingDecl *UD = BuildValid();
10156 
10157   // Some additional rules apply to inheriting constructors.
10158   if (UsingName.getName().getNameKind() ==
10159         DeclarationName::CXXConstructorName) {
10160     // Suppress access diagnostics; the access check is instead performed at the
10161     // point of use for an inheriting constructor.
10162     R.suppressDiagnostics();
10163     if (CheckInheritingConstructorUsingDecl(UD))
10164       return UD;
10165   }
10166 
10167   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10168     UsingShadowDecl *PrevDecl = nullptr;
10169     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10170       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10171   }
10172 
10173   return UD;
10174 }
10175 
10176 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10177                                     ArrayRef<NamedDecl *> Expansions) {
10178   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10179          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10180          isa<UsingPackDecl>(InstantiatedFrom));
10181 
10182   auto *UPD =
10183       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10184   UPD->setAccess(InstantiatedFrom->getAccess());
10185   CurContext->addDecl(UPD);
10186   return UPD;
10187 }
10188 
10189 /// Additional checks for a using declaration referring to a constructor name.
10190 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10191   assert(!UD->hasTypename() && "expecting a constructor name");
10192 
10193   const Type *SourceType = UD->getQualifier()->getAsType();
10194   assert(SourceType &&
10195          "Using decl naming constructor doesn't have type in scope spec.");
10196   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10197 
10198   // Check whether the named type is a direct base class.
10199   bool AnyDependentBases = false;
10200   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10201                                       AnyDependentBases);
10202   if (!Base && !AnyDependentBases) {
10203     Diag(UD->getUsingLoc(),
10204          diag::err_using_decl_constructor_not_in_direct_base)
10205       << UD->getNameInfo().getSourceRange()
10206       << QualType(SourceType, 0) << TargetClass;
10207     UD->setInvalidDecl();
10208     return true;
10209   }
10210 
10211   if (Base)
10212     Base->setInheritConstructors();
10213 
10214   return false;
10215 }
10216 
10217 /// Checks that the given using declaration is not an invalid
10218 /// redeclaration.  Note that this is checking only for the using decl
10219 /// itself, not for any ill-formedness among the UsingShadowDecls.
10220 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10221                                        bool HasTypenameKeyword,
10222                                        const CXXScopeSpec &SS,
10223                                        SourceLocation NameLoc,
10224                                        const LookupResult &Prev) {
10225   NestedNameSpecifier *Qual = SS.getScopeRep();
10226 
10227   // C++03 [namespace.udecl]p8:
10228   // C++0x [namespace.udecl]p10:
10229   //   A using-declaration is a declaration and can therefore be used
10230   //   repeatedly where (and only where) multiple declarations are
10231   //   allowed.
10232   //
10233   // That's in non-member contexts.
10234   if (!CurContext->getRedeclContext()->isRecord()) {
10235     // A dependent qualifier outside a class can only ever resolve to an
10236     // enumeration type. Therefore it conflicts with any other non-type
10237     // declaration in the same scope.
10238     // FIXME: How should we check for dependent type-type conflicts at block
10239     // scope?
10240     if (Qual->isDependent() && !HasTypenameKeyword) {
10241       for (auto *D : Prev) {
10242         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10243           bool OldCouldBeEnumerator =
10244               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10245           Diag(NameLoc,
10246                OldCouldBeEnumerator ? diag::err_redefinition
10247                                     : diag::err_redefinition_different_kind)
10248               << Prev.getLookupName();
10249           Diag(D->getLocation(), diag::note_previous_definition);
10250           return true;
10251         }
10252       }
10253     }
10254     return false;
10255   }
10256 
10257   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10258     NamedDecl *D = *I;
10259 
10260     bool DTypename;
10261     NestedNameSpecifier *DQual;
10262     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10263       DTypename = UD->hasTypename();
10264       DQual = UD->getQualifier();
10265     } else if (UnresolvedUsingValueDecl *UD
10266                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10267       DTypename = false;
10268       DQual = UD->getQualifier();
10269     } else if (UnresolvedUsingTypenameDecl *UD
10270                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10271       DTypename = true;
10272       DQual = UD->getQualifier();
10273     } else continue;
10274 
10275     // using decls differ if one says 'typename' and the other doesn't.
10276     // FIXME: non-dependent using decls?
10277     if (HasTypenameKeyword != DTypename) continue;
10278 
10279     // using decls differ if they name different scopes (but note that
10280     // template instantiation can cause this check to trigger when it
10281     // didn't before instantiation).
10282     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10283         Context.getCanonicalNestedNameSpecifier(DQual))
10284       continue;
10285 
10286     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10287     Diag(D->getLocation(), diag::note_using_decl) << 1;
10288     return true;
10289   }
10290 
10291   return false;
10292 }
10293 
10294 
10295 /// Checks that the given nested-name qualifier used in a using decl
10296 /// in the current context is appropriately related to the current
10297 /// scope.  If an error is found, diagnoses it and returns true.
10298 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10299                                    bool HasTypename,
10300                                    const CXXScopeSpec &SS,
10301                                    const DeclarationNameInfo &NameInfo,
10302                                    SourceLocation NameLoc) {
10303   DeclContext *NamedContext = computeDeclContext(SS);
10304 
10305   if (!CurContext->isRecord()) {
10306     // C++03 [namespace.udecl]p3:
10307     // C++0x [namespace.udecl]p8:
10308     //   A using-declaration for a class member shall be a member-declaration.
10309 
10310     // If we weren't able to compute a valid scope, it might validly be a
10311     // dependent class scope or a dependent enumeration unscoped scope. If
10312     // we have a 'typename' keyword, the scope must resolve to a class type.
10313     if ((HasTypename && !NamedContext) ||
10314         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10315       auto *RD = NamedContext
10316                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10317                      : nullptr;
10318       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10319         RD = nullptr;
10320 
10321       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10322         << SS.getRange();
10323 
10324       // If we have a complete, non-dependent source type, try to suggest a
10325       // way to get the same effect.
10326       if (!RD)
10327         return true;
10328 
10329       // Find what this using-declaration was referring to.
10330       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10331       R.setHideTags(false);
10332       R.suppressDiagnostics();
10333       LookupQualifiedName(R, RD);
10334 
10335       if (R.getAsSingle<TypeDecl>()) {
10336         if (getLangOpts().CPlusPlus11) {
10337           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10338           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10339             << 0 // alias declaration
10340             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10341                                           NameInfo.getName().getAsString() +
10342                                               " = ");
10343         } else {
10344           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10345           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10346           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10347             << 1 // typedef declaration
10348             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10349             << FixItHint::CreateInsertion(
10350                    InsertLoc, " " + NameInfo.getName().getAsString());
10351         }
10352       } else if (R.getAsSingle<VarDecl>()) {
10353         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10354         // repeating the type of the static data member here.
10355         FixItHint FixIt;
10356         if (getLangOpts().CPlusPlus11) {
10357           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10358           FixIt = FixItHint::CreateReplacement(
10359               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10360         }
10361 
10362         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10363           << 2 // reference declaration
10364           << FixIt;
10365       } else if (R.getAsSingle<EnumConstantDecl>()) {
10366         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10367         // repeating the type of the enumeration here, and we can't do so if
10368         // the type is anonymous.
10369         FixItHint FixIt;
10370         if (getLangOpts().CPlusPlus11) {
10371           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10372           FixIt = FixItHint::CreateReplacement(
10373               UsingLoc,
10374               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10375         }
10376 
10377         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10378           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10379           << FixIt;
10380       }
10381       return true;
10382     }
10383 
10384     // Otherwise, this might be valid.
10385     return false;
10386   }
10387 
10388   // The current scope is a record.
10389 
10390   // If the named context is dependent, we can't decide much.
10391   if (!NamedContext) {
10392     // FIXME: in C++0x, we can diagnose if we can prove that the
10393     // nested-name-specifier does not refer to a base class, which is
10394     // still possible in some cases.
10395 
10396     // Otherwise we have to conservatively report that things might be
10397     // okay.
10398     return false;
10399   }
10400 
10401   if (!NamedContext->isRecord()) {
10402     // Ideally this would point at the last name in the specifier,
10403     // but we don't have that level of source info.
10404     Diag(SS.getRange().getBegin(),
10405          diag::err_using_decl_nested_name_specifier_is_not_class)
10406       << SS.getScopeRep() << SS.getRange();
10407     return true;
10408   }
10409 
10410   if (!NamedContext->isDependentContext() &&
10411       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10412     return true;
10413 
10414   if (getLangOpts().CPlusPlus11) {
10415     // C++11 [namespace.udecl]p3:
10416     //   In a using-declaration used as a member-declaration, the
10417     //   nested-name-specifier shall name a base class of the class
10418     //   being defined.
10419 
10420     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10421                                  cast<CXXRecordDecl>(NamedContext))) {
10422       if (CurContext == NamedContext) {
10423         Diag(NameLoc,
10424              diag::err_using_decl_nested_name_specifier_is_current_class)
10425           << SS.getRange();
10426         return true;
10427       }
10428 
10429       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10430         Diag(SS.getRange().getBegin(),
10431              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10432           << SS.getScopeRep()
10433           << cast<CXXRecordDecl>(CurContext)
10434           << SS.getRange();
10435       }
10436       return true;
10437     }
10438 
10439     return false;
10440   }
10441 
10442   // C++03 [namespace.udecl]p4:
10443   //   A using-declaration used as a member-declaration shall refer
10444   //   to a member of a base class of the class being defined [etc.].
10445 
10446   // Salient point: SS doesn't have to name a base class as long as
10447   // lookup only finds members from base classes.  Therefore we can
10448   // diagnose here only if we can prove that that can't happen,
10449   // i.e. if the class hierarchies provably don't intersect.
10450 
10451   // TODO: it would be nice if "definitely valid" results were cached
10452   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10453   // need to be repeated.
10454 
10455   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10456   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10457     Bases.insert(Base);
10458     return true;
10459   };
10460 
10461   // Collect all bases. Return false if we find a dependent base.
10462   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10463     return false;
10464 
10465   // Returns true if the base is dependent or is one of the accumulated base
10466   // classes.
10467   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10468     return !Bases.count(Base);
10469   };
10470 
10471   // Return false if the class has a dependent base or if it or one
10472   // of its bases is present in the base set of the current context.
10473   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10474       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10475     return false;
10476 
10477   Diag(SS.getRange().getBegin(),
10478        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10479     << SS.getScopeRep()
10480     << cast<CXXRecordDecl>(CurContext)
10481     << SS.getRange();
10482 
10483   return true;
10484 }
10485 
10486 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10487                                   MultiTemplateParamsArg TemplateParamLists,
10488                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10489                                   const ParsedAttributesView &AttrList,
10490                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10491   // Skip up to the relevant declaration scope.
10492   while (S->isTemplateParamScope())
10493     S = S->getParent();
10494   assert((S->getFlags() & Scope::DeclScope) &&
10495          "got alias-declaration outside of declaration scope");
10496 
10497   if (Type.isInvalid())
10498     return nullptr;
10499 
10500   bool Invalid = false;
10501   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10502   TypeSourceInfo *TInfo = nullptr;
10503   GetTypeFromParser(Type.get(), &TInfo);
10504 
10505   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10506     return nullptr;
10507 
10508   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10509                                       UPPC_DeclarationType)) {
10510     Invalid = true;
10511     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10512                                              TInfo->getTypeLoc().getBeginLoc());
10513   }
10514 
10515   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10516                         TemplateParamLists.size()
10517                             ? forRedeclarationInCurContext()
10518                             : ForVisibleRedeclaration);
10519   LookupName(Previous, S);
10520 
10521   // Warn about shadowing the name of a template parameter.
10522   if (Previous.isSingleResult() &&
10523       Previous.getFoundDecl()->isTemplateParameter()) {
10524     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10525     Previous.clear();
10526   }
10527 
10528   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10529          "name in alias declaration must be an identifier");
10530   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10531                                                Name.StartLocation,
10532                                                Name.Identifier, TInfo);
10533 
10534   NewTD->setAccess(AS);
10535 
10536   if (Invalid)
10537     NewTD->setInvalidDecl();
10538 
10539   ProcessDeclAttributeList(S, NewTD, AttrList);
10540   AddPragmaAttributes(S, NewTD);
10541 
10542   CheckTypedefForVariablyModifiedType(S, NewTD);
10543   Invalid |= NewTD->isInvalidDecl();
10544 
10545   bool Redeclaration = false;
10546 
10547   NamedDecl *NewND;
10548   if (TemplateParamLists.size()) {
10549     TypeAliasTemplateDecl *OldDecl = nullptr;
10550     TemplateParameterList *OldTemplateParams = nullptr;
10551 
10552     if (TemplateParamLists.size() != 1) {
10553       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10554         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10555          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10556     }
10557     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10558 
10559     // Check that we can declare a template here.
10560     if (CheckTemplateDeclScope(S, TemplateParams))
10561       return nullptr;
10562 
10563     // Only consider previous declarations in the same scope.
10564     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10565                          /*ExplicitInstantiationOrSpecialization*/false);
10566     if (!Previous.empty()) {
10567       Redeclaration = true;
10568 
10569       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10570       if (!OldDecl && !Invalid) {
10571         Diag(UsingLoc, diag::err_redefinition_different_kind)
10572           << Name.Identifier;
10573 
10574         NamedDecl *OldD = Previous.getRepresentativeDecl();
10575         if (OldD->getLocation().isValid())
10576           Diag(OldD->getLocation(), diag::note_previous_definition);
10577 
10578         Invalid = true;
10579       }
10580 
10581       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10582         if (TemplateParameterListsAreEqual(TemplateParams,
10583                                            OldDecl->getTemplateParameters(),
10584                                            /*Complain=*/true,
10585                                            TPL_TemplateMatch))
10586           OldTemplateParams =
10587               OldDecl->getMostRecentDecl()->getTemplateParameters();
10588         else
10589           Invalid = true;
10590 
10591         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10592         if (!Invalid &&
10593             !Context.hasSameType(OldTD->getUnderlyingType(),
10594                                  NewTD->getUnderlyingType())) {
10595           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10596           // but we can't reasonably accept it.
10597           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10598             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10599           if (OldTD->getLocation().isValid())
10600             Diag(OldTD->getLocation(), diag::note_previous_definition);
10601           Invalid = true;
10602         }
10603       }
10604     }
10605 
10606     // Merge any previous default template arguments into our parameters,
10607     // and check the parameter list.
10608     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10609                                    TPC_TypeAliasTemplate))
10610       return nullptr;
10611 
10612     TypeAliasTemplateDecl *NewDecl =
10613       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10614                                     Name.Identifier, TemplateParams,
10615                                     NewTD);
10616     NewTD->setDescribedAliasTemplate(NewDecl);
10617 
10618     NewDecl->setAccess(AS);
10619 
10620     if (Invalid)
10621       NewDecl->setInvalidDecl();
10622     else if (OldDecl) {
10623       NewDecl->setPreviousDecl(OldDecl);
10624       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10625     }
10626 
10627     NewND = NewDecl;
10628   } else {
10629     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10630       setTagNameForLinkagePurposes(TD, NewTD);
10631       handleTagNumbering(TD, S);
10632     }
10633     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10634     NewND = NewTD;
10635   }
10636 
10637   PushOnScopeChains(NewND, S);
10638   ActOnDocumentableDecl(NewND);
10639   return NewND;
10640 }
10641 
10642 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10643                                    SourceLocation AliasLoc,
10644                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10645                                    SourceLocation IdentLoc,
10646                                    IdentifierInfo *Ident) {
10647 
10648   // Lookup the namespace name.
10649   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10650   LookupParsedName(R, S, &SS);
10651 
10652   if (R.isAmbiguous())
10653     return nullptr;
10654 
10655   if (R.empty()) {
10656     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10657       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10658       return nullptr;
10659     }
10660   }
10661   assert(!R.isAmbiguous() && !R.empty());
10662   NamedDecl *ND = R.getRepresentativeDecl();
10663 
10664   // Check if we have a previous declaration with the same name.
10665   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10666                      ForVisibleRedeclaration);
10667   LookupName(PrevR, S);
10668 
10669   // Check we're not shadowing a template parameter.
10670   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10671     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10672     PrevR.clear();
10673   }
10674 
10675   // Filter out any other lookup result from an enclosing scope.
10676   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10677                        /*AllowInlineNamespace*/false);
10678 
10679   // Find the previous declaration and check that we can redeclare it.
10680   NamespaceAliasDecl *Prev = nullptr;
10681   if (PrevR.isSingleResult()) {
10682     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10683     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10684       // We already have an alias with the same name that points to the same
10685       // namespace; check that it matches.
10686       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10687         Prev = AD;
10688       } else if (isVisible(PrevDecl)) {
10689         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10690           << Alias;
10691         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10692           << AD->getNamespace();
10693         return nullptr;
10694       }
10695     } else if (isVisible(PrevDecl)) {
10696       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10697                             ? diag::err_redefinition
10698                             : diag::err_redefinition_different_kind;
10699       Diag(AliasLoc, DiagID) << Alias;
10700       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10701       return nullptr;
10702     }
10703   }
10704 
10705   // The use of a nested name specifier may trigger deprecation warnings.
10706   DiagnoseUseOfDecl(ND, IdentLoc);
10707 
10708   NamespaceAliasDecl *AliasDecl =
10709     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10710                                Alias, SS.getWithLocInContext(Context),
10711                                IdentLoc, ND);
10712   if (Prev)
10713     AliasDecl->setPreviousDecl(Prev);
10714 
10715   PushOnScopeChains(AliasDecl, S);
10716   return AliasDecl;
10717 }
10718 
10719 namespace {
10720 struct SpecialMemberExceptionSpecInfo
10721     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10722   SourceLocation Loc;
10723   Sema::ImplicitExceptionSpecification ExceptSpec;
10724 
10725   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10726                                  Sema::CXXSpecialMember CSM,
10727                                  Sema::InheritedConstructorInfo *ICI,
10728                                  SourceLocation Loc)
10729       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10730 
10731   bool visitBase(CXXBaseSpecifier *Base);
10732   bool visitField(FieldDecl *FD);
10733 
10734   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10735                            unsigned Quals);
10736 
10737   void visitSubobjectCall(Subobject Subobj,
10738                           Sema::SpecialMemberOverloadResult SMOR);
10739 };
10740 }
10741 
10742 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10743   auto *RT = Base->getType()->getAs<RecordType>();
10744   if (!RT)
10745     return false;
10746 
10747   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10748   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10749   if (auto *BaseCtor = SMOR.getMethod()) {
10750     visitSubobjectCall(Base, BaseCtor);
10751     return false;
10752   }
10753 
10754   visitClassSubobject(BaseClass, Base, 0);
10755   return false;
10756 }
10757 
10758 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10759   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10760     Expr *E = FD->getInClassInitializer();
10761     if (!E)
10762       // FIXME: It's a little wasteful to build and throw away a
10763       // CXXDefaultInitExpr here.
10764       // FIXME: We should have a single context note pointing at Loc, and
10765       // this location should be MD->getLocation() instead, since that's
10766       // the location where we actually use the default init expression.
10767       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10768     if (E)
10769       ExceptSpec.CalledExpr(E);
10770   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10771                             ->getAs<RecordType>()) {
10772     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10773                         FD->getType().getCVRQualifiers());
10774   }
10775   return false;
10776 }
10777 
10778 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10779                                                          Subobject Subobj,
10780                                                          unsigned Quals) {
10781   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10782   bool IsMutable = Field && Field->isMutable();
10783   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10784 }
10785 
10786 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10787     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10788   // Note, if lookup fails, it doesn't matter what exception specification we
10789   // choose because the special member will be deleted.
10790   if (CXXMethodDecl *MD = SMOR.getMethod())
10791     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10792 }
10793 
10794 namespace {
10795 /// RAII object to register a special member as being currently declared.
10796 struct ComputingExceptionSpec {
10797   Sema &S;
10798 
10799   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10800       : S(S) {
10801     Sema::CodeSynthesisContext Ctx;
10802     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10803     Ctx.PointOfInstantiation = Loc;
10804     Ctx.Entity = MD;
10805     S.pushCodeSynthesisContext(Ctx);
10806   }
10807   ~ComputingExceptionSpec() {
10808     S.popCodeSynthesisContext();
10809   }
10810 };
10811 }
10812 
10813 static Sema::ImplicitExceptionSpecification
10814 ComputeDefaultedSpecialMemberExceptionSpec(
10815     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10816     Sema::InheritedConstructorInfo *ICI) {
10817   ComputingExceptionSpec CES(S, MD, Loc);
10818 
10819   CXXRecordDecl *ClassDecl = MD->getParent();
10820 
10821   // C++ [except.spec]p14:
10822   //   An implicitly declared special member function (Clause 12) shall have an
10823   //   exception-specification. [...]
10824   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10825   if (ClassDecl->isInvalidDecl())
10826     return Info.ExceptSpec;
10827 
10828   // FIXME: If this diagnostic fires, we're probably missing a check for
10829   // attempting to resolve an exception specification before it's known
10830   // at a higher level.
10831   if (S.RequireCompleteType(MD->getLocation(),
10832                             S.Context.getRecordType(ClassDecl),
10833                             diag::err_exception_spec_incomplete_type))
10834     return Info.ExceptSpec;
10835 
10836   // C++1z [except.spec]p7:
10837   //   [Look for exceptions thrown by] a constructor selected [...] to
10838   //   initialize a potentially constructed subobject,
10839   // C++1z [except.spec]p8:
10840   //   The exception specification for an implicitly-declared destructor, or a
10841   //   destructor without a noexcept-specifier, is potentially-throwing if and
10842   //   only if any of the destructors for any of its potentially constructed
10843   //   subojects is potentially throwing.
10844   // FIXME: We respect the first rule but ignore the "potentially constructed"
10845   // in the second rule to resolve a core issue (no number yet) that would have
10846   // us reject:
10847   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10848   //   struct B : A {};
10849   //   struct C : B { void f(); };
10850   // ... due to giving B::~B() a non-throwing exception specification.
10851   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10852                                 : Info.VisitAllBases);
10853 
10854   return Info.ExceptSpec;
10855 }
10856 
10857 namespace {
10858 /// RAII object to register a special member as being currently declared.
10859 struct DeclaringSpecialMember {
10860   Sema &S;
10861   Sema::SpecialMemberDecl D;
10862   Sema::ContextRAII SavedContext;
10863   bool WasAlreadyBeingDeclared;
10864 
10865   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10866       : S(S), D(RD, CSM), SavedContext(S, RD) {
10867     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10868     if (WasAlreadyBeingDeclared)
10869       // This almost never happens, but if it does, ensure that our cache
10870       // doesn't contain a stale result.
10871       S.SpecialMemberCache.clear();
10872     else {
10873       // Register a note to be produced if we encounter an error while
10874       // declaring the special member.
10875       Sema::CodeSynthesisContext Ctx;
10876       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10877       // FIXME: We don't have a location to use here. Using the class's
10878       // location maintains the fiction that we declare all special members
10879       // with the class, but (1) it's not clear that lying about that helps our
10880       // users understand what's going on, and (2) there may be outer contexts
10881       // on the stack (some of which are relevant) and printing them exposes
10882       // our lies.
10883       Ctx.PointOfInstantiation = RD->getLocation();
10884       Ctx.Entity = RD;
10885       Ctx.SpecialMember = CSM;
10886       S.pushCodeSynthesisContext(Ctx);
10887     }
10888   }
10889   ~DeclaringSpecialMember() {
10890     if (!WasAlreadyBeingDeclared) {
10891       S.SpecialMembersBeingDeclared.erase(D);
10892       S.popCodeSynthesisContext();
10893     }
10894   }
10895 
10896   /// Are we already trying to declare this special member?
10897   bool isAlreadyBeingDeclared() const {
10898     return WasAlreadyBeingDeclared;
10899   }
10900 };
10901 }
10902 
10903 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10904   // Look up any existing declarations, but don't trigger declaration of all
10905   // implicit special members with this name.
10906   DeclarationName Name = FD->getDeclName();
10907   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10908                  ForExternalRedeclaration);
10909   for (auto *D : FD->getParent()->lookup(Name))
10910     if (auto *Acceptable = R.getAcceptableDecl(D))
10911       R.addDecl(Acceptable);
10912   R.resolveKind();
10913   R.suppressDiagnostics();
10914 
10915   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10916 }
10917 
10918 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10919                                                      CXXRecordDecl *ClassDecl) {
10920   // C++ [class.ctor]p5:
10921   //   A default constructor for a class X is a constructor of class X
10922   //   that can be called without an argument. If there is no
10923   //   user-declared constructor for class X, a default constructor is
10924   //   implicitly declared. An implicitly-declared default constructor
10925   //   is an inline public member of its class.
10926   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10927          "Should not build implicit default constructor!");
10928 
10929   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10930   if (DSM.isAlreadyBeingDeclared())
10931     return nullptr;
10932 
10933   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10934                                                      CXXDefaultConstructor,
10935                                                      false);
10936 
10937   // Create the actual constructor declaration.
10938   CanQualType ClassType
10939     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10940   SourceLocation ClassLoc = ClassDecl->getLocation();
10941   DeclarationName Name
10942     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10943   DeclarationNameInfo NameInfo(Name, ClassLoc);
10944   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10945       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10946       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10947       /*isImplicitlyDeclared=*/true, Constexpr);
10948   DefaultCon->setAccess(AS_public);
10949   DefaultCon->setDefaulted();
10950 
10951   if (getLangOpts().CUDA) {
10952     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10953                                             DefaultCon,
10954                                             /* ConstRHS */ false,
10955                                             /* Diagnose */ false);
10956   }
10957 
10958   // Build an exception specification pointing back at this constructor.
10959   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10960   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10961 
10962   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10963   // constructors is easy to compute.
10964   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10965 
10966   // Note that we have declared this constructor.
10967   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10968 
10969   Scope *S = getScopeForContext(ClassDecl);
10970   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10971 
10972   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10973     SetDeclDeleted(DefaultCon, ClassLoc);
10974 
10975   if (S)
10976     PushOnScopeChains(DefaultCon, S, false);
10977   ClassDecl->addDecl(DefaultCon);
10978 
10979   return DefaultCon;
10980 }
10981 
10982 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10983                                             CXXConstructorDecl *Constructor) {
10984   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10985           !Constructor->doesThisDeclarationHaveABody() &&
10986           !Constructor->isDeleted()) &&
10987     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10988   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10989     return;
10990 
10991   CXXRecordDecl *ClassDecl = Constructor->getParent();
10992   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10993 
10994   SynthesizedFunctionScope Scope(*this, Constructor);
10995 
10996   // The exception specification is needed because we are defining the
10997   // function.
10998   ResolveExceptionSpec(CurrentLocation,
10999                        Constructor->getType()->castAs<FunctionProtoType>());
11000   MarkVTableUsed(CurrentLocation, ClassDecl);
11001 
11002   // Add a context note for diagnostics produced after this point.
11003   Scope.addContextNote(CurrentLocation);
11004 
11005   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11006     Constructor->setInvalidDecl();
11007     return;
11008   }
11009 
11010   SourceLocation Loc = Constructor->getEndLoc().isValid()
11011                            ? Constructor->getEndLoc()
11012                            : Constructor->getLocation();
11013   Constructor->setBody(new (Context) CompoundStmt(Loc));
11014   Constructor->markUsed(Context);
11015 
11016   if (ASTMutationListener *L = getASTMutationListener()) {
11017     L->CompletedImplicitDefinition(Constructor);
11018   }
11019 
11020   DiagnoseUninitializedFields(*this, Constructor);
11021 }
11022 
11023 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11024   // Perform any delayed checks on exception specifications.
11025   CheckDelayedMemberExceptionSpecs();
11026 }
11027 
11028 /// Find or create the fake constructor we synthesize to model constructing an
11029 /// object of a derived class via a constructor of a base class.
11030 CXXConstructorDecl *
11031 Sema::findInheritingConstructor(SourceLocation Loc,
11032                                 CXXConstructorDecl *BaseCtor,
11033                                 ConstructorUsingShadowDecl *Shadow) {
11034   CXXRecordDecl *Derived = Shadow->getParent();
11035   SourceLocation UsingLoc = Shadow->getLocation();
11036 
11037   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11038   // For now we use the name of the base class constructor as a member of the
11039   // derived class to indicate a (fake) inherited constructor name.
11040   DeclarationName Name = BaseCtor->getDeclName();
11041 
11042   // Check to see if we already have a fake constructor for this inherited
11043   // constructor call.
11044   for (NamedDecl *Ctor : Derived->lookup(Name))
11045     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11046                                ->getInheritedConstructor()
11047                                .getConstructor(),
11048                            BaseCtor))
11049       return cast<CXXConstructorDecl>(Ctor);
11050 
11051   DeclarationNameInfo NameInfo(Name, UsingLoc);
11052   TypeSourceInfo *TInfo =
11053       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11054   FunctionProtoTypeLoc ProtoLoc =
11055       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11056 
11057   // Check the inherited constructor is valid and find the list of base classes
11058   // from which it was inherited.
11059   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11060 
11061   bool Constexpr =
11062       BaseCtor->isConstexpr() &&
11063       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11064                                         false, BaseCtor, &ICI);
11065 
11066   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11067       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11068       BaseCtor->isExplicit(), /*Inline=*/true,
11069       /*ImplicitlyDeclared=*/true, Constexpr,
11070       InheritedConstructor(Shadow, BaseCtor));
11071   if (Shadow->isInvalidDecl())
11072     DerivedCtor->setInvalidDecl();
11073 
11074   // Build an unevaluated exception specification for this fake constructor.
11075   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11076   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11077   EPI.ExceptionSpec.Type = EST_Unevaluated;
11078   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11079   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11080                                                FPT->getParamTypes(), EPI));
11081 
11082   // Build the parameter declarations.
11083   SmallVector<ParmVarDecl *, 16> ParamDecls;
11084   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11085     TypeSourceInfo *TInfo =
11086         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11087     ParmVarDecl *PD = ParmVarDecl::Create(
11088         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11089         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11090     PD->setScopeInfo(0, I);
11091     PD->setImplicit();
11092     // Ensure attributes are propagated onto parameters (this matters for
11093     // format, pass_object_size, ...).
11094     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11095     ParamDecls.push_back(PD);
11096     ProtoLoc.setParam(I, PD);
11097   }
11098 
11099   // Set up the new constructor.
11100   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11101   DerivedCtor->setAccess(BaseCtor->getAccess());
11102   DerivedCtor->setParams(ParamDecls);
11103   Derived->addDecl(DerivedCtor);
11104 
11105   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11106     SetDeclDeleted(DerivedCtor, UsingLoc);
11107 
11108   return DerivedCtor;
11109 }
11110 
11111 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11112   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11113                                Ctor->getInheritedConstructor().getShadowDecl());
11114   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11115                             /*Diagnose*/true);
11116 }
11117 
11118 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11119                                        CXXConstructorDecl *Constructor) {
11120   CXXRecordDecl *ClassDecl = Constructor->getParent();
11121   assert(Constructor->getInheritedConstructor() &&
11122          !Constructor->doesThisDeclarationHaveABody() &&
11123          !Constructor->isDeleted());
11124   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11125     return;
11126 
11127   // Initializations are performed "as if by a defaulted default constructor",
11128   // so enter the appropriate scope.
11129   SynthesizedFunctionScope Scope(*this, Constructor);
11130 
11131   // The exception specification is needed because we are defining the
11132   // function.
11133   ResolveExceptionSpec(CurrentLocation,
11134                        Constructor->getType()->castAs<FunctionProtoType>());
11135   MarkVTableUsed(CurrentLocation, ClassDecl);
11136 
11137   // Add a context note for diagnostics produced after this point.
11138   Scope.addContextNote(CurrentLocation);
11139 
11140   ConstructorUsingShadowDecl *Shadow =
11141       Constructor->getInheritedConstructor().getShadowDecl();
11142   CXXConstructorDecl *InheritedCtor =
11143       Constructor->getInheritedConstructor().getConstructor();
11144 
11145   // [class.inhctor.init]p1:
11146   //   initialization proceeds as if a defaulted default constructor is used to
11147   //   initialize the D object and each base class subobject from which the
11148   //   constructor was inherited
11149 
11150   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11151   CXXRecordDecl *RD = Shadow->getParent();
11152   SourceLocation InitLoc = Shadow->getLocation();
11153 
11154   // Build explicit initializers for all base classes from which the
11155   // constructor was inherited.
11156   SmallVector<CXXCtorInitializer*, 8> Inits;
11157   for (bool VBase : {false, true}) {
11158     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11159       if (B.isVirtual() != VBase)
11160         continue;
11161 
11162       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11163       if (!BaseRD)
11164         continue;
11165 
11166       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11167       if (!BaseCtor.first)
11168         continue;
11169 
11170       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11171       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11172           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11173 
11174       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11175       Inits.push_back(new (Context) CXXCtorInitializer(
11176           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11177           SourceLocation()));
11178     }
11179   }
11180 
11181   // We now proceed as if for a defaulted default constructor, with the relevant
11182   // initializers replaced.
11183 
11184   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11185     Constructor->setInvalidDecl();
11186     return;
11187   }
11188 
11189   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11190   Constructor->markUsed(Context);
11191 
11192   if (ASTMutationListener *L = getASTMutationListener()) {
11193     L->CompletedImplicitDefinition(Constructor);
11194   }
11195 
11196   DiagnoseUninitializedFields(*this, Constructor);
11197 }
11198 
11199 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11200   // C++ [class.dtor]p2:
11201   //   If a class has no user-declared destructor, a destructor is
11202   //   declared implicitly. An implicitly-declared destructor is an
11203   //   inline public member of its class.
11204   assert(ClassDecl->needsImplicitDestructor());
11205 
11206   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11207   if (DSM.isAlreadyBeingDeclared())
11208     return nullptr;
11209 
11210   // Create the actual destructor declaration.
11211   CanQualType ClassType
11212     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11213   SourceLocation ClassLoc = ClassDecl->getLocation();
11214   DeclarationName Name
11215     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11216   DeclarationNameInfo NameInfo(Name, ClassLoc);
11217   CXXDestructorDecl *Destructor
11218       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11219                                   QualType(), nullptr, /*isInline=*/true,
11220                                   /*isImplicitlyDeclared=*/true);
11221   Destructor->setAccess(AS_public);
11222   Destructor->setDefaulted();
11223 
11224   if (getLangOpts().CUDA) {
11225     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11226                                             Destructor,
11227                                             /* ConstRHS */ false,
11228                                             /* Diagnose */ false);
11229   }
11230 
11231   // Build an exception specification pointing back at this destructor.
11232   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11233   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11234 
11235   // We don't need to use SpecialMemberIsTrivial here; triviality for
11236   // destructors is easy to compute.
11237   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11238   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11239                                 ClassDecl->hasTrivialDestructorForCall());
11240 
11241   // Note that we have declared this destructor.
11242   ++ASTContext::NumImplicitDestructorsDeclared;
11243 
11244   Scope *S = getScopeForContext(ClassDecl);
11245   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11246 
11247   // We can't check whether an implicit destructor is deleted before we complete
11248   // the definition of the class, because its validity depends on the alignment
11249   // of the class. We'll check this from ActOnFields once the class is complete.
11250   if (ClassDecl->isCompleteDefinition() &&
11251       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11252     SetDeclDeleted(Destructor, ClassLoc);
11253 
11254   // Introduce this destructor into its scope.
11255   if (S)
11256     PushOnScopeChains(Destructor, S, false);
11257   ClassDecl->addDecl(Destructor);
11258 
11259   return Destructor;
11260 }
11261 
11262 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11263                                     CXXDestructorDecl *Destructor) {
11264   assert((Destructor->isDefaulted() &&
11265           !Destructor->doesThisDeclarationHaveABody() &&
11266           !Destructor->isDeleted()) &&
11267          "DefineImplicitDestructor - call it for implicit default dtor");
11268   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11269     return;
11270 
11271   CXXRecordDecl *ClassDecl = Destructor->getParent();
11272   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11273 
11274   SynthesizedFunctionScope Scope(*this, Destructor);
11275 
11276   // The exception specification is needed because we are defining the
11277   // function.
11278   ResolveExceptionSpec(CurrentLocation,
11279                        Destructor->getType()->castAs<FunctionProtoType>());
11280   MarkVTableUsed(CurrentLocation, ClassDecl);
11281 
11282   // Add a context note for diagnostics produced after this point.
11283   Scope.addContextNote(CurrentLocation);
11284 
11285   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11286                                          Destructor->getParent());
11287 
11288   if (CheckDestructor(Destructor)) {
11289     Destructor->setInvalidDecl();
11290     return;
11291   }
11292 
11293   SourceLocation Loc = Destructor->getEndLoc().isValid()
11294                            ? Destructor->getEndLoc()
11295                            : Destructor->getLocation();
11296   Destructor->setBody(new (Context) CompoundStmt(Loc));
11297   Destructor->markUsed(Context);
11298 
11299   if (ASTMutationListener *L = getASTMutationListener()) {
11300     L->CompletedImplicitDefinition(Destructor);
11301   }
11302 }
11303 
11304 /// Perform any semantic analysis which needs to be delayed until all
11305 /// pending class member declarations have been parsed.
11306 void Sema::ActOnFinishCXXMemberDecls() {
11307   // If the context is an invalid C++ class, just suppress these checks.
11308   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11309     if (Record->isInvalidDecl()) {
11310       DelayedOverridingExceptionSpecChecks.clear();
11311       DelayedEquivalentExceptionSpecChecks.clear();
11312       DelayedDefaultedMemberExceptionSpecs.clear();
11313       return;
11314     }
11315     checkForMultipleExportedDefaultConstructors(*this, Record);
11316   }
11317 }
11318 
11319 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11320   referenceDLLExportedClassMethods();
11321 }
11322 
11323 void Sema::referenceDLLExportedClassMethods() {
11324   if (!DelayedDllExportClasses.empty()) {
11325     // Calling ReferenceDllExportedMembers might cause the current function to
11326     // be called again, so use a local copy of DelayedDllExportClasses.
11327     SmallVector<CXXRecordDecl *, 4> WorkList;
11328     std::swap(DelayedDllExportClasses, WorkList);
11329     for (CXXRecordDecl *Class : WorkList)
11330       ReferenceDllExportedMembers(*this, Class);
11331   }
11332 }
11333 
11334 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11335   assert(getLangOpts().CPlusPlus11 &&
11336          "adjusting dtor exception specs was introduced in c++11");
11337 
11338   if (Destructor->isDependentContext())
11339     return;
11340 
11341   // C++11 [class.dtor]p3:
11342   //   A declaration of a destructor that does not have an exception-
11343   //   specification is implicitly considered to have the same exception-
11344   //   specification as an implicit declaration.
11345   const FunctionProtoType *DtorType = Destructor->getType()->
11346                                         getAs<FunctionProtoType>();
11347   if (DtorType->hasExceptionSpec())
11348     return;
11349 
11350   // Replace the destructor's type, building off the existing one. Fortunately,
11351   // the only thing of interest in the destructor type is its extended info.
11352   // The return and arguments are fixed.
11353   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11354   EPI.ExceptionSpec.Type = EST_Unevaluated;
11355   EPI.ExceptionSpec.SourceDecl = Destructor;
11356   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11357 
11358   // FIXME: If the destructor has a body that could throw, and the newly created
11359   // spec doesn't allow exceptions, we should emit a warning, because this
11360   // change in behavior can break conforming C++03 programs at runtime.
11361   // However, we don't have a body or an exception specification yet, so it
11362   // needs to be done somewhere else.
11363 }
11364 
11365 namespace {
11366 /// An abstract base class for all helper classes used in building the
11367 //  copy/move operators. These classes serve as factory functions and help us
11368 //  avoid using the same Expr* in the AST twice.
11369 class ExprBuilder {
11370   ExprBuilder(const ExprBuilder&) = delete;
11371   ExprBuilder &operator=(const ExprBuilder&) = delete;
11372 
11373 protected:
11374   static Expr *assertNotNull(Expr *E) {
11375     assert(E && "Expression construction must not fail.");
11376     return E;
11377   }
11378 
11379 public:
11380   ExprBuilder() {}
11381   virtual ~ExprBuilder() {}
11382 
11383   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11384 };
11385 
11386 class RefBuilder: public ExprBuilder {
11387   VarDecl *Var;
11388   QualType VarType;
11389 
11390 public:
11391   Expr *build(Sema &S, SourceLocation Loc) const override {
11392     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11393   }
11394 
11395   RefBuilder(VarDecl *Var, QualType VarType)
11396       : Var(Var), VarType(VarType) {}
11397 };
11398 
11399 class ThisBuilder: public ExprBuilder {
11400 public:
11401   Expr *build(Sema &S, SourceLocation Loc) const override {
11402     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11403   }
11404 };
11405 
11406 class CastBuilder: public ExprBuilder {
11407   const ExprBuilder &Builder;
11408   QualType Type;
11409   ExprValueKind Kind;
11410   const CXXCastPath &Path;
11411 
11412 public:
11413   Expr *build(Sema &S, SourceLocation Loc) const override {
11414     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11415                                              CK_UncheckedDerivedToBase, Kind,
11416                                              &Path).get());
11417   }
11418 
11419   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11420               const CXXCastPath &Path)
11421       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11422 };
11423 
11424 class DerefBuilder: public ExprBuilder {
11425   const ExprBuilder &Builder;
11426 
11427 public:
11428   Expr *build(Sema &S, SourceLocation Loc) const override {
11429     return assertNotNull(
11430         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11431   }
11432 
11433   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11434 };
11435 
11436 class MemberBuilder: public ExprBuilder {
11437   const ExprBuilder &Builder;
11438   QualType Type;
11439   CXXScopeSpec SS;
11440   bool IsArrow;
11441   LookupResult &MemberLookup;
11442 
11443 public:
11444   Expr *build(Sema &S, SourceLocation Loc) const override {
11445     return assertNotNull(S.BuildMemberReferenceExpr(
11446         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11447         nullptr, MemberLookup, nullptr, nullptr).get());
11448   }
11449 
11450   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11451                 LookupResult &MemberLookup)
11452       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11453         MemberLookup(MemberLookup) {}
11454 };
11455 
11456 class MoveCastBuilder: public ExprBuilder {
11457   const ExprBuilder &Builder;
11458 
11459 public:
11460   Expr *build(Sema &S, SourceLocation Loc) const override {
11461     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11462   }
11463 
11464   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11465 };
11466 
11467 class LvalueConvBuilder: public ExprBuilder {
11468   const ExprBuilder &Builder;
11469 
11470 public:
11471   Expr *build(Sema &S, SourceLocation Loc) const override {
11472     return assertNotNull(
11473         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11474   }
11475 
11476   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11477 };
11478 
11479 class SubscriptBuilder: public ExprBuilder {
11480   const ExprBuilder &Base;
11481   const ExprBuilder &Index;
11482 
11483 public:
11484   Expr *build(Sema &S, SourceLocation Loc) const override {
11485     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11486         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11487   }
11488 
11489   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11490       : Base(Base), Index(Index) {}
11491 };
11492 
11493 } // end anonymous namespace
11494 
11495 /// When generating a defaulted copy or move assignment operator, if a field
11496 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11497 /// do so. This optimization only applies for arrays of scalars, and for arrays
11498 /// of class type where the selected copy/move-assignment operator is trivial.
11499 static StmtResult
11500 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11501                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11502   // Compute the size of the memory buffer to be copied.
11503   QualType SizeType = S.Context.getSizeType();
11504   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11505                    S.Context.getTypeSizeInChars(T).getQuantity());
11506 
11507   // Take the address of the field references for "from" and "to". We
11508   // directly construct UnaryOperators here because semantic analysis
11509   // does not permit us to take the address of an xvalue.
11510   Expr *From = FromB.build(S, Loc);
11511   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11512                          S.Context.getPointerType(From->getType()),
11513                          VK_RValue, OK_Ordinary, Loc, false);
11514   Expr *To = ToB.build(S, Loc);
11515   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11516                        S.Context.getPointerType(To->getType()),
11517                        VK_RValue, OK_Ordinary, Loc, false);
11518 
11519   const Type *E = T->getBaseElementTypeUnsafe();
11520   bool NeedsCollectableMemCpy =
11521     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11522 
11523   // Create a reference to the __builtin_objc_memmove_collectable function
11524   StringRef MemCpyName = NeedsCollectableMemCpy ?
11525     "__builtin_objc_memmove_collectable" :
11526     "__builtin_memcpy";
11527   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11528                  Sema::LookupOrdinaryName);
11529   S.LookupName(R, S.TUScope, true);
11530 
11531   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11532   if (!MemCpy)
11533     // Something went horribly wrong earlier, and we will have complained
11534     // about it.
11535     return StmtError();
11536 
11537   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11538                                             VK_RValue, Loc, nullptr);
11539   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11540 
11541   Expr *CallArgs[] = {
11542     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11543   };
11544   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11545                                     Loc, CallArgs, Loc);
11546 
11547   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11548   return Call.getAs<Stmt>();
11549 }
11550 
11551 /// Builds a statement that copies/moves the given entity from \p From to
11552 /// \c To.
11553 ///
11554 /// This routine is used to copy/move the members of a class with an
11555 /// implicitly-declared copy/move assignment operator. When the entities being
11556 /// copied are arrays, this routine builds for loops to copy them.
11557 ///
11558 /// \param S The Sema object used for type-checking.
11559 ///
11560 /// \param Loc The location where the implicit copy/move is being generated.
11561 ///
11562 /// \param T The type of the expressions being copied/moved. Both expressions
11563 /// must have this type.
11564 ///
11565 /// \param To The expression we are copying/moving to.
11566 ///
11567 /// \param From The expression we are copying/moving from.
11568 ///
11569 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11570 /// Otherwise, it's a non-static member subobject.
11571 ///
11572 /// \param Copying Whether we're copying or moving.
11573 ///
11574 /// \param Depth Internal parameter recording the depth of the recursion.
11575 ///
11576 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11577 /// if a memcpy should be used instead.
11578 static StmtResult
11579 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11580                                  const ExprBuilder &To, const ExprBuilder &From,
11581                                  bool CopyingBaseSubobject, bool Copying,
11582                                  unsigned Depth = 0) {
11583   // C++11 [class.copy]p28:
11584   //   Each subobject is assigned in the manner appropriate to its type:
11585   //
11586   //     - if the subobject is of class type, as if by a call to operator= with
11587   //       the subobject as the object expression and the corresponding
11588   //       subobject of x as a single function argument (as if by explicit
11589   //       qualification; that is, ignoring any possible virtual overriding
11590   //       functions in more derived classes);
11591   //
11592   // C++03 [class.copy]p13:
11593   //     - if the subobject is of class type, the copy assignment operator for
11594   //       the class is used (as if by explicit qualification; that is,
11595   //       ignoring any possible virtual overriding functions in more derived
11596   //       classes);
11597   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11598     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11599 
11600     // Look for operator=.
11601     DeclarationName Name
11602       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11603     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11604     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11605 
11606     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11607     // operator.
11608     if (!S.getLangOpts().CPlusPlus11) {
11609       LookupResult::Filter F = OpLookup.makeFilter();
11610       while (F.hasNext()) {
11611         NamedDecl *D = F.next();
11612         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11613           if (Method->isCopyAssignmentOperator() ||
11614               (!Copying && Method->isMoveAssignmentOperator()))
11615             continue;
11616 
11617         F.erase();
11618       }
11619       F.done();
11620     }
11621 
11622     // Suppress the protected check (C++ [class.protected]) for each of the
11623     // assignment operators we found. This strange dance is required when
11624     // we're assigning via a base classes's copy-assignment operator. To
11625     // ensure that we're getting the right base class subobject (without
11626     // ambiguities), we need to cast "this" to that subobject type; to
11627     // ensure that we don't go through the virtual call mechanism, we need
11628     // to qualify the operator= name with the base class (see below). However,
11629     // this means that if the base class has a protected copy assignment
11630     // operator, the protected member access check will fail. So, we
11631     // rewrite "protected" access to "public" access in this case, since we
11632     // know by construction that we're calling from a derived class.
11633     if (CopyingBaseSubobject) {
11634       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11635            L != LEnd; ++L) {
11636         if (L.getAccess() == AS_protected)
11637           L.setAccess(AS_public);
11638       }
11639     }
11640 
11641     // Create the nested-name-specifier that will be used to qualify the
11642     // reference to operator=; this is required to suppress the virtual
11643     // call mechanism.
11644     CXXScopeSpec SS;
11645     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11646     SS.MakeTrivial(S.Context,
11647                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11648                                                CanonicalT),
11649                    Loc);
11650 
11651     // Create the reference to operator=.
11652     ExprResult OpEqualRef
11653       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11654                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11655                                    /*FirstQualifierInScope=*/nullptr,
11656                                    OpLookup,
11657                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11658                                    /*SuppressQualifierCheck=*/true);
11659     if (OpEqualRef.isInvalid())
11660       return StmtError();
11661 
11662     // Build the call to the assignment operator.
11663 
11664     Expr *FromInst = From.build(S, Loc);
11665     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11666                                                   OpEqualRef.getAs<Expr>(),
11667                                                   Loc, FromInst, Loc);
11668     if (Call.isInvalid())
11669       return StmtError();
11670 
11671     // If we built a call to a trivial 'operator=' while copying an array,
11672     // bail out. We'll replace the whole shebang with a memcpy.
11673     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11674     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11675       return StmtResult((Stmt*)nullptr);
11676 
11677     // Convert to an expression-statement, and clean up any produced
11678     // temporaries.
11679     return S.ActOnExprStmt(Call);
11680   }
11681 
11682   //     - if the subobject is of scalar type, the built-in assignment
11683   //       operator is used.
11684   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11685   if (!ArrayTy) {
11686     ExprResult Assignment = S.CreateBuiltinBinOp(
11687         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11688     if (Assignment.isInvalid())
11689       return StmtError();
11690     return S.ActOnExprStmt(Assignment);
11691   }
11692 
11693   //     - if the subobject is an array, each element is assigned, in the
11694   //       manner appropriate to the element type;
11695 
11696   // Construct a loop over the array bounds, e.g.,
11697   //
11698   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11699   //
11700   // that will copy each of the array elements.
11701   QualType SizeType = S.Context.getSizeType();
11702 
11703   // Create the iteration variable.
11704   IdentifierInfo *IterationVarName = nullptr;
11705   {
11706     SmallString<8> Str;
11707     llvm::raw_svector_ostream OS(Str);
11708     OS << "__i" << Depth;
11709     IterationVarName = &S.Context.Idents.get(OS.str());
11710   }
11711   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11712                                           IterationVarName, SizeType,
11713                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11714                                           SC_None);
11715 
11716   // Initialize the iteration variable to zero.
11717   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11718   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11719 
11720   // Creates a reference to the iteration variable.
11721   RefBuilder IterationVarRef(IterationVar, SizeType);
11722   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11723 
11724   // Create the DeclStmt that holds the iteration variable.
11725   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11726 
11727   // Subscript the "from" and "to" expressions with the iteration variable.
11728   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11729   MoveCastBuilder FromIndexMove(FromIndexCopy);
11730   const ExprBuilder *FromIndex;
11731   if (Copying)
11732     FromIndex = &FromIndexCopy;
11733   else
11734     FromIndex = &FromIndexMove;
11735 
11736   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11737 
11738   // Build the copy/move for an individual element of the array.
11739   StmtResult Copy =
11740     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11741                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11742                                      Copying, Depth + 1);
11743   // Bail out if copying fails or if we determined that we should use memcpy.
11744   if (Copy.isInvalid() || !Copy.get())
11745     return Copy;
11746 
11747   // Create the comparison against the array bound.
11748   llvm::APInt Upper
11749     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11750   Expr *Comparison
11751     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11752                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11753                                      BO_NE, S.Context.BoolTy,
11754                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11755 
11756   // Create the pre-increment of the iteration variable. We can determine
11757   // whether the increment will overflow based on the value of the array
11758   // bound.
11759   Expr *Increment = new (S.Context)
11760       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11761                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11762 
11763   // Construct the loop that copies all elements of this array.
11764   return S.ActOnForStmt(
11765       Loc, Loc, InitStmt,
11766       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11767       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11768 }
11769 
11770 static StmtResult
11771 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11772                       const ExprBuilder &To, const ExprBuilder &From,
11773                       bool CopyingBaseSubobject, bool Copying) {
11774   // Maybe we should use a memcpy?
11775   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11776       T.isTriviallyCopyableType(S.Context))
11777     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11778 
11779   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11780                                                      CopyingBaseSubobject,
11781                                                      Copying, 0));
11782 
11783   // If we ended up picking a trivial assignment operator for an array of a
11784   // non-trivially-copyable class type, just emit a memcpy.
11785   if (!Result.isInvalid() && !Result.get())
11786     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11787 
11788   return Result;
11789 }
11790 
11791 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11792   // Note: The following rules are largely analoguous to the copy
11793   // constructor rules. Note that virtual bases are not taken into account
11794   // for determining the argument type of the operator. Note also that
11795   // operators taking an object instead of a reference are allowed.
11796   assert(ClassDecl->needsImplicitCopyAssignment());
11797 
11798   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11799   if (DSM.isAlreadyBeingDeclared())
11800     return nullptr;
11801 
11802   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11803   QualType RetType = Context.getLValueReferenceType(ArgType);
11804   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11805   if (Const)
11806     ArgType = ArgType.withConst();
11807   ArgType = Context.getLValueReferenceType(ArgType);
11808 
11809   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11810                                                      CXXCopyAssignment,
11811                                                      Const);
11812 
11813   //   An implicitly-declared copy assignment operator is an inline public
11814   //   member of its class.
11815   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11816   SourceLocation ClassLoc = ClassDecl->getLocation();
11817   DeclarationNameInfo NameInfo(Name, ClassLoc);
11818   CXXMethodDecl *CopyAssignment =
11819       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11820                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11821                             /*isInline=*/true, Constexpr, SourceLocation());
11822   CopyAssignment->setAccess(AS_public);
11823   CopyAssignment->setDefaulted();
11824   CopyAssignment->setImplicit();
11825 
11826   if (getLangOpts().CUDA) {
11827     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11828                                             CopyAssignment,
11829                                             /* ConstRHS */ Const,
11830                                             /* Diagnose */ false);
11831   }
11832 
11833   // Build an exception specification pointing back at this member.
11834   FunctionProtoType::ExtProtoInfo EPI =
11835       getImplicitMethodEPI(*this, CopyAssignment);
11836   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11837 
11838   // Add the parameter to the operator.
11839   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11840                                                ClassLoc, ClassLoc,
11841                                                /*Id=*/nullptr, ArgType,
11842                                                /*TInfo=*/nullptr, SC_None,
11843                                                nullptr);
11844   CopyAssignment->setParams(FromParam);
11845 
11846   CopyAssignment->setTrivial(
11847     ClassDecl->needsOverloadResolutionForCopyAssignment()
11848       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11849       : ClassDecl->hasTrivialCopyAssignment());
11850 
11851   // Note that we have added this copy-assignment operator.
11852   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11853 
11854   Scope *S = getScopeForContext(ClassDecl);
11855   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11856 
11857   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11858     SetDeclDeleted(CopyAssignment, ClassLoc);
11859 
11860   if (S)
11861     PushOnScopeChains(CopyAssignment, S, false);
11862   ClassDecl->addDecl(CopyAssignment);
11863 
11864   return CopyAssignment;
11865 }
11866 
11867 /// Diagnose an implicit copy operation for a class which is odr-used, but
11868 /// which is deprecated because the class has a user-declared copy constructor,
11869 /// copy assignment operator, or destructor.
11870 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11871   assert(CopyOp->isImplicit());
11872 
11873   CXXRecordDecl *RD = CopyOp->getParent();
11874   CXXMethodDecl *UserDeclaredOperation = nullptr;
11875 
11876   // In Microsoft mode, assignment operations don't affect constructors and
11877   // vice versa.
11878   if (RD->hasUserDeclaredDestructor()) {
11879     UserDeclaredOperation = RD->getDestructor();
11880   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11881              RD->hasUserDeclaredCopyConstructor() &&
11882              !S.getLangOpts().MSVCCompat) {
11883     // Find any user-declared copy constructor.
11884     for (auto *I : RD->ctors()) {
11885       if (I->isCopyConstructor()) {
11886         UserDeclaredOperation = I;
11887         break;
11888       }
11889     }
11890     assert(UserDeclaredOperation);
11891   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11892              RD->hasUserDeclaredCopyAssignment() &&
11893              !S.getLangOpts().MSVCCompat) {
11894     // Find any user-declared move assignment operator.
11895     for (auto *I : RD->methods()) {
11896       if (I->isCopyAssignmentOperator()) {
11897         UserDeclaredOperation = I;
11898         break;
11899       }
11900     }
11901     assert(UserDeclaredOperation);
11902   }
11903 
11904   if (UserDeclaredOperation) {
11905     S.Diag(UserDeclaredOperation->getLocation(),
11906          diag::warn_deprecated_copy_operation)
11907       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11908       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11909   }
11910 }
11911 
11912 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11913                                         CXXMethodDecl *CopyAssignOperator) {
11914   assert((CopyAssignOperator->isDefaulted() &&
11915           CopyAssignOperator->isOverloadedOperator() &&
11916           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11917           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11918           !CopyAssignOperator->isDeleted()) &&
11919          "DefineImplicitCopyAssignment called for wrong function");
11920   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11921     return;
11922 
11923   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11924   if (ClassDecl->isInvalidDecl()) {
11925     CopyAssignOperator->setInvalidDecl();
11926     return;
11927   }
11928 
11929   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11930 
11931   // The exception specification is needed because we are defining the
11932   // function.
11933   ResolveExceptionSpec(CurrentLocation,
11934                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11935 
11936   // Add a context note for diagnostics produced after this point.
11937   Scope.addContextNote(CurrentLocation);
11938 
11939   // C++11 [class.copy]p18:
11940   //   The [definition of an implicitly declared copy assignment operator] is
11941   //   deprecated if the class has a user-declared copy constructor or a
11942   //   user-declared destructor.
11943   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11944     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11945 
11946   // C++0x [class.copy]p30:
11947   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11948   //   for a non-union class X performs memberwise copy assignment of its
11949   //   subobjects. The direct base classes of X are assigned first, in the
11950   //   order of their declaration in the base-specifier-list, and then the
11951   //   immediate non-static data members of X are assigned, in the order in
11952   //   which they were declared in the class definition.
11953 
11954   // The statements that form the synthesized function body.
11955   SmallVector<Stmt*, 8> Statements;
11956 
11957   // The parameter for the "other" object, which we are copying from.
11958   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11959   Qualifiers OtherQuals = Other->getType().getQualifiers();
11960   QualType OtherRefType = Other->getType();
11961   if (const LValueReferenceType *OtherRef
11962                                 = OtherRefType->getAs<LValueReferenceType>()) {
11963     OtherRefType = OtherRef->getPointeeType();
11964     OtherQuals = OtherRefType.getQualifiers();
11965   }
11966 
11967   // Our location for everything implicitly-generated.
11968   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11969                            ? CopyAssignOperator->getEndLoc()
11970                            : CopyAssignOperator->getLocation();
11971 
11972   // Builds a DeclRefExpr for the "other" object.
11973   RefBuilder OtherRef(Other, OtherRefType);
11974 
11975   // Builds the "this" pointer.
11976   ThisBuilder This;
11977 
11978   // Assign base classes.
11979   bool Invalid = false;
11980   for (auto &Base : ClassDecl->bases()) {
11981     // Form the assignment:
11982     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11983     QualType BaseType = Base.getType().getUnqualifiedType();
11984     if (!BaseType->isRecordType()) {
11985       Invalid = true;
11986       continue;
11987     }
11988 
11989     CXXCastPath BasePath;
11990     BasePath.push_back(&Base);
11991 
11992     // Construct the "from" expression, which is an implicit cast to the
11993     // appropriately-qualified base type.
11994     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11995                      VK_LValue, BasePath);
11996 
11997     // Dereference "this".
11998     DerefBuilder DerefThis(This);
11999     CastBuilder To(DerefThis,
12000                    Context.getQualifiedType(
12001                        BaseType, CopyAssignOperator->getTypeQualifiers()),
12002                    VK_LValue, BasePath);
12003 
12004     // Build the copy.
12005     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12006                                             To, From,
12007                                             /*CopyingBaseSubobject=*/true,
12008                                             /*Copying=*/true);
12009     if (Copy.isInvalid()) {
12010       CopyAssignOperator->setInvalidDecl();
12011       return;
12012     }
12013 
12014     // Success! Record the copy.
12015     Statements.push_back(Copy.getAs<Expr>());
12016   }
12017 
12018   // Assign non-static members.
12019   for (auto *Field : ClassDecl->fields()) {
12020     // FIXME: We should form some kind of AST representation for the implied
12021     // memcpy in a union copy operation.
12022     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12023       continue;
12024 
12025     if (Field->isInvalidDecl()) {
12026       Invalid = true;
12027       continue;
12028     }
12029 
12030     // Check for members of reference type; we can't copy those.
12031     if (Field->getType()->isReferenceType()) {
12032       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12033         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12034       Diag(Field->getLocation(), diag::note_declared_at);
12035       Invalid = true;
12036       continue;
12037     }
12038 
12039     // Check for members of const-qualified, non-class type.
12040     QualType BaseType = Context.getBaseElementType(Field->getType());
12041     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12042       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12043         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12044       Diag(Field->getLocation(), diag::note_declared_at);
12045       Invalid = true;
12046       continue;
12047     }
12048 
12049     // Suppress assigning zero-width bitfields.
12050     if (Field->isZeroLengthBitField(Context))
12051       continue;
12052 
12053     QualType FieldType = Field->getType().getNonReferenceType();
12054     if (FieldType->isIncompleteArrayType()) {
12055       assert(ClassDecl->hasFlexibleArrayMember() &&
12056              "Incomplete array type is not valid");
12057       continue;
12058     }
12059 
12060     // Build references to the field in the object we're copying from and to.
12061     CXXScopeSpec SS; // Intentionally empty
12062     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12063                               LookupMemberName);
12064     MemberLookup.addDecl(Field);
12065     MemberLookup.resolveKind();
12066 
12067     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12068 
12069     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12070 
12071     // Build the copy of this field.
12072     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12073                                             To, From,
12074                                             /*CopyingBaseSubobject=*/false,
12075                                             /*Copying=*/true);
12076     if (Copy.isInvalid()) {
12077       CopyAssignOperator->setInvalidDecl();
12078       return;
12079     }
12080 
12081     // Success! Record the copy.
12082     Statements.push_back(Copy.getAs<Stmt>());
12083   }
12084 
12085   if (!Invalid) {
12086     // Add a "return *this;"
12087     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12088 
12089     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12090     if (Return.isInvalid())
12091       Invalid = true;
12092     else
12093       Statements.push_back(Return.getAs<Stmt>());
12094   }
12095 
12096   if (Invalid) {
12097     CopyAssignOperator->setInvalidDecl();
12098     return;
12099   }
12100 
12101   StmtResult Body;
12102   {
12103     CompoundScopeRAII CompoundScope(*this);
12104     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12105                              /*isStmtExpr=*/false);
12106     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12107   }
12108   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12109   CopyAssignOperator->markUsed(Context);
12110 
12111   if (ASTMutationListener *L = getASTMutationListener()) {
12112     L->CompletedImplicitDefinition(CopyAssignOperator);
12113   }
12114 }
12115 
12116 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12117   assert(ClassDecl->needsImplicitMoveAssignment());
12118 
12119   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12120   if (DSM.isAlreadyBeingDeclared())
12121     return nullptr;
12122 
12123   // Note: The following rules are largely analoguous to the move
12124   // constructor rules.
12125 
12126   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12127   QualType RetType = Context.getLValueReferenceType(ArgType);
12128   ArgType = Context.getRValueReferenceType(ArgType);
12129 
12130   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12131                                                      CXXMoveAssignment,
12132                                                      false);
12133 
12134   //   An implicitly-declared move assignment operator is an inline public
12135   //   member of its class.
12136   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12137   SourceLocation ClassLoc = ClassDecl->getLocation();
12138   DeclarationNameInfo NameInfo(Name, ClassLoc);
12139   CXXMethodDecl *MoveAssignment =
12140       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12141                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12142                             /*isInline=*/true, Constexpr, SourceLocation());
12143   MoveAssignment->setAccess(AS_public);
12144   MoveAssignment->setDefaulted();
12145   MoveAssignment->setImplicit();
12146 
12147   if (getLangOpts().CUDA) {
12148     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12149                                             MoveAssignment,
12150                                             /* ConstRHS */ false,
12151                                             /* Diagnose */ false);
12152   }
12153 
12154   // Build an exception specification pointing back at this member.
12155   FunctionProtoType::ExtProtoInfo EPI =
12156       getImplicitMethodEPI(*this, MoveAssignment);
12157   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12158 
12159   // Add the parameter to the operator.
12160   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12161                                                ClassLoc, ClassLoc,
12162                                                /*Id=*/nullptr, ArgType,
12163                                                /*TInfo=*/nullptr, SC_None,
12164                                                nullptr);
12165   MoveAssignment->setParams(FromParam);
12166 
12167   MoveAssignment->setTrivial(
12168     ClassDecl->needsOverloadResolutionForMoveAssignment()
12169       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12170       : ClassDecl->hasTrivialMoveAssignment());
12171 
12172   // Note that we have added this copy-assignment operator.
12173   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12174 
12175   Scope *S = getScopeForContext(ClassDecl);
12176   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12177 
12178   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12179     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12180     SetDeclDeleted(MoveAssignment, ClassLoc);
12181   }
12182 
12183   if (S)
12184     PushOnScopeChains(MoveAssignment, S, false);
12185   ClassDecl->addDecl(MoveAssignment);
12186 
12187   return MoveAssignment;
12188 }
12189 
12190 /// Check if we're implicitly defining a move assignment operator for a class
12191 /// with virtual bases. Such a move assignment might move-assign the virtual
12192 /// base multiple times.
12193 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12194                                                SourceLocation CurrentLocation) {
12195   assert(!Class->isDependentContext() && "should not define dependent move");
12196 
12197   // Only a virtual base could get implicitly move-assigned multiple times.
12198   // Only a non-trivial move assignment can observe this. We only want to
12199   // diagnose if we implicitly define an assignment operator that assigns
12200   // two base classes, both of which move-assign the same virtual base.
12201   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12202       Class->getNumBases() < 2)
12203     return;
12204 
12205   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12206   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12207   VBaseMap VBases;
12208 
12209   for (auto &BI : Class->bases()) {
12210     Worklist.push_back(&BI);
12211     while (!Worklist.empty()) {
12212       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12213       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12214 
12215       // If the base has no non-trivial move assignment operators,
12216       // we don't care about moves from it.
12217       if (!Base->hasNonTrivialMoveAssignment())
12218         continue;
12219 
12220       // If there's nothing virtual here, skip it.
12221       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12222         continue;
12223 
12224       // If we're not actually going to call a move assignment for this base,
12225       // or the selected move assignment is trivial, skip it.
12226       Sema::SpecialMemberOverloadResult SMOR =
12227         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12228                               /*ConstArg*/false, /*VolatileArg*/false,
12229                               /*RValueThis*/true, /*ConstThis*/false,
12230                               /*VolatileThis*/false);
12231       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12232           !SMOR.getMethod()->isMoveAssignmentOperator())
12233         continue;
12234 
12235       if (BaseSpec->isVirtual()) {
12236         // We're going to move-assign this virtual base, and its move
12237         // assignment operator is not trivial. If this can happen for
12238         // multiple distinct direct bases of Class, diagnose it. (If it
12239         // only happens in one base, we'll diagnose it when synthesizing
12240         // that base class's move assignment operator.)
12241         CXXBaseSpecifier *&Existing =
12242             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12243                 .first->second;
12244         if (Existing && Existing != &BI) {
12245           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12246             << Class << Base;
12247           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12248               << (Base->getCanonicalDecl() ==
12249                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12250               << Base << Existing->getType() << Existing->getSourceRange();
12251           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12252               << (Base->getCanonicalDecl() ==
12253                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12254               << Base << BI.getType() << BaseSpec->getSourceRange();
12255 
12256           // Only diagnose each vbase once.
12257           Existing = nullptr;
12258         }
12259       } else {
12260         // Only walk over bases that have defaulted move assignment operators.
12261         // We assume that any user-provided move assignment operator handles
12262         // the multiple-moves-of-vbase case itself somehow.
12263         if (!SMOR.getMethod()->isDefaulted())
12264           continue;
12265 
12266         // We're going to move the base classes of Base. Add them to the list.
12267         for (auto &BI : Base->bases())
12268           Worklist.push_back(&BI);
12269       }
12270     }
12271   }
12272 }
12273 
12274 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12275                                         CXXMethodDecl *MoveAssignOperator) {
12276   assert((MoveAssignOperator->isDefaulted() &&
12277           MoveAssignOperator->isOverloadedOperator() &&
12278           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12279           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12280           !MoveAssignOperator->isDeleted()) &&
12281          "DefineImplicitMoveAssignment called for wrong function");
12282   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12283     return;
12284 
12285   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12286   if (ClassDecl->isInvalidDecl()) {
12287     MoveAssignOperator->setInvalidDecl();
12288     return;
12289   }
12290 
12291   // C++0x [class.copy]p28:
12292   //   The implicitly-defined or move assignment operator for a non-union class
12293   //   X performs memberwise move assignment of its subobjects. The direct base
12294   //   classes of X are assigned first, in the order of their declaration in the
12295   //   base-specifier-list, and then the immediate non-static data members of X
12296   //   are assigned, in the order in which they were declared in the class
12297   //   definition.
12298 
12299   // Issue a warning if our implicit move assignment operator will move
12300   // from a virtual base more than once.
12301   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12302 
12303   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12304 
12305   // The exception specification is needed because we are defining the
12306   // function.
12307   ResolveExceptionSpec(CurrentLocation,
12308                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12309 
12310   // Add a context note for diagnostics produced after this point.
12311   Scope.addContextNote(CurrentLocation);
12312 
12313   // The statements that form the synthesized function body.
12314   SmallVector<Stmt*, 8> Statements;
12315 
12316   // The parameter for the "other" object, which we are move from.
12317   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12318   QualType OtherRefType = Other->getType()->
12319       getAs<RValueReferenceType>()->getPointeeType();
12320   assert(!OtherRefType.getQualifiers() &&
12321          "Bad argument type of defaulted move assignment");
12322 
12323   // Our location for everything implicitly-generated.
12324   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12325                            ? MoveAssignOperator->getEndLoc()
12326                            : MoveAssignOperator->getLocation();
12327 
12328   // Builds a reference to the "other" object.
12329   RefBuilder OtherRef(Other, OtherRefType);
12330   // Cast to rvalue.
12331   MoveCastBuilder MoveOther(OtherRef);
12332 
12333   // Builds the "this" pointer.
12334   ThisBuilder This;
12335 
12336   // Assign base classes.
12337   bool Invalid = false;
12338   for (auto &Base : ClassDecl->bases()) {
12339     // C++11 [class.copy]p28:
12340     //   It is unspecified whether subobjects representing virtual base classes
12341     //   are assigned more than once by the implicitly-defined copy assignment
12342     //   operator.
12343     // FIXME: Do not assign to a vbase that will be assigned by some other base
12344     // class. For a move-assignment, this can result in the vbase being moved
12345     // multiple times.
12346 
12347     // Form the assignment:
12348     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12349     QualType BaseType = Base.getType().getUnqualifiedType();
12350     if (!BaseType->isRecordType()) {
12351       Invalid = true;
12352       continue;
12353     }
12354 
12355     CXXCastPath BasePath;
12356     BasePath.push_back(&Base);
12357 
12358     // Construct the "from" expression, which is an implicit cast to the
12359     // appropriately-qualified base type.
12360     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12361 
12362     // Dereference "this".
12363     DerefBuilder DerefThis(This);
12364 
12365     // Implicitly cast "this" to the appropriately-qualified base type.
12366     CastBuilder To(DerefThis,
12367                    Context.getQualifiedType(
12368                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12369                    VK_LValue, BasePath);
12370 
12371     // Build the move.
12372     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12373                                             To, From,
12374                                             /*CopyingBaseSubobject=*/true,
12375                                             /*Copying=*/false);
12376     if (Move.isInvalid()) {
12377       MoveAssignOperator->setInvalidDecl();
12378       return;
12379     }
12380 
12381     // Success! Record the move.
12382     Statements.push_back(Move.getAs<Expr>());
12383   }
12384 
12385   // Assign non-static members.
12386   for (auto *Field : ClassDecl->fields()) {
12387     // FIXME: We should form some kind of AST representation for the implied
12388     // memcpy in a union copy operation.
12389     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12390       continue;
12391 
12392     if (Field->isInvalidDecl()) {
12393       Invalid = true;
12394       continue;
12395     }
12396 
12397     // Check for members of reference type; we can't move those.
12398     if (Field->getType()->isReferenceType()) {
12399       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12400         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12401       Diag(Field->getLocation(), diag::note_declared_at);
12402       Invalid = true;
12403       continue;
12404     }
12405 
12406     // Check for members of const-qualified, non-class type.
12407     QualType BaseType = Context.getBaseElementType(Field->getType());
12408     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12409       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12410         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12411       Diag(Field->getLocation(), diag::note_declared_at);
12412       Invalid = true;
12413       continue;
12414     }
12415 
12416     // Suppress assigning zero-width bitfields.
12417     if (Field->isZeroLengthBitField(Context))
12418       continue;
12419 
12420     QualType FieldType = Field->getType().getNonReferenceType();
12421     if (FieldType->isIncompleteArrayType()) {
12422       assert(ClassDecl->hasFlexibleArrayMember() &&
12423              "Incomplete array type is not valid");
12424       continue;
12425     }
12426 
12427     // Build references to the field in the object we're copying from and to.
12428     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12429                               LookupMemberName);
12430     MemberLookup.addDecl(Field);
12431     MemberLookup.resolveKind();
12432     MemberBuilder From(MoveOther, OtherRefType,
12433                        /*IsArrow=*/false, MemberLookup);
12434     MemberBuilder To(This, getCurrentThisType(),
12435                      /*IsArrow=*/true, MemberLookup);
12436 
12437     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12438         "Member reference with rvalue base must be rvalue except for reference "
12439         "members, which aren't allowed for move assignment.");
12440 
12441     // Build the move of this field.
12442     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12443                                             To, From,
12444                                             /*CopyingBaseSubobject=*/false,
12445                                             /*Copying=*/false);
12446     if (Move.isInvalid()) {
12447       MoveAssignOperator->setInvalidDecl();
12448       return;
12449     }
12450 
12451     // Success! Record the copy.
12452     Statements.push_back(Move.getAs<Stmt>());
12453   }
12454 
12455   if (!Invalid) {
12456     // Add a "return *this;"
12457     ExprResult ThisObj =
12458         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12459 
12460     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12461     if (Return.isInvalid())
12462       Invalid = true;
12463     else
12464       Statements.push_back(Return.getAs<Stmt>());
12465   }
12466 
12467   if (Invalid) {
12468     MoveAssignOperator->setInvalidDecl();
12469     return;
12470   }
12471 
12472   StmtResult Body;
12473   {
12474     CompoundScopeRAII CompoundScope(*this);
12475     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12476                              /*isStmtExpr=*/false);
12477     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12478   }
12479   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12480   MoveAssignOperator->markUsed(Context);
12481 
12482   if (ASTMutationListener *L = getASTMutationListener()) {
12483     L->CompletedImplicitDefinition(MoveAssignOperator);
12484   }
12485 }
12486 
12487 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12488                                                     CXXRecordDecl *ClassDecl) {
12489   // C++ [class.copy]p4:
12490   //   If the class definition does not explicitly declare a copy
12491   //   constructor, one is declared implicitly.
12492   assert(ClassDecl->needsImplicitCopyConstructor());
12493 
12494   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12495   if (DSM.isAlreadyBeingDeclared())
12496     return nullptr;
12497 
12498   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12499   QualType ArgType = ClassType;
12500   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12501   if (Const)
12502     ArgType = ArgType.withConst();
12503   ArgType = Context.getLValueReferenceType(ArgType);
12504 
12505   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12506                                                      CXXCopyConstructor,
12507                                                      Const);
12508 
12509   DeclarationName Name
12510     = Context.DeclarationNames.getCXXConstructorName(
12511                                            Context.getCanonicalType(ClassType));
12512   SourceLocation ClassLoc = ClassDecl->getLocation();
12513   DeclarationNameInfo NameInfo(Name, ClassLoc);
12514 
12515   //   An implicitly-declared copy constructor is an inline public
12516   //   member of its class.
12517   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12518       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12519       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12520       Constexpr);
12521   CopyConstructor->setAccess(AS_public);
12522   CopyConstructor->setDefaulted();
12523 
12524   if (getLangOpts().CUDA) {
12525     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12526                                             CopyConstructor,
12527                                             /* ConstRHS */ Const,
12528                                             /* Diagnose */ false);
12529   }
12530 
12531   // Build an exception specification pointing back at this member.
12532   FunctionProtoType::ExtProtoInfo EPI =
12533       getImplicitMethodEPI(*this, CopyConstructor);
12534   CopyConstructor->setType(
12535       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12536 
12537   // Add the parameter to the constructor.
12538   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12539                                                ClassLoc, ClassLoc,
12540                                                /*IdentifierInfo=*/nullptr,
12541                                                ArgType, /*TInfo=*/nullptr,
12542                                                SC_None, nullptr);
12543   CopyConstructor->setParams(FromParam);
12544 
12545   CopyConstructor->setTrivial(
12546       ClassDecl->needsOverloadResolutionForCopyConstructor()
12547           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12548           : ClassDecl->hasTrivialCopyConstructor());
12549 
12550   CopyConstructor->setTrivialForCall(
12551       ClassDecl->hasAttr<TrivialABIAttr>() ||
12552       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12553            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12554              TAH_ConsiderTrivialABI)
12555            : ClassDecl->hasTrivialCopyConstructorForCall()));
12556 
12557   // Note that we have declared this constructor.
12558   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12559 
12560   Scope *S = getScopeForContext(ClassDecl);
12561   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12562 
12563   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12564     ClassDecl->setImplicitCopyConstructorIsDeleted();
12565     SetDeclDeleted(CopyConstructor, ClassLoc);
12566   }
12567 
12568   if (S)
12569     PushOnScopeChains(CopyConstructor, S, false);
12570   ClassDecl->addDecl(CopyConstructor);
12571 
12572   return CopyConstructor;
12573 }
12574 
12575 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12576                                          CXXConstructorDecl *CopyConstructor) {
12577   assert((CopyConstructor->isDefaulted() &&
12578           CopyConstructor->isCopyConstructor() &&
12579           !CopyConstructor->doesThisDeclarationHaveABody() &&
12580           !CopyConstructor->isDeleted()) &&
12581          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12582   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12583     return;
12584 
12585   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12586   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12587 
12588   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12589 
12590   // The exception specification is needed because we are defining the
12591   // function.
12592   ResolveExceptionSpec(CurrentLocation,
12593                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12594   MarkVTableUsed(CurrentLocation, ClassDecl);
12595 
12596   // Add a context note for diagnostics produced after this point.
12597   Scope.addContextNote(CurrentLocation);
12598 
12599   // C++11 [class.copy]p7:
12600   //   The [definition of an implicitly declared copy constructor] is
12601   //   deprecated if the class has a user-declared copy assignment operator
12602   //   or a user-declared destructor.
12603   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12604     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12605 
12606   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12607     CopyConstructor->setInvalidDecl();
12608   }  else {
12609     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12610                              ? CopyConstructor->getEndLoc()
12611                              : CopyConstructor->getLocation();
12612     Sema::CompoundScopeRAII CompoundScope(*this);
12613     CopyConstructor->setBody(
12614         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12615     CopyConstructor->markUsed(Context);
12616   }
12617 
12618   if (ASTMutationListener *L = getASTMutationListener()) {
12619     L->CompletedImplicitDefinition(CopyConstructor);
12620   }
12621 }
12622 
12623 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12624                                                     CXXRecordDecl *ClassDecl) {
12625   assert(ClassDecl->needsImplicitMoveConstructor());
12626 
12627   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12628   if (DSM.isAlreadyBeingDeclared())
12629     return nullptr;
12630 
12631   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12632   QualType ArgType = Context.getRValueReferenceType(ClassType);
12633 
12634   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12635                                                      CXXMoveConstructor,
12636                                                      false);
12637 
12638   DeclarationName Name
12639     = Context.DeclarationNames.getCXXConstructorName(
12640                                            Context.getCanonicalType(ClassType));
12641   SourceLocation ClassLoc = ClassDecl->getLocation();
12642   DeclarationNameInfo NameInfo(Name, ClassLoc);
12643 
12644   // C++11 [class.copy]p11:
12645   //   An implicitly-declared copy/move constructor is an inline public
12646   //   member of its class.
12647   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12648       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12649       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12650       Constexpr);
12651   MoveConstructor->setAccess(AS_public);
12652   MoveConstructor->setDefaulted();
12653 
12654   if (getLangOpts().CUDA) {
12655     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12656                                             MoveConstructor,
12657                                             /* ConstRHS */ false,
12658                                             /* Diagnose */ false);
12659   }
12660 
12661   // Build an exception specification pointing back at this member.
12662   FunctionProtoType::ExtProtoInfo EPI =
12663       getImplicitMethodEPI(*this, MoveConstructor);
12664   MoveConstructor->setType(
12665       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12666 
12667   // Add the parameter to the constructor.
12668   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12669                                                ClassLoc, ClassLoc,
12670                                                /*IdentifierInfo=*/nullptr,
12671                                                ArgType, /*TInfo=*/nullptr,
12672                                                SC_None, nullptr);
12673   MoveConstructor->setParams(FromParam);
12674 
12675   MoveConstructor->setTrivial(
12676       ClassDecl->needsOverloadResolutionForMoveConstructor()
12677           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12678           : ClassDecl->hasTrivialMoveConstructor());
12679 
12680   MoveConstructor->setTrivialForCall(
12681       ClassDecl->hasAttr<TrivialABIAttr>() ||
12682       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12683            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12684                                     TAH_ConsiderTrivialABI)
12685            : ClassDecl->hasTrivialMoveConstructorForCall()));
12686 
12687   // Note that we have declared this constructor.
12688   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12689 
12690   Scope *S = getScopeForContext(ClassDecl);
12691   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12692 
12693   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12694     ClassDecl->setImplicitMoveConstructorIsDeleted();
12695     SetDeclDeleted(MoveConstructor, ClassLoc);
12696   }
12697 
12698   if (S)
12699     PushOnScopeChains(MoveConstructor, S, false);
12700   ClassDecl->addDecl(MoveConstructor);
12701 
12702   return MoveConstructor;
12703 }
12704 
12705 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12706                                          CXXConstructorDecl *MoveConstructor) {
12707   assert((MoveConstructor->isDefaulted() &&
12708           MoveConstructor->isMoveConstructor() &&
12709           !MoveConstructor->doesThisDeclarationHaveABody() &&
12710           !MoveConstructor->isDeleted()) &&
12711          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12712   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12713     return;
12714 
12715   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12716   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12717 
12718   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12719 
12720   // The exception specification is needed because we are defining the
12721   // function.
12722   ResolveExceptionSpec(CurrentLocation,
12723                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12724   MarkVTableUsed(CurrentLocation, ClassDecl);
12725 
12726   // Add a context note for diagnostics produced after this point.
12727   Scope.addContextNote(CurrentLocation);
12728 
12729   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12730     MoveConstructor->setInvalidDecl();
12731   } else {
12732     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12733                              ? MoveConstructor->getEndLoc()
12734                              : MoveConstructor->getLocation();
12735     Sema::CompoundScopeRAII CompoundScope(*this);
12736     MoveConstructor->setBody(ActOnCompoundStmt(
12737         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12738     MoveConstructor->markUsed(Context);
12739   }
12740 
12741   if (ASTMutationListener *L = getASTMutationListener()) {
12742     L->CompletedImplicitDefinition(MoveConstructor);
12743   }
12744 }
12745 
12746 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12747   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12748 }
12749 
12750 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12751                             SourceLocation CurrentLocation,
12752                             CXXConversionDecl *Conv) {
12753   SynthesizedFunctionScope Scope(*this, Conv);
12754   assert(!Conv->getReturnType()->isUndeducedType());
12755 
12756   CXXRecordDecl *Lambda = Conv->getParent();
12757   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12758   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12759 
12760   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12761     CallOp = InstantiateFunctionDeclaration(
12762         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12763     if (!CallOp)
12764       return;
12765 
12766     Invoker = InstantiateFunctionDeclaration(
12767         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12768     if (!Invoker)
12769       return;
12770   }
12771 
12772   if (CallOp->isInvalidDecl())
12773     return;
12774 
12775   // Mark the call operator referenced (and add to pending instantiations
12776   // if necessary).
12777   // For both the conversion and static-invoker template specializations
12778   // we construct their body's in this function, so no need to add them
12779   // to the PendingInstantiations.
12780   MarkFunctionReferenced(CurrentLocation, CallOp);
12781 
12782   // Fill in the __invoke function with a dummy implementation. IR generation
12783   // will fill in the actual details. Update its type in case it contained
12784   // an 'auto'.
12785   Invoker->markUsed(Context);
12786   Invoker->setReferenced();
12787   Invoker->setType(Conv->getReturnType()->getPointeeType());
12788   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12789 
12790   // Construct the body of the conversion function { return __invoke; }.
12791   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12792                                        VK_LValue, Conv->getLocation()).get();
12793   assert(FunctionRef && "Can't refer to __invoke function?");
12794   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12795   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12796                                      Conv->getLocation()));
12797   Conv->markUsed(Context);
12798   Conv->setReferenced();
12799 
12800   if (ASTMutationListener *L = getASTMutationListener()) {
12801     L->CompletedImplicitDefinition(Conv);
12802     L->CompletedImplicitDefinition(Invoker);
12803   }
12804 }
12805 
12806 
12807 
12808 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12809        SourceLocation CurrentLocation,
12810        CXXConversionDecl *Conv)
12811 {
12812   assert(!Conv->getParent()->isGenericLambda());
12813 
12814   SynthesizedFunctionScope Scope(*this, Conv);
12815 
12816   // Copy-initialize the lambda object as needed to capture it.
12817   Expr *This = ActOnCXXThis(CurrentLocation).get();
12818   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12819 
12820   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12821                                                         Conv->getLocation(),
12822                                                         Conv, DerefThis);
12823 
12824   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12825   // behavior.  Note that only the general conversion function does this
12826   // (since it's unusable otherwise); in the case where we inline the
12827   // block literal, it has block literal lifetime semantics.
12828   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12829     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12830                                           CK_CopyAndAutoreleaseBlockObject,
12831                                           BuildBlock.get(), nullptr, VK_RValue);
12832 
12833   if (BuildBlock.isInvalid()) {
12834     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12835     Conv->setInvalidDecl();
12836     return;
12837   }
12838 
12839   // Create the return statement that returns the block from the conversion
12840   // function.
12841   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12842   if (Return.isInvalid()) {
12843     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12844     Conv->setInvalidDecl();
12845     return;
12846   }
12847 
12848   // Set the body of the conversion function.
12849   Stmt *ReturnS = Return.get();
12850   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12851                                      Conv->getLocation()));
12852   Conv->markUsed(Context);
12853 
12854   // We're done; notify the mutation listener, if any.
12855   if (ASTMutationListener *L = getASTMutationListener()) {
12856     L->CompletedImplicitDefinition(Conv);
12857   }
12858 }
12859 
12860 /// Determine whether the given list arguments contains exactly one
12861 /// "real" (non-default) argument.
12862 static bool hasOneRealArgument(MultiExprArg Args) {
12863   switch (Args.size()) {
12864   case 0:
12865     return false;
12866 
12867   default:
12868     if (!Args[1]->isDefaultArgument())
12869       return false;
12870 
12871     LLVM_FALLTHROUGH;
12872   case 1:
12873     return !Args[0]->isDefaultArgument();
12874   }
12875 
12876   return false;
12877 }
12878 
12879 ExprResult
12880 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12881                             NamedDecl *FoundDecl,
12882                             CXXConstructorDecl *Constructor,
12883                             MultiExprArg ExprArgs,
12884                             bool HadMultipleCandidates,
12885                             bool IsListInitialization,
12886                             bool IsStdInitListInitialization,
12887                             bool RequiresZeroInit,
12888                             unsigned ConstructKind,
12889                             SourceRange ParenRange) {
12890   bool Elidable = false;
12891 
12892   // C++0x [class.copy]p34:
12893   //   When certain criteria are met, an implementation is allowed to
12894   //   omit the copy/move construction of a class object, even if the
12895   //   copy/move constructor and/or destructor for the object have
12896   //   side effects. [...]
12897   //     - when a temporary class object that has not been bound to a
12898   //       reference (12.2) would be copied/moved to a class object
12899   //       with the same cv-unqualified type, the copy/move operation
12900   //       can be omitted by constructing the temporary object
12901   //       directly into the target of the omitted copy/move
12902   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12903       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12904     Expr *SubExpr = ExprArgs[0];
12905     Elidable = SubExpr->isTemporaryObject(
12906         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12907   }
12908 
12909   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12910                                FoundDecl, Constructor,
12911                                Elidable, ExprArgs, HadMultipleCandidates,
12912                                IsListInitialization,
12913                                IsStdInitListInitialization, RequiresZeroInit,
12914                                ConstructKind, ParenRange);
12915 }
12916 
12917 ExprResult
12918 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12919                             NamedDecl *FoundDecl,
12920                             CXXConstructorDecl *Constructor,
12921                             bool Elidable,
12922                             MultiExprArg ExprArgs,
12923                             bool HadMultipleCandidates,
12924                             bool IsListInitialization,
12925                             bool IsStdInitListInitialization,
12926                             bool RequiresZeroInit,
12927                             unsigned ConstructKind,
12928                             SourceRange ParenRange) {
12929   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12930     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12931     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12932       return ExprError();
12933   }
12934 
12935   return BuildCXXConstructExpr(
12936       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12937       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12938       RequiresZeroInit, ConstructKind, ParenRange);
12939 }
12940 
12941 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12942 /// including handling of its default argument expressions.
12943 ExprResult
12944 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12945                             CXXConstructorDecl *Constructor,
12946                             bool Elidable,
12947                             MultiExprArg ExprArgs,
12948                             bool HadMultipleCandidates,
12949                             bool IsListInitialization,
12950                             bool IsStdInitListInitialization,
12951                             bool RequiresZeroInit,
12952                             unsigned ConstructKind,
12953                             SourceRange ParenRange) {
12954   assert(declaresSameEntity(
12955              Constructor->getParent(),
12956              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12957          "given constructor for wrong type");
12958   MarkFunctionReferenced(ConstructLoc, Constructor);
12959   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12960     return ExprError();
12961 
12962   return CXXConstructExpr::Create(
12963       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12964       ExprArgs, HadMultipleCandidates, IsListInitialization,
12965       IsStdInitListInitialization, RequiresZeroInit,
12966       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12967       ParenRange);
12968 }
12969 
12970 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12971   assert(Field->hasInClassInitializer());
12972 
12973   // If we already have the in-class initializer nothing needs to be done.
12974   if (Field->getInClassInitializer())
12975     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12976 
12977   // If we might have already tried and failed to instantiate, don't try again.
12978   if (Field->isInvalidDecl())
12979     return ExprError();
12980 
12981   // Maybe we haven't instantiated the in-class initializer. Go check the
12982   // pattern FieldDecl to see if it has one.
12983   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12984 
12985   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12986     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12987     DeclContext::lookup_result Lookup =
12988         ClassPattern->lookup(Field->getDeclName());
12989 
12990     // Lookup can return at most two results: the pattern for the field, or the
12991     // injected class name of the parent record. No other member can have the
12992     // same name as the field.
12993     // In modules mode, lookup can return multiple results (coming from
12994     // different modules).
12995     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12996            "more than two lookup results for field name");
12997     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12998     if (!Pattern) {
12999       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13000              "cannot have other non-field member with same name");
13001       for (auto L : Lookup)
13002         if (isa<FieldDecl>(L)) {
13003           Pattern = cast<FieldDecl>(L);
13004           break;
13005         }
13006       assert(Pattern && "We must have set the Pattern!");
13007     }
13008 
13009     if (!Pattern->hasInClassInitializer() ||
13010         InstantiateInClassInitializer(Loc, Field, Pattern,
13011                                       getTemplateInstantiationArgs(Field))) {
13012       // Don't diagnose this again.
13013       Field->setInvalidDecl();
13014       return ExprError();
13015     }
13016     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13017   }
13018 
13019   // DR1351:
13020   //   If the brace-or-equal-initializer of a non-static data member
13021   //   invokes a defaulted default constructor of its class or of an
13022   //   enclosing class in a potentially evaluated subexpression, the
13023   //   program is ill-formed.
13024   //
13025   // This resolution is unworkable: the exception specification of the
13026   // default constructor can be needed in an unevaluated context, in
13027   // particular, in the operand of a noexcept-expression, and we can be
13028   // unable to compute an exception specification for an enclosed class.
13029   //
13030   // Any attempt to resolve the exception specification of a defaulted default
13031   // constructor before the initializer is lexically complete will ultimately
13032   // come here at which point we can diagnose it.
13033   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13034   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13035       << OutermostClass << Field;
13036   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13037   // Recover by marking the field invalid, unless we're in a SFINAE context.
13038   if (!isSFINAEContext())
13039     Field->setInvalidDecl();
13040   return ExprError();
13041 }
13042 
13043 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13044   if (VD->isInvalidDecl()) return;
13045 
13046   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13047   if (ClassDecl->isInvalidDecl()) return;
13048   if (ClassDecl->hasIrrelevantDestructor()) return;
13049   if (ClassDecl->isDependentContext()) return;
13050 
13051   if (VD->isNoDestroy(getASTContext()))
13052     return;
13053 
13054   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13055   MarkFunctionReferenced(VD->getLocation(), Destructor);
13056   CheckDestructorAccess(VD->getLocation(), Destructor,
13057                         PDiag(diag::err_access_dtor_var)
13058                         << VD->getDeclName()
13059                         << VD->getType());
13060   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13061 
13062   if (Destructor->isTrivial()) return;
13063   if (!VD->hasGlobalStorage()) return;
13064 
13065   // Emit warning for non-trivial dtor in global scope (a real global,
13066   // class-static, function-static).
13067   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13068 
13069   // TODO: this should be re-enabled for static locals by !CXAAtExit
13070   if (!VD->isStaticLocal())
13071     Diag(VD->getLocation(), diag::warn_global_destructor);
13072 }
13073 
13074 /// Given a constructor and the set of arguments provided for the
13075 /// constructor, convert the arguments and add any required default arguments
13076 /// to form a proper call to this constructor.
13077 ///
13078 /// \returns true if an error occurred, false otherwise.
13079 bool
13080 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13081                               MultiExprArg ArgsPtr,
13082                               SourceLocation Loc,
13083                               SmallVectorImpl<Expr*> &ConvertedArgs,
13084                               bool AllowExplicit,
13085                               bool IsListInitialization) {
13086   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13087   unsigned NumArgs = ArgsPtr.size();
13088   Expr **Args = ArgsPtr.data();
13089 
13090   const FunctionProtoType *Proto
13091     = Constructor->getType()->getAs<FunctionProtoType>();
13092   assert(Proto && "Constructor without a prototype?");
13093   unsigned NumParams = Proto->getNumParams();
13094 
13095   // If too few arguments are available, we'll fill in the rest with defaults.
13096   if (NumArgs < NumParams)
13097     ConvertedArgs.reserve(NumParams);
13098   else
13099     ConvertedArgs.reserve(NumArgs);
13100 
13101   VariadicCallType CallType =
13102     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13103   SmallVector<Expr *, 8> AllArgs;
13104   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13105                                         Proto, 0,
13106                                         llvm::makeArrayRef(Args, NumArgs),
13107                                         AllArgs,
13108                                         CallType, AllowExplicit,
13109                                         IsListInitialization);
13110   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13111 
13112   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13113 
13114   CheckConstructorCall(Constructor,
13115                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13116                        Proto, Loc);
13117 
13118   return Invalid;
13119 }
13120 
13121 static inline bool
13122 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13123                                        const FunctionDecl *FnDecl) {
13124   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13125   if (isa<NamespaceDecl>(DC)) {
13126     return SemaRef.Diag(FnDecl->getLocation(),
13127                         diag::err_operator_new_delete_declared_in_namespace)
13128       << FnDecl->getDeclName();
13129   }
13130 
13131   if (isa<TranslationUnitDecl>(DC) &&
13132       FnDecl->getStorageClass() == SC_Static) {
13133     return SemaRef.Diag(FnDecl->getLocation(),
13134                         diag::err_operator_new_delete_declared_static)
13135       << FnDecl->getDeclName();
13136   }
13137 
13138   return false;
13139 }
13140 
13141 static QualType
13142 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13143   QualType QTy = PtrTy->getPointeeType();
13144   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13145   return SemaRef.Context.getPointerType(QTy);
13146 }
13147 
13148 static inline bool
13149 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13150                             CanQualType ExpectedResultType,
13151                             CanQualType ExpectedFirstParamType,
13152                             unsigned DependentParamTypeDiag,
13153                             unsigned InvalidParamTypeDiag) {
13154   QualType ResultType =
13155       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13156 
13157   // Check that the result type is not dependent.
13158   if (ResultType->isDependentType())
13159     return SemaRef.Diag(FnDecl->getLocation(),
13160                         diag::err_operator_new_delete_dependent_result_type)
13161     << FnDecl->getDeclName() << ExpectedResultType;
13162 
13163   // OpenCL C++: the operator is valid on any address space.
13164   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13165     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13166       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13167     }
13168   }
13169 
13170   // Check that the result type is what we expect.
13171   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13172     return SemaRef.Diag(FnDecl->getLocation(),
13173                         diag::err_operator_new_delete_invalid_result_type)
13174     << FnDecl->getDeclName() << ExpectedResultType;
13175 
13176   // A function template must have at least 2 parameters.
13177   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13178     return SemaRef.Diag(FnDecl->getLocation(),
13179                       diag::err_operator_new_delete_template_too_few_parameters)
13180         << FnDecl->getDeclName();
13181 
13182   // The function decl must have at least 1 parameter.
13183   if (FnDecl->getNumParams() == 0)
13184     return SemaRef.Diag(FnDecl->getLocation(),
13185                         diag::err_operator_new_delete_too_few_parameters)
13186       << FnDecl->getDeclName();
13187 
13188   // Check the first parameter type is not dependent.
13189   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13190   if (FirstParamType->isDependentType())
13191     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13192       << FnDecl->getDeclName() << ExpectedFirstParamType;
13193 
13194   // Check that the first parameter type is what we expect.
13195   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13196     // OpenCL C++: the operator is valid on any address space.
13197     if (auto *PtrTy =
13198             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13199       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13200     }
13201   }
13202   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13203       ExpectedFirstParamType)
13204     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13205     << FnDecl->getDeclName() << ExpectedFirstParamType;
13206 
13207   return false;
13208 }
13209 
13210 static bool
13211 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13212   // C++ [basic.stc.dynamic.allocation]p1:
13213   //   A program is ill-formed if an allocation function is declared in a
13214   //   namespace scope other than global scope or declared static in global
13215   //   scope.
13216   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13217     return true;
13218 
13219   CanQualType SizeTy =
13220     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13221 
13222   // C++ [basic.stc.dynamic.allocation]p1:
13223   //  The return type shall be void*. The first parameter shall have type
13224   //  std::size_t.
13225   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13226                                   SizeTy,
13227                                   diag::err_operator_new_dependent_param_type,
13228                                   diag::err_operator_new_param_type))
13229     return true;
13230 
13231   // C++ [basic.stc.dynamic.allocation]p1:
13232   //  The first parameter shall not have an associated default argument.
13233   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13234     return SemaRef.Diag(FnDecl->getLocation(),
13235                         diag::err_operator_new_default_arg)
13236       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13237 
13238   return false;
13239 }
13240 
13241 static bool
13242 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13243   // C++ [basic.stc.dynamic.deallocation]p1:
13244   //   A program is ill-formed if deallocation functions are declared in a
13245   //   namespace scope other than global scope or declared static in global
13246   //   scope.
13247   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13248     return true;
13249 
13250   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13251 
13252   // C++ P0722:
13253   //   Within a class C, the first parameter of a destroying operator delete
13254   //   shall be of type C *. The first parameter of any other deallocation
13255   //   function shall be of type void *.
13256   CanQualType ExpectedFirstParamType =
13257       MD && MD->isDestroyingOperatorDelete()
13258           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13259                 SemaRef.Context.getRecordType(MD->getParent())))
13260           : SemaRef.Context.VoidPtrTy;
13261 
13262   // C++ [basic.stc.dynamic.deallocation]p2:
13263   //   Each deallocation function shall return void
13264   if (CheckOperatorNewDeleteTypes(
13265           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13266           diag::err_operator_delete_dependent_param_type,
13267           diag::err_operator_delete_param_type))
13268     return true;
13269 
13270   // C++ P0722:
13271   //   A destroying operator delete shall be a usual deallocation function.
13272   if (MD && !MD->getParent()->isDependentContext() &&
13273       MD->isDestroyingOperatorDelete() &&
13274       !SemaRef.isUsualDeallocationFunction(MD)) {
13275     SemaRef.Diag(MD->getLocation(),
13276                  diag::err_destroying_operator_delete_not_usual);
13277     return true;
13278   }
13279 
13280   return false;
13281 }
13282 
13283 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13284 /// of this overloaded operator is well-formed. If so, returns false;
13285 /// otherwise, emits appropriate diagnostics and returns true.
13286 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13287   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13288          "Expected an overloaded operator declaration");
13289 
13290   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13291 
13292   // C++ [over.oper]p5:
13293   //   The allocation and deallocation functions, operator new,
13294   //   operator new[], operator delete and operator delete[], are
13295   //   described completely in 3.7.3. The attributes and restrictions
13296   //   found in the rest of this subclause do not apply to them unless
13297   //   explicitly stated in 3.7.3.
13298   if (Op == OO_Delete || Op == OO_Array_Delete)
13299     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13300 
13301   if (Op == OO_New || Op == OO_Array_New)
13302     return CheckOperatorNewDeclaration(*this, FnDecl);
13303 
13304   // C++ [over.oper]p6:
13305   //   An operator function shall either be a non-static member
13306   //   function or be a non-member function and have at least one
13307   //   parameter whose type is a class, a reference to a class, an
13308   //   enumeration, or a reference to an enumeration.
13309   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13310     if (MethodDecl->isStatic())
13311       return Diag(FnDecl->getLocation(),
13312                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13313   } else {
13314     bool ClassOrEnumParam = false;
13315     for (auto Param : FnDecl->parameters()) {
13316       QualType ParamType = Param->getType().getNonReferenceType();
13317       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13318           ParamType->isEnumeralType()) {
13319         ClassOrEnumParam = true;
13320         break;
13321       }
13322     }
13323 
13324     if (!ClassOrEnumParam)
13325       return Diag(FnDecl->getLocation(),
13326                   diag::err_operator_overload_needs_class_or_enum)
13327         << FnDecl->getDeclName();
13328   }
13329 
13330   // C++ [over.oper]p8:
13331   //   An operator function cannot have default arguments (8.3.6),
13332   //   except where explicitly stated below.
13333   //
13334   // Only the function-call operator allows default arguments
13335   // (C++ [over.call]p1).
13336   if (Op != OO_Call) {
13337     for (auto Param : FnDecl->parameters()) {
13338       if (Param->hasDefaultArg())
13339         return Diag(Param->getLocation(),
13340                     diag::err_operator_overload_default_arg)
13341           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13342     }
13343   }
13344 
13345   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13346     { false, false, false }
13347 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13348     , { Unary, Binary, MemberOnly }
13349 #include "clang/Basic/OperatorKinds.def"
13350   };
13351 
13352   bool CanBeUnaryOperator = OperatorUses[Op][0];
13353   bool CanBeBinaryOperator = OperatorUses[Op][1];
13354   bool MustBeMemberOperator = OperatorUses[Op][2];
13355 
13356   // C++ [over.oper]p8:
13357   //   [...] Operator functions cannot have more or fewer parameters
13358   //   than the number required for the corresponding operator, as
13359   //   described in the rest of this subclause.
13360   unsigned NumParams = FnDecl->getNumParams()
13361                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13362   if (Op != OO_Call &&
13363       ((NumParams == 1 && !CanBeUnaryOperator) ||
13364        (NumParams == 2 && !CanBeBinaryOperator) ||
13365        (NumParams < 1) || (NumParams > 2))) {
13366     // We have the wrong number of parameters.
13367     unsigned ErrorKind;
13368     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13369       ErrorKind = 2;  // 2 -> unary or binary.
13370     } else if (CanBeUnaryOperator) {
13371       ErrorKind = 0;  // 0 -> unary
13372     } else {
13373       assert(CanBeBinaryOperator &&
13374              "All non-call overloaded operators are unary or binary!");
13375       ErrorKind = 1;  // 1 -> binary
13376     }
13377 
13378     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13379       << FnDecl->getDeclName() << NumParams << ErrorKind;
13380   }
13381 
13382   // Overloaded operators other than operator() cannot be variadic.
13383   if (Op != OO_Call &&
13384       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13385     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13386       << FnDecl->getDeclName();
13387   }
13388 
13389   // Some operators must be non-static member functions.
13390   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13391     return Diag(FnDecl->getLocation(),
13392                 diag::err_operator_overload_must_be_member)
13393       << FnDecl->getDeclName();
13394   }
13395 
13396   // C++ [over.inc]p1:
13397   //   The user-defined function called operator++ implements the
13398   //   prefix and postfix ++ operator. If this function is a member
13399   //   function with no parameters, or a non-member function with one
13400   //   parameter of class or enumeration type, it defines the prefix
13401   //   increment operator ++ for objects of that type. If the function
13402   //   is a member function with one parameter (which shall be of type
13403   //   int) or a non-member function with two parameters (the second
13404   //   of which shall be of type int), it defines the postfix
13405   //   increment operator ++ for objects of that type.
13406   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13407     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13408     QualType ParamType = LastParam->getType();
13409 
13410     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13411         !ParamType->isDependentType())
13412       return Diag(LastParam->getLocation(),
13413                   diag::err_operator_overload_post_incdec_must_be_int)
13414         << LastParam->getType() << (Op == OO_MinusMinus);
13415   }
13416 
13417   return false;
13418 }
13419 
13420 static bool
13421 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13422                                           FunctionTemplateDecl *TpDecl) {
13423   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13424 
13425   // Must have one or two template parameters.
13426   if (TemplateParams->size() == 1) {
13427     NonTypeTemplateParmDecl *PmDecl =
13428         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13429 
13430     // The template parameter must be a char parameter pack.
13431     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13432         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13433       return false;
13434 
13435   } else if (TemplateParams->size() == 2) {
13436     TemplateTypeParmDecl *PmType =
13437         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13438     NonTypeTemplateParmDecl *PmArgs =
13439         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13440 
13441     // The second template parameter must be a parameter pack with the
13442     // first template parameter as its type.
13443     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13444         PmArgs->isTemplateParameterPack()) {
13445       const TemplateTypeParmType *TArgs =
13446           PmArgs->getType()->getAs<TemplateTypeParmType>();
13447       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13448           TArgs->getIndex() == PmType->getIndex()) {
13449         if (!SemaRef.inTemplateInstantiation())
13450           SemaRef.Diag(TpDecl->getLocation(),
13451                        diag::ext_string_literal_operator_template);
13452         return false;
13453       }
13454     }
13455   }
13456 
13457   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13458                diag::err_literal_operator_template)
13459       << TpDecl->getTemplateParameters()->getSourceRange();
13460   return true;
13461 }
13462 
13463 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13464 /// of this literal operator function is well-formed. If so, returns
13465 /// false; otherwise, emits appropriate diagnostics and returns true.
13466 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13467   if (isa<CXXMethodDecl>(FnDecl)) {
13468     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13469       << FnDecl->getDeclName();
13470     return true;
13471   }
13472 
13473   if (FnDecl->isExternC()) {
13474     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13475     if (const LinkageSpecDecl *LSD =
13476             FnDecl->getDeclContext()->getExternCContext())
13477       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13478     return true;
13479   }
13480 
13481   // This might be the definition of a literal operator template.
13482   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13483 
13484   // This might be a specialization of a literal operator template.
13485   if (!TpDecl)
13486     TpDecl = FnDecl->getPrimaryTemplate();
13487 
13488   // template <char...> type operator "" name() and
13489   // template <class T, T...> type operator "" name() are the only valid
13490   // template signatures, and the only valid signatures with no parameters.
13491   if (TpDecl) {
13492     if (FnDecl->param_size() != 0) {
13493       Diag(FnDecl->getLocation(),
13494            diag::err_literal_operator_template_with_params);
13495       return true;
13496     }
13497 
13498     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13499       return true;
13500 
13501   } else if (FnDecl->param_size() == 1) {
13502     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13503 
13504     QualType ParamType = Param->getType().getUnqualifiedType();
13505 
13506     // Only unsigned long long int, long double, any character type, and const
13507     // char * are allowed as the only parameters.
13508     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13509         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13510         Context.hasSameType(ParamType, Context.CharTy) ||
13511         Context.hasSameType(ParamType, Context.WideCharTy) ||
13512         Context.hasSameType(ParamType, Context.Char8Ty) ||
13513         Context.hasSameType(ParamType, Context.Char16Ty) ||
13514         Context.hasSameType(ParamType, Context.Char32Ty)) {
13515     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13516       QualType InnerType = Ptr->getPointeeType();
13517 
13518       // Pointer parameter must be a const char *.
13519       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13520                                 Context.CharTy) &&
13521             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13522         Diag(Param->getSourceRange().getBegin(),
13523              diag::err_literal_operator_param)
13524             << ParamType << "'const char *'" << Param->getSourceRange();
13525         return true;
13526       }
13527 
13528     } else if (ParamType->isRealFloatingType()) {
13529       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13530           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13531       return true;
13532 
13533     } else if (ParamType->isIntegerType()) {
13534       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13535           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13536       return true;
13537 
13538     } else {
13539       Diag(Param->getSourceRange().getBegin(),
13540            diag::err_literal_operator_invalid_param)
13541           << ParamType << Param->getSourceRange();
13542       return true;
13543     }
13544 
13545   } else if (FnDecl->param_size() == 2) {
13546     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13547 
13548     // First, verify that the first parameter is correct.
13549 
13550     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13551 
13552     // Two parameter function must have a pointer to const as a
13553     // first parameter; let's strip those qualifiers.
13554     const PointerType *PT = FirstParamType->getAs<PointerType>();
13555 
13556     if (!PT) {
13557       Diag((*Param)->getSourceRange().getBegin(),
13558            diag::err_literal_operator_param)
13559           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13560       return true;
13561     }
13562 
13563     QualType PointeeType = PT->getPointeeType();
13564     // First parameter must be const
13565     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13566       Diag((*Param)->getSourceRange().getBegin(),
13567            diag::err_literal_operator_param)
13568           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13569       return true;
13570     }
13571 
13572     QualType InnerType = PointeeType.getUnqualifiedType();
13573     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13574     // const char32_t* are allowed as the first parameter to a two-parameter
13575     // function
13576     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13577           Context.hasSameType(InnerType, Context.WideCharTy) ||
13578           Context.hasSameType(InnerType, Context.Char8Ty) ||
13579           Context.hasSameType(InnerType, Context.Char16Ty) ||
13580           Context.hasSameType(InnerType, Context.Char32Ty))) {
13581       Diag((*Param)->getSourceRange().getBegin(),
13582            diag::err_literal_operator_param)
13583           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13584       return true;
13585     }
13586 
13587     // Move on to the second and final parameter.
13588     ++Param;
13589 
13590     // The second parameter must be a std::size_t.
13591     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13592     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13593       Diag((*Param)->getSourceRange().getBegin(),
13594            diag::err_literal_operator_param)
13595           << SecondParamType << Context.getSizeType()
13596           << (*Param)->getSourceRange();
13597       return true;
13598     }
13599   } else {
13600     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13601     return true;
13602   }
13603 
13604   // Parameters are good.
13605 
13606   // A parameter-declaration-clause containing a default argument is not
13607   // equivalent to any of the permitted forms.
13608   for (auto Param : FnDecl->parameters()) {
13609     if (Param->hasDefaultArg()) {
13610       Diag(Param->getDefaultArgRange().getBegin(),
13611            diag::err_literal_operator_default_argument)
13612         << Param->getDefaultArgRange();
13613       break;
13614     }
13615   }
13616 
13617   StringRef LiteralName
13618     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13619   if (LiteralName[0] != '_' &&
13620       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13621     // C++11 [usrlit.suffix]p1:
13622     //   Literal suffix identifiers that do not start with an underscore
13623     //   are reserved for future standardization.
13624     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13625       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13626   }
13627 
13628   return false;
13629 }
13630 
13631 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13632 /// linkage specification, including the language and (if present)
13633 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13634 /// language string literal. LBraceLoc, if valid, provides the location of
13635 /// the '{' brace. Otherwise, this linkage specification does not
13636 /// have any braces.
13637 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13638                                            Expr *LangStr,
13639                                            SourceLocation LBraceLoc) {
13640   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13641   if (!Lit->isAscii()) {
13642     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13643       << LangStr->getSourceRange();
13644     return nullptr;
13645   }
13646 
13647   StringRef Lang = Lit->getString();
13648   LinkageSpecDecl::LanguageIDs Language;
13649   if (Lang == "C")
13650     Language = LinkageSpecDecl::lang_c;
13651   else if (Lang == "C++")
13652     Language = LinkageSpecDecl::lang_cxx;
13653   else {
13654     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13655       << LangStr->getSourceRange();
13656     return nullptr;
13657   }
13658 
13659   // FIXME: Add all the various semantics of linkage specifications
13660 
13661   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13662                                                LangStr->getExprLoc(), Language,
13663                                                LBraceLoc.isValid());
13664   CurContext->addDecl(D);
13665   PushDeclContext(S, D);
13666   return D;
13667 }
13668 
13669 /// ActOnFinishLinkageSpecification - Complete the definition of
13670 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13671 /// valid, it's the position of the closing '}' brace in a linkage
13672 /// specification that uses braces.
13673 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13674                                             Decl *LinkageSpec,
13675                                             SourceLocation RBraceLoc) {
13676   if (RBraceLoc.isValid()) {
13677     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13678     LSDecl->setRBraceLoc(RBraceLoc);
13679   }
13680   PopDeclContext();
13681   return LinkageSpec;
13682 }
13683 
13684 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13685                                   const ParsedAttributesView &AttrList,
13686                                   SourceLocation SemiLoc) {
13687   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13688   // Attribute declarations appertain to empty declaration so we handle
13689   // them here.
13690   ProcessDeclAttributeList(S, ED, AttrList);
13691 
13692   CurContext->addDecl(ED);
13693   return ED;
13694 }
13695 
13696 /// Perform semantic analysis for the variable declaration that
13697 /// occurs within a C++ catch clause, returning the newly-created
13698 /// variable.
13699 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13700                                          TypeSourceInfo *TInfo,
13701                                          SourceLocation StartLoc,
13702                                          SourceLocation Loc,
13703                                          IdentifierInfo *Name) {
13704   bool Invalid = false;
13705   QualType ExDeclType = TInfo->getType();
13706 
13707   // Arrays and functions decay.
13708   if (ExDeclType->isArrayType())
13709     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13710   else if (ExDeclType->isFunctionType())
13711     ExDeclType = Context.getPointerType(ExDeclType);
13712 
13713   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13714   // The exception-declaration shall not denote a pointer or reference to an
13715   // incomplete type, other than [cv] void*.
13716   // N2844 forbids rvalue references.
13717   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13718     Diag(Loc, diag::err_catch_rvalue_ref);
13719     Invalid = true;
13720   }
13721 
13722   if (ExDeclType->isVariablyModifiedType()) {
13723     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13724     Invalid = true;
13725   }
13726 
13727   QualType BaseType = ExDeclType;
13728   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13729   unsigned DK = diag::err_catch_incomplete;
13730   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13731     BaseType = Ptr->getPointeeType();
13732     Mode = 1;
13733     DK = diag::err_catch_incomplete_ptr;
13734   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13735     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13736     BaseType = Ref->getPointeeType();
13737     Mode = 2;
13738     DK = diag::err_catch_incomplete_ref;
13739   }
13740   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13741       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13742     Invalid = true;
13743 
13744   if (!Invalid && !ExDeclType->isDependentType() &&
13745       RequireNonAbstractType(Loc, ExDeclType,
13746                              diag::err_abstract_type_in_decl,
13747                              AbstractVariableType))
13748     Invalid = true;
13749 
13750   // Only the non-fragile NeXT runtime currently supports C++ catches
13751   // of ObjC types, and no runtime supports catching ObjC types by value.
13752   if (!Invalid && getLangOpts().ObjC) {
13753     QualType T = ExDeclType;
13754     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13755       T = RT->getPointeeType();
13756 
13757     if (T->isObjCObjectType()) {
13758       Diag(Loc, diag::err_objc_object_catch);
13759       Invalid = true;
13760     } else if (T->isObjCObjectPointerType()) {
13761       // FIXME: should this be a test for macosx-fragile specifically?
13762       if (getLangOpts().ObjCRuntime.isFragile())
13763         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13764     }
13765   }
13766 
13767   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13768                                     ExDeclType, TInfo, SC_None);
13769   ExDecl->setExceptionVariable(true);
13770 
13771   // In ARC, infer 'retaining' for variables of retainable type.
13772   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13773     Invalid = true;
13774 
13775   if (!Invalid && !ExDeclType->isDependentType()) {
13776     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13777       // Insulate this from anything else we might currently be parsing.
13778       EnterExpressionEvaluationContext scope(
13779           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13780 
13781       // C++ [except.handle]p16:
13782       //   The object declared in an exception-declaration or, if the
13783       //   exception-declaration does not specify a name, a temporary (12.2) is
13784       //   copy-initialized (8.5) from the exception object. [...]
13785       //   The object is destroyed when the handler exits, after the destruction
13786       //   of any automatic objects initialized within the handler.
13787       //
13788       // We just pretend to initialize the object with itself, then make sure
13789       // it can be destroyed later.
13790       QualType initType = Context.getExceptionObjectType(ExDeclType);
13791 
13792       InitializedEntity entity =
13793         InitializedEntity::InitializeVariable(ExDecl);
13794       InitializationKind initKind =
13795         InitializationKind::CreateCopy(Loc, SourceLocation());
13796 
13797       Expr *opaqueValue =
13798         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13799       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13800       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13801       if (result.isInvalid())
13802         Invalid = true;
13803       else {
13804         // If the constructor used was non-trivial, set this as the
13805         // "initializer".
13806         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13807         if (!construct->getConstructor()->isTrivial()) {
13808           Expr *init = MaybeCreateExprWithCleanups(construct);
13809           ExDecl->setInit(init);
13810         }
13811 
13812         // And make sure it's destructable.
13813         FinalizeVarWithDestructor(ExDecl, recordType);
13814       }
13815     }
13816   }
13817 
13818   if (Invalid)
13819     ExDecl->setInvalidDecl();
13820 
13821   return ExDecl;
13822 }
13823 
13824 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13825 /// handler.
13826 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13827   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13828   bool Invalid = D.isInvalidType();
13829 
13830   // Check for unexpanded parameter packs.
13831   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13832                                       UPPC_ExceptionType)) {
13833     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13834                                              D.getIdentifierLoc());
13835     Invalid = true;
13836   }
13837 
13838   IdentifierInfo *II = D.getIdentifier();
13839   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13840                                              LookupOrdinaryName,
13841                                              ForVisibleRedeclaration)) {
13842     // The scope should be freshly made just for us. There is just no way
13843     // it contains any previous declaration, except for function parameters in
13844     // a function-try-block's catch statement.
13845     assert(!S->isDeclScope(PrevDecl));
13846     if (isDeclInScope(PrevDecl, CurContext, S)) {
13847       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13848         << D.getIdentifier();
13849       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13850       Invalid = true;
13851     } else if (PrevDecl->isTemplateParameter())
13852       // Maybe we will complain about the shadowed template parameter.
13853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13854   }
13855 
13856   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13857     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13858       << D.getCXXScopeSpec().getRange();
13859     Invalid = true;
13860   }
13861 
13862   VarDecl *ExDecl = BuildExceptionDeclaration(
13863       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13864   if (Invalid)
13865     ExDecl->setInvalidDecl();
13866 
13867   // Add the exception declaration into this scope.
13868   if (II)
13869     PushOnScopeChains(ExDecl, S);
13870   else
13871     CurContext->addDecl(ExDecl);
13872 
13873   ProcessDeclAttributes(S, ExDecl, D);
13874   return ExDecl;
13875 }
13876 
13877 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13878                                          Expr *AssertExpr,
13879                                          Expr *AssertMessageExpr,
13880                                          SourceLocation RParenLoc) {
13881   StringLiteral *AssertMessage =
13882       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13883 
13884   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13885     return nullptr;
13886 
13887   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13888                                       AssertMessage, RParenLoc, false);
13889 }
13890 
13891 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13892                                          Expr *AssertExpr,
13893                                          StringLiteral *AssertMessage,
13894                                          SourceLocation RParenLoc,
13895                                          bool Failed) {
13896   assert(AssertExpr != nullptr && "Expected non-null condition");
13897   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13898       !Failed) {
13899     // In a static_assert-declaration, the constant-expression shall be a
13900     // constant expression that can be contextually converted to bool.
13901     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13902     if (Converted.isInvalid())
13903       Failed = true;
13904     else
13905       Converted = ConstantExpr::Create(Context, Converted.get());
13906 
13907     llvm::APSInt Cond;
13908     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13909           diag::err_static_assert_expression_is_not_constant,
13910           /*AllowFold=*/false).isInvalid())
13911       Failed = true;
13912 
13913     if (!Failed && !Cond) {
13914       SmallString<256> MsgBuffer;
13915       llvm::raw_svector_ostream Msg(MsgBuffer);
13916       if (AssertMessage)
13917         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13918 
13919       Expr *InnerCond = nullptr;
13920       std::string InnerCondDescription;
13921       std::tie(InnerCond, InnerCondDescription) =
13922         findFailedBooleanCondition(Converted.get());
13923       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13924                     && !isa<IntegerLiteral>(InnerCond)) {
13925         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13926           << InnerCondDescription << !AssertMessage
13927           << Msg.str() << InnerCond->getSourceRange();
13928       } else {
13929         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13930           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13931       }
13932       Failed = true;
13933     }
13934   }
13935 
13936   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13937                                                   /*DiscardedValue*/false,
13938                                                   /*IsConstexpr*/true);
13939   if (FullAssertExpr.isInvalid())
13940     Failed = true;
13941   else
13942     AssertExpr = FullAssertExpr.get();
13943 
13944   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13945                                         AssertExpr, AssertMessage, RParenLoc,
13946                                         Failed);
13947 
13948   CurContext->addDecl(Decl);
13949   return Decl;
13950 }
13951 
13952 /// Perform semantic analysis of the given friend type declaration.
13953 ///
13954 /// \returns A friend declaration that.
13955 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13956                                       SourceLocation FriendLoc,
13957                                       TypeSourceInfo *TSInfo) {
13958   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13959 
13960   QualType T = TSInfo->getType();
13961   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13962 
13963   // C++03 [class.friend]p2:
13964   //   An elaborated-type-specifier shall be used in a friend declaration
13965   //   for a class.*
13966   //
13967   //   * The class-key of the elaborated-type-specifier is required.
13968   if (!CodeSynthesisContexts.empty()) {
13969     // Do not complain about the form of friend template types during any kind
13970     // of code synthesis. For template instantiation, we will have complained
13971     // when the template was defined.
13972   } else {
13973     if (!T->isElaboratedTypeSpecifier()) {
13974       // If we evaluated the type to a record type, suggest putting
13975       // a tag in front.
13976       if (const RecordType *RT = T->getAs<RecordType>()) {
13977         RecordDecl *RD = RT->getDecl();
13978 
13979         SmallString<16> InsertionText(" ");
13980         InsertionText += RD->getKindName();
13981 
13982         Diag(TypeRange.getBegin(),
13983              getLangOpts().CPlusPlus11 ?
13984                diag::warn_cxx98_compat_unelaborated_friend_type :
13985                diag::ext_unelaborated_friend_type)
13986           << (unsigned) RD->getTagKind()
13987           << T
13988           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13989                                         InsertionText);
13990       } else {
13991         Diag(FriendLoc,
13992              getLangOpts().CPlusPlus11 ?
13993                diag::warn_cxx98_compat_nonclass_type_friend :
13994                diag::ext_nonclass_type_friend)
13995           << T
13996           << TypeRange;
13997       }
13998     } else if (T->getAs<EnumType>()) {
13999       Diag(FriendLoc,
14000            getLangOpts().CPlusPlus11 ?
14001              diag::warn_cxx98_compat_enum_friend :
14002              diag::ext_enum_friend)
14003         << T
14004         << TypeRange;
14005     }
14006 
14007     // C++11 [class.friend]p3:
14008     //   A friend declaration that does not declare a function shall have one
14009     //   of the following forms:
14010     //     friend elaborated-type-specifier ;
14011     //     friend simple-type-specifier ;
14012     //     friend typename-specifier ;
14013     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14014       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14015   }
14016 
14017   //   If the type specifier in a friend declaration designates a (possibly
14018   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14019   //   the friend declaration is ignored.
14020   return FriendDecl::Create(Context, CurContext,
14021                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14022                             FriendLoc);
14023 }
14024 
14025 /// Handle a friend tag declaration where the scope specifier was
14026 /// templated.
14027 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14028                                     unsigned TagSpec, SourceLocation TagLoc,
14029                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14030                                     SourceLocation NameLoc,
14031                                     const ParsedAttributesView &Attr,
14032                                     MultiTemplateParamsArg TempParamLists) {
14033   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14034 
14035   bool IsMemberSpecialization = false;
14036   bool Invalid = false;
14037 
14038   if (TemplateParameterList *TemplateParams =
14039           MatchTemplateParametersToScopeSpecifier(
14040               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14041               IsMemberSpecialization, Invalid)) {
14042     if (TemplateParams->size() > 0) {
14043       // This is a declaration of a class template.
14044       if (Invalid)
14045         return nullptr;
14046 
14047       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14048                                 NameLoc, Attr, TemplateParams, AS_public,
14049                                 /*ModulePrivateLoc=*/SourceLocation(),
14050                                 FriendLoc, TempParamLists.size() - 1,
14051                                 TempParamLists.data()).get();
14052     } else {
14053       // The "template<>" header is extraneous.
14054       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14055         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14056       IsMemberSpecialization = true;
14057     }
14058   }
14059 
14060   if (Invalid) return nullptr;
14061 
14062   bool isAllExplicitSpecializations = true;
14063   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14064     if (TempParamLists[I]->size()) {
14065       isAllExplicitSpecializations = false;
14066       break;
14067     }
14068   }
14069 
14070   // FIXME: don't ignore attributes.
14071 
14072   // If it's explicit specializations all the way down, just forget
14073   // about the template header and build an appropriate non-templated
14074   // friend.  TODO: for source fidelity, remember the headers.
14075   if (isAllExplicitSpecializations) {
14076     if (SS.isEmpty()) {
14077       bool Owned = false;
14078       bool IsDependent = false;
14079       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14080                       Attr, AS_public,
14081                       /*ModulePrivateLoc=*/SourceLocation(),
14082                       MultiTemplateParamsArg(), Owned, IsDependent,
14083                       /*ScopedEnumKWLoc=*/SourceLocation(),
14084                       /*ScopedEnumUsesClassTag=*/false,
14085                       /*UnderlyingType=*/TypeResult(),
14086                       /*IsTypeSpecifier=*/false,
14087                       /*IsTemplateParamOrArg=*/false);
14088     }
14089 
14090     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14091     ElaboratedTypeKeyword Keyword
14092       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14093     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14094                                    *Name, NameLoc);
14095     if (T.isNull())
14096       return nullptr;
14097 
14098     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14099     if (isa<DependentNameType>(T)) {
14100       DependentNameTypeLoc TL =
14101           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14102       TL.setElaboratedKeywordLoc(TagLoc);
14103       TL.setQualifierLoc(QualifierLoc);
14104       TL.setNameLoc(NameLoc);
14105     } else {
14106       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14107       TL.setElaboratedKeywordLoc(TagLoc);
14108       TL.setQualifierLoc(QualifierLoc);
14109       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14110     }
14111 
14112     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14113                                             TSI, FriendLoc, TempParamLists);
14114     Friend->setAccess(AS_public);
14115     CurContext->addDecl(Friend);
14116     return Friend;
14117   }
14118 
14119   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14120 
14121 
14122 
14123   // Handle the case of a templated-scope friend class.  e.g.
14124   //   template <class T> class A<T>::B;
14125   // FIXME: we don't support these right now.
14126   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14127     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14128   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14129   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14130   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14131   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14132   TL.setElaboratedKeywordLoc(TagLoc);
14133   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14134   TL.setNameLoc(NameLoc);
14135 
14136   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14137                                           TSI, FriendLoc, TempParamLists);
14138   Friend->setAccess(AS_public);
14139   Friend->setUnsupportedFriend(true);
14140   CurContext->addDecl(Friend);
14141   return Friend;
14142 }
14143 
14144 /// Handle a friend type declaration.  This works in tandem with
14145 /// ActOnTag.
14146 ///
14147 /// Notes on friend class templates:
14148 ///
14149 /// We generally treat friend class declarations as if they were
14150 /// declaring a class.  So, for example, the elaborated type specifier
14151 /// in a friend declaration is required to obey the restrictions of a
14152 /// class-head (i.e. no typedefs in the scope chain), template
14153 /// parameters are required to match up with simple template-ids, &c.
14154 /// However, unlike when declaring a template specialization, it's
14155 /// okay to refer to a template specialization without an empty
14156 /// template parameter declaration, e.g.
14157 ///   friend class A<T>::B<unsigned>;
14158 /// We permit this as a special case; if there are any template
14159 /// parameters present at all, require proper matching, i.e.
14160 ///   template <> template \<class T> friend class A<int>::B;
14161 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14162                                 MultiTemplateParamsArg TempParams) {
14163   SourceLocation Loc = DS.getBeginLoc();
14164 
14165   assert(DS.isFriendSpecified());
14166   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14167 
14168   // C++ [class.friend]p3:
14169   // A friend declaration that does not declare a function shall have one of
14170   // the following forms:
14171   //     friend elaborated-type-specifier ;
14172   //     friend simple-type-specifier ;
14173   //     friend typename-specifier ;
14174   //
14175   // Any declaration with a type qualifier does not have that form. (It's
14176   // legal to specify a qualified type as a friend, you just can't write the
14177   // keywords.)
14178   if (DS.getTypeQualifiers()) {
14179     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14180       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14181     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14182       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14183     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14184       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14185     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14186       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14187     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14188       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14189   }
14190 
14191   // Try to convert the decl specifier to a type.  This works for
14192   // friend templates because ActOnTag never produces a ClassTemplateDecl
14193   // for a TUK_Friend.
14194   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14195   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14196   QualType T = TSI->getType();
14197   if (TheDeclarator.isInvalidType())
14198     return nullptr;
14199 
14200   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14201     return nullptr;
14202 
14203   // This is definitely an error in C++98.  It's probably meant to
14204   // be forbidden in C++0x, too, but the specification is just
14205   // poorly written.
14206   //
14207   // The problem is with declarations like the following:
14208   //   template <T> friend A<T>::foo;
14209   // where deciding whether a class C is a friend or not now hinges
14210   // on whether there exists an instantiation of A that causes
14211   // 'foo' to equal C.  There are restrictions on class-heads
14212   // (which we declare (by fiat) elaborated friend declarations to
14213   // be) that makes this tractable.
14214   //
14215   // FIXME: handle "template <> friend class A<T>;", which
14216   // is possibly well-formed?  Who even knows?
14217   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14218     Diag(Loc, diag::err_tagless_friend_type_template)
14219       << DS.getSourceRange();
14220     return nullptr;
14221   }
14222 
14223   // C++98 [class.friend]p1: A friend of a class is a function
14224   //   or class that is not a member of the class . . .
14225   // This is fixed in DR77, which just barely didn't make the C++03
14226   // deadline.  It's also a very silly restriction that seriously
14227   // affects inner classes and which nobody else seems to implement;
14228   // thus we never diagnose it, not even in -pedantic.
14229   //
14230   // But note that we could warn about it: it's always useless to
14231   // friend one of your own members (it's not, however, worthless to
14232   // friend a member of an arbitrary specialization of your template).
14233 
14234   Decl *D;
14235   if (!TempParams.empty())
14236     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14237                                    TempParams,
14238                                    TSI,
14239                                    DS.getFriendSpecLoc());
14240   else
14241     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14242 
14243   if (!D)
14244     return nullptr;
14245 
14246   D->setAccess(AS_public);
14247   CurContext->addDecl(D);
14248 
14249   return D;
14250 }
14251 
14252 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14253                                         MultiTemplateParamsArg TemplateParams) {
14254   const DeclSpec &DS = D.getDeclSpec();
14255 
14256   assert(DS.isFriendSpecified());
14257   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14258 
14259   SourceLocation Loc = D.getIdentifierLoc();
14260   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14261 
14262   // C++ [class.friend]p1
14263   //   A friend of a class is a function or class....
14264   // Note that this sees through typedefs, which is intended.
14265   // It *doesn't* see through dependent types, which is correct
14266   // according to [temp.arg.type]p3:
14267   //   If a declaration acquires a function type through a
14268   //   type dependent on a template-parameter and this causes
14269   //   a declaration that does not use the syntactic form of a
14270   //   function declarator to have a function type, the program
14271   //   is ill-formed.
14272   if (!TInfo->getType()->isFunctionType()) {
14273     Diag(Loc, diag::err_unexpected_friend);
14274 
14275     // It might be worthwhile to try to recover by creating an
14276     // appropriate declaration.
14277     return nullptr;
14278   }
14279 
14280   // C++ [namespace.memdef]p3
14281   //  - If a friend declaration in a non-local class first declares a
14282   //    class or function, the friend class or function is a member
14283   //    of the innermost enclosing namespace.
14284   //  - The name of the friend is not found by simple name lookup
14285   //    until a matching declaration is provided in that namespace
14286   //    scope (either before or after the class declaration granting
14287   //    friendship).
14288   //  - If a friend function is called, its name may be found by the
14289   //    name lookup that considers functions from namespaces and
14290   //    classes associated with the types of the function arguments.
14291   //  - When looking for a prior declaration of a class or a function
14292   //    declared as a friend, scopes outside the innermost enclosing
14293   //    namespace scope are not considered.
14294 
14295   CXXScopeSpec &SS = D.getCXXScopeSpec();
14296   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14297   DeclarationName Name = NameInfo.getName();
14298   assert(Name);
14299 
14300   // Check for unexpanded parameter packs.
14301   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14302       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14303       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14304     return nullptr;
14305 
14306   // The context we found the declaration in, or in which we should
14307   // create the declaration.
14308   DeclContext *DC;
14309   Scope *DCScope = S;
14310   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14311                         ForExternalRedeclaration);
14312 
14313   // There are five cases here.
14314   //   - There's no scope specifier and we're in a local class. Only look
14315   //     for functions declared in the immediately-enclosing block scope.
14316   // We recover from invalid scope qualifiers as if they just weren't there.
14317   FunctionDecl *FunctionContainingLocalClass = nullptr;
14318   if ((SS.isInvalid() || !SS.isSet()) &&
14319       (FunctionContainingLocalClass =
14320            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14321     // C++11 [class.friend]p11:
14322     //   If a friend declaration appears in a local class and the name
14323     //   specified is an unqualified name, a prior declaration is
14324     //   looked up without considering scopes that are outside the
14325     //   innermost enclosing non-class scope. For a friend function
14326     //   declaration, if there is no prior declaration, the program is
14327     //   ill-formed.
14328 
14329     // Find the innermost enclosing non-class scope. This is the block
14330     // scope containing the local class definition (or for a nested class,
14331     // the outer local class).
14332     DCScope = S->getFnParent();
14333 
14334     // Look up the function name in the scope.
14335     Previous.clear(LookupLocalFriendName);
14336     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14337 
14338     if (!Previous.empty()) {
14339       // All possible previous declarations must have the same context:
14340       // either they were declared at block scope or they are members of
14341       // one of the enclosing local classes.
14342       DC = Previous.getRepresentativeDecl()->getDeclContext();
14343     } else {
14344       // This is ill-formed, but provide the context that we would have
14345       // declared the function in, if we were permitted to, for error recovery.
14346       DC = FunctionContainingLocalClass;
14347     }
14348     adjustContextForLocalExternDecl(DC);
14349 
14350     // C++ [class.friend]p6:
14351     //   A function can be defined in a friend declaration of a class if and
14352     //   only if the class is a non-local class (9.8), the function name is
14353     //   unqualified, and the function has namespace scope.
14354     if (D.isFunctionDefinition()) {
14355       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14356     }
14357 
14358   //   - There's no scope specifier, in which case we just go to the
14359   //     appropriate scope and look for a function or function template
14360   //     there as appropriate.
14361   } else if (SS.isInvalid() || !SS.isSet()) {
14362     // C++11 [namespace.memdef]p3:
14363     //   If the name in a friend declaration is neither qualified nor
14364     //   a template-id and the declaration is a function or an
14365     //   elaborated-type-specifier, the lookup to determine whether
14366     //   the entity has been previously declared shall not consider
14367     //   any scopes outside the innermost enclosing namespace.
14368     bool isTemplateId =
14369         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14370 
14371     // Find the appropriate context according to the above.
14372     DC = CurContext;
14373 
14374     // Skip class contexts.  If someone can cite chapter and verse
14375     // for this behavior, that would be nice --- it's what GCC and
14376     // EDG do, and it seems like a reasonable intent, but the spec
14377     // really only says that checks for unqualified existing
14378     // declarations should stop at the nearest enclosing namespace,
14379     // not that they should only consider the nearest enclosing
14380     // namespace.
14381     while (DC->isRecord())
14382       DC = DC->getParent();
14383 
14384     DeclContext *LookupDC = DC;
14385     while (LookupDC->isTransparentContext())
14386       LookupDC = LookupDC->getParent();
14387 
14388     while (true) {
14389       LookupQualifiedName(Previous, LookupDC);
14390 
14391       if (!Previous.empty()) {
14392         DC = LookupDC;
14393         break;
14394       }
14395 
14396       if (isTemplateId) {
14397         if (isa<TranslationUnitDecl>(LookupDC)) break;
14398       } else {
14399         if (LookupDC->isFileContext()) break;
14400       }
14401       LookupDC = LookupDC->getParent();
14402     }
14403 
14404     DCScope = getScopeForDeclContext(S, DC);
14405 
14406   //   - There's a non-dependent scope specifier, in which case we
14407   //     compute it and do a previous lookup there for a function
14408   //     or function template.
14409   } else if (!SS.getScopeRep()->isDependent()) {
14410     DC = computeDeclContext(SS);
14411     if (!DC) return nullptr;
14412 
14413     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14414 
14415     LookupQualifiedName(Previous, DC);
14416 
14417     // Ignore things found implicitly in the wrong scope.
14418     // TODO: better diagnostics for this case.  Suggesting the right
14419     // qualified scope would be nice...
14420     LookupResult::Filter F = Previous.makeFilter();
14421     while (F.hasNext()) {
14422       NamedDecl *D = F.next();
14423       if (!DC->InEnclosingNamespaceSetOf(
14424               D->getDeclContext()->getRedeclContext()))
14425         F.erase();
14426     }
14427     F.done();
14428 
14429     if (Previous.empty()) {
14430       D.setInvalidType();
14431       Diag(Loc, diag::err_qualified_friend_not_found)
14432           << Name << TInfo->getType();
14433       return nullptr;
14434     }
14435 
14436     // C++ [class.friend]p1: A friend of a class is a function or
14437     //   class that is not a member of the class . . .
14438     if (DC->Equals(CurContext))
14439       Diag(DS.getFriendSpecLoc(),
14440            getLangOpts().CPlusPlus11 ?
14441              diag::warn_cxx98_compat_friend_is_member :
14442              diag::err_friend_is_member);
14443 
14444     if (D.isFunctionDefinition()) {
14445       // C++ [class.friend]p6:
14446       //   A function can be defined in a friend declaration of a class if and
14447       //   only if the class is a non-local class (9.8), the function name is
14448       //   unqualified, and the function has namespace scope.
14449       SemaDiagnosticBuilder DB
14450         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14451 
14452       DB << SS.getScopeRep();
14453       if (DC->isFileContext())
14454         DB << FixItHint::CreateRemoval(SS.getRange());
14455       SS.clear();
14456     }
14457 
14458   //   - There's a scope specifier that does not match any template
14459   //     parameter lists, in which case we use some arbitrary context,
14460   //     create a method or method template, and wait for instantiation.
14461   //   - There's a scope specifier that does match some template
14462   //     parameter lists, which we don't handle right now.
14463   } else {
14464     if (D.isFunctionDefinition()) {
14465       // C++ [class.friend]p6:
14466       //   A function can be defined in a friend declaration of a class if and
14467       //   only if the class is a non-local class (9.8), the function name is
14468       //   unqualified, and the function has namespace scope.
14469       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14470         << SS.getScopeRep();
14471     }
14472 
14473     DC = CurContext;
14474     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14475   }
14476 
14477   if (!DC->isRecord()) {
14478     int DiagArg = -1;
14479     switch (D.getName().getKind()) {
14480     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14481     case UnqualifiedIdKind::IK_ConstructorName:
14482       DiagArg = 0;
14483       break;
14484     case UnqualifiedIdKind::IK_DestructorName:
14485       DiagArg = 1;
14486       break;
14487     case UnqualifiedIdKind::IK_ConversionFunctionId:
14488       DiagArg = 2;
14489       break;
14490     case UnqualifiedIdKind::IK_DeductionGuideName:
14491       DiagArg = 3;
14492       break;
14493     case UnqualifiedIdKind::IK_Identifier:
14494     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14495     case UnqualifiedIdKind::IK_LiteralOperatorId:
14496     case UnqualifiedIdKind::IK_OperatorFunctionId:
14497     case UnqualifiedIdKind::IK_TemplateId:
14498       break;
14499     }
14500     // This implies that it has to be an operator or function.
14501     if (DiagArg >= 0) {
14502       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14503       return nullptr;
14504     }
14505   }
14506 
14507   // FIXME: This is an egregious hack to cope with cases where the scope stack
14508   // does not contain the declaration context, i.e., in an out-of-line
14509   // definition of a class.
14510   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14511   if (!DCScope) {
14512     FakeDCScope.setEntity(DC);
14513     DCScope = &FakeDCScope;
14514   }
14515 
14516   bool AddToScope = true;
14517   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14518                                           TemplateParams, AddToScope);
14519   if (!ND) return nullptr;
14520 
14521   assert(ND->getLexicalDeclContext() == CurContext);
14522 
14523   // If we performed typo correction, we might have added a scope specifier
14524   // and changed the decl context.
14525   DC = ND->getDeclContext();
14526 
14527   // Add the function declaration to the appropriate lookup tables,
14528   // adjusting the redeclarations list as necessary.  We don't
14529   // want to do this yet if the friending class is dependent.
14530   //
14531   // Also update the scope-based lookup if the target context's
14532   // lookup context is in lexical scope.
14533   if (!CurContext->isDependentContext()) {
14534     DC = DC->getRedeclContext();
14535     DC->makeDeclVisibleInContext(ND);
14536     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14537       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14538   }
14539 
14540   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14541                                        D.getIdentifierLoc(), ND,
14542                                        DS.getFriendSpecLoc());
14543   FrD->setAccess(AS_public);
14544   CurContext->addDecl(FrD);
14545 
14546   if (ND->isInvalidDecl()) {
14547     FrD->setInvalidDecl();
14548   } else {
14549     if (DC->isRecord()) CheckFriendAccess(ND);
14550 
14551     FunctionDecl *FD;
14552     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14553       FD = FTD->getTemplatedDecl();
14554     else
14555       FD = cast<FunctionDecl>(ND);
14556 
14557     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14558     // default argument expression, that declaration shall be a definition
14559     // and shall be the only declaration of the function or function
14560     // template in the translation unit.
14561     if (functionDeclHasDefaultArgument(FD)) {
14562       // We can't look at FD->getPreviousDecl() because it may not have been set
14563       // if we're in a dependent context. If the function is known to be a
14564       // redeclaration, we will have narrowed Previous down to the right decl.
14565       if (D.isRedeclaration()) {
14566         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14567         Diag(Previous.getRepresentativeDecl()->getLocation(),
14568              diag::note_previous_declaration);
14569       } else if (!D.isFunctionDefinition())
14570         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14571     }
14572 
14573     // Mark templated-scope function declarations as unsupported.
14574     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14575       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14576         << SS.getScopeRep() << SS.getRange()
14577         << cast<CXXRecordDecl>(CurContext);
14578       FrD->setUnsupportedFriend(true);
14579     }
14580   }
14581 
14582   return ND;
14583 }
14584 
14585 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14586   AdjustDeclIfTemplate(Dcl);
14587 
14588   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14589   if (!Fn) {
14590     Diag(DelLoc, diag::err_deleted_non_function);
14591     return;
14592   }
14593 
14594   // Deleted function does not have a body.
14595   Fn->setWillHaveBody(false);
14596 
14597   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14598     // Don't consider the implicit declaration we generate for explicit
14599     // specializations. FIXME: Do not generate these implicit declarations.
14600     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14601          Prev->getPreviousDecl()) &&
14602         !Prev->isDefined()) {
14603       Diag(DelLoc, diag::err_deleted_decl_not_first);
14604       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14605            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14606                               : diag::note_previous_declaration);
14607     }
14608     // If the declaration wasn't the first, we delete the function anyway for
14609     // recovery.
14610     Fn = Fn->getCanonicalDecl();
14611   }
14612 
14613   // dllimport/dllexport cannot be deleted.
14614   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14615     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14616     Fn->setInvalidDecl();
14617   }
14618 
14619   if (Fn->isDeleted())
14620     return;
14621 
14622   // See if we're deleting a function which is already known to override a
14623   // non-deleted virtual function.
14624   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14625     bool IssuedDiagnostic = false;
14626     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14627       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14628         if (!IssuedDiagnostic) {
14629           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14630           IssuedDiagnostic = true;
14631         }
14632         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14633       }
14634     }
14635     // If this function was implicitly deleted because it was defaulted,
14636     // explain why it was deleted.
14637     if (IssuedDiagnostic && MD->isDefaulted())
14638       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14639                                 /*Diagnose*/true);
14640   }
14641 
14642   // C++11 [basic.start.main]p3:
14643   //   A program that defines main as deleted [...] is ill-formed.
14644   if (Fn->isMain())
14645     Diag(DelLoc, diag::err_deleted_main);
14646 
14647   // C++11 [dcl.fct.def.delete]p4:
14648   //  A deleted function is implicitly inline.
14649   Fn->setImplicitlyInline();
14650   Fn->setDeletedAsWritten();
14651 }
14652 
14653 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14654   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14655 
14656   if (MD) {
14657     if (MD->getParent()->isDependentType()) {
14658       MD->setDefaulted();
14659       MD->setExplicitlyDefaulted();
14660       return;
14661     }
14662 
14663     CXXSpecialMember Member = getSpecialMember(MD);
14664     if (Member == CXXInvalid) {
14665       if (!MD->isInvalidDecl())
14666         Diag(DefaultLoc, diag::err_default_special_members);
14667       return;
14668     }
14669 
14670     MD->setDefaulted();
14671     MD->setExplicitlyDefaulted();
14672 
14673     // Unset that we will have a body for this function. We might not,
14674     // if it turns out to be trivial, and we don't need this marking now
14675     // that we've marked it as defaulted.
14676     MD->setWillHaveBody(false);
14677 
14678     // If this definition appears within the record, do the checking when
14679     // the record is complete.
14680     const FunctionDecl *Primary = MD;
14681     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14682       // Ask the template instantiation pattern that actually had the
14683       // '= default' on it.
14684       Primary = Pattern;
14685 
14686     // If the method was defaulted on its first declaration, we will have
14687     // already performed the checking in CheckCompletedCXXClass. Such a
14688     // declaration doesn't trigger an implicit definition.
14689     if (Primary->getCanonicalDecl()->isDefaulted())
14690       return;
14691 
14692     CheckExplicitlyDefaultedSpecialMember(MD);
14693 
14694     if (!MD->isInvalidDecl())
14695       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14696   } else {
14697     Diag(DefaultLoc, diag::err_default_special_members);
14698   }
14699 }
14700 
14701 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14702   for (Stmt *SubStmt : S->children()) {
14703     if (!SubStmt)
14704       continue;
14705     if (isa<ReturnStmt>(SubStmt))
14706       Self.Diag(SubStmt->getBeginLoc(),
14707                 diag::err_return_in_constructor_handler);
14708     if (!isa<Expr>(SubStmt))
14709       SearchForReturnInStmt(Self, SubStmt);
14710   }
14711 }
14712 
14713 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14714   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14715     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14716     SearchForReturnInStmt(*this, Handler);
14717   }
14718 }
14719 
14720 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14721                                              const CXXMethodDecl *Old) {
14722   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14723   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14724 
14725   if (OldFT->hasExtParameterInfos()) {
14726     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14727       // A parameter of the overriding method should be annotated with noescape
14728       // if the corresponding parameter of the overridden method is annotated.
14729       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14730           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14731         Diag(New->getParamDecl(I)->getLocation(),
14732              diag::warn_overriding_method_missing_noescape);
14733         Diag(Old->getParamDecl(I)->getLocation(),
14734              diag::note_overridden_marked_noescape);
14735       }
14736   }
14737 
14738   // Virtual overrides must have the same code_seg.
14739   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14740   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14741   if ((NewCSA || OldCSA) &&
14742       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14743     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14744     Diag(Old->getLocation(), diag::note_previous_declaration);
14745     return true;
14746   }
14747 
14748   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14749 
14750   // If the calling conventions match, everything is fine
14751   if (NewCC == OldCC)
14752     return false;
14753 
14754   // If the calling conventions mismatch because the new function is static,
14755   // suppress the calling convention mismatch error; the error about static
14756   // function override (err_static_overrides_virtual from
14757   // Sema::CheckFunctionDeclaration) is more clear.
14758   if (New->getStorageClass() == SC_Static)
14759     return false;
14760 
14761   Diag(New->getLocation(),
14762        diag::err_conflicting_overriding_cc_attributes)
14763     << New->getDeclName() << New->getType() << Old->getType();
14764   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14765   return true;
14766 }
14767 
14768 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14769                                              const CXXMethodDecl *Old) {
14770   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14771   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14772 
14773   if (Context.hasSameType(NewTy, OldTy) ||
14774       NewTy->isDependentType() || OldTy->isDependentType())
14775     return false;
14776 
14777   // Check if the return types are covariant
14778   QualType NewClassTy, OldClassTy;
14779 
14780   /// Both types must be pointers or references to classes.
14781   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14782     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14783       NewClassTy = NewPT->getPointeeType();
14784       OldClassTy = OldPT->getPointeeType();
14785     }
14786   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14787     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14788       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14789         NewClassTy = NewRT->getPointeeType();
14790         OldClassTy = OldRT->getPointeeType();
14791       }
14792     }
14793   }
14794 
14795   // The return types aren't either both pointers or references to a class type.
14796   if (NewClassTy.isNull()) {
14797     Diag(New->getLocation(),
14798          diag::err_different_return_type_for_overriding_virtual_function)
14799         << New->getDeclName() << NewTy << OldTy
14800         << New->getReturnTypeSourceRange();
14801     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14802         << Old->getReturnTypeSourceRange();
14803 
14804     return true;
14805   }
14806 
14807   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14808     // C++14 [class.virtual]p8:
14809     //   If the class type in the covariant return type of D::f differs from
14810     //   that of B::f, the class type in the return type of D::f shall be
14811     //   complete at the point of declaration of D::f or shall be the class
14812     //   type D.
14813     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14814       if (!RT->isBeingDefined() &&
14815           RequireCompleteType(New->getLocation(), NewClassTy,
14816                               diag::err_covariant_return_incomplete,
14817                               New->getDeclName()))
14818         return true;
14819     }
14820 
14821     // Check if the new class derives from the old class.
14822     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14823       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14824           << New->getDeclName() << NewTy << OldTy
14825           << New->getReturnTypeSourceRange();
14826       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14827           << Old->getReturnTypeSourceRange();
14828       return true;
14829     }
14830 
14831     // Check if we the conversion from derived to base is valid.
14832     if (CheckDerivedToBaseConversion(
14833             NewClassTy, OldClassTy,
14834             diag::err_covariant_return_inaccessible_base,
14835             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14836             New->getLocation(), New->getReturnTypeSourceRange(),
14837             New->getDeclName(), nullptr)) {
14838       // FIXME: this note won't trigger for delayed access control
14839       // diagnostics, and it's impossible to get an undelayed error
14840       // here from access control during the original parse because
14841       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14842       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14843           << Old->getReturnTypeSourceRange();
14844       return true;
14845     }
14846   }
14847 
14848   // The qualifiers of the return types must be the same.
14849   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14850     Diag(New->getLocation(),
14851          diag::err_covariant_return_type_different_qualifications)
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 
14860   // The new class type must have the same or less qualifiers as the old type.
14861   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14862     Diag(New->getLocation(),
14863          diag::err_covariant_return_type_class_type_more_qualified)
14864         << New->getDeclName() << NewTy << OldTy
14865         << New->getReturnTypeSourceRange();
14866     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14867         << Old->getReturnTypeSourceRange();
14868     return true;
14869   }
14870 
14871   return false;
14872 }
14873 
14874 /// Mark the given method pure.
14875 ///
14876 /// \param Method the method to be marked pure.
14877 ///
14878 /// \param InitRange the source range that covers the "0" initializer.
14879 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14880   SourceLocation EndLoc = InitRange.getEnd();
14881   if (EndLoc.isValid())
14882     Method->setRangeEnd(EndLoc);
14883 
14884   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14885     Method->setPure();
14886     return false;
14887   }
14888 
14889   if (!Method->isInvalidDecl())
14890     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14891       << Method->getDeclName() << InitRange;
14892   return true;
14893 }
14894 
14895 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14896   if (D->getFriendObjectKind())
14897     Diag(D->getLocation(), diag::err_pure_friend);
14898   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14899     CheckPureMethod(M, ZeroLoc);
14900   else
14901     Diag(D->getLocation(), diag::err_illegal_initializer);
14902 }
14903 
14904 /// Determine whether the given declaration is a global variable or
14905 /// static data member.
14906 static bool isNonlocalVariable(const Decl *D) {
14907   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14908     return Var->hasGlobalStorage();
14909 
14910   return false;
14911 }
14912 
14913 /// Invoked when we are about to parse an initializer for the declaration
14914 /// 'Dcl'.
14915 ///
14916 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14917 /// static data member of class X, names should be looked up in the scope of
14918 /// class X. If the declaration had a scope specifier, a scope will have
14919 /// been created and passed in for this purpose. Otherwise, S will be null.
14920 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14921   // If there is no declaration, there was an error parsing it.
14922   if (!D || D->isInvalidDecl())
14923     return;
14924 
14925   // We will always have a nested name specifier here, but this declaration
14926   // might not be out of line if the specifier names the current namespace:
14927   //   extern int n;
14928   //   int ::n = 0;
14929   if (S && D->isOutOfLine())
14930     EnterDeclaratorContext(S, D->getDeclContext());
14931 
14932   // If we are parsing the initializer for a static data member, push a
14933   // new expression evaluation context that is associated with this static
14934   // data member.
14935   if (isNonlocalVariable(D))
14936     PushExpressionEvaluationContext(
14937         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14938 }
14939 
14940 /// Invoked after we are finished parsing an initializer for the declaration D.
14941 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14942   // If there is no declaration, there was an error parsing it.
14943   if (!D || D->isInvalidDecl())
14944     return;
14945 
14946   if (isNonlocalVariable(D))
14947     PopExpressionEvaluationContext();
14948 
14949   if (S && D->isOutOfLine())
14950     ExitDeclaratorContext(S);
14951 }
14952 
14953 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14954 /// C++ if/switch/while/for statement.
14955 /// e.g: "if (int x = f()) {...}"
14956 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14957   // C++ 6.4p2:
14958   // The declarator shall not specify a function or an array.
14959   // The type-specifier-seq shall not contain typedef and shall not declare a
14960   // new class or enumeration.
14961   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14962          "Parser allowed 'typedef' as storage class of condition decl.");
14963 
14964   Decl *Dcl = ActOnDeclarator(S, D);
14965   if (!Dcl)
14966     return true;
14967 
14968   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14969     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14970       << D.getSourceRange();
14971     return true;
14972   }
14973 
14974   return Dcl;
14975 }
14976 
14977 void Sema::LoadExternalVTableUses() {
14978   if (!ExternalSource)
14979     return;
14980 
14981   SmallVector<ExternalVTableUse, 4> VTables;
14982   ExternalSource->ReadUsedVTables(VTables);
14983   SmallVector<VTableUse, 4> NewUses;
14984   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14985     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14986       = VTablesUsed.find(VTables[I].Record);
14987     // Even if a definition wasn't required before, it may be required now.
14988     if (Pos != VTablesUsed.end()) {
14989       if (!Pos->second && VTables[I].DefinitionRequired)
14990         Pos->second = true;
14991       continue;
14992     }
14993 
14994     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14995     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14996   }
14997 
14998   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14999 }
15000 
15001 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15002                           bool DefinitionRequired) {
15003   // Ignore any vtable uses in unevaluated operands or for classes that do
15004   // not have a vtable.
15005   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15006       CurContext->isDependentContext() || isUnevaluatedContext())
15007     return;
15008   // Do not mark as used if compiling for the device outside of the target
15009   // region.
15010   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15011       !isInOpenMPDeclareTargetContext() &&
15012       !isInOpenMPTargetExecutionDirective()) {
15013     if (!DefinitionRequired)
15014       MarkVirtualMembersReferenced(Loc, Class);
15015     return;
15016   }
15017 
15018   // Try to insert this class into the map.
15019   LoadExternalVTableUses();
15020   Class = Class->getCanonicalDecl();
15021   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15022     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15023   if (!Pos.second) {
15024     // If we already had an entry, check to see if we are promoting this vtable
15025     // to require a definition. If so, we need to reappend to the VTableUses
15026     // list, since we may have already processed the first entry.
15027     if (DefinitionRequired && !Pos.first->second) {
15028       Pos.first->second = true;
15029     } else {
15030       // Otherwise, we can early exit.
15031       return;
15032     }
15033   } else {
15034     // The Microsoft ABI requires that we perform the destructor body
15035     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15036     // the deleting destructor is emitted with the vtable, not with the
15037     // destructor definition as in the Itanium ABI.
15038     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15039       CXXDestructorDecl *DD = Class->getDestructor();
15040       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15041         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15042           // If this is an out-of-line declaration, marking it referenced will
15043           // not do anything. Manually call CheckDestructor to look up operator
15044           // delete().
15045           ContextRAII SavedContext(*this, DD);
15046           CheckDestructor(DD);
15047         } else {
15048           MarkFunctionReferenced(Loc, Class->getDestructor());
15049         }
15050       }
15051     }
15052   }
15053 
15054   // Local classes need to have their virtual members marked
15055   // immediately. For all other classes, we mark their virtual members
15056   // at the end of the translation unit.
15057   if (Class->isLocalClass())
15058     MarkVirtualMembersReferenced(Loc, Class);
15059   else
15060     VTableUses.push_back(std::make_pair(Class, Loc));
15061 }
15062 
15063 bool Sema::DefineUsedVTables() {
15064   LoadExternalVTableUses();
15065   if (VTableUses.empty())
15066     return false;
15067 
15068   // Note: The VTableUses vector could grow as a result of marking
15069   // the members of a class as "used", so we check the size each
15070   // time through the loop and prefer indices (which are stable) to
15071   // iterators (which are not).
15072   bool DefinedAnything = false;
15073   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15074     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15075     if (!Class)
15076       continue;
15077     TemplateSpecializationKind ClassTSK =
15078         Class->getTemplateSpecializationKind();
15079 
15080     SourceLocation Loc = VTableUses[I].second;
15081 
15082     bool DefineVTable = true;
15083 
15084     // If this class has a key function, but that key function is
15085     // defined in another translation unit, we don't need to emit the
15086     // vtable even though we're using it.
15087     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15088     if (KeyFunction && !KeyFunction->hasBody()) {
15089       // The key function is in another translation unit.
15090       DefineVTable = false;
15091       TemplateSpecializationKind TSK =
15092           KeyFunction->getTemplateSpecializationKind();
15093       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15094              TSK != TSK_ImplicitInstantiation &&
15095              "Instantiations don't have key functions");
15096       (void)TSK;
15097     } else if (!KeyFunction) {
15098       // If we have a class with no key function that is the subject
15099       // of an explicit instantiation declaration, suppress the
15100       // vtable; it will live with the explicit instantiation
15101       // definition.
15102       bool IsExplicitInstantiationDeclaration =
15103           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15104       for (auto R : Class->redecls()) {
15105         TemplateSpecializationKind TSK
15106           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15107         if (TSK == TSK_ExplicitInstantiationDeclaration)
15108           IsExplicitInstantiationDeclaration = true;
15109         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15110           IsExplicitInstantiationDeclaration = false;
15111           break;
15112         }
15113       }
15114 
15115       if (IsExplicitInstantiationDeclaration)
15116         DefineVTable = false;
15117     }
15118 
15119     // The exception specifications for all virtual members may be needed even
15120     // if we are not providing an authoritative form of the vtable in this TU.
15121     // We may choose to emit it available_externally anyway.
15122     if (!DefineVTable) {
15123       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15124       continue;
15125     }
15126 
15127     // Mark all of the virtual members of this class as referenced, so
15128     // that we can build a vtable. Then, tell the AST consumer that a
15129     // vtable for this class is required.
15130     DefinedAnything = true;
15131     MarkVirtualMembersReferenced(Loc, Class);
15132     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15133     if (VTablesUsed[Canonical])
15134       Consumer.HandleVTable(Class);
15135 
15136     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15137     // no key function or the key function is inlined. Don't warn in C++ ABIs
15138     // that lack key functions, since the user won't be able to make one.
15139     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15140         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15141       const FunctionDecl *KeyFunctionDef = nullptr;
15142       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15143                            KeyFunctionDef->isInlined())) {
15144         Diag(Class->getLocation(),
15145              ClassTSK == TSK_ExplicitInstantiationDefinition
15146                  ? diag::warn_weak_template_vtable
15147                  : diag::warn_weak_vtable)
15148             << Class;
15149       }
15150     }
15151   }
15152   VTableUses.clear();
15153 
15154   return DefinedAnything;
15155 }
15156 
15157 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15158                                                  const CXXRecordDecl *RD) {
15159   for (const auto *I : RD->methods())
15160     if (I->isVirtual() && !I->isPure())
15161       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15162 }
15163 
15164 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15165                                         const CXXRecordDecl *RD) {
15166   // Mark all functions which will appear in RD's vtable as used.
15167   CXXFinalOverriderMap FinalOverriders;
15168   RD->getFinalOverriders(FinalOverriders);
15169   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15170                                             E = FinalOverriders.end();
15171        I != E; ++I) {
15172     for (OverridingMethods::const_iterator OI = I->second.begin(),
15173                                            OE = I->second.end();
15174          OI != OE; ++OI) {
15175       assert(OI->second.size() > 0 && "no final overrider");
15176       CXXMethodDecl *Overrider = OI->second.front().Method;
15177 
15178       // C++ [basic.def.odr]p2:
15179       //   [...] A virtual member function is used if it is not pure. [...]
15180       if (!Overrider->isPure())
15181         MarkFunctionReferenced(Loc, Overrider);
15182     }
15183   }
15184 
15185   // Only classes that have virtual bases need a VTT.
15186   if (RD->getNumVBases() == 0)
15187     return;
15188 
15189   for (const auto &I : RD->bases()) {
15190     const CXXRecordDecl *Base =
15191         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15192     if (Base->getNumVBases() == 0)
15193       continue;
15194     MarkVirtualMembersReferenced(Loc, Base);
15195   }
15196 }
15197 
15198 /// SetIvarInitializers - This routine builds initialization ASTs for the
15199 /// Objective-C implementation whose ivars need be initialized.
15200 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15201   if (!getLangOpts().CPlusPlus)
15202     return;
15203   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15204     SmallVector<ObjCIvarDecl*, 8> ivars;
15205     CollectIvarsToConstructOrDestruct(OID, ivars);
15206     if (ivars.empty())
15207       return;
15208     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15209     for (unsigned i = 0; i < ivars.size(); i++) {
15210       FieldDecl *Field = ivars[i];
15211       if (Field->isInvalidDecl())
15212         continue;
15213 
15214       CXXCtorInitializer *Member;
15215       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15216       InitializationKind InitKind =
15217         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15218 
15219       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15220       ExprResult MemberInit =
15221         InitSeq.Perform(*this, InitEntity, InitKind, None);
15222       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15223       // Note, MemberInit could actually come back empty if no initialization
15224       // is required (e.g., because it would call a trivial default constructor)
15225       if (!MemberInit.get() || MemberInit.isInvalid())
15226         continue;
15227 
15228       Member =
15229         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15230                                          SourceLocation(),
15231                                          MemberInit.getAs<Expr>(),
15232                                          SourceLocation());
15233       AllToInit.push_back(Member);
15234 
15235       // Be sure that the destructor is accessible and is marked as referenced.
15236       if (const RecordType *RecordTy =
15237               Context.getBaseElementType(Field->getType())
15238                   ->getAs<RecordType>()) {
15239         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15240         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15241           MarkFunctionReferenced(Field->getLocation(), Destructor);
15242           CheckDestructorAccess(Field->getLocation(), Destructor,
15243                             PDiag(diag::err_access_dtor_ivar)
15244                               << Context.getBaseElementType(Field->getType()));
15245         }
15246       }
15247     }
15248     ObjCImplementation->setIvarInitializers(Context,
15249                                             AllToInit.data(), AllToInit.size());
15250   }
15251 }
15252 
15253 static
15254 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15255                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15256                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15257                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15258                            Sema &S) {
15259   if (Ctor->isInvalidDecl())
15260     return;
15261 
15262   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15263 
15264   // Target may not be determinable yet, for instance if this is a dependent
15265   // call in an uninstantiated template.
15266   if (Target) {
15267     const FunctionDecl *FNTarget = nullptr;
15268     (void)Target->hasBody(FNTarget);
15269     Target = const_cast<CXXConstructorDecl*>(
15270       cast_or_null<CXXConstructorDecl>(FNTarget));
15271   }
15272 
15273   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15274                      // Avoid dereferencing a null pointer here.
15275                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15276 
15277   if (!Current.insert(Canonical).second)
15278     return;
15279 
15280   // We know that beyond here, we aren't chaining into a cycle.
15281   if (!Target || !Target->isDelegatingConstructor() ||
15282       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15283     Valid.insert(Current.begin(), Current.end());
15284     Current.clear();
15285   // We've hit a cycle.
15286   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15287              Current.count(TCanonical)) {
15288     // If we haven't diagnosed this cycle yet, do so now.
15289     if (!Invalid.count(TCanonical)) {
15290       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15291              diag::warn_delegating_ctor_cycle)
15292         << Ctor;
15293 
15294       // Don't add a note for a function delegating directly to itself.
15295       if (TCanonical != Canonical)
15296         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15297 
15298       CXXConstructorDecl *C = Target;
15299       while (C->getCanonicalDecl() != Canonical) {
15300         const FunctionDecl *FNTarget = nullptr;
15301         (void)C->getTargetConstructor()->hasBody(FNTarget);
15302         assert(FNTarget && "Ctor cycle through bodiless function");
15303 
15304         C = const_cast<CXXConstructorDecl*>(
15305           cast<CXXConstructorDecl>(FNTarget));
15306         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15307       }
15308     }
15309 
15310     Invalid.insert(Current.begin(), Current.end());
15311     Current.clear();
15312   } else {
15313     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15314   }
15315 }
15316 
15317 
15318 void Sema::CheckDelegatingCtorCycles() {
15319   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15320 
15321   for (DelegatingCtorDeclsType::iterator
15322          I = DelegatingCtorDecls.begin(ExternalSource),
15323          E = DelegatingCtorDecls.end();
15324        I != E; ++I)
15325     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15326 
15327   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15328     (*CI)->setInvalidDecl();
15329 }
15330 
15331 namespace {
15332   /// AST visitor that finds references to the 'this' expression.
15333   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15334     Sema &S;
15335 
15336   public:
15337     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15338 
15339     bool VisitCXXThisExpr(CXXThisExpr *E) {
15340       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15341         << E->isImplicit();
15342       return false;
15343     }
15344   };
15345 }
15346 
15347 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15348   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15349   if (!TSInfo)
15350     return false;
15351 
15352   TypeLoc TL = TSInfo->getTypeLoc();
15353   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15354   if (!ProtoTL)
15355     return false;
15356 
15357   // C++11 [expr.prim.general]p3:
15358   //   [The expression this] shall not appear before the optional
15359   //   cv-qualifier-seq and it shall not appear within the declaration of a
15360   //   static member function (although its type and value category are defined
15361   //   within a static member function as they are within a non-static member
15362   //   function). [ Note: this is because declaration matching does not occur
15363   //  until the complete declarator is known. - end note ]
15364   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15365   FindCXXThisExpr Finder(*this);
15366 
15367   // If the return type came after the cv-qualifier-seq, check it now.
15368   if (Proto->hasTrailingReturn() &&
15369       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15370     return true;
15371 
15372   // Check the exception specification.
15373   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15374     return true;
15375 
15376   return checkThisInStaticMemberFunctionAttributes(Method);
15377 }
15378 
15379 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15380   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15381   if (!TSInfo)
15382     return false;
15383 
15384   TypeLoc TL = TSInfo->getTypeLoc();
15385   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15386   if (!ProtoTL)
15387     return false;
15388 
15389   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15390   FindCXXThisExpr Finder(*this);
15391 
15392   switch (Proto->getExceptionSpecType()) {
15393   case EST_Unparsed:
15394   case EST_Uninstantiated:
15395   case EST_Unevaluated:
15396   case EST_BasicNoexcept:
15397   case EST_DynamicNone:
15398   case EST_MSAny:
15399   case EST_None:
15400     break;
15401 
15402   case EST_DependentNoexcept:
15403   case EST_NoexceptFalse:
15404   case EST_NoexceptTrue:
15405     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15406       return true;
15407     LLVM_FALLTHROUGH;
15408 
15409   case EST_Dynamic:
15410     for (const auto &E : Proto->exceptions()) {
15411       if (!Finder.TraverseType(E))
15412         return true;
15413     }
15414     break;
15415   }
15416 
15417   return false;
15418 }
15419 
15420 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15421   FindCXXThisExpr Finder(*this);
15422 
15423   // Check attributes.
15424   for (const auto *A : Method->attrs()) {
15425     // FIXME: This should be emitted by tblgen.
15426     Expr *Arg = nullptr;
15427     ArrayRef<Expr *> Args;
15428     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15429       Arg = G->getArg();
15430     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15431       Arg = G->getArg();
15432     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15433       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15434     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15435       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15436     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15437       Arg = ETLF->getSuccessValue();
15438       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15439     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15440       Arg = STLF->getSuccessValue();
15441       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15442     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15443       Arg = LR->getArg();
15444     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15445       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15446     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15447       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15448     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15449       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15450     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15451       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15452     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15453       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15454 
15455     if (Arg && !Finder.TraverseStmt(Arg))
15456       return true;
15457 
15458     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15459       if (!Finder.TraverseStmt(Args[I]))
15460         return true;
15461     }
15462   }
15463 
15464   return false;
15465 }
15466 
15467 void Sema::checkExceptionSpecification(
15468     bool IsTopLevel, ExceptionSpecificationType EST,
15469     ArrayRef<ParsedType> DynamicExceptions,
15470     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15471     SmallVectorImpl<QualType> &Exceptions,
15472     FunctionProtoType::ExceptionSpecInfo &ESI) {
15473   Exceptions.clear();
15474   ESI.Type = EST;
15475   if (EST == EST_Dynamic) {
15476     Exceptions.reserve(DynamicExceptions.size());
15477     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15478       // FIXME: Preserve type source info.
15479       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15480 
15481       if (IsTopLevel) {
15482         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15483         collectUnexpandedParameterPacks(ET, Unexpanded);
15484         if (!Unexpanded.empty()) {
15485           DiagnoseUnexpandedParameterPacks(
15486               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15487               Unexpanded);
15488           continue;
15489         }
15490       }
15491 
15492       // Check that the type is valid for an exception spec, and
15493       // drop it if not.
15494       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15495         Exceptions.push_back(ET);
15496     }
15497     ESI.Exceptions = Exceptions;
15498     return;
15499   }
15500 
15501   if (isComputedNoexcept(EST)) {
15502     assert((NoexceptExpr->isTypeDependent() ||
15503             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15504             Context.BoolTy) &&
15505            "Parser should have made sure that the expression is boolean");
15506     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15507       ESI.Type = EST_BasicNoexcept;
15508       return;
15509     }
15510 
15511     ESI.NoexceptExpr = NoexceptExpr;
15512     return;
15513   }
15514 }
15515 
15516 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15517              ExceptionSpecificationType EST,
15518              SourceRange SpecificationRange,
15519              ArrayRef<ParsedType> DynamicExceptions,
15520              ArrayRef<SourceRange> DynamicExceptionRanges,
15521              Expr *NoexceptExpr) {
15522   if (!MethodD)
15523     return;
15524 
15525   // Dig out the method we're referring to.
15526   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15527     MethodD = FunTmpl->getTemplatedDecl();
15528 
15529   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15530   if (!Method)
15531     return;
15532 
15533   // Check the exception specification.
15534   llvm::SmallVector<QualType, 4> Exceptions;
15535   FunctionProtoType::ExceptionSpecInfo ESI;
15536   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15537                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15538                               ESI);
15539 
15540   // Update the exception specification on the function type.
15541   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15542 
15543   if (Method->isStatic())
15544     checkThisInStaticMemberFunctionExceptionSpec(Method);
15545 
15546   if (Method->isVirtual()) {
15547     // Check overrides, which we previously had to delay.
15548     for (const CXXMethodDecl *O : Method->overridden_methods())
15549       CheckOverridingFunctionExceptionSpec(Method, O);
15550   }
15551 }
15552 
15553 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15554 ///
15555 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15556                                        SourceLocation DeclStart, Declarator &D,
15557                                        Expr *BitWidth,
15558                                        InClassInitStyle InitStyle,
15559                                        AccessSpecifier AS,
15560                                        const ParsedAttr &MSPropertyAttr) {
15561   IdentifierInfo *II = D.getIdentifier();
15562   if (!II) {
15563     Diag(DeclStart, diag::err_anonymous_property);
15564     return nullptr;
15565   }
15566   SourceLocation Loc = D.getIdentifierLoc();
15567 
15568   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15569   QualType T = TInfo->getType();
15570   if (getLangOpts().CPlusPlus) {
15571     CheckExtraCXXDefaultArguments(D);
15572 
15573     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15574                                         UPPC_DataMemberType)) {
15575       D.setInvalidType();
15576       T = Context.IntTy;
15577       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15578     }
15579   }
15580 
15581   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15582 
15583   if (D.getDeclSpec().isInlineSpecified())
15584     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15585         << getLangOpts().CPlusPlus17;
15586   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15587     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15588          diag::err_invalid_thread)
15589       << DeclSpec::getSpecifierName(TSCS);
15590 
15591   // Check to see if this name was declared as a member previously
15592   NamedDecl *PrevDecl = nullptr;
15593   LookupResult Previous(*this, II, Loc, LookupMemberName,
15594                         ForVisibleRedeclaration);
15595   LookupName(Previous, S);
15596   switch (Previous.getResultKind()) {
15597   case LookupResult::Found:
15598   case LookupResult::FoundUnresolvedValue:
15599     PrevDecl = Previous.getAsSingle<NamedDecl>();
15600     break;
15601 
15602   case LookupResult::FoundOverloaded:
15603     PrevDecl = Previous.getRepresentativeDecl();
15604     break;
15605 
15606   case LookupResult::NotFound:
15607   case LookupResult::NotFoundInCurrentInstantiation:
15608   case LookupResult::Ambiguous:
15609     break;
15610   }
15611 
15612   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15613     // Maybe we will complain about the shadowed template parameter.
15614     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15615     // Just pretend that we didn't see the previous declaration.
15616     PrevDecl = nullptr;
15617   }
15618 
15619   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15620     PrevDecl = nullptr;
15621 
15622   SourceLocation TSSL = D.getBeginLoc();
15623   MSPropertyDecl *NewPD =
15624       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15625                              MSPropertyAttr.getPropertyDataGetter(),
15626                              MSPropertyAttr.getPropertyDataSetter());
15627   ProcessDeclAttributes(TUScope, NewPD, D);
15628   NewPD->setAccess(AS);
15629 
15630   if (NewPD->isInvalidDecl())
15631     Record->setInvalidDecl();
15632 
15633   if (D.getDeclSpec().isModulePrivateSpecified())
15634     NewPD->setModulePrivate();
15635 
15636   if (NewPD->isInvalidDecl() && PrevDecl) {
15637     // Don't introduce NewFD into scope; there's already something
15638     // with the same name in the same scope.
15639   } else if (II) {
15640     PushOnScopeChains(NewPD, S);
15641   } else
15642     Record->addDecl(NewPD);
15643 
15644   return NewPD;
15645 }
15646