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->getLocStart(),
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->getLocStart(),
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->getLocStart(),
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->getLocStart(),
148                    diag::err_lambda_capture_default_arg);
149   }
150 }
151 
152 void
153 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
154                                                  const CXXMethodDecl *Method) {
155   // If we have an MSAny spec already, don't bother.
156   if (!Method || ComputedEST == EST_MSAny)
157     return;
158 
159   const FunctionProtoType *Proto
160     = Method->getType()->getAs<FunctionProtoType>();
161   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
162   if (!Proto)
163     return;
164 
165   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
166 
167   // If we have a throw-all spec at this point, ignore the function.
168   if (ComputedEST == EST_None)
169     return;
170 
171   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
172     EST = EST_BasicNoexcept;
173 
174   switch (EST) {
175   case EST_Unparsed:
176   case EST_Uninstantiated:
177   case EST_Unevaluated:
178     llvm_unreachable("should not see unresolved exception specs here");
179 
180   // If this function can throw any exceptions, make a note of that.
181   case EST_MSAny:
182   case EST_None:
183     // FIXME: Whichever we see last of MSAny and None determines our result.
184     // We should make a consistent, order-independent choice here.
185     ClearExceptions();
186     ComputedEST = EST;
187     return;
188   case EST_NoexceptFalse:
189     ClearExceptions();
190     ComputedEST = EST_None;
191     return;
192   // FIXME: If the call to this decl is using any of its default arguments, we
193   // need to search them for potentially-throwing calls.
194   // If this function has a basic noexcept, it doesn't affect the outcome.
195   case EST_BasicNoexcept:
196   case EST_NoexceptTrue:
197     return;
198   // If we're still at noexcept(true) and there's a throw() callee,
199   // change to that specification.
200   case EST_DynamicNone:
201     if (ComputedEST == EST_BasicNoexcept)
202       ComputedEST = EST_DynamicNone;
203     return;
204   case EST_DependentNoexcept:
205     llvm_unreachable(
206         "should not generate implicit declarations for dependent cases");
207   case EST_Dynamic:
208     break;
209   }
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // C++11 [dcl.fct.default]p3
322   //   A default argument expression [...] shall not be specified for a
323   //   parameter pack.
324   if (Param->isParameterPack()) {
325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326         << DefaultArg->getSourceRange();
327     return;
328   }
329 
330   // Check that the default argument is well-formed
331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332   if (DefaultArgChecker.Visit(DefaultArg)) {
333     Param->setInvalidDecl();
334     return;
335   }
336 
337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 }
339 
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345                                              SourceLocation EqualLoc,
346                                              SourceLocation ArgLoc) {
347   if (!param)
348     return;
349 
350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
351   Param->setUnparsedDefaultArg();
352   UnparsedDefaultArgLocs[Param] = ArgLoc;
353 }
354 
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358                                           SourceLocation EqualLoc) {
359   if (!param)
360     return;
361 
362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
363   Param->setInvalidDecl();
364   UnparsedDefaultArgLocs.erase(Param);
365   Param->setDefaultArg(new(Context)
366                        OpaqueValueExpr(EqualLoc,
367                                        Param->getType().getNonReferenceType(),
368                                        VK_RValue));
369 }
370 
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377   // C++ [dcl.fct.default]p3
378   //   A default argument expression shall be specified only in the
379   //   parameter-declaration-clause of a function declaration or in a
380   //   template-parameter (14.1). It shall not be specified for a
381   //   parameter pack. If it is specified in a
382   //   parameter-declaration-clause, it shall not occur within a
383   //   declarator or abstract-declarator of a parameter-declaration.
384   bool MightBeFunction = D.isFunctionDeclarationContext();
385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386     DeclaratorChunk &chunk = D.getTypeObject(i);
387     if (chunk.Kind == DeclaratorChunk::Function) {
388       if (MightBeFunction) {
389         // This is a function declaration. It can have default arguments, but
390         // keep looking in case its return type is a function type with default
391         // arguments.
392         MightBeFunction = false;
393         continue;
394       }
395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396            ++argIdx) {
397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398         if (Param->hasUnparsedDefaultArg()) {
399           std::unique_ptr<CachedTokens> Toks =
400               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401           SourceRange SR;
402           if (Toks->size() > 1)
403             SR = SourceRange((*Toks)[1].getLocation(),
404                              Toks->back().getLocation());
405           else
406             SR = UnparsedDefaultArgLocs[Param];
407           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408             << SR;
409         } else if (Param->getDefaultArg()) {
410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411             << Param->getDefaultArg()->getSourceRange();
412           Param->setDefaultArg(nullptr);
413         }
414       }
415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
416       MightBeFunction = false;
417     }
418   }
419 }
420 
421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424     if (!PVD->hasDefaultArg())
425       return false;
426     if (!PVD->hasInheritedDefaultArg())
427       return true;
428   }
429   return false;
430 }
431 
432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
433 /// function, once we already know that they have the same
434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435 /// error, false otherwise.
436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437                                 Scope *S) {
438   bool Invalid = false;
439 
440   // The declaration context corresponding to the scope is the semantic
441   // parent, unless this is a local function declaration, in which case
442   // it is that surrounding function.
443   DeclContext *ScopeDC = New->isLocalExternDecl()
444                              ? New->getLexicalDeclContext()
445                              : New->getDeclContext();
446 
447   // Find the previous declaration for the purpose of default arguments.
448   FunctionDecl *PrevForDefaultArgs = Old;
449   for (/**/; PrevForDefaultArgs;
450        // Don't bother looking back past the latest decl if this is a local
451        // extern declaration; nothing else could work.
452        PrevForDefaultArgs = New->isLocalExternDecl()
453                                 ? nullptr
454                                 : PrevForDefaultArgs->getPreviousDecl()) {
455     // Ignore hidden declarations.
456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457       continue;
458 
459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460         !New->isCXXClassMember()) {
461       // Ignore default arguments of old decl if they are not in
462       // the same scope and this is not an out-of-line definition of
463       // a member function.
464       continue;
465     }
466 
467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468       // If only one of these is a local function declaration, then they are
469       // declared in different scopes, even though isDeclInScope may think
470       // they're in the same scope. (If both are local, the scope check is
471       // sufficient, and if neither is local, then they are in the same scope.)
472       continue;
473     }
474 
475     // We found the right previous declaration.
476     break;
477   }
478 
479   // C++ [dcl.fct.default]p4:
480   //   For non-template functions, default arguments can be added in
481   //   later declarations of a function in the same
482   //   scope. Declarations in different scopes have completely
483   //   distinct sets of default arguments. That is, declarations in
484   //   inner scopes do not acquire default arguments from
485   //   declarations in outer scopes, and vice versa. In a given
486   //   function declaration, all parameters subsequent to a
487   //   parameter with a default argument shall have default
488   //   arguments supplied in this or previous declarations. A
489   //   default argument shall not be redefined by a later
490   //   declaration (not even to the same value).
491   //
492   // C++ [dcl.fct.default]p6:
493   //   Except for member functions of class templates, the default arguments
494   //   in a member function definition that appears outside of the class
495   //   definition are added to the set of default arguments provided by the
496   //   member function declaration in the class definition.
497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
498                                        ? PrevForDefaultArgs->getNumParams()
499                                        : 0;
500        p < NumParams; ++p) {
501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502     ParmVarDecl *NewParam = New->getParamDecl(p);
503 
504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505     bool NewParamHasDfl = NewParam->hasDefaultArg();
506 
507     if (OldParamHasDfl && NewParamHasDfl) {
508       unsigned DiagDefaultParamID =
509         diag::err_param_default_argument_redefinition;
510 
511       // MSVC accepts that default parameters be redefined for member functions
512       // of template class. The new default parameter's value is ignored.
513       Invalid = true;
514       if (getLangOpts().MicrosoftExt) {
515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
517           // Merge the old default argument into the new parameter.
518           NewParam->setHasInheritedDefaultArg();
519           if (OldParam->hasUninstantiatedDefaultArg())
520             NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522           else
523             NewParam->setDefaultArg(OldParam->getInit());
524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525           Invalid = false;
526         }
527       }
528 
529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530       // hint here. Alternatively, we could walk the type-source information
531       // for NewParam to find the last source location in the type... but it
532       // isn't worth the effort right now. This is the kind of test case that
533       // is hard to get right:
534       //   int f(int);
535       //   void g(int (*fp)(int) = f);
536       //   void g(int (*fp)(int) = &f);
537       Diag(NewParam->getLocation(), DiagDefaultParamID)
538         << NewParam->getDefaultArgRange();
539 
540       // Look for the function declaration where the default argument was
541       // actually written, which may be a declaration prior to Old.
542       for (auto Older = PrevForDefaultArgs;
543            OldParam->hasInheritedDefaultArg(); /**/) {
544         Older = Older->getPreviousDecl();
545         OldParam = Older->getParamDecl(p);
546       }
547 
548       Diag(OldParam->getLocation(), diag::note_previous_definition)
549         << OldParam->getDefaultArgRange();
550     } else if (OldParamHasDfl) {
551       // Merge the old default argument into the new parameter unless the new
552       // function is a friend declaration in a template class. In the latter
553       // case the default arguments will be inherited when the friend
554       // declaration will be instantiated.
555       if (New->getFriendObjectKind() == Decl::FOK_None ||
556           !New->getLexicalDeclContext()->isDependentContext()) {
557         // It's important to use getInit() here;  getDefaultArg()
558         // strips off any top-level ExprWithCleanups.
559         NewParam->setHasInheritedDefaultArg();
560         if (OldParam->hasUnparsedDefaultArg())
561           NewParam->setUnparsedDefaultArg();
562         else if (OldParam->hasUninstantiatedDefaultArg())
563           NewParam->setUninstantiatedDefaultArg(
564                                        OldParam->getUninstantiatedDefaultArg());
565         else
566           NewParam->setDefaultArg(OldParam->getInit());
567       }
568     } else if (NewParamHasDfl) {
569       if (New->getDescribedFunctionTemplate()) {
570         // Paragraph 4, quoted above, only applies to non-template functions.
571         Diag(NewParam->getLocation(),
572              diag::err_param_default_argument_template_redecl)
573           << NewParam->getDefaultArgRange();
574         Diag(PrevForDefaultArgs->getLocation(),
575              diag::note_template_prev_declaration)
576             << false;
577       } else if (New->getTemplateSpecializationKind()
578                    != TSK_ImplicitInstantiation &&
579                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
580         // C++ [temp.expr.spec]p21:
581         //   Default function arguments shall not be specified in a declaration
582         //   or a definition for one of the following explicit specializations:
583         //     - the explicit specialization of a function template;
584         //     - the explicit specialization of a member function template;
585         //     - the explicit specialization of a member function of a class
586         //       template where the class template specialization to which the
587         //       member function specialization belongs is implicitly
588         //       instantiated.
589         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
591           << New->getDeclName()
592           << NewParam->getDefaultArgRange();
593       } else if (New->getDeclContext()->isDependentContext()) {
594         // C++ [dcl.fct.default]p6 (DR217):
595         //   Default arguments for a member function of a class template shall
596         //   be specified on the initial declaration of the member function
597         //   within the class template.
598         //
599         // Reading the tea leaves a bit in DR217 and its reference to DR205
600         // leads me to the conclusion that one cannot add default function
601         // arguments for an out-of-line definition of a member function of a
602         // dependent type.
603         int WhichKind = 2;
604         if (CXXRecordDecl *Record
605               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
606           if (Record->getDescribedClassTemplate())
607             WhichKind = 0;
608           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
609             WhichKind = 1;
610           else
611             WhichKind = 2;
612         }
613 
614         Diag(NewParam->getLocation(),
615              diag::err_param_default_argument_member_template_redecl)
616           << WhichKind
617           << NewParam->getDefaultArgRange();
618       }
619     }
620   }
621 
622   // DR1344: If a default argument is added outside a class definition and that
623   // default argument makes the function a special member function, the program
624   // is ill-formed. This can only happen for constructors.
625   if (isa<CXXConstructorDecl>(New) &&
626       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
627     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
628                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
629     if (NewSM != OldSM) {
630       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
631       assert(NewParam->hasDefaultArg());
632       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
633         << NewParam->getDefaultArgRange() << NewSM;
634       Diag(Old->getLocation(), diag::note_previous_declaration);
635     }
636   }
637 
638   const FunctionDecl *Def;
639   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
640   // template has a constexpr specifier then all its declarations shall
641   // contain the constexpr specifier.
642   if (New->isConstexpr() != Old->isConstexpr()) {
643     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
644       << New << New->isConstexpr();
645     Diag(Old->getLocation(), diag::note_previous_declaration);
646     Invalid = true;
647   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
648              Old->isDefined(Def) &&
649              // If a friend function is inlined but does not have 'inline'
650              // specifier, it is a definition. Do not report attribute conflict
651              // in this case, redefinition will be diagnosed later.
652              (New->isInlineSpecified() ||
653               New->getFriendObjectKind() == Decl::FOK_None)) {
654     // C++11 [dcl.fcn.spec]p4:
655     //   If the definition of a function appears in a translation unit before its
656     //   first declaration as inline, the program is ill-formed.
657     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
658     Diag(Def->getLocation(), diag::note_previous_definition);
659     Invalid = true;
660   }
661 
662   // FIXME: It's not clear what should happen if multiple declarations of a
663   // deduction guide have different explicitness. For now at least we simply
664   // reject any case where the explicitness changes.
665   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
666   if (NewGuide && NewGuide->isExplicitSpecified() !=
667                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
668     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
669       << NewGuide->isExplicitSpecified();
670     Diag(Old->getLocation(), diag::note_previous_declaration);
671   }
672 
673   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
674   // argument expression, that declaration shall be a definition and shall be
675   // the only declaration of the function or function template in the
676   // translation unit.
677   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
678       functionDeclHasDefaultArgument(Old)) {
679     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
680     Diag(Old->getLocation(), diag::note_previous_declaration);
681     Invalid = true;
682   }
683 
684   return Invalid;
685 }
686 
687 NamedDecl *
688 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
689                                    MultiTemplateParamsArg TemplateParamLists) {
690   assert(D.isDecompositionDeclarator());
691   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
692 
693   // The syntax only allows a decomposition declarator as a simple-declaration,
694   // a for-range-declaration, or a condition in Clang, but we parse it in more
695   // cases than that.
696   if (!D.mayHaveDecompositionDeclarator()) {
697     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
698       << Decomp.getSourceRange();
699     return nullptr;
700   }
701 
702   if (!TemplateParamLists.empty()) {
703     // FIXME: There's no rule against this, but there are also no rules that
704     // would actually make it usable, so we reject it for now.
705     Diag(TemplateParamLists.front()->getTemplateLoc(),
706          diag::err_decomp_decl_template);
707     return nullptr;
708   }
709 
710   Diag(Decomp.getLSquareLoc(),
711        !getLangOpts().CPlusPlus17
712            ? diag::ext_decomp_decl
713            : D.getContext() == DeclaratorContext::ConditionContext
714                  ? diag::ext_decomp_decl_cond
715                  : diag::warn_cxx14_compat_decomp_decl)
716       << Decomp.getSourceRange();
717 
718   // The semantic context is always just the current context.
719   DeclContext *const DC = CurContext;
720 
721   // C++1z [dcl.dcl]/8:
722   //   The decl-specifier-seq shall contain only the type-specifier auto
723   //   and cv-qualifiers.
724   auto &DS = D.getDeclSpec();
725   {
726     SmallVector<StringRef, 8> BadSpecifiers;
727     SmallVector<SourceLocation, 8> BadSpecifierLocs;
728     if (auto SCS = DS.getStorageClassSpec()) {
729       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
730       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
731     }
732     if (auto TSCS = DS.getThreadStorageClassSpec()) {
733       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
734       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
735     }
736     if (DS.isConstexprSpecified()) {
737       BadSpecifiers.push_back("constexpr");
738       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
739     }
740     if (DS.isInlineSpecified()) {
741       BadSpecifiers.push_back("inline");
742       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
743     }
744     if (!BadSpecifiers.empty()) {
745       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
746       Err << (int)BadSpecifiers.size()
747           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
748       // Don't add FixItHints to remove the specifiers; we do still respect
749       // them when building the underlying variable.
750       for (auto Loc : BadSpecifierLocs)
751         Err << SourceRange(Loc, Loc);
752     }
753     // We can't recover from it being declared as a typedef.
754     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
755       return nullptr;
756   }
757 
758   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
759   QualType R = TInfo->getType();
760 
761   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
762                                       UPPC_DeclarationType))
763     D.setInvalidType();
764 
765   // The syntax only allows a single ref-qualifier prior to the decomposition
766   // declarator. No other declarator chunks are permitted. Also check the type
767   // specifier here.
768   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
769       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
770       (D.getNumTypeObjects() == 1 &&
771        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
772     Diag(Decomp.getLSquareLoc(),
773          (D.hasGroupingParens() ||
774           (D.getNumTypeObjects() &&
775            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
776              ? diag::err_decomp_decl_parens
777              : diag::err_decomp_decl_type)
778         << R;
779 
780     // In most cases, there's no actual problem with an explicitly-specified
781     // type, but a function type won't work here, and ActOnVariableDeclarator
782     // shouldn't be called for such a type.
783     if (R->isFunctionType())
784       D.setInvalidType();
785   }
786 
787   // Build the BindingDecls.
788   SmallVector<BindingDecl*, 8> Bindings;
789 
790   // Build the BindingDecls.
791   for (auto &B : D.getDecompositionDeclarator().bindings()) {
792     // Check for name conflicts.
793     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
794     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
795                           ForVisibleRedeclaration);
796     LookupName(Previous, S,
797                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
798 
799     // It's not permitted to shadow a template parameter name.
800     if (Previous.isSingleResult() &&
801         Previous.getFoundDecl()->isTemplateParameter()) {
802       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
803                                       Previous.getFoundDecl());
804       Previous.clear();
805     }
806 
807     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
808                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
809     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
810                          /*AllowInlineNamespace*/false);
811     if (!Previous.empty()) {
812       auto *Old = Previous.getRepresentativeDecl();
813       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
814       Diag(Old->getLocation(), diag::note_previous_definition);
815     }
816 
817     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
818     PushOnScopeChains(BD, S, true);
819     Bindings.push_back(BD);
820     ParsingInitForAutoVars.insert(BD);
821   }
822 
823   // There are no prior lookup results for the variable itself, because it
824   // is unnamed.
825   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
826                                Decomp.getLSquareLoc());
827   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
828                         ForVisibleRedeclaration);
829 
830   // Build the variable that holds the non-decomposed object.
831   bool AddToScope = true;
832   NamedDecl *New =
833       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
834                               MultiTemplateParamsArg(), AddToScope, Bindings);
835   if (AddToScope) {
836     S->AddDecl(New);
837     CurContext->addHiddenDecl(New);
838   }
839 
840   if (isInOpenMPDeclareTargetContext())
841     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
842 
843   return New;
844 }
845 
846 static bool checkSimpleDecomposition(
847     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
848     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
849     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
850   if ((int64_t)Bindings.size() != NumElems) {
851     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
852         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
853         << (NumElems < Bindings.size());
854     return true;
855   }
856 
857   unsigned I = 0;
858   for (auto *B : Bindings) {
859     SourceLocation Loc = B->getLocation();
860     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
861     if (E.isInvalid())
862       return true;
863     E = GetInit(Loc, E.get(), I++);
864     if (E.isInvalid())
865       return true;
866     B->setBinding(ElemType, E.get());
867   }
868 
869   return false;
870 }
871 
872 static bool checkArrayLikeDecomposition(Sema &S,
873                                         ArrayRef<BindingDecl *> Bindings,
874                                         ValueDecl *Src, QualType DecompType,
875                                         const llvm::APSInt &NumElems,
876                                         QualType ElemType) {
877   return checkSimpleDecomposition(
878       S, Bindings, Src, DecompType, NumElems, ElemType,
879       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
880         ExprResult E = S.ActOnIntegerConstant(Loc, I);
881         if (E.isInvalid())
882           return ExprError();
883         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
884       });
885 }
886 
887 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
888                                     ValueDecl *Src, QualType DecompType,
889                                     const ConstantArrayType *CAT) {
890   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
891                                      llvm::APSInt(CAT->getSize()),
892                                      CAT->getElementType());
893 }
894 
895 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
896                                      ValueDecl *Src, QualType DecompType,
897                                      const VectorType *VT) {
898   return checkArrayLikeDecomposition(
899       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
900       S.Context.getQualifiedType(VT->getElementType(),
901                                  DecompType.getQualifiers()));
902 }
903 
904 static bool checkComplexDecomposition(Sema &S,
905                                       ArrayRef<BindingDecl *> Bindings,
906                                       ValueDecl *Src, QualType DecompType,
907                                       const ComplexType *CT) {
908   return checkSimpleDecomposition(
909       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
910       S.Context.getQualifiedType(CT->getElementType(),
911                                  DecompType.getQualifiers()),
912       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
913         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
914       });
915 }
916 
917 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
918                                      TemplateArgumentListInfo &Args) {
919   SmallString<128> SS;
920   llvm::raw_svector_ostream OS(SS);
921   bool First = true;
922   for (auto &Arg : Args.arguments()) {
923     if (!First)
924       OS << ", ";
925     Arg.getArgument().print(PrintingPolicy, OS);
926     First = false;
927   }
928   return OS.str();
929 }
930 
931 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
932                                      SourceLocation Loc, StringRef Trait,
933                                      TemplateArgumentListInfo &Args,
934                                      unsigned DiagID) {
935   auto DiagnoseMissing = [&] {
936     if (DiagID)
937       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
938                                                Args);
939     return true;
940   };
941 
942   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
943   NamespaceDecl *Std = S.getStdNamespace();
944   if (!Std)
945     return DiagnoseMissing();
946 
947   // Look up the trait itself, within namespace std. We can diagnose various
948   // problems with this lookup even if we've been asked to not diagnose a
949   // missing specialization, because this can only fail if the user has been
950   // declaring their own names in namespace std or we don't support the
951   // standard library implementation in use.
952   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
953                       Loc, Sema::LookupOrdinaryName);
954   if (!S.LookupQualifiedName(Result, Std))
955     return DiagnoseMissing();
956   if (Result.isAmbiguous())
957     return true;
958 
959   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
960   if (!TraitTD) {
961     Result.suppressDiagnostics();
962     NamedDecl *Found = *Result.begin();
963     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
964     S.Diag(Found->getLocation(), diag::note_declared_at);
965     return true;
966   }
967 
968   // Build the template-id.
969   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
970   if (TraitTy.isNull())
971     return true;
972   if (!S.isCompleteType(Loc, TraitTy)) {
973     if (DiagID)
974       S.RequireCompleteType(
975           Loc, TraitTy, DiagID,
976           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
977     return true;
978   }
979 
980   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
981   assert(RD && "specialization of class template is not a class?");
982 
983   // Look up the member of the trait type.
984   S.LookupQualifiedName(TraitMemberLookup, RD);
985   return TraitMemberLookup.isAmbiguous();
986 }
987 
988 static TemplateArgumentLoc
989 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
990                                    uint64_t I) {
991   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
992   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
993 }
994 
995 static TemplateArgumentLoc
996 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
997   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
998 }
999 
1000 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1001 
1002 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1003                                llvm::APSInt &Size) {
1004   EnterExpressionEvaluationContext ContextRAII(
1005       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1006 
1007   DeclarationName Value = S.PP.getIdentifierInfo("value");
1008   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1009 
1010   // Form template argument list for tuple_size<T>.
1011   TemplateArgumentListInfo Args(Loc, Loc);
1012   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1013 
1014   // If there's no tuple_size specialization, it's not tuple-like.
1015   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1016     return IsTupleLike::NotTupleLike;
1017 
1018   // If we get this far, we've committed to the tuple interpretation, but
1019   // we can still fail if there actually isn't a usable ::value.
1020 
1021   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1022     LookupResult &R;
1023     TemplateArgumentListInfo &Args;
1024     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1025         : R(R), Args(Args) {}
1026     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1027       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1028           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1029     }
1030   } Diagnoser(R, Args);
1031 
1032   if (R.empty()) {
1033     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1034     return IsTupleLike::Error;
1035   }
1036 
1037   ExprResult E =
1038       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1039   if (E.isInvalid())
1040     return IsTupleLike::Error;
1041 
1042   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1043   if (E.isInvalid())
1044     return IsTupleLike::Error;
1045 
1046   return IsTupleLike::TupleLike;
1047 }
1048 
1049 /// \return std::tuple_element<I, T>::type.
1050 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1051                                         unsigned I, QualType T) {
1052   // Form template argument list for tuple_element<I, T>.
1053   TemplateArgumentListInfo Args(Loc, Loc);
1054   Args.addArgument(
1055       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1056   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1057 
1058   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1059   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1060   if (lookupStdTypeTraitMember(
1061           S, R, Loc, "tuple_element", Args,
1062           diag::err_decomp_decl_std_tuple_element_not_specialized))
1063     return QualType();
1064 
1065   auto *TD = R.getAsSingle<TypeDecl>();
1066   if (!TD) {
1067     R.suppressDiagnostics();
1068     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1069       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1070     if (!R.empty())
1071       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1072     return QualType();
1073   }
1074 
1075   return S.Context.getTypeDeclType(TD);
1076 }
1077 
1078 namespace {
1079 struct BindingDiagnosticTrap {
1080   Sema &S;
1081   DiagnosticErrorTrap Trap;
1082   BindingDecl *BD;
1083 
1084   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1085       : S(S), Trap(S.Diags), BD(BD) {}
1086   ~BindingDiagnosticTrap() {
1087     if (Trap.hasErrorOccurred())
1088       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1089   }
1090 };
1091 }
1092 
1093 static bool checkTupleLikeDecomposition(Sema &S,
1094                                         ArrayRef<BindingDecl *> Bindings,
1095                                         VarDecl *Src, QualType DecompType,
1096                                         const llvm::APSInt &TupleSize) {
1097   if ((int64_t)Bindings.size() != TupleSize) {
1098     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1099         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1100         << (TupleSize < Bindings.size());
1101     return true;
1102   }
1103 
1104   if (Bindings.empty())
1105     return false;
1106 
1107   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1108 
1109   // [dcl.decomp]p3:
1110   //   The unqualified-id get is looked up in the scope of E by class member
1111   //   access lookup
1112   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1113   bool UseMemberGet = false;
1114   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1115     if (auto *RD = DecompType->getAsCXXRecordDecl())
1116       S.LookupQualifiedName(MemberGet, RD);
1117     if (MemberGet.isAmbiguous())
1118       return true;
1119     UseMemberGet = !MemberGet.empty();
1120     S.FilterAcceptableTemplateNames(MemberGet);
1121   }
1122 
1123   unsigned I = 0;
1124   for (auto *B : Bindings) {
1125     BindingDiagnosticTrap Trap(S, B);
1126     SourceLocation Loc = B->getLocation();
1127 
1128     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1129     if (E.isInvalid())
1130       return true;
1131 
1132     //   e is an lvalue if the type of the entity is an lvalue reference and
1133     //   an xvalue otherwise
1134     if (!Src->getType()->isLValueReferenceType())
1135       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1136                                    E.get(), nullptr, VK_XValue);
1137 
1138     TemplateArgumentListInfo Args(Loc, Loc);
1139     Args.addArgument(
1140         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1141 
1142     if (UseMemberGet) {
1143       //   if [lookup of member get] finds at least one declaration, the
1144       //   initializer is e.get<i-1>().
1145       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1146                                      CXXScopeSpec(), SourceLocation(), nullptr,
1147                                      MemberGet, &Args, nullptr);
1148       if (E.isInvalid())
1149         return true;
1150 
1151       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1152     } else {
1153       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1154       //   in the associated namespaces.
1155       Expr *Get = UnresolvedLookupExpr::Create(
1156           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1157           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1158           UnresolvedSetIterator(), UnresolvedSetIterator());
1159 
1160       Expr *Arg = E.get();
1161       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1162     }
1163     if (E.isInvalid())
1164       return true;
1165     Expr *Init = E.get();
1166 
1167     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1168     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1169     if (T.isNull())
1170       return true;
1171 
1172     //   each vi is a variable of type "reference to T" initialized with the
1173     //   initializer, where the reference is an lvalue reference if the
1174     //   initializer is an lvalue and an rvalue reference otherwise
1175     QualType RefType =
1176         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1177     if (RefType.isNull())
1178       return true;
1179     auto *RefVD = VarDecl::Create(
1180         S.Context, Src->getDeclContext(), Loc, Loc,
1181         B->getDeclName().getAsIdentifierInfo(), RefType,
1182         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1183     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1184     RefVD->setTSCSpec(Src->getTSCSpec());
1185     RefVD->setImplicit();
1186     if (Src->isInlineSpecified())
1187       RefVD->setInlineSpecified();
1188     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1189 
1190     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1191     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1192     InitializationSequence Seq(S, Entity, Kind, Init);
1193     E = Seq.Perform(S, Entity, Kind, Init);
1194     if (E.isInvalid())
1195       return true;
1196     E = S.ActOnFinishFullExpr(E.get(), Loc);
1197     if (E.isInvalid())
1198       return true;
1199     RefVD->setInit(E.get());
1200     RefVD->checkInitIsICE();
1201 
1202     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1203                                    DeclarationNameInfo(B->getDeclName(), Loc),
1204                                    RefVD);
1205     if (E.isInvalid())
1206       return true;
1207 
1208     B->setBinding(T, E.get());
1209     I++;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 /// Find the base class to decompose in a built-in decomposition of a class type.
1216 /// This base class search is, unfortunately, not quite like any other that we
1217 /// perform anywhere else in C++.
1218 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1219                                                       SourceLocation Loc,
1220                                                       const CXXRecordDecl *RD,
1221                                                       CXXCastPath &BasePath) {
1222   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1223                           CXXBasePath &Path) {
1224     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1225   };
1226 
1227   const CXXRecordDecl *ClassWithFields = nullptr;
1228   if (RD->hasDirectFields())
1229     // [dcl.decomp]p4:
1230     //   Otherwise, all of E's non-static data members shall be public direct
1231     //   members of E ...
1232     ClassWithFields = RD;
1233   else {
1234     //   ... or of ...
1235     CXXBasePaths Paths;
1236     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1237     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1238       // If no classes have fields, just decompose RD itself. (This will work
1239       // if and only if zero bindings were provided.)
1240       return RD;
1241     }
1242 
1243     CXXBasePath *BestPath = nullptr;
1244     for (auto &P : Paths) {
1245       if (!BestPath)
1246         BestPath = &P;
1247       else if (!S.Context.hasSameType(P.back().Base->getType(),
1248                                       BestPath->back().Base->getType())) {
1249         //   ... the same ...
1250         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1251           << false << RD << BestPath->back().Base->getType()
1252           << P.back().Base->getType();
1253         return nullptr;
1254       } else if (P.Access < BestPath->Access) {
1255         BestPath = &P;
1256       }
1257     }
1258 
1259     //   ... unambiguous ...
1260     QualType BaseType = BestPath->back().Base->getType();
1261     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1262       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1263         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1264       return nullptr;
1265     }
1266 
1267     //   ... public base class of E.
1268     if (BestPath->Access != AS_public) {
1269       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1270         << RD << BaseType;
1271       for (auto &BS : *BestPath) {
1272         if (BS.Base->getAccessSpecifier() != AS_public) {
1273           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1274             << (BS.Base->getAccessSpecifier() == AS_protected)
1275             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1276           break;
1277         }
1278       }
1279       return nullptr;
1280     }
1281 
1282     ClassWithFields = BaseType->getAsCXXRecordDecl();
1283     S.BuildBasePathArray(Paths, BasePath);
1284   }
1285 
1286   // The above search did not check whether the selected class itself has base
1287   // classes with fields, so check that now.
1288   CXXBasePaths Paths;
1289   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1290     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1291       << (ClassWithFields == RD) << RD << ClassWithFields
1292       << Paths.front().back().Base->getType();
1293     return nullptr;
1294   }
1295 
1296   return ClassWithFields;
1297 }
1298 
1299 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1300                                      ValueDecl *Src, QualType DecompType,
1301                                      const CXXRecordDecl *RD) {
1302   CXXCastPath BasePath;
1303   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1304   if (!RD)
1305     return true;
1306   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1307                                                  DecompType.getQualifiers());
1308 
1309   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1310     unsigned NumFields =
1311         std::count_if(RD->field_begin(), RD->field_end(),
1312                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1313     assert(Bindings.size() != NumFields);
1314     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1315         << DecompType << (unsigned)Bindings.size() << NumFields
1316         << (NumFields < Bindings.size());
1317     return true;
1318   };
1319 
1320   //   all of E's non-static data members shall be public [...] members,
1321   //   E shall not have an anonymous union member, ...
1322   unsigned I = 0;
1323   for (auto *FD : RD->fields()) {
1324     if (FD->isUnnamedBitfield())
1325       continue;
1326 
1327     if (FD->isAnonymousStructOrUnion()) {
1328       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1329         << DecompType << FD->getType()->isUnionType();
1330       S.Diag(FD->getLocation(), diag::note_declared_at);
1331       return true;
1332     }
1333 
1334     // We have a real field to bind.
1335     if (I >= Bindings.size())
1336       return DiagnoseBadNumberOfBindings();
1337     auto *B = Bindings[I++];
1338 
1339     SourceLocation Loc = B->getLocation();
1340     if (FD->getAccess() != AS_public) {
1341       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1342 
1343       // Determine whether the access specifier was explicit.
1344       bool Implicit = true;
1345       for (const auto *D : RD->decls()) {
1346         if (declaresSameEntity(D, FD))
1347           break;
1348         if (isa<AccessSpecDecl>(D)) {
1349           Implicit = false;
1350           break;
1351         }
1352       }
1353 
1354       S.Diag(FD->getLocation(), diag::note_access_natural)
1355         << (FD->getAccess() == AS_protected) << Implicit;
1356       return true;
1357     }
1358 
1359     // Initialize the binding to Src.FD.
1360     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1361     if (E.isInvalid())
1362       return true;
1363     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1364                             VK_LValue, &BasePath);
1365     if (E.isInvalid())
1366       return true;
1367     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1368                                   CXXScopeSpec(), FD,
1369                                   DeclAccessPair::make(FD, FD->getAccess()),
1370                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1371     if (E.isInvalid())
1372       return true;
1373 
1374     // If the type of the member is T, the referenced type is cv T, where cv is
1375     // the cv-qualification of the decomposition expression.
1376     //
1377     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1378     // 'const' to the type of the field.
1379     Qualifiers Q = DecompType.getQualifiers();
1380     if (FD->isMutable())
1381       Q.removeConst();
1382     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1383   }
1384 
1385   if (I != Bindings.size())
1386     return DiagnoseBadNumberOfBindings();
1387 
1388   return false;
1389 }
1390 
1391 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1392   QualType DecompType = DD->getType();
1393 
1394   // If the type of the decomposition is dependent, then so is the type of
1395   // each binding.
1396   if (DecompType->isDependentType()) {
1397     for (auto *B : DD->bindings())
1398       B->setType(Context.DependentTy);
1399     return;
1400   }
1401 
1402   DecompType = DecompType.getNonReferenceType();
1403   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1404 
1405   // C++1z [dcl.decomp]/2:
1406   //   If E is an array type [...]
1407   // As an extension, we also support decomposition of built-in complex and
1408   // vector types.
1409   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1410     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1411       DD->setInvalidDecl();
1412     return;
1413   }
1414   if (auto *VT = DecompType->getAs<VectorType>()) {
1415     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1416       DD->setInvalidDecl();
1417     return;
1418   }
1419   if (auto *CT = DecompType->getAs<ComplexType>()) {
1420     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1421       DD->setInvalidDecl();
1422     return;
1423   }
1424 
1425   // C++1z [dcl.decomp]/3:
1426   //   if the expression std::tuple_size<E>::value is a well-formed integral
1427   //   constant expression, [...]
1428   llvm::APSInt TupleSize(32);
1429   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1430   case IsTupleLike::Error:
1431     DD->setInvalidDecl();
1432     return;
1433 
1434   case IsTupleLike::TupleLike:
1435     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1436       DD->setInvalidDecl();
1437     return;
1438 
1439   case IsTupleLike::NotTupleLike:
1440     break;
1441   }
1442 
1443   // C++1z [dcl.dcl]/8:
1444   //   [E shall be of array or non-union class type]
1445   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1446   if (!RD || RD->isUnion()) {
1447     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1448         << DD << !RD << DecompType;
1449     DD->setInvalidDecl();
1450     return;
1451   }
1452 
1453   // C++1z [dcl.decomp]/4:
1454   //   all of E's non-static data members shall be [...] direct members of
1455   //   E or of the same unambiguous public base class of E, ...
1456   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1457     DD->setInvalidDecl();
1458 }
1459 
1460 /// Merge the exception specifications of two variable declarations.
1461 ///
1462 /// This is called when there's a redeclaration of a VarDecl. The function
1463 /// checks if the redeclaration might have an exception specification and
1464 /// validates compatibility and merges the specs if necessary.
1465 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1466   // Shortcut if exceptions are disabled.
1467   if (!getLangOpts().CXXExceptions)
1468     return;
1469 
1470   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1471          "Should only be called if types are otherwise the same.");
1472 
1473   QualType NewType = New->getType();
1474   QualType OldType = Old->getType();
1475 
1476   // We're only interested in pointers and references to functions, as well
1477   // as pointers to member functions.
1478   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1479     NewType = R->getPointeeType();
1480     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1481   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1482     NewType = P->getPointeeType();
1483     OldType = OldType->getAs<PointerType>()->getPointeeType();
1484   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1485     NewType = M->getPointeeType();
1486     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1487   }
1488 
1489   if (!NewType->isFunctionProtoType())
1490     return;
1491 
1492   // There's lots of special cases for functions. For function pointers, system
1493   // libraries are hopefully not as broken so that we don't need these
1494   // workarounds.
1495   if (CheckEquivalentExceptionSpec(
1496         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1497         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1498     New->setInvalidDecl();
1499   }
1500 }
1501 
1502 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1503 /// function declaration are well-formed according to C++
1504 /// [dcl.fct.default].
1505 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1506   unsigned NumParams = FD->getNumParams();
1507   unsigned p;
1508 
1509   // Find first parameter with a default argument
1510   for (p = 0; p < NumParams; ++p) {
1511     ParmVarDecl *Param = FD->getParamDecl(p);
1512     if (Param->hasDefaultArg())
1513       break;
1514   }
1515 
1516   // C++11 [dcl.fct.default]p4:
1517   //   In a given function declaration, each parameter subsequent to a parameter
1518   //   with a default argument shall have a default argument supplied in this or
1519   //   a previous declaration or shall be a function parameter pack. A default
1520   //   argument shall not be redefined by a later declaration (not even to the
1521   //   same value).
1522   unsigned LastMissingDefaultArg = 0;
1523   for (; p < NumParams; ++p) {
1524     ParmVarDecl *Param = FD->getParamDecl(p);
1525     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1526       if (Param->isInvalidDecl())
1527         /* We already complained about this parameter. */;
1528       else if (Param->getIdentifier())
1529         Diag(Param->getLocation(),
1530              diag::err_param_default_argument_missing_name)
1531           << Param->getIdentifier();
1532       else
1533         Diag(Param->getLocation(),
1534              diag::err_param_default_argument_missing);
1535 
1536       LastMissingDefaultArg = p;
1537     }
1538   }
1539 
1540   if (LastMissingDefaultArg > 0) {
1541     // Some default arguments were missing. Clear out all of the
1542     // default arguments up to (and including) the last missing
1543     // default argument, so that we leave the function parameters
1544     // in a semantically valid state.
1545     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1546       ParmVarDecl *Param = FD->getParamDecl(p);
1547       if (Param->hasDefaultArg()) {
1548         Param->setDefaultArg(nullptr);
1549       }
1550     }
1551   }
1552 }
1553 
1554 // CheckConstexprParameterTypes - Check whether a function's parameter types
1555 // are all literal types. If so, return true. If not, produce a suitable
1556 // diagnostic and return false.
1557 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1558                                          const FunctionDecl *FD) {
1559   unsigned ArgIndex = 0;
1560   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1561   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1562                                               e = FT->param_type_end();
1563        i != e; ++i, ++ArgIndex) {
1564     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1565     SourceLocation ParamLoc = PD->getLocation();
1566     if (!(*i)->isDependentType() &&
1567         SemaRef.RequireLiteralType(ParamLoc, *i,
1568                                    diag::err_constexpr_non_literal_param,
1569                                    ArgIndex+1, PD->getSourceRange(),
1570                                    isa<CXXConstructorDecl>(FD)))
1571       return false;
1572   }
1573   return true;
1574 }
1575 
1576 /// Get diagnostic %select index for tag kind for
1577 /// record diagnostic message.
1578 /// WARNING: Indexes apply to particular diagnostics only!
1579 ///
1580 /// \returns diagnostic %select index.
1581 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1582   switch (Tag) {
1583   case TTK_Struct: return 0;
1584   case TTK_Interface: return 1;
1585   case TTK_Class:  return 2;
1586   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1587   }
1588 }
1589 
1590 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1591 // the requirements of a constexpr function definition or a constexpr
1592 // constructor definition. If so, return true. If not, produce appropriate
1593 // diagnostics and return false.
1594 //
1595 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1596 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1597   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1598   if (MD && MD->isInstance()) {
1599     // C++11 [dcl.constexpr]p4:
1600     //  The definition of a constexpr constructor shall satisfy the following
1601     //  constraints:
1602     //  - the class shall not have any virtual base classes;
1603     const CXXRecordDecl *RD = MD->getParent();
1604     if (RD->getNumVBases()) {
1605       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1606         << isa<CXXConstructorDecl>(NewFD)
1607         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1608       for (const auto &I : RD->vbases())
1609         Diag(I.getLocStart(),
1610              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1611       return false;
1612     }
1613   }
1614 
1615   if (!isa<CXXConstructorDecl>(NewFD)) {
1616     // C++11 [dcl.constexpr]p3:
1617     //  The definition of a constexpr function shall satisfy the following
1618     //  constraints:
1619     // - it shall not be virtual;
1620     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1621     if (Method && Method->isVirtual()) {
1622       Method = Method->getCanonicalDecl();
1623       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1624 
1625       // If it's not obvious why this function is virtual, find an overridden
1626       // function which uses the 'virtual' keyword.
1627       const CXXMethodDecl *WrittenVirtual = Method;
1628       while (!WrittenVirtual->isVirtualAsWritten())
1629         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1630       if (WrittenVirtual != Method)
1631         Diag(WrittenVirtual->getLocation(),
1632              diag::note_overridden_virtual_function);
1633       return false;
1634     }
1635 
1636     // - its return type shall be a literal type;
1637     QualType RT = NewFD->getReturnType();
1638     if (!RT->isDependentType() &&
1639         RequireLiteralType(NewFD->getLocation(), RT,
1640                            diag::err_constexpr_non_literal_return))
1641       return false;
1642   }
1643 
1644   // - each of its parameter types shall be a literal type;
1645   if (!CheckConstexprParameterTypes(*this, NewFD))
1646     return false;
1647 
1648   return true;
1649 }
1650 
1651 /// Check the given declaration statement is legal within a constexpr function
1652 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1653 ///
1654 /// \return true if the body is OK (maybe only as an extension), false if we
1655 ///         have diagnosed a problem.
1656 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1657                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1658   // C++11 [dcl.constexpr]p3 and p4:
1659   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1660   //  contain only
1661   for (const auto *DclIt : DS->decls()) {
1662     switch (DclIt->getKind()) {
1663     case Decl::StaticAssert:
1664     case Decl::Using:
1665     case Decl::UsingShadow:
1666     case Decl::UsingDirective:
1667     case Decl::UnresolvedUsingTypename:
1668     case Decl::UnresolvedUsingValue:
1669       //   - static_assert-declarations
1670       //   - using-declarations,
1671       //   - using-directives,
1672       continue;
1673 
1674     case Decl::Typedef:
1675     case Decl::TypeAlias: {
1676       //   - typedef declarations and alias-declarations that do not define
1677       //     classes or enumerations,
1678       const auto *TN = cast<TypedefNameDecl>(DclIt);
1679       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1680         // Don't allow variably-modified types in constexpr functions.
1681         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1682         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1683           << TL.getSourceRange() << TL.getType()
1684           << isa<CXXConstructorDecl>(Dcl);
1685         return false;
1686       }
1687       continue;
1688     }
1689 
1690     case Decl::Enum:
1691     case Decl::CXXRecord:
1692       // C++1y allows types to be defined, not just declared.
1693       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1694         SemaRef.Diag(DS->getLocStart(),
1695                      SemaRef.getLangOpts().CPlusPlus14
1696                        ? diag::warn_cxx11_compat_constexpr_type_definition
1697                        : diag::ext_constexpr_type_definition)
1698           << isa<CXXConstructorDecl>(Dcl);
1699       continue;
1700 
1701     case Decl::EnumConstant:
1702     case Decl::IndirectField:
1703     case Decl::ParmVar:
1704       // These can only appear with other declarations which are banned in
1705       // C++11 and permitted in C++1y, so ignore them.
1706       continue;
1707 
1708     case Decl::Var:
1709     case Decl::Decomposition: {
1710       // C++1y [dcl.constexpr]p3 allows anything except:
1711       //   a definition of a variable of non-literal type or of static or
1712       //   thread storage duration or for which no initialization is performed.
1713       const auto *VD = cast<VarDecl>(DclIt);
1714       if (VD->isThisDeclarationADefinition()) {
1715         if (VD->isStaticLocal()) {
1716           SemaRef.Diag(VD->getLocation(),
1717                        diag::err_constexpr_local_var_static)
1718             << isa<CXXConstructorDecl>(Dcl)
1719             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1720           return false;
1721         }
1722         if (!VD->getType()->isDependentType() &&
1723             SemaRef.RequireLiteralType(
1724               VD->getLocation(), VD->getType(),
1725               diag::err_constexpr_local_var_non_literal_type,
1726               isa<CXXConstructorDecl>(Dcl)))
1727           return false;
1728         if (!VD->getType()->isDependentType() &&
1729             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1730           SemaRef.Diag(VD->getLocation(),
1731                        diag::err_constexpr_local_var_no_init)
1732             << isa<CXXConstructorDecl>(Dcl);
1733           return false;
1734         }
1735       }
1736       SemaRef.Diag(VD->getLocation(),
1737                    SemaRef.getLangOpts().CPlusPlus14
1738                     ? diag::warn_cxx11_compat_constexpr_local_var
1739                     : diag::ext_constexpr_local_var)
1740         << isa<CXXConstructorDecl>(Dcl);
1741       continue;
1742     }
1743 
1744     case Decl::NamespaceAlias:
1745     case Decl::Function:
1746       // These are disallowed in C++11 and permitted in C++1y. Allow them
1747       // everywhere as an extension.
1748       if (!Cxx1yLoc.isValid())
1749         Cxx1yLoc = DS->getLocStart();
1750       continue;
1751 
1752     default:
1753       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1754         << isa<CXXConstructorDecl>(Dcl);
1755       return false;
1756     }
1757   }
1758 
1759   return true;
1760 }
1761 
1762 /// Check that the given field is initialized within a constexpr constructor.
1763 ///
1764 /// \param Dcl The constexpr constructor being checked.
1765 /// \param Field The field being checked. This may be a member of an anonymous
1766 ///        struct or union nested within the class being checked.
1767 /// \param Inits All declarations, including anonymous struct/union members and
1768 ///        indirect members, for which any initialization was provided.
1769 /// \param Diagnosed Set to true if an error is produced.
1770 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1771                                           const FunctionDecl *Dcl,
1772                                           FieldDecl *Field,
1773                                           llvm::SmallSet<Decl*, 16> &Inits,
1774                                           bool &Diagnosed) {
1775   if (Field->isInvalidDecl())
1776     return;
1777 
1778   if (Field->isUnnamedBitfield())
1779     return;
1780 
1781   // Anonymous unions with no variant members and empty anonymous structs do not
1782   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1783   // indirect fields don't need initializing.
1784   if (Field->isAnonymousStructOrUnion() &&
1785       (Field->getType()->isUnionType()
1786            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1787            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1788     return;
1789 
1790   if (!Inits.count(Field)) {
1791     if (!Diagnosed) {
1792       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1793       Diagnosed = true;
1794     }
1795     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1796   } else if (Field->isAnonymousStructOrUnion()) {
1797     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1798     for (auto *I : RD->fields())
1799       // If an anonymous union contains an anonymous struct of which any member
1800       // is initialized, all members must be initialized.
1801       if (!RD->isUnion() || Inits.count(I))
1802         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1803   }
1804 }
1805 
1806 /// Check the provided statement is allowed in a constexpr function
1807 /// definition.
1808 static bool
1809 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1810                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1811                            SourceLocation &Cxx1yLoc) {
1812   // - its function-body shall be [...] a compound-statement that contains only
1813   switch (S->getStmtClass()) {
1814   case Stmt::NullStmtClass:
1815     //   - null statements,
1816     return true;
1817 
1818   case Stmt::DeclStmtClass:
1819     //   - static_assert-declarations
1820     //   - using-declarations,
1821     //   - using-directives,
1822     //   - typedef declarations and alias-declarations that do not define
1823     //     classes or enumerations,
1824     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1825       return false;
1826     return true;
1827 
1828   case Stmt::ReturnStmtClass:
1829     //   - and exactly one return statement;
1830     if (isa<CXXConstructorDecl>(Dcl)) {
1831       // C++1y allows return statements in constexpr constructors.
1832       if (!Cxx1yLoc.isValid())
1833         Cxx1yLoc = S->getLocStart();
1834       return true;
1835     }
1836 
1837     ReturnStmts.push_back(S->getLocStart());
1838     return true;
1839 
1840   case Stmt::CompoundStmtClass: {
1841     // C++1y allows compound-statements.
1842     if (!Cxx1yLoc.isValid())
1843       Cxx1yLoc = S->getLocStart();
1844 
1845     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1846     for (auto *BodyIt : CompStmt->body()) {
1847       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1848                                       Cxx1yLoc))
1849         return false;
1850     }
1851     return true;
1852   }
1853 
1854   case Stmt::AttributedStmtClass:
1855     if (!Cxx1yLoc.isValid())
1856       Cxx1yLoc = S->getLocStart();
1857     return true;
1858 
1859   case Stmt::IfStmtClass: {
1860     // C++1y allows if-statements.
1861     if (!Cxx1yLoc.isValid())
1862       Cxx1yLoc = S->getLocStart();
1863 
1864     IfStmt *If = cast<IfStmt>(S);
1865     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1866                                     Cxx1yLoc))
1867       return false;
1868     if (If->getElse() &&
1869         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1870                                     Cxx1yLoc))
1871       return false;
1872     return true;
1873   }
1874 
1875   case Stmt::WhileStmtClass:
1876   case Stmt::DoStmtClass:
1877   case Stmt::ForStmtClass:
1878   case Stmt::CXXForRangeStmtClass:
1879   case Stmt::ContinueStmtClass:
1880     // C++1y allows all of these. We don't allow them as extensions in C++11,
1881     // because they don't make sense without variable mutation.
1882     if (!SemaRef.getLangOpts().CPlusPlus14)
1883       break;
1884     if (!Cxx1yLoc.isValid())
1885       Cxx1yLoc = S->getLocStart();
1886     for (Stmt *SubStmt : S->children())
1887       if (SubStmt &&
1888           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1889                                       Cxx1yLoc))
1890         return false;
1891     return true;
1892 
1893   case Stmt::SwitchStmtClass:
1894   case Stmt::CaseStmtClass:
1895   case Stmt::DefaultStmtClass:
1896   case Stmt::BreakStmtClass:
1897     // C++1y allows switch-statements, and since they don't need variable
1898     // mutation, we can reasonably allow them in C++11 as an extension.
1899     if (!Cxx1yLoc.isValid())
1900       Cxx1yLoc = S->getLocStart();
1901     for (Stmt *SubStmt : S->children())
1902       if (SubStmt &&
1903           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1904                                       Cxx1yLoc))
1905         return false;
1906     return true;
1907 
1908   default:
1909     if (!isa<Expr>(S))
1910       break;
1911 
1912     // C++1y allows expression-statements.
1913     if (!Cxx1yLoc.isValid())
1914       Cxx1yLoc = S->getLocStart();
1915     return true;
1916   }
1917 
1918   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1919     << isa<CXXConstructorDecl>(Dcl);
1920   return false;
1921 }
1922 
1923 /// Check the body for the given constexpr function declaration only contains
1924 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1925 ///
1926 /// \return true if the body is OK, false if we have diagnosed a problem.
1927 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1928   if (isa<CXXTryStmt>(Body)) {
1929     // C++11 [dcl.constexpr]p3:
1930     //  The definition of a constexpr function shall satisfy the following
1931     //  constraints: [...]
1932     // - its function-body shall be = delete, = default, or a
1933     //   compound-statement
1934     //
1935     // C++11 [dcl.constexpr]p4:
1936     //  In the definition of a constexpr constructor, [...]
1937     // - its function-body shall not be a function-try-block;
1938     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1939       << isa<CXXConstructorDecl>(Dcl);
1940     return false;
1941   }
1942 
1943   SmallVector<SourceLocation, 4> ReturnStmts;
1944 
1945   // - its function-body shall be [...] a compound-statement that contains only
1946   //   [... list of cases ...]
1947   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1948   SourceLocation Cxx1yLoc;
1949   for (auto *BodyIt : CompBody->body()) {
1950     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1951       return false;
1952   }
1953 
1954   if (Cxx1yLoc.isValid())
1955     Diag(Cxx1yLoc,
1956          getLangOpts().CPlusPlus14
1957            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1958            : diag::ext_constexpr_body_invalid_stmt)
1959       << isa<CXXConstructorDecl>(Dcl);
1960 
1961   if (const CXXConstructorDecl *Constructor
1962         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1963     const CXXRecordDecl *RD = Constructor->getParent();
1964     // DR1359:
1965     // - every non-variant non-static data member and base class sub-object
1966     //   shall be initialized;
1967     // DR1460:
1968     // - if the class is a union having variant members, exactly one of them
1969     //   shall be initialized;
1970     if (RD->isUnion()) {
1971       if (Constructor->getNumCtorInitializers() == 0 &&
1972           RD->hasVariantMembers()) {
1973         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1974         return false;
1975       }
1976     } else if (!Constructor->isDependentContext() &&
1977                !Constructor->isDelegatingConstructor()) {
1978       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1979 
1980       // Skip detailed checking if we have enough initializers, and we would
1981       // allow at most one initializer per member.
1982       bool AnyAnonStructUnionMembers = false;
1983       unsigned Fields = 0;
1984       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1985            E = RD->field_end(); I != E; ++I, ++Fields) {
1986         if (I->isAnonymousStructOrUnion()) {
1987           AnyAnonStructUnionMembers = true;
1988           break;
1989         }
1990       }
1991       // DR1460:
1992       // - if the class is a union-like class, but is not a union, for each of
1993       //   its anonymous union members having variant members, exactly one of
1994       //   them shall be initialized;
1995       if (AnyAnonStructUnionMembers ||
1996           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1997         // Check initialization of non-static data members. Base classes are
1998         // always initialized so do not need to be checked. Dependent bases
1999         // might not have initializers in the member initializer list.
2000         llvm::SmallSet<Decl*, 16> Inits;
2001         for (const auto *I: Constructor->inits()) {
2002           if (FieldDecl *FD = I->getMember())
2003             Inits.insert(FD);
2004           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2005             Inits.insert(ID->chain_begin(), ID->chain_end());
2006         }
2007 
2008         bool Diagnosed = false;
2009         for (auto *I : RD->fields())
2010           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2011         if (Diagnosed)
2012           return false;
2013       }
2014     }
2015   } else {
2016     if (ReturnStmts.empty()) {
2017       // C++1y doesn't require constexpr functions to contain a 'return'
2018       // statement. We still do, unless the return type might be void, because
2019       // otherwise if there's no return statement, the function cannot
2020       // be used in a core constant expression.
2021       bool OK = getLangOpts().CPlusPlus14 &&
2022                 (Dcl->getReturnType()->isVoidType() ||
2023                  Dcl->getReturnType()->isDependentType());
2024       Diag(Dcl->getLocation(),
2025            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2026               : diag::err_constexpr_body_no_return);
2027       if (!OK)
2028         return false;
2029     } else if (ReturnStmts.size() > 1) {
2030       Diag(ReturnStmts.back(),
2031            getLangOpts().CPlusPlus14
2032              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2033              : diag::ext_constexpr_body_multiple_return);
2034       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2035         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2036     }
2037   }
2038 
2039   // C++11 [dcl.constexpr]p5:
2040   //   if no function argument values exist such that the function invocation
2041   //   substitution would produce a constant expression, the program is
2042   //   ill-formed; no diagnostic required.
2043   // C++11 [dcl.constexpr]p3:
2044   //   - every constructor call and implicit conversion used in initializing the
2045   //     return value shall be one of those allowed in a constant expression.
2046   // C++11 [dcl.constexpr]p4:
2047   //   - every constructor involved in initializing non-static data members and
2048   //     base class sub-objects shall be a constexpr constructor.
2049   SmallVector<PartialDiagnosticAt, 8> Diags;
2050   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2051     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2052       << isa<CXXConstructorDecl>(Dcl);
2053     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2054       Diag(Diags[I].first, Diags[I].second);
2055     // Don't return false here: we allow this for compatibility in
2056     // system headers.
2057   }
2058 
2059   return true;
2060 }
2061 
2062 /// Get the class that is directly named by the current context. This is the
2063 /// class for which an unqualified-id in this scope could name a constructor
2064 /// or destructor.
2065 ///
2066 /// If the scope specifier denotes a class, this will be that class.
2067 /// If the scope specifier is empty, this will be the class whose
2068 /// member-specification we are currently within. Otherwise, there
2069 /// is no such class.
2070 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2071   assert(getLangOpts().CPlusPlus && "No class names in C!");
2072 
2073   if (SS && SS->isInvalid())
2074     return nullptr;
2075 
2076   if (SS && SS->isNotEmpty()) {
2077     DeclContext *DC = computeDeclContext(*SS, true);
2078     return dyn_cast_or_null<CXXRecordDecl>(DC);
2079   }
2080 
2081   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2082 }
2083 
2084 /// isCurrentClassName - Determine whether the identifier II is the
2085 /// name of the class type currently being defined. In the case of
2086 /// nested classes, this will only return true if II is the name of
2087 /// the innermost class.
2088 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2089                               const CXXScopeSpec *SS) {
2090   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2091   return CurDecl && &II == CurDecl->getIdentifier();
2092 }
2093 
2094 /// Determine whether the identifier II is a typo for the name of
2095 /// the class type currently being defined. If so, update it to the identifier
2096 /// that should have been used.
2097 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2098   assert(getLangOpts().CPlusPlus && "No class names in C!");
2099 
2100   if (!getLangOpts().SpellChecking)
2101     return false;
2102 
2103   CXXRecordDecl *CurDecl;
2104   if (SS && SS->isSet() && !SS->isInvalid()) {
2105     DeclContext *DC = computeDeclContext(*SS, true);
2106     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2107   } else
2108     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2109 
2110   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2111       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2112           < II->getLength()) {
2113     II = CurDecl->getIdentifier();
2114     return true;
2115   }
2116 
2117   return false;
2118 }
2119 
2120 /// Determine whether the given class is a base class of the given
2121 /// class, including looking at dependent bases.
2122 static bool findCircularInheritance(const CXXRecordDecl *Class,
2123                                     const CXXRecordDecl *Current) {
2124   SmallVector<const CXXRecordDecl*, 8> Queue;
2125 
2126   Class = Class->getCanonicalDecl();
2127   while (true) {
2128     for (const auto &I : Current->bases()) {
2129       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2130       if (!Base)
2131         continue;
2132 
2133       Base = Base->getDefinition();
2134       if (!Base)
2135         continue;
2136 
2137       if (Base->getCanonicalDecl() == Class)
2138         return true;
2139 
2140       Queue.push_back(Base);
2141     }
2142 
2143     if (Queue.empty())
2144       return false;
2145 
2146     Current = Queue.pop_back_val();
2147   }
2148 
2149   return false;
2150 }
2151 
2152 /// Check the validity of a C++ base class specifier.
2153 ///
2154 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2155 /// and returns NULL otherwise.
2156 CXXBaseSpecifier *
2157 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2158                          SourceRange SpecifierRange,
2159                          bool Virtual, AccessSpecifier Access,
2160                          TypeSourceInfo *TInfo,
2161                          SourceLocation EllipsisLoc) {
2162   QualType BaseType = TInfo->getType();
2163 
2164   // C++ [class.union]p1:
2165   //   A union shall not have base classes.
2166   if (Class->isUnion()) {
2167     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2168       << SpecifierRange;
2169     return nullptr;
2170   }
2171 
2172   if (EllipsisLoc.isValid() &&
2173       !TInfo->getType()->containsUnexpandedParameterPack()) {
2174     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2175       << TInfo->getTypeLoc().getSourceRange();
2176     EllipsisLoc = SourceLocation();
2177   }
2178 
2179   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2180 
2181   if (BaseType->isDependentType()) {
2182     // Make sure that we don't have circular inheritance among our dependent
2183     // bases. For non-dependent bases, the check for completeness below handles
2184     // this.
2185     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2186       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2187           ((BaseDecl = BaseDecl->getDefinition()) &&
2188            findCircularInheritance(Class, BaseDecl))) {
2189         Diag(BaseLoc, diag::err_circular_inheritance)
2190           << BaseType << Context.getTypeDeclType(Class);
2191 
2192         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2193           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2194             << BaseType;
2195 
2196         return nullptr;
2197       }
2198     }
2199 
2200     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2201                                           Class->getTagKind() == TTK_Class,
2202                                           Access, TInfo, EllipsisLoc);
2203   }
2204 
2205   // Base specifiers must be record types.
2206   if (!BaseType->isRecordType()) {
2207     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2208     return nullptr;
2209   }
2210 
2211   // C++ [class.union]p1:
2212   //   A union shall not be used as a base class.
2213   if (BaseType->isUnionType()) {
2214     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2215     return nullptr;
2216   }
2217 
2218   // For the MS ABI, propagate DLL attributes to base class templates.
2219   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2220     if (Attr *ClassAttr = getDLLAttr(Class)) {
2221       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2222               BaseType->getAsCXXRecordDecl())) {
2223         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2224                                             BaseLoc);
2225       }
2226     }
2227   }
2228 
2229   // C++ [class.derived]p2:
2230   //   The class-name in a base-specifier shall not be an incompletely
2231   //   defined class.
2232   if (RequireCompleteType(BaseLoc, BaseType,
2233                           diag::err_incomplete_base_class, SpecifierRange)) {
2234     Class->setInvalidDecl();
2235     return nullptr;
2236   }
2237 
2238   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2239   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2240   assert(BaseDecl && "Record type has no declaration");
2241   BaseDecl = BaseDecl->getDefinition();
2242   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2243   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2244   assert(CXXBaseDecl && "Base type is not a C++ type");
2245 
2246   // Microsoft docs say:
2247   // "If a base-class has a code_seg attribute, derived classes must have the
2248   // same attribute."
2249   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2250   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2251   if ((DerivedCSA || BaseCSA) &&
2252       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2253     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2254     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2255       << CXXBaseDecl;
2256     return nullptr;
2257   }
2258 
2259   // A class which contains a flexible array member is not suitable for use as a
2260   // base class:
2261   //   - If the layout determines that a base comes before another base,
2262   //     the flexible array member would index into the subsequent base.
2263   //   - If the layout determines that base comes before the derived class,
2264   //     the flexible array member would index into the derived class.
2265   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2266     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2267       << CXXBaseDecl->getDeclName();
2268     return nullptr;
2269   }
2270 
2271   // C++ [class]p3:
2272   //   If a class is marked final and it appears as a base-type-specifier in
2273   //   base-clause, the program is ill-formed.
2274   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2275     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2276       << CXXBaseDecl->getDeclName()
2277       << FA->isSpelledAsSealed();
2278     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2279         << CXXBaseDecl->getDeclName() << FA->getRange();
2280     return nullptr;
2281   }
2282 
2283   if (BaseDecl->isInvalidDecl())
2284     Class->setInvalidDecl();
2285 
2286   // Create the base specifier.
2287   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2288                                         Class->getTagKind() == TTK_Class,
2289                                         Access, TInfo, EllipsisLoc);
2290 }
2291 
2292 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2293 /// one entry in the base class list of a class specifier, for
2294 /// example:
2295 ///    class foo : public bar, virtual private baz {
2296 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2297 BaseResult
2298 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2299                          ParsedAttributes &Attributes,
2300                          bool Virtual, AccessSpecifier Access,
2301                          ParsedType basetype, SourceLocation BaseLoc,
2302                          SourceLocation EllipsisLoc) {
2303   if (!classdecl)
2304     return true;
2305 
2306   AdjustDeclIfTemplate(classdecl);
2307   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2308   if (!Class)
2309     return true;
2310 
2311   // We haven't yet attached the base specifiers.
2312   Class->setIsParsingBaseSpecifiers();
2313 
2314   // We do not support any C++11 attributes on base-specifiers yet.
2315   // Diagnose any attributes we see.
2316   for (const ParsedAttr &AL : Attributes) {
2317     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2318       continue;
2319     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2320                           ? diag::warn_unknown_attribute_ignored
2321                           : diag::err_base_specifier_attribute)
2322         << AL.getName();
2323   }
2324 
2325   TypeSourceInfo *TInfo = nullptr;
2326   GetTypeFromParser(basetype, &TInfo);
2327 
2328   if (EllipsisLoc.isInvalid() &&
2329       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2330                                       UPPC_BaseType))
2331     return true;
2332 
2333   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2334                                                       Virtual, Access, TInfo,
2335                                                       EllipsisLoc))
2336     return BaseSpec;
2337   else
2338     Class->setInvalidDecl();
2339 
2340   return true;
2341 }
2342 
2343 /// Use small set to collect indirect bases.  As this is only used
2344 /// locally, there's no need to abstract the small size parameter.
2345 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2346 
2347 /// Recursively add the bases of Type.  Don't add Type itself.
2348 static void
2349 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2350                   const QualType &Type)
2351 {
2352   // Even though the incoming type is a base, it might not be
2353   // a class -- it could be a template parm, for instance.
2354   if (auto Rec = Type->getAs<RecordType>()) {
2355     auto Decl = Rec->getAsCXXRecordDecl();
2356 
2357     // Iterate over its bases.
2358     for (const auto &BaseSpec : Decl->bases()) {
2359       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2360         .getUnqualifiedType();
2361       if (Set.insert(Base).second)
2362         // If we've not already seen it, recurse.
2363         NoteIndirectBases(Context, Set, Base);
2364     }
2365   }
2366 }
2367 
2368 /// Performs the actual work of attaching the given base class
2369 /// specifiers to a C++ class.
2370 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2371                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2372  if (Bases.empty())
2373     return false;
2374 
2375   // Used to keep track of which base types we have already seen, so
2376   // that we can properly diagnose redundant direct base types. Note
2377   // that the key is always the unqualified canonical type of the base
2378   // class.
2379   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2380 
2381   // Used to track indirect bases so we can see if a direct base is
2382   // ambiguous.
2383   IndirectBaseSet IndirectBaseTypes;
2384 
2385   // Copy non-redundant base specifiers into permanent storage.
2386   unsigned NumGoodBases = 0;
2387   bool Invalid = false;
2388   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2389     QualType NewBaseType
2390       = Context.getCanonicalType(Bases[idx]->getType());
2391     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2392 
2393     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2394     if (KnownBase) {
2395       // C++ [class.mi]p3:
2396       //   A class shall not be specified as a direct base class of a
2397       //   derived class more than once.
2398       Diag(Bases[idx]->getLocStart(),
2399            diag::err_duplicate_base_class)
2400         << KnownBase->getType()
2401         << Bases[idx]->getSourceRange();
2402 
2403       // Delete the duplicate base class specifier; we're going to
2404       // overwrite its pointer later.
2405       Context.Deallocate(Bases[idx]);
2406 
2407       Invalid = true;
2408     } else {
2409       // Okay, add this new base class.
2410       KnownBase = Bases[idx];
2411       Bases[NumGoodBases++] = Bases[idx];
2412 
2413       // Note this base's direct & indirect bases, if there could be ambiguity.
2414       if (Bases.size() > 1)
2415         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2416 
2417       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2418         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2419         if (Class->isInterface() &&
2420               (!RD->isInterfaceLike() ||
2421                KnownBase->getAccessSpecifier() != AS_public)) {
2422           // The Microsoft extension __interface does not permit bases that
2423           // are not themselves public interfaces.
2424           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2425             << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2426             << RD->getSourceRange();
2427           Invalid = true;
2428         }
2429         if (RD->hasAttr<WeakAttr>())
2430           Class->addAttr(WeakAttr::CreateImplicit(Context));
2431       }
2432     }
2433   }
2434 
2435   // Attach the remaining base class specifiers to the derived class.
2436   Class->setBases(Bases.data(), NumGoodBases);
2437 
2438   // Check that the only base classes that are duplicate are virtual.
2439   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2440     // Check whether this direct base is inaccessible due to ambiguity.
2441     QualType BaseType = Bases[idx]->getType();
2442 
2443     // Skip all dependent types in templates being used as base specifiers.
2444     // Checks below assume that the base specifier is a CXXRecord.
2445     if (BaseType->isDependentType())
2446       continue;
2447 
2448     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2449       .getUnqualifiedType();
2450 
2451     if (IndirectBaseTypes.count(CanonicalBase)) {
2452       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2453                          /*DetectVirtual=*/true);
2454       bool found
2455         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2456       assert(found);
2457       (void)found;
2458 
2459       if (Paths.isAmbiguous(CanonicalBase))
2460         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2461           << BaseType << getAmbiguousPathsDisplayString(Paths)
2462           << Bases[idx]->getSourceRange();
2463       else
2464         assert(Bases[idx]->isVirtual());
2465     }
2466 
2467     // Delete the base class specifier, since its data has been copied
2468     // into the CXXRecordDecl.
2469     Context.Deallocate(Bases[idx]);
2470   }
2471 
2472   return Invalid;
2473 }
2474 
2475 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2476 /// class, after checking whether there are any duplicate base
2477 /// classes.
2478 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2479                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2480   if (!ClassDecl || Bases.empty())
2481     return;
2482 
2483   AdjustDeclIfTemplate(ClassDecl);
2484   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2485 }
2486 
2487 /// Determine whether the type \p Derived is a C++ class that is
2488 /// derived from the type \p Base.
2489 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2490   if (!getLangOpts().CPlusPlus)
2491     return false;
2492 
2493   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2494   if (!DerivedRD)
2495     return false;
2496 
2497   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2498   if (!BaseRD)
2499     return false;
2500 
2501   // If either the base or the derived type is invalid, don't try to
2502   // check whether one is derived from the other.
2503   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2504     return false;
2505 
2506   // FIXME: In a modules build, do we need the entire path to be visible for us
2507   // to be able to use the inheritance relationship?
2508   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2509     return false;
2510 
2511   return DerivedRD->isDerivedFrom(BaseRD);
2512 }
2513 
2514 /// Determine whether the type \p Derived is a C++ class that is
2515 /// derived from the type \p Base.
2516 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2517                          CXXBasePaths &Paths) {
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 (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2530     return false;
2531 
2532   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2533 }
2534 
2535 static void BuildBasePathArray(const CXXBasePath &Path,
2536                                CXXCastPath &BasePathArray) {
2537   // We first go backward and check if we have a virtual base.
2538   // FIXME: It would be better if CXXBasePath had the base specifier for
2539   // the nearest virtual base.
2540   unsigned Start = 0;
2541   for (unsigned I = Path.size(); I != 0; --I) {
2542     if (Path[I - 1].Base->isVirtual()) {
2543       Start = I - 1;
2544       break;
2545     }
2546   }
2547 
2548   // Now add all bases.
2549   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2550     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2551 }
2552 
2553 
2554 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2555                               CXXCastPath &BasePathArray) {
2556   assert(BasePathArray.empty() && "Base path array must be empty!");
2557   assert(Paths.isRecordingPaths() && "Must record paths!");
2558   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2559 }
2560 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2561 /// conversion (where Derived and Base are class types) is
2562 /// well-formed, meaning that the conversion is unambiguous (and
2563 /// that all of the base classes are accessible). Returns true
2564 /// and emits a diagnostic if the code is ill-formed, returns false
2565 /// otherwise. Loc is the location where this routine should point to
2566 /// if there is an error, and Range is the source range to highlight
2567 /// if there is an error.
2568 ///
2569 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2570 /// diagnostic for the respective type of error will be suppressed, but the
2571 /// check for ill-formed code will still be performed.
2572 bool
2573 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2574                                    unsigned InaccessibleBaseID,
2575                                    unsigned AmbigiousBaseConvID,
2576                                    SourceLocation Loc, SourceRange Range,
2577                                    DeclarationName Name,
2578                                    CXXCastPath *BasePath,
2579                                    bool IgnoreAccess) {
2580   // First, determine whether the path from Derived to Base is
2581   // ambiguous. This is slightly more expensive than checking whether
2582   // the Derived to Base conversion exists, because here we need to
2583   // explore multiple paths to determine if there is an ambiguity.
2584   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2585                      /*DetectVirtual=*/false);
2586   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2587   if (!DerivationOkay)
2588     return true;
2589 
2590   const CXXBasePath *Path = nullptr;
2591   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2592     Path = &Paths.front();
2593 
2594   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2595   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2596   // user to access such bases.
2597   if (!Path && getLangOpts().MSVCCompat) {
2598     for (const CXXBasePath &PossiblePath : Paths) {
2599       if (PossiblePath.size() == 1) {
2600         Path = &PossiblePath;
2601         if (AmbigiousBaseConvID)
2602           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2603               << Base << Derived << Range;
2604         break;
2605       }
2606     }
2607   }
2608 
2609   if (Path) {
2610     if (!IgnoreAccess) {
2611       // Check that the base class can be accessed.
2612       switch (
2613           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2614       case AR_inaccessible:
2615         return true;
2616       case AR_accessible:
2617       case AR_dependent:
2618       case AR_delayed:
2619         break;
2620       }
2621     }
2622 
2623     // Build a base path if necessary.
2624     if (BasePath)
2625       ::BuildBasePathArray(*Path, *BasePath);
2626     return false;
2627   }
2628 
2629   if (AmbigiousBaseConvID) {
2630     // We know that the derived-to-base conversion is ambiguous, and
2631     // we're going to produce a diagnostic. Perform the derived-to-base
2632     // search just one more time to compute all of the possible paths so
2633     // that we can print them out. This is more expensive than any of
2634     // the previous derived-to-base checks we've done, but at this point
2635     // performance isn't as much of an issue.
2636     Paths.clear();
2637     Paths.setRecordingPaths(true);
2638     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2639     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2640     (void)StillOkay;
2641 
2642     // Build up a textual representation of the ambiguous paths, e.g.,
2643     // D -> B -> A, that will be used to illustrate the ambiguous
2644     // conversions in the diagnostic. We only print one of the paths
2645     // to each base class subobject.
2646     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2647 
2648     Diag(Loc, AmbigiousBaseConvID)
2649     << Derived << Base << PathDisplayStr << Range << Name;
2650   }
2651   return true;
2652 }
2653 
2654 bool
2655 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2656                                    SourceLocation Loc, SourceRange Range,
2657                                    CXXCastPath *BasePath,
2658                                    bool IgnoreAccess) {
2659   return CheckDerivedToBaseConversion(
2660       Derived, Base, diag::err_upcast_to_inaccessible_base,
2661       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2662       BasePath, IgnoreAccess);
2663 }
2664 
2665 
2666 /// Builds a string representing ambiguous paths from a
2667 /// specific derived class to different subobjects of the same base
2668 /// class.
2669 ///
2670 /// This function builds a string that can be used in error messages
2671 /// to show the different paths that one can take through the
2672 /// inheritance hierarchy to go from the derived class to different
2673 /// subobjects of a base class. The result looks something like this:
2674 /// @code
2675 /// struct D -> struct B -> struct A
2676 /// struct D -> struct C -> struct A
2677 /// @endcode
2678 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2679   std::string PathDisplayStr;
2680   std::set<unsigned> DisplayedPaths;
2681   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2682        Path != Paths.end(); ++Path) {
2683     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2684       // We haven't displayed a path to this particular base
2685       // class subobject yet.
2686       PathDisplayStr += "\n    ";
2687       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2688       for (CXXBasePath::const_iterator Element = Path->begin();
2689            Element != Path->end(); ++Element)
2690         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2691     }
2692   }
2693 
2694   return PathDisplayStr;
2695 }
2696 
2697 //===----------------------------------------------------------------------===//
2698 // C++ class member Handling
2699 //===----------------------------------------------------------------------===//
2700 
2701 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2702 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2703                                 SourceLocation ColonLoc,
2704                                 const ParsedAttributesView &Attrs) {
2705   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2706   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2707                                                   ASLoc, ColonLoc);
2708   CurContext->addHiddenDecl(ASDecl);
2709   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2710 }
2711 
2712 /// CheckOverrideControl - Check C++11 override control semantics.
2713 void Sema::CheckOverrideControl(NamedDecl *D) {
2714   if (D->isInvalidDecl())
2715     return;
2716 
2717   // We only care about "override" and "final" declarations.
2718   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2719     return;
2720 
2721   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2722 
2723   // We can't check dependent instance methods.
2724   if (MD && MD->isInstance() &&
2725       (MD->getParent()->hasAnyDependentBases() ||
2726        MD->getType()->isDependentType()))
2727     return;
2728 
2729   if (MD && !MD->isVirtual()) {
2730     // If we have a non-virtual method, check if if hides a virtual method.
2731     // (In that case, it's most likely the method has the wrong type.)
2732     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2733     FindHiddenVirtualMethods(MD, OverloadedMethods);
2734 
2735     if (!OverloadedMethods.empty()) {
2736       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2737         Diag(OA->getLocation(),
2738              diag::override_keyword_hides_virtual_member_function)
2739           << "override" << (OverloadedMethods.size() > 1);
2740       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2741         Diag(FA->getLocation(),
2742              diag::override_keyword_hides_virtual_member_function)
2743           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2744           << (OverloadedMethods.size() > 1);
2745       }
2746       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2747       MD->setInvalidDecl();
2748       return;
2749     }
2750     // Fall through into the general case diagnostic.
2751     // FIXME: We might want to attempt typo correction here.
2752   }
2753 
2754   if (!MD || !MD->isVirtual()) {
2755     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2756       Diag(OA->getLocation(),
2757            diag::override_keyword_only_allowed_on_virtual_member_functions)
2758         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2759       D->dropAttr<OverrideAttr>();
2760     }
2761     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2762       Diag(FA->getLocation(),
2763            diag::override_keyword_only_allowed_on_virtual_member_functions)
2764         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2765         << FixItHint::CreateRemoval(FA->getLocation());
2766       D->dropAttr<FinalAttr>();
2767     }
2768     return;
2769   }
2770 
2771   // C++11 [class.virtual]p5:
2772   //   If a function is marked with the virt-specifier override and
2773   //   does not override a member function of a base class, the program is
2774   //   ill-formed.
2775   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2776   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2777     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2778       << MD->getDeclName();
2779 }
2780 
2781 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2782   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2783     return;
2784   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2785   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2786     return;
2787 
2788   SourceLocation Loc = MD->getLocation();
2789   SourceLocation SpellingLoc = Loc;
2790   if (getSourceManager().isMacroArgExpansion(Loc))
2791     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2792   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2793   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2794       return;
2795 
2796   if (MD->size_overridden_methods() > 0) {
2797     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2798                           ? diag::warn_destructor_marked_not_override_overriding
2799                           : diag::warn_function_marked_not_override_overriding;
2800     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2801     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2802     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2803   }
2804 }
2805 
2806 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2807 /// function overrides a virtual member function marked 'final', according to
2808 /// C++11 [class.virtual]p4.
2809 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2810                                                   const CXXMethodDecl *Old) {
2811   FinalAttr *FA = Old->getAttr<FinalAttr>();
2812   if (!FA)
2813     return false;
2814 
2815   Diag(New->getLocation(), diag::err_final_function_overridden)
2816     << New->getDeclName()
2817     << FA->isSpelledAsSealed();
2818   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2819   return true;
2820 }
2821 
2822 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2823   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2824   // FIXME: Destruction of ObjC lifetime types has side-effects.
2825   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2826     return !RD->isCompleteDefinition() ||
2827            !RD->hasTrivialDefaultConstructor() ||
2828            !RD->hasTrivialDestructor();
2829   return false;
2830 }
2831 
2832 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2833   ParsedAttributesView::const_iterator Itr =
2834       llvm::find_if(list, [](const ParsedAttr &AL) {
2835         return AL.isDeclspecPropertyAttribute();
2836       });
2837   if (Itr != list.end())
2838     return &*Itr;
2839   return nullptr;
2840 }
2841 
2842 // Check if there is a field shadowing.
2843 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2844                                       DeclarationName FieldName,
2845                                       const CXXRecordDecl *RD) {
2846   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2847     return;
2848 
2849   // To record a shadowed field in a base
2850   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2851   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2852                            CXXBasePath &Path) {
2853     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2854     // Record an ambiguous path directly
2855     if (Bases.find(Base) != Bases.end())
2856       return true;
2857     for (const auto Field : Base->lookup(FieldName)) {
2858       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2859           Field->getAccess() != AS_private) {
2860         assert(Field->getAccess() != AS_none);
2861         assert(Bases.find(Base) == Bases.end());
2862         Bases[Base] = Field;
2863         return true;
2864       }
2865     }
2866     return false;
2867   };
2868 
2869   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2870                      /*DetectVirtual=*/true);
2871   if (!RD->lookupInBases(FieldShadowed, Paths))
2872     return;
2873 
2874   for (const auto &P : Paths) {
2875     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2876     auto It = Bases.find(Base);
2877     // Skip duplicated bases
2878     if (It == Bases.end())
2879       continue;
2880     auto BaseField = It->second;
2881     assert(BaseField->getAccess() != AS_private);
2882     if (AS_none !=
2883         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2884       Diag(Loc, diag::warn_shadow_field)
2885         << FieldName << RD << Base;
2886       Diag(BaseField->getLocation(), diag::note_shadow_field);
2887       Bases.erase(It);
2888     }
2889   }
2890 }
2891 
2892 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2893 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2894 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2895 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2896 /// present (but parsing it has been deferred).
2897 NamedDecl *
2898 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2899                                MultiTemplateParamsArg TemplateParameterLists,
2900                                Expr *BW, const VirtSpecifiers &VS,
2901                                InClassInitStyle InitStyle) {
2902   const DeclSpec &DS = D.getDeclSpec();
2903   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2904   DeclarationName Name = NameInfo.getName();
2905   SourceLocation Loc = NameInfo.getLoc();
2906 
2907   // For anonymous bitfields, the location should point to the type.
2908   if (Loc.isInvalid())
2909     Loc = D.getLocStart();
2910 
2911   Expr *BitWidth = static_cast<Expr*>(BW);
2912 
2913   assert(isa<CXXRecordDecl>(CurContext));
2914   assert(!DS.isFriendSpecified());
2915 
2916   bool isFunc = D.isDeclarationOfFunction();
2917   const ParsedAttr *MSPropertyAttr =
2918       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2919 
2920   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2921     // The Microsoft extension __interface only permits public member functions
2922     // and prohibits constructors, destructors, operators, non-public member
2923     // functions, static methods and data members.
2924     unsigned InvalidDecl;
2925     bool ShowDeclName = true;
2926     if (!isFunc &&
2927         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2928       InvalidDecl = 0;
2929     else if (!isFunc)
2930       InvalidDecl = 1;
2931     else if (AS != AS_public)
2932       InvalidDecl = 2;
2933     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2934       InvalidDecl = 3;
2935     else switch (Name.getNameKind()) {
2936       case DeclarationName::CXXConstructorName:
2937         InvalidDecl = 4;
2938         ShowDeclName = false;
2939         break;
2940 
2941       case DeclarationName::CXXDestructorName:
2942         InvalidDecl = 5;
2943         ShowDeclName = false;
2944         break;
2945 
2946       case DeclarationName::CXXOperatorName:
2947       case DeclarationName::CXXConversionFunctionName:
2948         InvalidDecl = 6;
2949         break;
2950 
2951       default:
2952         InvalidDecl = 0;
2953         break;
2954     }
2955 
2956     if (InvalidDecl) {
2957       if (ShowDeclName)
2958         Diag(Loc, diag::err_invalid_member_in_interface)
2959           << (InvalidDecl-1) << Name;
2960       else
2961         Diag(Loc, diag::err_invalid_member_in_interface)
2962           << (InvalidDecl-1) << "";
2963       return nullptr;
2964     }
2965   }
2966 
2967   // C++ 9.2p6: A member shall not be declared to have automatic storage
2968   // duration (auto, register) or with the extern storage-class-specifier.
2969   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2970   // data members and cannot be applied to names declared const or static,
2971   // and cannot be applied to reference members.
2972   switch (DS.getStorageClassSpec()) {
2973   case DeclSpec::SCS_unspecified:
2974   case DeclSpec::SCS_typedef:
2975   case DeclSpec::SCS_static:
2976     break;
2977   case DeclSpec::SCS_mutable:
2978     if (isFunc) {
2979       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2980 
2981       // FIXME: It would be nicer if the keyword was ignored only for this
2982       // declarator. Otherwise we could get follow-up errors.
2983       D.getMutableDeclSpec().ClearStorageClassSpecs();
2984     }
2985     break;
2986   default:
2987     Diag(DS.getStorageClassSpecLoc(),
2988          diag::err_storageclass_invalid_for_member);
2989     D.getMutableDeclSpec().ClearStorageClassSpecs();
2990     break;
2991   }
2992 
2993   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2994                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2995                       !isFunc);
2996 
2997   if (DS.isConstexprSpecified() && isInstField) {
2998     SemaDiagnosticBuilder B =
2999         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3000     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3001     if (InitStyle == ICIS_NoInit) {
3002       B << 0 << 0;
3003       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3004         B << FixItHint::CreateRemoval(ConstexprLoc);
3005       else {
3006         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3007         D.getMutableDeclSpec().ClearConstexprSpec();
3008         const char *PrevSpec;
3009         unsigned DiagID;
3010         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3011             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3012         (void)Failed;
3013         assert(!Failed && "Making a constexpr member const shouldn't fail");
3014       }
3015     } else {
3016       B << 1;
3017       const char *PrevSpec;
3018       unsigned DiagID;
3019       if (D.getMutableDeclSpec().SetStorageClassSpec(
3020           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3021           Context.getPrintingPolicy())) {
3022         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3023                "This is the only DeclSpec that should fail to be applied");
3024         B << 1;
3025       } else {
3026         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3027         isInstField = false;
3028       }
3029     }
3030   }
3031 
3032   NamedDecl *Member;
3033   if (isInstField) {
3034     CXXScopeSpec &SS = D.getCXXScopeSpec();
3035 
3036     // Data members must have identifiers for names.
3037     if (!Name.isIdentifier()) {
3038       Diag(Loc, diag::err_bad_variable_name)
3039         << Name;
3040       return nullptr;
3041     }
3042 
3043     IdentifierInfo *II = Name.getAsIdentifierInfo();
3044 
3045     // Member field could not be with "template" keyword.
3046     // So TemplateParameterLists should be empty in this case.
3047     if (TemplateParameterLists.size()) {
3048       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3049       if (TemplateParams->size()) {
3050         // There is no such thing as a member field template.
3051         Diag(D.getIdentifierLoc(), diag::err_template_member)
3052             << II
3053             << SourceRange(TemplateParams->getTemplateLoc(),
3054                 TemplateParams->getRAngleLoc());
3055       } else {
3056         // There is an extraneous 'template<>' for this member.
3057         Diag(TemplateParams->getTemplateLoc(),
3058             diag::err_template_member_noparams)
3059             << II
3060             << SourceRange(TemplateParams->getTemplateLoc(),
3061                 TemplateParams->getRAngleLoc());
3062       }
3063       return nullptr;
3064     }
3065 
3066     if (SS.isSet() && !SS.isInvalid()) {
3067       // The user provided a superfluous scope specifier inside a class
3068       // definition:
3069       //
3070       // class X {
3071       //   int X::member;
3072       // };
3073       if (DeclContext *DC = computeDeclContext(SS, false))
3074         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3075                                      D.getName().getKind() ==
3076                                          UnqualifiedIdKind::IK_TemplateId);
3077       else
3078         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3079           << Name << SS.getRange();
3080 
3081       SS.clear();
3082     }
3083 
3084     if (MSPropertyAttr) {
3085       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3086                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3087       if (!Member)
3088         return nullptr;
3089       isInstField = false;
3090     } else {
3091       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3092                                 BitWidth, InitStyle, AS);
3093       if (!Member)
3094         return nullptr;
3095     }
3096 
3097     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3098   } else {
3099     Member = HandleDeclarator(S, D, TemplateParameterLists);
3100     if (!Member)
3101       return nullptr;
3102 
3103     // Non-instance-fields can't have a bitfield.
3104     if (BitWidth) {
3105       if (Member->isInvalidDecl()) {
3106         // don't emit another diagnostic.
3107       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3108         // C++ 9.6p3: A bit-field shall not be a static member.
3109         // "static member 'A' cannot be a bit-field"
3110         Diag(Loc, diag::err_static_not_bitfield)
3111           << Name << BitWidth->getSourceRange();
3112       } else if (isa<TypedefDecl>(Member)) {
3113         // "typedef member 'x' cannot be a bit-field"
3114         Diag(Loc, diag::err_typedef_not_bitfield)
3115           << Name << BitWidth->getSourceRange();
3116       } else {
3117         // A function typedef ("typedef int f(); f a;").
3118         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3119         Diag(Loc, diag::err_not_integral_type_bitfield)
3120           << Name << cast<ValueDecl>(Member)->getType()
3121           << BitWidth->getSourceRange();
3122       }
3123 
3124       BitWidth = nullptr;
3125       Member->setInvalidDecl();
3126     }
3127 
3128     NamedDecl *NonTemplateMember = Member;
3129     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3130       NonTemplateMember = FunTmpl->getTemplatedDecl();
3131     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3132       NonTemplateMember = VarTmpl->getTemplatedDecl();
3133 
3134     Member->setAccess(AS);
3135 
3136     // If we have declared a member function template or static data member
3137     // template, set the access of the templated declaration as well.
3138     if (NonTemplateMember != Member)
3139       NonTemplateMember->setAccess(AS);
3140 
3141     // C++ [temp.deduct.guide]p3:
3142     //   A deduction guide [...] for a member class template [shall be
3143     //   declared] with the same access [as the template].
3144     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3145       auto *TD = DG->getDeducedTemplate();
3146       if (AS != TD->getAccess()) {
3147         Diag(DG->getLocStart(), diag::err_deduction_guide_wrong_access);
3148         Diag(TD->getLocStart(), diag::note_deduction_guide_template_access)
3149           << TD->getAccess();
3150         const AccessSpecDecl *LastAccessSpec = nullptr;
3151         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3152           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3153             LastAccessSpec = AccessSpec;
3154         }
3155         assert(LastAccessSpec && "differing access with no access specifier");
3156         Diag(LastAccessSpec->getLocStart(), diag::note_deduction_guide_access)
3157           << AS;
3158       }
3159     }
3160   }
3161 
3162   if (VS.isOverrideSpecified())
3163     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3164   if (VS.isFinalSpecified())
3165     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3166                                             VS.isFinalSpelledSealed()));
3167 
3168   if (VS.getLastLocation().isValid()) {
3169     // Update the end location of a method that has a virt-specifiers.
3170     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3171       MD->setRangeEnd(VS.getLastLocation());
3172   }
3173 
3174   CheckOverrideControl(Member);
3175 
3176   assert((Name || isInstField) && "No identifier for non-field ?");
3177 
3178   if (isInstField) {
3179     FieldDecl *FD = cast<FieldDecl>(Member);
3180     FieldCollector->Add(FD);
3181 
3182     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3183       // Remember all explicit private FieldDecls that have a name, no side
3184       // effects and are not part of a dependent type declaration.
3185       if (!FD->isImplicit() && FD->getDeclName() &&
3186           FD->getAccess() == AS_private &&
3187           !FD->hasAttr<UnusedAttr>() &&
3188           !FD->getParent()->isDependentContext() &&
3189           !InitializationHasSideEffects(*FD))
3190         UnusedPrivateFields.insert(FD);
3191     }
3192   }
3193 
3194   return Member;
3195 }
3196 
3197 namespace {
3198   class UninitializedFieldVisitor
3199       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3200     Sema &S;
3201     // List of Decls to generate a warning on.  Also remove Decls that become
3202     // initialized.
3203     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3204     // List of base classes of the record.  Classes are removed after their
3205     // initializers.
3206     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3207     // Vector of decls to be removed from the Decl set prior to visiting the
3208     // nodes.  These Decls may have been initialized in the prior initializer.
3209     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3210     // If non-null, add a note to the warning pointing back to the constructor.
3211     const CXXConstructorDecl *Constructor;
3212     // Variables to hold state when processing an initializer list.  When
3213     // InitList is true, special case initialization of FieldDecls matching
3214     // InitListFieldDecl.
3215     bool InitList;
3216     FieldDecl *InitListFieldDecl;
3217     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3218 
3219   public:
3220     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3221     UninitializedFieldVisitor(Sema &S,
3222                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3223                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3224       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3225         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3226 
3227     // Returns true if the use of ME is not an uninitialized use.
3228     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3229                                          bool CheckReferenceOnly) {
3230       llvm::SmallVector<FieldDecl*, 4> Fields;
3231       bool ReferenceField = false;
3232       while (ME) {
3233         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3234         if (!FD)
3235           return false;
3236         Fields.push_back(FD);
3237         if (FD->getType()->isReferenceType())
3238           ReferenceField = true;
3239         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3240       }
3241 
3242       // Binding a reference to an unintialized field is not an
3243       // uninitialized use.
3244       if (CheckReferenceOnly && !ReferenceField)
3245         return true;
3246 
3247       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3248       // Discard the first field since it is the field decl that is being
3249       // initialized.
3250       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3251         UsedFieldIndex.push_back((*I)->getFieldIndex());
3252       }
3253 
3254       for (auto UsedIter = UsedFieldIndex.begin(),
3255                 UsedEnd = UsedFieldIndex.end(),
3256                 OrigIter = InitFieldIndex.begin(),
3257                 OrigEnd = InitFieldIndex.end();
3258            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3259         if (*UsedIter < *OrigIter)
3260           return true;
3261         if (*UsedIter > *OrigIter)
3262           break;
3263       }
3264 
3265       return false;
3266     }
3267 
3268     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3269                           bool AddressOf) {
3270       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3271         return;
3272 
3273       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3274       // or union.
3275       MemberExpr *FieldME = ME;
3276 
3277       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3278 
3279       Expr *Base = ME;
3280       while (MemberExpr *SubME =
3281                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3282 
3283         if (isa<VarDecl>(SubME->getMemberDecl()))
3284           return;
3285 
3286         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3287           if (!FD->isAnonymousStructOrUnion())
3288             FieldME = SubME;
3289 
3290         if (!FieldME->getType().isPODType(S.Context))
3291           AllPODFields = false;
3292 
3293         Base = SubME->getBase();
3294       }
3295 
3296       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3297         return;
3298 
3299       if (AddressOf && AllPODFields)
3300         return;
3301 
3302       ValueDecl* FoundVD = FieldME->getMemberDecl();
3303 
3304       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3305         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3306           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3307         }
3308 
3309         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3310           QualType T = BaseCast->getType();
3311           if (T->isPointerType() &&
3312               BaseClasses.count(T->getPointeeType())) {
3313             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3314                 << T->getPointeeType() << FoundVD;
3315           }
3316         }
3317       }
3318 
3319       if (!Decls.count(FoundVD))
3320         return;
3321 
3322       const bool IsReference = FoundVD->getType()->isReferenceType();
3323 
3324       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3325         // Special checking for initializer lists.
3326         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3327           return;
3328         }
3329       } else {
3330         // Prevent double warnings on use of unbounded references.
3331         if (CheckReferenceOnly && !IsReference)
3332           return;
3333       }
3334 
3335       unsigned diag = IsReference
3336           ? diag::warn_reference_field_is_uninit
3337           : diag::warn_field_is_uninit;
3338       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3339       if (Constructor)
3340         S.Diag(Constructor->getLocation(),
3341                diag::note_uninit_in_this_constructor)
3342           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3343 
3344     }
3345 
3346     void HandleValue(Expr *E, bool AddressOf) {
3347       E = E->IgnoreParens();
3348 
3349       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3350         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3351                          AddressOf /*AddressOf*/);
3352         return;
3353       }
3354 
3355       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3356         Visit(CO->getCond());
3357         HandleValue(CO->getTrueExpr(), AddressOf);
3358         HandleValue(CO->getFalseExpr(), AddressOf);
3359         return;
3360       }
3361 
3362       if (BinaryConditionalOperator *BCO =
3363               dyn_cast<BinaryConditionalOperator>(E)) {
3364         Visit(BCO->getCond());
3365         HandleValue(BCO->getFalseExpr(), AddressOf);
3366         return;
3367       }
3368 
3369       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3370         HandleValue(OVE->getSourceExpr(), AddressOf);
3371         return;
3372       }
3373 
3374       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3375         switch (BO->getOpcode()) {
3376         default:
3377           break;
3378         case(BO_PtrMemD):
3379         case(BO_PtrMemI):
3380           HandleValue(BO->getLHS(), AddressOf);
3381           Visit(BO->getRHS());
3382           return;
3383         case(BO_Comma):
3384           Visit(BO->getLHS());
3385           HandleValue(BO->getRHS(), AddressOf);
3386           return;
3387         }
3388       }
3389 
3390       Visit(E);
3391     }
3392 
3393     void CheckInitListExpr(InitListExpr *ILE) {
3394       InitFieldIndex.push_back(0);
3395       for (auto Child : ILE->children()) {
3396         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3397           CheckInitListExpr(SubList);
3398         } else {
3399           Visit(Child);
3400         }
3401         ++InitFieldIndex.back();
3402       }
3403       InitFieldIndex.pop_back();
3404     }
3405 
3406     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3407                           FieldDecl *Field, const Type *BaseClass) {
3408       // Remove Decls that may have been initialized in the previous
3409       // initializer.
3410       for (ValueDecl* VD : DeclsToRemove)
3411         Decls.erase(VD);
3412       DeclsToRemove.clear();
3413 
3414       Constructor = FieldConstructor;
3415       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3416 
3417       if (ILE && Field) {
3418         InitList = true;
3419         InitListFieldDecl = Field;
3420         InitFieldIndex.clear();
3421         CheckInitListExpr(ILE);
3422       } else {
3423         InitList = false;
3424         Visit(E);
3425       }
3426 
3427       if (Field)
3428         Decls.erase(Field);
3429       if (BaseClass)
3430         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3431     }
3432 
3433     void VisitMemberExpr(MemberExpr *ME) {
3434       // All uses of unbounded reference fields will warn.
3435       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3436     }
3437 
3438     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3439       if (E->getCastKind() == CK_LValueToRValue) {
3440         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3441         return;
3442       }
3443 
3444       Inherited::VisitImplicitCastExpr(E);
3445     }
3446 
3447     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3448       if (E->getConstructor()->isCopyConstructor()) {
3449         Expr *ArgExpr = E->getArg(0);
3450         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3451           if (ILE->getNumInits() == 1)
3452             ArgExpr = ILE->getInit(0);
3453         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3454           if (ICE->getCastKind() == CK_NoOp)
3455             ArgExpr = ICE->getSubExpr();
3456         HandleValue(ArgExpr, false /*AddressOf*/);
3457         return;
3458       }
3459       Inherited::VisitCXXConstructExpr(E);
3460     }
3461 
3462     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3463       Expr *Callee = E->getCallee();
3464       if (isa<MemberExpr>(Callee)) {
3465         HandleValue(Callee, false /*AddressOf*/);
3466         for (auto Arg : E->arguments())
3467           Visit(Arg);
3468         return;
3469       }
3470 
3471       Inherited::VisitCXXMemberCallExpr(E);
3472     }
3473 
3474     void VisitCallExpr(CallExpr *E) {
3475       // Treat std::move as a use.
3476       if (E->isCallToStdMove()) {
3477         HandleValue(E->getArg(0), /*AddressOf=*/false);
3478         return;
3479       }
3480 
3481       Inherited::VisitCallExpr(E);
3482     }
3483 
3484     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3485       Expr *Callee = E->getCallee();
3486 
3487       if (isa<UnresolvedLookupExpr>(Callee))
3488         return Inherited::VisitCXXOperatorCallExpr(E);
3489 
3490       Visit(Callee);
3491       for (auto Arg : E->arguments())
3492         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3493     }
3494 
3495     void VisitBinaryOperator(BinaryOperator *E) {
3496       // If a field assignment is detected, remove the field from the
3497       // uninitiailized field set.
3498       if (E->getOpcode() == BO_Assign)
3499         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3500           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3501             if (!FD->getType()->isReferenceType())
3502               DeclsToRemove.push_back(FD);
3503 
3504       if (E->isCompoundAssignmentOp()) {
3505         HandleValue(E->getLHS(), false /*AddressOf*/);
3506         Visit(E->getRHS());
3507         return;
3508       }
3509 
3510       Inherited::VisitBinaryOperator(E);
3511     }
3512 
3513     void VisitUnaryOperator(UnaryOperator *E) {
3514       if (E->isIncrementDecrementOp()) {
3515         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3516         return;
3517       }
3518       if (E->getOpcode() == UO_AddrOf) {
3519         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3520           HandleValue(ME->getBase(), true /*AddressOf*/);
3521           return;
3522         }
3523       }
3524 
3525       Inherited::VisitUnaryOperator(E);
3526     }
3527   };
3528 
3529   // Diagnose value-uses of fields to initialize themselves, e.g.
3530   //   foo(foo)
3531   // where foo is not also a parameter to the constructor.
3532   // Also diagnose across field uninitialized use such as
3533   //   x(y), y(x)
3534   // TODO: implement -Wuninitialized and fold this into that framework.
3535   static void DiagnoseUninitializedFields(
3536       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3537 
3538     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3539                                            Constructor->getLocation())) {
3540       return;
3541     }
3542 
3543     if (Constructor->isInvalidDecl())
3544       return;
3545 
3546     const CXXRecordDecl *RD = Constructor->getParent();
3547 
3548     if (RD->getDescribedClassTemplate())
3549       return;
3550 
3551     // Holds fields that are uninitialized.
3552     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3553 
3554     // At the beginning, all fields are uninitialized.
3555     for (auto *I : RD->decls()) {
3556       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3557         UninitializedFields.insert(FD);
3558       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3559         UninitializedFields.insert(IFD->getAnonField());
3560       }
3561     }
3562 
3563     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3564     for (auto I : RD->bases())
3565       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3566 
3567     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3568       return;
3569 
3570     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3571                                                    UninitializedFields,
3572                                                    UninitializedBaseClasses);
3573 
3574     for (const auto *FieldInit : Constructor->inits()) {
3575       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3576         break;
3577 
3578       Expr *InitExpr = FieldInit->getInit();
3579       if (!InitExpr)
3580         continue;
3581 
3582       if (CXXDefaultInitExpr *Default =
3583               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3584         InitExpr = Default->getExpr();
3585         if (!InitExpr)
3586           continue;
3587         // In class initializers will point to the constructor.
3588         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3589                                               FieldInit->getAnyMember(),
3590                                               FieldInit->getBaseClass());
3591       } else {
3592         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3593                                               FieldInit->getAnyMember(),
3594                                               FieldInit->getBaseClass());
3595       }
3596     }
3597   }
3598 } // namespace
3599 
3600 /// Enter a new C++ default initializer scope. After calling this, the
3601 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3602 /// parsing or instantiating the initializer failed.
3603 void Sema::ActOnStartCXXInClassMemberInitializer() {
3604   // Create a synthetic function scope to represent the call to the constructor
3605   // that notionally surrounds a use of this initializer.
3606   PushFunctionScope();
3607 }
3608 
3609 /// This is invoked after parsing an in-class initializer for a
3610 /// non-static C++ class member, and after instantiating an in-class initializer
3611 /// in a class template. Such actions are deferred until the class is complete.
3612 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3613                                                   SourceLocation InitLoc,
3614                                                   Expr *InitExpr) {
3615   // Pop the notional constructor scope we created earlier.
3616   PopFunctionScopeInfo(nullptr, D);
3617 
3618   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3619   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3620          "must set init style when field is created");
3621 
3622   if (!InitExpr) {
3623     D->setInvalidDecl();
3624     if (FD)
3625       FD->removeInClassInitializer();
3626     return;
3627   }
3628 
3629   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3630     FD->setInvalidDecl();
3631     FD->removeInClassInitializer();
3632     return;
3633   }
3634 
3635   ExprResult Init = InitExpr;
3636   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3637     InitializedEntity Entity =
3638         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3639     InitializationKind Kind =
3640         FD->getInClassInitStyle() == ICIS_ListInit
3641             ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3642                                                    InitExpr->getLocStart(),
3643                                                    InitExpr->getLocEnd())
3644             : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3645     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3646     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3647     if (Init.isInvalid()) {
3648       FD->setInvalidDecl();
3649       return;
3650     }
3651   }
3652 
3653   // C++11 [class.base.init]p7:
3654   //   The initialization of each base and member constitutes a
3655   //   full-expression.
3656   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3657   if (Init.isInvalid()) {
3658     FD->setInvalidDecl();
3659     return;
3660   }
3661 
3662   InitExpr = Init.get();
3663 
3664   FD->setInClassInitializer(InitExpr);
3665 }
3666 
3667 /// Find the direct and/or virtual base specifiers that
3668 /// correspond to the given base type, for use in base initialization
3669 /// within a constructor.
3670 static bool FindBaseInitializer(Sema &SemaRef,
3671                                 CXXRecordDecl *ClassDecl,
3672                                 QualType BaseType,
3673                                 const CXXBaseSpecifier *&DirectBaseSpec,
3674                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3675   // First, check for a direct base class.
3676   DirectBaseSpec = nullptr;
3677   for (const auto &Base : ClassDecl->bases()) {
3678     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3679       // We found a direct base of this type. That's what we're
3680       // initializing.
3681       DirectBaseSpec = &Base;
3682       break;
3683     }
3684   }
3685 
3686   // Check for a virtual base class.
3687   // FIXME: We might be able to short-circuit this if we know in advance that
3688   // there are no virtual bases.
3689   VirtualBaseSpec = nullptr;
3690   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3691     // We haven't found a base yet; search the class hierarchy for a
3692     // virtual base class.
3693     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3694                        /*DetectVirtual=*/false);
3695     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3696                               SemaRef.Context.getTypeDeclType(ClassDecl),
3697                               BaseType, Paths)) {
3698       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3699            Path != Paths.end(); ++Path) {
3700         if (Path->back().Base->isVirtual()) {
3701           VirtualBaseSpec = Path->back().Base;
3702           break;
3703         }
3704       }
3705     }
3706   }
3707 
3708   return DirectBaseSpec || VirtualBaseSpec;
3709 }
3710 
3711 /// Handle a C++ member initializer using braced-init-list syntax.
3712 MemInitResult
3713 Sema::ActOnMemInitializer(Decl *ConstructorD,
3714                           Scope *S,
3715                           CXXScopeSpec &SS,
3716                           IdentifierInfo *MemberOrBase,
3717                           ParsedType TemplateTypeTy,
3718                           const DeclSpec &DS,
3719                           SourceLocation IdLoc,
3720                           Expr *InitList,
3721                           SourceLocation EllipsisLoc) {
3722   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3723                              DS, IdLoc, InitList,
3724                              EllipsisLoc);
3725 }
3726 
3727 /// Handle a C++ member initializer using parentheses syntax.
3728 MemInitResult
3729 Sema::ActOnMemInitializer(Decl *ConstructorD,
3730                           Scope *S,
3731                           CXXScopeSpec &SS,
3732                           IdentifierInfo *MemberOrBase,
3733                           ParsedType TemplateTypeTy,
3734                           const DeclSpec &DS,
3735                           SourceLocation IdLoc,
3736                           SourceLocation LParenLoc,
3737                           ArrayRef<Expr *> Args,
3738                           SourceLocation RParenLoc,
3739                           SourceLocation EllipsisLoc) {
3740   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3741                                            Args, RParenLoc);
3742   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3743                              DS, IdLoc, List, EllipsisLoc);
3744 }
3745 
3746 namespace {
3747 
3748 // Callback to only accept typo corrections that can be a valid C++ member
3749 // intializer: either a non-static field member or a base class.
3750 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3751 public:
3752   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3753       : ClassDecl(ClassDecl) {}
3754 
3755   bool ValidateCandidate(const TypoCorrection &candidate) override {
3756     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3757       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3758         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3759       return isa<TypeDecl>(ND);
3760     }
3761     return false;
3762   }
3763 
3764 private:
3765   CXXRecordDecl *ClassDecl;
3766 };
3767 
3768 }
3769 
3770 /// Handle a C++ member initializer.
3771 MemInitResult
3772 Sema::BuildMemInitializer(Decl *ConstructorD,
3773                           Scope *S,
3774                           CXXScopeSpec &SS,
3775                           IdentifierInfo *MemberOrBase,
3776                           ParsedType TemplateTypeTy,
3777                           const DeclSpec &DS,
3778                           SourceLocation IdLoc,
3779                           Expr *Init,
3780                           SourceLocation EllipsisLoc) {
3781   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3782   if (!Res.isUsable())
3783     return true;
3784   Init = Res.get();
3785 
3786   if (!ConstructorD)
3787     return true;
3788 
3789   AdjustDeclIfTemplate(ConstructorD);
3790 
3791   CXXConstructorDecl *Constructor
3792     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3793   if (!Constructor) {
3794     // The user wrote a constructor initializer on a function that is
3795     // not a C++ constructor. Ignore the error for now, because we may
3796     // have more member initializers coming; we'll diagnose it just
3797     // once in ActOnMemInitializers.
3798     return true;
3799   }
3800 
3801   CXXRecordDecl *ClassDecl = Constructor->getParent();
3802 
3803   // C++ [class.base.init]p2:
3804   //   Names in a mem-initializer-id are looked up in the scope of the
3805   //   constructor's class and, if not found in that scope, are looked
3806   //   up in the scope containing the constructor's definition.
3807   //   [Note: if the constructor's class contains a member with the
3808   //   same name as a direct or virtual base class of the class, a
3809   //   mem-initializer-id naming the member or base class and composed
3810   //   of a single identifier refers to the class member. A
3811   //   mem-initializer-id for the hidden base class may be specified
3812   //   using a qualified name. ]
3813   if (!SS.getScopeRep() && !TemplateTypeTy) {
3814     // Look for a member, first.
3815     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3816     if (!Result.empty()) {
3817       ValueDecl *Member;
3818       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3819           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3820         if (EllipsisLoc.isValid())
3821           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3822             << MemberOrBase
3823             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3824 
3825         return BuildMemberInitializer(Member, Init, IdLoc);
3826       }
3827     }
3828   }
3829   // It didn't name a member, so see if it names a class.
3830   QualType BaseType;
3831   TypeSourceInfo *TInfo = nullptr;
3832 
3833   if (TemplateTypeTy) {
3834     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3835   } else if (DS.getTypeSpecType() == TST_decltype) {
3836     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3837   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3838     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3839     return true;
3840   } else {
3841     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3842     LookupParsedName(R, S, &SS);
3843 
3844     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3845     if (!TyD) {
3846       if (R.isAmbiguous()) return true;
3847 
3848       // We don't want access-control diagnostics here.
3849       R.suppressDiagnostics();
3850 
3851       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3852         bool NotUnknownSpecialization = false;
3853         DeclContext *DC = computeDeclContext(SS, false);
3854         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3855           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3856 
3857         if (!NotUnknownSpecialization) {
3858           // When the scope specifier can refer to a member of an unknown
3859           // specialization, we take it as a type name.
3860           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3861                                        SS.getWithLocInContext(Context),
3862                                        *MemberOrBase, IdLoc);
3863           if (BaseType.isNull())
3864             return true;
3865 
3866           TInfo = Context.CreateTypeSourceInfo(BaseType);
3867           DependentNameTypeLoc TL =
3868               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3869           if (!TL.isNull()) {
3870             TL.setNameLoc(IdLoc);
3871             TL.setElaboratedKeywordLoc(SourceLocation());
3872             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3873           }
3874 
3875           R.clear();
3876           R.setLookupName(MemberOrBase);
3877         }
3878       }
3879 
3880       // If no results were found, try to correct typos.
3881       TypoCorrection Corr;
3882       if (R.empty() && BaseType.isNull() &&
3883           (Corr = CorrectTypo(
3884                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3885                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3886                CTK_ErrorRecovery, ClassDecl))) {
3887         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3888           // We have found a non-static data member with a similar
3889           // name to what was typed; complain and initialize that
3890           // member.
3891           diagnoseTypo(Corr,
3892                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3893                          << MemberOrBase << true);
3894           return BuildMemberInitializer(Member, Init, IdLoc);
3895         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3896           const CXXBaseSpecifier *DirectBaseSpec;
3897           const CXXBaseSpecifier *VirtualBaseSpec;
3898           if (FindBaseInitializer(*this, ClassDecl,
3899                                   Context.getTypeDeclType(Type),
3900                                   DirectBaseSpec, VirtualBaseSpec)) {
3901             // We have found a direct or virtual base class with a
3902             // similar name to what was typed; complain and initialize
3903             // that base class.
3904             diagnoseTypo(Corr,
3905                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3906                            << MemberOrBase << false,
3907                          PDiag() /*Suppress note, we provide our own.*/);
3908 
3909             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3910                                                               : VirtualBaseSpec;
3911             Diag(BaseSpec->getLocStart(),
3912                  diag::note_base_class_specified_here)
3913               << BaseSpec->getType()
3914               << BaseSpec->getSourceRange();
3915 
3916             TyD = Type;
3917           }
3918         }
3919       }
3920 
3921       if (!TyD && BaseType.isNull()) {
3922         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3923           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3924         return true;
3925       }
3926     }
3927 
3928     if (BaseType.isNull()) {
3929       BaseType = Context.getTypeDeclType(TyD);
3930       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3931       if (SS.isSet()) {
3932         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3933                                              BaseType);
3934         TInfo = Context.CreateTypeSourceInfo(BaseType);
3935         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3936         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3937         TL.setElaboratedKeywordLoc(SourceLocation());
3938         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3939       }
3940     }
3941   }
3942 
3943   if (!TInfo)
3944     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3945 
3946   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3947 }
3948 
3949 /// Checks a member initializer expression for cases where reference (or
3950 /// pointer) members are bound to by-value parameters (or their addresses).
3951 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3952                                                Expr *Init,
3953                                                SourceLocation IdLoc) {
3954   QualType MemberTy = Member->getType();
3955 
3956   // We only handle pointers and references currently.
3957   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3958   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3959     return;
3960 
3961   const bool IsPointer = MemberTy->isPointerType();
3962   if (IsPointer) {
3963     if (const UnaryOperator *Op
3964           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3965       // The only case we're worried about with pointers requires taking the
3966       // address.
3967       if (Op->getOpcode() != UO_AddrOf)
3968         return;
3969 
3970       Init = Op->getSubExpr();
3971     } else {
3972       // We only handle address-of expression initializers for pointers.
3973       return;
3974     }
3975   }
3976 
3977   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3978     // We only warn when referring to a non-reference parameter declaration.
3979     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3980     if (!Parameter || Parameter->getType()->isReferenceType())
3981       return;
3982 
3983     S.Diag(Init->getExprLoc(),
3984            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3985                      : diag::warn_bind_ref_member_to_parameter)
3986       << Member << Parameter << Init->getSourceRange();
3987   } else {
3988     // Other initializers are fine.
3989     return;
3990   }
3991 
3992   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3993     << (unsigned)IsPointer;
3994 }
3995 
3996 MemInitResult
3997 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3998                              SourceLocation IdLoc) {
3999   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4000   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4001   assert((DirectMember || IndirectMember) &&
4002          "Member must be a FieldDecl or IndirectFieldDecl");
4003 
4004   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4005     return true;
4006 
4007   if (Member->isInvalidDecl())
4008     return true;
4009 
4010   MultiExprArg Args;
4011   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4012     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4013   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4014     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4015   } else {
4016     // Template instantiation doesn't reconstruct ParenListExprs for us.
4017     Args = Init;
4018   }
4019 
4020   SourceRange InitRange = Init->getSourceRange();
4021 
4022   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4023     // Can't check initialization for a member of dependent type or when
4024     // any of the arguments are type-dependent expressions.
4025     DiscardCleanupsInEvaluationContext();
4026   } else {
4027     bool InitList = false;
4028     if (isa<InitListExpr>(Init)) {
4029       InitList = true;
4030       Args = Init;
4031     }
4032 
4033     // Initialize the member.
4034     InitializedEntity MemberEntity =
4035       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4036                    : InitializedEntity::InitializeMember(IndirectMember,
4037                                                          nullptr);
4038     InitializationKind Kind =
4039         InitList ? InitializationKind::CreateDirectList(
4040                        IdLoc, Init->getLocStart(), Init->getLocEnd())
4041                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4042                                                     InitRange.getEnd());
4043 
4044     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4045     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4046                                             nullptr);
4047     if (MemberInit.isInvalid())
4048       return true;
4049 
4050     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
4051 
4052     // C++11 [class.base.init]p7:
4053     //   The initialization of each base and member constitutes a
4054     //   full-expression.
4055     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4056     if (MemberInit.isInvalid())
4057       return true;
4058 
4059     Init = MemberInit.get();
4060   }
4061 
4062   if (DirectMember) {
4063     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4064                                             InitRange.getBegin(), Init,
4065                                             InitRange.getEnd());
4066   } else {
4067     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4068                                             InitRange.getBegin(), Init,
4069                                             InitRange.getEnd());
4070   }
4071 }
4072 
4073 MemInitResult
4074 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4075                                  CXXRecordDecl *ClassDecl) {
4076   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4077   if (!LangOpts.CPlusPlus11)
4078     return Diag(NameLoc, diag::err_delegating_ctor)
4079       << TInfo->getTypeLoc().getLocalSourceRange();
4080   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4081 
4082   bool InitList = true;
4083   MultiExprArg Args = Init;
4084   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4085     InitList = false;
4086     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4087   }
4088 
4089   SourceRange InitRange = Init->getSourceRange();
4090   // Initialize the object.
4091   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4092                                      QualType(ClassDecl->getTypeForDecl(), 0));
4093   InitializationKind Kind =
4094       InitList ? InitializationKind::CreateDirectList(
4095                      NameLoc, Init->getLocStart(), Init->getLocEnd())
4096                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4097                                                   InitRange.getEnd());
4098   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4099   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4100                                               Args, nullptr);
4101   if (DelegationInit.isInvalid())
4102     return true;
4103 
4104   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4105          "Delegating constructor with no target?");
4106 
4107   // C++11 [class.base.init]p7:
4108   //   The initialization of each base and member constitutes a
4109   //   full-expression.
4110   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4111                                        InitRange.getBegin());
4112   if (DelegationInit.isInvalid())
4113     return true;
4114 
4115   // If we are in a dependent context, template instantiation will
4116   // perform this type-checking again. Just save the arguments that we
4117   // received in a ParenListExpr.
4118   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4119   // of the information that we have about the base
4120   // initializer. However, deconstructing the ASTs is a dicey process,
4121   // and this approach is far more likely to get the corner cases right.
4122   if (CurContext->isDependentContext())
4123     DelegationInit = Init;
4124 
4125   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4126                                           DelegationInit.getAs<Expr>(),
4127                                           InitRange.getEnd());
4128 }
4129 
4130 MemInitResult
4131 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4132                            Expr *Init, CXXRecordDecl *ClassDecl,
4133                            SourceLocation EllipsisLoc) {
4134   SourceLocation BaseLoc
4135     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4136 
4137   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4138     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4139              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4140 
4141   // C++ [class.base.init]p2:
4142   //   [...] Unless the mem-initializer-id names a nonstatic data
4143   //   member of the constructor's class or a direct or virtual base
4144   //   of that class, the mem-initializer is ill-formed. A
4145   //   mem-initializer-list can initialize a base class using any
4146   //   name that denotes that base class type.
4147   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4148 
4149   SourceRange InitRange = Init->getSourceRange();
4150   if (EllipsisLoc.isValid()) {
4151     // This is a pack expansion.
4152     if (!BaseType->containsUnexpandedParameterPack())  {
4153       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4154         << SourceRange(BaseLoc, InitRange.getEnd());
4155 
4156       EllipsisLoc = SourceLocation();
4157     }
4158   } else {
4159     // Check for any unexpanded parameter packs.
4160     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4161       return true;
4162 
4163     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4164       return true;
4165   }
4166 
4167   // Check for direct and virtual base classes.
4168   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4169   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4170   if (!Dependent) {
4171     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4172                                        BaseType))
4173       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4174 
4175     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4176                         VirtualBaseSpec);
4177 
4178     // C++ [base.class.init]p2:
4179     // Unless the mem-initializer-id names a nonstatic data member of the
4180     // constructor's class or a direct or virtual base of that class, the
4181     // mem-initializer is ill-formed.
4182     if (!DirectBaseSpec && !VirtualBaseSpec) {
4183       // If the class has any dependent bases, then it's possible that
4184       // one of those types will resolve to the same type as
4185       // BaseType. Therefore, just treat this as a dependent base
4186       // class initialization.  FIXME: Should we try to check the
4187       // initialization anyway? It seems odd.
4188       if (ClassDecl->hasAnyDependentBases())
4189         Dependent = true;
4190       else
4191         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4192           << BaseType << Context.getTypeDeclType(ClassDecl)
4193           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4194     }
4195   }
4196 
4197   if (Dependent) {
4198     DiscardCleanupsInEvaluationContext();
4199 
4200     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4201                                             /*IsVirtual=*/false,
4202                                             InitRange.getBegin(), Init,
4203                                             InitRange.getEnd(), EllipsisLoc);
4204   }
4205 
4206   // C++ [base.class.init]p2:
4207   //   If a mem-initializer-id is ambiguous because it designates both
4208   //   a direct non-virtual base class and an inherited virtual base
4209   //   class, the mem-initializer is ill-formed.
4210   if (DirectBaseSpec && VirtualBaseSpec)
4211     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4212       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4213 
4214   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4215   if (!BaseSpec)
4216     BaseSpec = VirtualBaseSpec;
4217 
4218   // Initialize the base.
4219   bool InitList = true;
4220   MultiExprArg Args = Init;
4221   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4222     InitList = false;
4223     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4224   }
4225 
4226   InitializedEntity BaseEntity =
4227     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4228   InitializationKind Kind =
4229       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4230                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4231                                                   InitRange.getEnd());
4232   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4233   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4234   if (BaseInit.isInvalid())
4235     return true;
4236 
4237   // C++11 [class.base.init]p7:
4238   //   The initialization of each base and member constitutes a
4239   //   full-expression.
4240   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4241   if (BaseInit.isInvalid())
4242     return true;
4243 
4244   // If we are in a dependent context, template instantiation will
4245   // perform this type-checking again. Just save the arguments that we
4246   // received in a ParenListExpr.
4247   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4248   // of the information that we have about the base
4249   // initializer. However, deconstructing the ASTs is a dicey process,
4250   // and this approach is far more likely to get the corner cases right.
4251   if (CurContext->isDependentContext())
4252     BaseInit = Init;
4253 
4254   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4255                                           BaseSpec->isVirtual(),
4256                                           InitRange.getBegin(),
4257                                           BaseInit.getAs<Expr>(),
4258                                           InitRange.getEnd(), EllipsisLoc);
4259 }
4260 
4261 // Create a static_cast\<T&&>(expr).
4262 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4263   if (T.isNull()) T = E->getType();
4264   QualType TargetType = SemaRef.BuildReferenceType(
4265       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4266   SourceLocation ExprLoc = E->getLocStart();
4267   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4268       TargetType, ExprLoc);
4269 
4270   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4271                                    SourceRange(ExprLoc, ExprLoc),
4272                                    E->getSourceRange()).get();
4273 }
4274 
4275 /// ImplicitInitializerKind - How an implicit base or member initializer should
4276 /// initialize its base or member.
4277 enum ImplicitInitializerKind {
4278   IIK_Default,
4279   IIK_Copy,
4280   IIK_Move,
4281   IIK_Inherit
4282 };
4283 
4284 static bool
4285 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4286                              ImplicitInitializerKind ImplicitInitKind,
4287                              CXXBaseSpecifier *BaseSpec,
4288                              bool IsInheritedVirtualBase,
4289                              CXXCtorInitializer *&CXXBaseInit) {
4290   InitializedEntity InitEntity
4291     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4292                                         IsInheritedVirtualBase);
4293 
4294   ExprResult BaseInit;
4295 
4296   switch (ImplicitInitKind) {
4297   case IIK_Inherit:
4298   case IIK_Default: {
4299     InitializationKind InitKind
4300       = InitializationKind::CreateDefault(Constructor->getLocation());
4301     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4302     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4303     break;
4304   }
4305 
4306   case IIK_Move:
4307   case IIK_Copy: {
4308     bool Moving = ImplicitInitKind == IIK_Move;
4309     ParmVarDecl *Param = Constructor->getParamDecl(0);
4310     QualType ParamType = Param->getType().getNonReferenceType();
4311 
4312     Expr *CopyCtorArg =
4313       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4314                           SourceLocation(), Param, false,
4315                           Constructor->getLocation(), ParamType,
4316                           VK_LValue, nullptr);
4317 
4318     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4319 
4320     // Cast to the base class to avoid ambiguities.
4321     QualType ArgTy =
4322       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4323                                        ParamType.getQualifiers());
4324 
4325     if (Moving) {
4326       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4327     }
4328 
4329     CXXCastPath BasePath;
4330     BasePath.push_back(BaseSpec);
4331     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4332                                             CK_UncheckedDerivedToBase,
4333                                             Moving ? VK_XValue : VK_LValue,
4334                                             &BasePath).get();
4335 
4336     InitializationKind InitKind
4337       = InitializationKind::CreateDirect(Constructor->getLocation(),
4338                                          SourceLocation(), SourceLocation());
4339     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4340     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4341     break;
4342   }
4343   }
4344 
4345   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4346   if (BaseInit.isInvalid())
4347     return true;
4348 
4349   CXXBaseInit =
4350     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4351                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4352                                                         SourceLocation()),
4353                                              BaseSpec->isVirtual(),
4354                                              SourceLocation(),
4355                                              BaseInit.getAs<Expr>(),
4356                                              SourceLocation(),
4357                                              SourceLocation());
4358 
4359   return false;
4360 }
4361 
4362 static bool RefersToRValueRef(Expr *MemRef) {
4363   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4364   return Referenced->getType()->isRValueReferenceType();
4365 }
4366 
4367 static bool
4368 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4369                                ImplicitInitializerKind ImplicitInitKind,
4370                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4371                                CXXCtorInitializer *&CXXMemberInit) {
4372   if (Field->isInvalidDecl())
4373     return true;
4374 
4375   SourceLocation Loc = Constructor->getLocation();
4376 
4377   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4378     bool Moving = ImplicitInitKind == IIK_Move;
4379     ParmVarDecl *Param = Constructor->getParamDecl(0);
4380     QualType ParamType = Param->getType().getNonReferenceType();
4381 
4382     // Suppress copying zero-width bitfields.
4383     if (Field->isZeroLengthBitField(SemaRef.Context))
4384       return false;
4385 
4386     Expr *MemberExprBase =
4387       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4388                           SourceLocation(), Param, false,
4389                           Loc, ParamType, VK_LValue, nullptr);
4390 
4391     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4392 
4393     if (Moving) {
4394       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4395     }
4396 
4397     // Build a reference to this field within the parameter.
4398     CXXScopeSpec SS;
4399     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4400                               Sema::LookupMemberName);
4401     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4402                                   : cast<ValueDecl>(Field), AS_public);
4403     MemberLookup.resolveKind();
4404     ExprResult CtorArg
4405       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4406                                          ParamType, Loc,
4407                                          /*IsArrow=*/false,
4408                                          SS,
4409                                          /*TemplateKWLoc=*/SourceLocation(),
4410                                          /*FirstQualifierInScope=*/nullptr,
4411                                          MemberLookup,
4412                                          /*TemplateArgs=*/nullptr,
4413                                          /*S*/nullptr);
4414     if (CtorArg.isInvalid())
4415       return true;
4416 
4417     // C++11 [class.copy]p15:
4418     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4419     //     with static_cast<T&&>(x.m);
4420     if (RefersToRValueRef(CtorArg.get())) {
4421       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4422     }
4423 
4424     InitializedEntity Entity =
4425         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4426                                                        /*Implicit*/ true)
4427                  : InitializedEntity::InitializeMember(Field, nullptr,
4428                                                        /*Implicit*/ true);
4429 
4430     // Direct-initialize to use the copy constructor.
4431     InitializationKind InitKind =
4432       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4433 
4434     Expr *CtorArgE = CtorArg.getAs<Expr>();
4435     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4436     ExprResult MemberInit =
4437         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4438     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4439     if (MemberInit.isInvalid())
4440       return true;
4441 
4442     if (Indirect)
4443       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4444           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4445     else
4446       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4447           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4448     return false;
4449   }
4450 
4451   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4452          "Unhandled implicit init kind!");
4453 
4454   QualType FieldBaseElementType =
4455     SemaRef.Context.getBaseElementType(Field->getType());
4456 
4457   if (FieldBaseElementType->isRecordType()) {
4458     InitializedEntity InitEntity =
4459         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4460                                                        /*Implicit*/ true)
4461                  : InitializedEntity::InitializeMember(Field, nullptr,
4462                                                        /*Implicit*/ true);
4463     InitializationKind InitKind =
4464       InitializationKind::CreateDefault(Loc);
4465 
4466     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4467     ExprResult MemberInit =
4468       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4469 
4470     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4471     if (MemberInit.isInvalid())
4472       return true;
4473 
4474     if (Indirect)
4475       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4476                                                                Indirect, Loc,
4477                                                                Loc,
4478                                                                MemberInit.get(),
4479                                                                Loc);
4480     else
4481       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4482                                                                Field, Loc, Loc,
4483                                                                MemberInit.get(),
4484                                                                Loc);
4485     return false;
4486   }
4487 
4488   if (!Field->getParent()->isUnion()) {
4489     if (FieldBaseElementType->isReferenceType()) {
4490       SemaRef.Diag(Constructor->getLocation(),
4491                    diag::err_uninitialized_member_in_ctor)
4492       << (int)Constructor->isImplicit()
4493       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4494       << 0 << Field->getDeclName();
4495       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4496       return true;
4497     }
4498 
4499     if (FieldBaseElementType.isConstQualified()) {
4500       SemaRef.Diag(Constructor->getLocation(),
4501                    diag::err_uninitialized_member_in_ctor)
4502       << (int)Constructor->isImplicit()
4503       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4504       << 1 << Field->getDeclName();
4505       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4506       return true;
4507     }
4508   }
4509 
4510   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4511     // ARC and Weak:
4512     //   Default-initialize Objective-C pointers to NULL.
4513     CXXMemberInit
4514       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4515                                                  Loc, Loc,
4516                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4517                                                  Loc);
4518     return false;
4519   }
4520 
4521   // Nothing to initialize.
4522   CXXMemberInit = nullptr;
4523   return false;
4524 }
4525 
4526 namespace {
4527 struct BaseAndFieldInfo {
4528   Sema &S;
4529   CXXConstructorDecl *Ctor;
4530   bool AnyErrorsInInits;
4531   ImplicitInitializerKind IIK;
4532   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4533   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4534   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4535 
4536   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4537     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4538     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4539     if (Ctor->getInheritedConstructor())
4540       IIK = IIK_Inherit;
4541     else if (Generated && Ctor->isCopyConstructor())
4542       IIK = IIK_Copy;
4543     else if (Generated && Ctor->isMoveConstructor())
4544       IIK = IIK_Move;
4545     else
4546       IIK = IIK_Default;
4547   }
4548 
4549   bool isImplicitCopyOrMove() const {
4550     switch (IIK) {
4551     case IIK_Copy:
4552     case IIK_Move:
4553       return true;
4554 
4555     case IIK_Default:
4556     case IIK_Inherit:
4557       return false;
4558     }
4559 
4560     llvm_unreachable("Invalid ImplicitInitializerKind!");
4561   }
4562 
4563   bool addFieldInitializer(CXXCtorInitializer *Init) {
4564     AllToInit.push_back(Init);
4565 
4566     // Check whether this initializer makes the field "used".
4567     if (Init->getInit()->HasSideEffects(S.Context))
4568       S.UnusedPrivateFields.remove(Init->getAnyMember());
4569 
4570     return false;
4571   }
4572 
4573   bool isInactiveUnionMember(FieldDecl *Field) {
4574     RecordDecl *Record = Field->getParent();
4575     if (!Record->isUnion())
4576       return false;
4577 
4578     if (FieldDecl *Active =
4579             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4580       return Active != Field->getCanonicalDecl();
4581 
4582     // In an implicit copy or move constructor, ignore any in-class initializer.
4583     if (isImplicitCopyOrMove())
4584       return true;
4585 
4586     // If there's no explicit initialization, the field is active only if it
4587     // has an in-class initializer...
4588     if (Field->hasInClassInitializer())
4589       return false;
4590     // ... or it's an anonymous struct or union whose class has an in-class
4591     // initializer.
4592     if (!Field->isAnonymousStructOrUnion())
4593       return true;
4594     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4595     return !FieldRD->hasInClassInitializer();
4596   }
4597 
4598   /// Determine whether the given field is, or is within, a union member
4599   /// that is inactive (because there was an initializer given for a different
4600   /// member of the union, or because the union was not initialized at all).
4601   bool isWithinInactiveUnionMember(FieldDecl *Field,
4602                                    IndirectFieldDecl *Indirect) {
4603     if (!Indirect)
4604       return isInactiveUnionMember(Field);
4605 
4606     for (auto *C : Indirect->chain()) {
4607       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4608       if (Field && isInactiveUnionMember(Field))
4609         return true;
4610     }
4611     return false;
4612   }
4613 };
4614 }
4615 
4616 /// Determine whether the given type is an incomplete or zero-lenfgth
4617 /// array type.
4618 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4619   if (T->isIncompleteArrayType())
4620     return true;
4621 
4622   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4623     if (!ArrayT->getSize())
4624       return true;
4625 
4626     T = ArrayT->getElementType();
4627   }
4628 
4629   return false;
4630 }
4631 
4632 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4633                                     FieldDecl *Field,
4634                                     IndirectFieldDecl *Indirect = nullptr) {
4635   if (Field->isInvalidDecl())
4636     return false;
4637 
4638   // Overwhelmingly common case: we have a direct initializer for this field.
4639   if (CXXCtorInitializer *Init =
4640           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4641     return Info.addFieldInitializer(Init);
4642 
4643   // C++11 [class.base.init]p8:
4644   //   if the entity is a non-static data member that has a
4645   //   brace-or-equal-initializer and either
4646   //   -- the constructor's class is a union and no other variant member of that
4647   //      union is designated by a mem-initializer-id or
4648   //   -- the constructor's class is not a union, and, if the entity is a member
4649   //      of an anonymous union, no other member of that union is designated by
4650   //      a mem-initializer-id,
4651   //   the entity is initialized as specified in [dcl.init].
4652   //
4653   // We also apply the same rules to handle anonymous structs within anonymous
4654   // unions.
4655   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4656     return false;
4657 
4658   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4659     ExprResult DIE =
4660         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4661     if (DIE.isInvalid())
4662       return true;
4663 
4664     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4665     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4666 
4667     CXXCtorInitializer *Init;
4668     if (Indirect)
4669       Init = new (SemaRef.Context)
4670           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4671                              SourceLocation(), DIE.get(), SourceLocation());
4672     else
4673       Init = new (SemaRef.Context)
4674           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4675                              SourceLocation(), DIE.get(), SourceLocation());
4676     return Info.addFieldInitializer(Init);
4677   }
4678 
4679   // Don't initialize incomplete or zero-length arrays.
4680   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4681     return false;
4682 
4683   // Don't try to build an implicit initializer if there were semantic
4684   // errors in any of the initializers (and therefore we might be
4685   // missing some that the user actually wrote).
4686   if (Info.AnyErrorsInInits)
4687     return false;
4688 
4689   CXXCtorInitializer *Init = nullptr;
4690   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4691                                      Indirect, Init))
4692     return true;
4693 
4694   if (!Init)
4695     return false;
4696 
4697   return Info.addFieldInitializer(Init);
4698 }
4699 
4700 bool
4701 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4702                                CXXCtorInitializer *Initializer) {
4703   assert(Initializer->isDelegatingInitializer());
4704   Constructor->setNumCtorInitializers(1);
4705   CXXCtorInitializer **initializer =
4706     new (Context) CXXCtorInitializer*[1];
4707   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4708   Constructor->setCtorInitializers(initializer);
4709 
4710   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4711     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4712     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4713   }
4714 
4715   DelegatingCtorDecls.push_back(Constructor);
4716 
4717   DiagnoseUninitializedFields(*this, Constructor);
4718 
4719   return false;
4720 }
4721 
4722 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4723                                ArrayRef<CXXCtorInitializer *> Initializers) {
4724   if (Constructor->isDependentContext()) {
4725     // Just store the initializers as written, they will be checked during
4726     // instantiation.
4727     if (!Initializers.empty()) {
4728       Constructor->setNumCtorInitializers(Initializers.size());
4729       CXXCtorInitializer **baseOrMemberInitializers =
4730         new (Context) CXXCtorInitializer*[Initializers.size()];
4731       memcpy(baseOrMemberInitializers, Initializers.data(),
4732              Initializers.size() * sizeof(CXXCtorInitializer*));
4733       Constructor->setCtorInitializers(baseOrMemberInitializers);
4734     }
4735 
4736     // Let template instantiation know whether we had errors.
4737     if (AnyErrors)
4738       Constructor->setInvalidDecl();
4739 
4740     return false;
4741   }
4742 
4743   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4744 
4745   // We need to build the initializer AST according to order of construction
4746   // and not what user specified in the Initializers list.
4747   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4748   if (!ClassDecl)
4749     return true;
4750 
4751   bool HadError = false;
4752 
4753   for (unsigned i = 0; i < Initializers.size(); i++) {
4754     CXXCtorInitializer *Member = Initializers[i];
4755 
4756     if (Member->isBaseInitializer())
4757       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4758     else {
4759       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4760 
4761       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4762         for (auto *C : F->chain()) {
4763           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4764           if (FD && FD->getParent()->isUnion())
4765             Info.ActiveUnionMember.insert(std::make_pair(
4766                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4767         }
4768       } else if (FieldDecl *FD = Member->getMember()) {
4769         if (FD->getParent()->isUnion())
4770           Info.ActiveUnionMember.insert(std::make_pair(
4771               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4772       }
4773     }
4774   }
4775 
4776   // Keep track of the direct virtual bases.
4777   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4778   for (auto &I : ClassDecl->bases()) {
4779     if (I.isVirtual())
4780       DirectVBases.insert(&I);
4781   }
4782 
4783   // Push virtual bases before others.
4784   for (auto &VBase : ClassDecl->vbases()) {
4785     if (CXXCtorInitializer *Value
4786         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4787       // [class.base.init]p7, per DR257:
4788       //   A mem-initializer where the mem-initializer-id names a virtual base
4789       //   class is ignored during execution of a constructor of any class that
4790       //   is not the most derived class.
4791       if (ClassDecl->isAbstract()) {
4792         // FIXME: Provide a fixit to remove the base specifier. This requires
4793         // tracking the location of the associated comma for a base specifier.
4794         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4795           << VBase.getType() << ClassDecl;
4796         DiagnoseAbstractType(ClassDecl);
4797       }
4798 
4799       Info.AllToInit.push_back(Value);
4800     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4801       // [class.base.init]p8, per DR257:
4802       //   If a given [...] base class is not named by a mem-initializer-id
4803       //   [...] and the entity is not a virtual base class of an abstract
4804       //   class, then [...] the entity is default-initialized.
4805       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4806       CXXCtorInitializer *CXXBaseInit;
4807       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4808                                        &VBase, IsInheritedVirtualBase,
4809                                        CXXBaseInit)) {
4810         HadError = true;
4811         continue;
4812       }
4813 
4814       Info.AllToInit.push_back(CXXBaseInit);
4815     }
4816   }
4817 
4818   // Non-virtual bases.
4819   for (auto &Base : ClassDecl->bases()) {
4820     // Virtuals are in the virtual base list and already constructed.
4821     if (Base.isVirtual())
4822       continue;
4823 
4824     if (CXXCtorInitializer *Value
4825           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4826       Info.AllToInit.push_back(Value);
4827     } else if (!AnyErrors) {
4828       CXXCtorInitializer *CXXBaseInit;
4829       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4830                                        &Base, /*IsInheritedVirtualBase=*/false,
4831                                        CXXBaseInit)) {
4832         HadError = true;
4833         continue;
4834       }
4835 
4836       Info.AllToInit.push_back(CXXBaseInit);
4837     }
4838   }
4839 
4840   // Fields.
4841   for (auto *Mem : ClassDecl->decls()) {
4842     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4843       // C++ [class.bit]p2:
4844       //   A declaration for a bit-field that omits the identifier declares an
4845       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4846       //   initialized.
4847       if (F->isUnnamedBitfield())
4848         continue;
4849 
4850       // If we're not generating the implicit copy/move constructor, then we'll
4851       // handle anonymous struct/union fields based on their individual
4852       // indirect fields.
4853       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4854         continue;
4855 
4856       if (CollectFieldInitializer(*this, Info, F))
4857         HadError = true;
4858       continue;
4859     }
4860 
4861     // Beyond this point, we only consider default initialization.
4862     if (Info.isImplicitCopyOrMove())
4863       continue;
4864 
4865     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4866       if (F->getType()->isIncompleteArrayType()) {
4867         assert(ClassDecl->hasFlexibleArrayMember() &&
4868                "Incomplete array type is not valid");
4869         continue;
4870       }
4871 
4872       // Initialize each field of an anonymous struct individually.
4873       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4874         HadError = true;
4875 
4876       continue;
4877     }
4878   }
4879 
4880   unsigned NumInitializers = Info.AllToInit.size();
4881   if (NumInitializers > 0) {
4882     Constructor->setNumCtorInitializers(NumInitializers);
4883     CXXCtorInitializer **baseOrMemberInitializers =
4884       new (Context) CXXCtorInitializer*[NumInitializers];
4885     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4886            NumInitializers * sizeof(CXXCtorInitializer*));
4887     Constructor->setCtorInitializers(baseOrMemberInitializers);
4888 
4889     // Constructors implicitly reference the base and member
4890     // destructors.
4891     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4892                                            Constructor->getParent());
4893   }
4894 
4895   return HadError;
4896 }
4897 
4898 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4899   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4900     const RecordDecl *RD = RT->getDecl();
4901     if (RD->isAnonymousStructOrUnion()) {
4902       for (auto *Field : RD->fields())
4903         PopulateKeysForFields(Field, IdealInits);
4904       return;
4905     }
4906   }
4907   IdealInits.push_back(Field->getCanonicalDecl());
4908 }
4909 
4910 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4911   return Context.getCanonicalType(BaseType).getTypePtr();
4912 }
4913 
4914 static const void *GetKeyForMember(ASTContext &Context,
4915                                    CXXCtorInitializer *Member) {
4916   if (!Member->isAnyMemberInitializer())
4917     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4918 
4919   return Member->getAnyMember()->getCanonicalDecl();
4920 }
4921 
4922 static void DiagnoseBaseOrMemInitializerOrder(
4923     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4924     ArrayRef<CXXCtorInitializer *> Inits) {
4925   if (Constructor->getDeclContext()->isDependentContext())
4926     return;
4927 
4928   // Don't check initializers order unless the warning is enabled at the
4929   // location of at least one initializer.
4930   bool ShouldCheckOrder = false;
4931   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4932     CXXCtorInitializer *Init = Inits[InitIndex];
4933     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4934                                  Init->getSourceLocation())) {
4935       ShouldCheckOrder = true;
4936       break;
4937     }
4938   }
4939   if (!ShouldCheckOrder)
4940     return;
4941 
4942   // Build the list of bases and members in the order that they'll
4943   // actually be initialized.  The explicit initializers should be in
4944   // this same order but may be missing things.
4945   SmallVector<const void*, 32> IdealInitKeys;
4946 
4947   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4948 
4949   // 1. Virtual bases.
4950   for (const auto &VBase : ClassDecl->vbases())
4951     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4952 
4953   // 2. Non-virtual bases.
4954   for (const auto &Base : ClassDecl->bases()) {
4955     if (Base.isVirtual())
4956       continue;
4957     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4958   }
4959 
4960   // 3. Direct fields.
4961   for (auto *Field : ClassDecl->fields()) {
4962     if (Field->isUnnamedBitfield())
4963       continue;
4964 
4965     PopulateKeysForFields(Field, IdealInitKeys);
4966   }
4967 
4968   unsigned NumIdealInits = IdealInitKeys.size();
4969   unsigned IdealIndex = 0;
4970 
4971   CXXCtorInitializer *PrevInit = nullptr;
4972   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4973     CXXCtorInitializer *Init = Inits[InitIndex];
4974     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4975 
4976     // Scan forward to try to find this initializer in the idealized
4977     // initializers list.
4978     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4979       if (InitKey == IdealInitKeys[IdealIndex])
4980         break;
4981 
4982     // If we didn't find this initializer, it must be because we
4983     // scanned past it on a previous iteration.  That can only
4984     // happen if we're out of order;  emit a warning.
4985     if (IdealIndex == NumIdealInits && PrevInit) {
4986       Sema::SemaDiagnosticBuilder D =
4987         SemaRef.Diag(PrevInit->getSourceLocation(),
4988                      diag::warn_initializer_out_of_order);
4989 
4990       if (PrevInit->isAnyMemberInitializer())
4991         D << 0 << PrevInit->getAnyMember()->getDeclName();
4992       else
4993         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4994 
4995       if (Init->isAnyMemberInitializer())
4996         D << 0 << Init->getAnyMember()->getDeclName();
4997       else
4998         D << 1 << Init->getTypeSourceInfo()->getType();
4999 
5000       // Move back to the initializer's location in the ideal list.
5001       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5002         if (InitKey == IdealInitKeys[IdealIndex])
5003           break;
5004 
5005       assert(IdealIndex < NumIdealInits &&
5006              "initializer not found in initializer list");
5007     }
5008 
5009     PrevInit = Init;
5010   }
5011 }
5012 
5013 namespace {
5014 bool CheckRedundantInit(Sema &S,
5015                         CXXCtorInitializer *Init,
5016                         CXXCtorInitializer *&PrevInit) {
5017   if (!PrevInit) {
5018     PrevInit = Init;
5019     return false;
5020   }
5021 
5022   if (FieldDecl *Field = Init->getAnyMember())
5023     S.Diag(Init->getSourceLocation(),
5024            diag::err_multiple_mem_initialization)
5025       << Field->getDeclName()
5026       << Init->getSourceRange();
5027   else {
5028     const Type *BaseClass = Init->getBaseClass();
5029     assert(BaseClass && "neither field nor base");
5030     S.Diag(Init->getSourceLocation(),
5031            diag::err_multiple_base_initialization)
5032       << QualType(BaseClass, 0)
5033       << Init->getSourceRange();
5034   }
5035   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5036     << 0 << PrevInit->getSourceRange();
5037 
5038   return true;
5039 }
5040 
5041 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5042 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5043 
5044 bool CheckRedundantUnionInit(Sema &S,
5045                              CXXCtorInitializer *Init,
5046                              RedundantUnionMap &Unions) {
5047   FieldDecl *Field = Init->getAnyMember();
5048   RecordDecl *Parent = Field->getParent();
5049   NamedDecl *Child = Field;
5050 
5051   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5052     if (Parent->isUnion()) {
5053       UnionEntry &En = Unions[Parent];
5054       if (En.first && En.first != Child) {
5055         S.Diag(Init->getSourceLocation(),
5056                diag::err_multiple_mem_union_initialization)
5057           << Field->getDeclName()
5058           << Init->getSourceRange();
5059         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5060           << 0 << En.second->getSourceRange();
5061         return true;
5062       }
5063       if (!En.first) {
5064         En.first = Child;
5065         En.second = Init;
5066       }
5067       if (!Parent->isAnonymousStructOrUnion())
5068         return false;
5069     }
5070 
5071     Child = Parent;
5072     Parent = cast<RecordDecl>(Parent->getDeclContext());
5073   }
5074 
5075   return false;
5076 }
5077 }
5078 
5079 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5080 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5081                                 SourceLocation ColonLoc,
5082                                 ArrayRef<CXXCtorInitializer*> MemInits,
5083                                 bool AnyErrors) {
5084   if (!ConstructorDecl)
5085     return;
5086 
5087   AdjustDeclIfTemplate(ConstructorDecl);
5088 
5089   CXXConstructorDecl *Constructor
5090     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5091 
5092   if (!Constructor) {
5093     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5094     return;
5095   }
5096 
5097   // Mapping for the duplicate initializers check.
5098   // For member initializers, this is keyed with a FieldDecl*.
5099   // For base initializers, this is keyed with a Type*.
5100   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5101 
5102   // Mapping for the inconsistent anonymous-union initializers check.
5103   RedundantUnionMap MemberUnions;
5104 
5105   bool HadError = false;
5106   for (unsigned i = 0; i < MemInits.size(); i++) {
5107     CXXCtorInitializer *Init = MemInits[i];
5108 
5109     // Set the source order index.
5110     Init->setSourceOrder(i);
5111 
5112     if (Init->isAnyMemberInitializer()) {
5113       const void *Key = GetKeyForMember(Context, Init);
5114       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5115           CheckRedundantUnionInit(*this, Init, MemberUnions))
5116         HadError = true;
5117     } else if (Init->isBaseInitializer()) {
5118       const void *Key = GetKeyForMember(Context, Init);
5119       if (CheckRedundantInit(*this, Init, Members[Key]))
5120         HadError = true;
5121     } else {
5122       assert(Init->isDelegatingInitializer());
5123       // This must be the only initializer
5124       if (MemInits.size() != 1) {
5125         Diag(Init->getSourceLocation(),
5126              diag::err_delegating_initializer_alone)
5127           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5128         // We will treat this as being the only initializer.
5129       }
5130       SetDelegatingInitializer(Constructor, MemInits[i]);
5131       // Return immediately as the initializer is set.
5132       return;
5133     }
5134   }
5135 
5136   if (HadError)
5137     return;
5138 
5139   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5140 
5141   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5142 
5143   DiagnoseUninitializedFields(*this, Constructor);
5144 }
5145 
5146 void
5147 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5148                                              CXXRecordDecl *ClassDecl) {
5149   // Ignore dependent contexts. Also ignore unions, since their members never
5150   // have destructors implicitly called.
5151   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5152     return;
5153 
5154   // FIXME: all the access-control diagnostics are positioned on the
5155   // field/base declaration.  That's probably good; that said, the
5156   // user might reasonably want to know why the destructor is being
5157   // emitted, and we currently don't say.
5158 
5159   // Non-static data members.
5160   for (auto *Field : ClassDecl->fields()) {
5161     if (Field->isInvalidDecl())
5162       continue;
5163 
5164     // Don't destroy incomplete or zero-length arrays.
5165     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5166       continue;
5167 
5168     QualType FieldType = Context.getBaseElementType(Field->getType());
5169 
5170     const RecordType* RT = FieldType->getAs<RecordType>();
5171     if (!RT)
5172       continue;
5173 
5174     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5175     if (FieldClassDecl->isInvalidDecl())
5176       continue;
5177     if (FieldClassDecl->hasIrrelevantDestructor())
5178       continue;
5179     // The destructor for an implicit anonymous union member is never invoked.
5180     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5181       continue;
5182 
5183     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5184     assert(Dtor && "No dtor found for FieldClassDecl!");
5185     CheckDestructorAccess(Field->getLocation(), Dtor,
5186                           PDiag(diag::err_access_dtor_field)
5187                             << Field->getDeclName()
5188                             << FieldType);
5189 
5190     MarkFunctionReferenced(Location, Dtor);
5191     DiagnoseUseOfDecl(Dtor, Location);
5192   }
5193 
5194   // We only potentially invoke the destructors of potentially constructed
5195   // subobjects.
5196   bool VisitVirtualBases = !ClassDecl->isAbstract();
5197 
5198   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5199 
5200   // Bases.
5201   for (const auto &Base : ClassDecl->bases()) {
5202     // Bases are always records in a well-formed non-dependent class.
5203     const RecordType *RT = Base.getType()->getAs<RecordType>();
5204 
5205     // Remember direct virtual bases.
5206     if (Base.isVirtual()) {
5207       if (!VisitVirtualBases)
5208         continue;
5209       DirectVirtualBases.insert(RT);
5210     }
5211 
5212     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5213     // If our base class is invalid, we probably can't get its dtor anyway.
5214     if (BaseClassDecl->isInvalidDecl())
5215       continue;
5216     if (BaseClassDecl->hasIrrelevantDestructor())
5217       continue;
5218 
5219     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5220     assert(Dtor && "No dtor found for BaseClassDecl!");
5221 
5222     // FIXME: caret should be on the start of the class name
5223     CheckDestructorAccess(Base.getLocStart(), Dtor,
5224                           PDiag(diag::err_access_dtor_base)
5225                             << Base.getType()
5226                             << Base.getSourceRange(),
5227                           Context.getTypeDeclType(ClassDecl));
5228 
5229     MarkFunctionReferenced(Location, Dtor);
5230     DiagnoseUseOfDecl(Dtor, Location);
5231   }
5232 
5233   if (!VisitVirtualBases)
5234     return;
5235 
5236   // Virtual bases.
5237   for (const auto &VBase : ClassDecl->vbases()) {
5238     // Bases are always records in a well-formed non-dependent class.
5239     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5240 
5241     // Ignore direct virtual bases.
5242     if (DirectVirtualBases.count(RT))
5243       continue;
5244 
5245     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5246     // If our base class is invalid, we probably can't get its dtor anyway.
5247     if (BaseClassDecl->isInvalidDecl())
5248       continue;
5249     if (BaseClassDecl->hasIrrelevantDestructor())
5250       continue;
5251 
5252     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5253     assert(Dtor && "No dtor found for BaseClassDecl!");
5254     if (CheckDestructorAccess(
5255             ClassDecl->getLocation(), Dtor,
5256             PDiag(diag::err_access_dtor_vbase)
5257                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5258             Context.getTypeDeclType(ClassDecl)) ==
5259         AR_accessible) {
5260       CheckDerivedToBaseConversion(
5261           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5262           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5263           SourceRange(), DeclarationName(), nullptr);
5264     }
5265 
5266     MarkFunctionReferenced(Location, Dtor);
5267     DiagnoseUseOfDecl(Dtor, Location);
5268   }
5269 }
5270 
5271 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5272   if (!CDtorDecl)
5273     return;
5274 
5275   if (CXXConstructorDecl *Constructor
5276       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5277     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5278     DiagnoseUninitializedFields(*this, Constructor);
5279   }
5280 }
5281 
5282 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5283   if (!getLangOpts().CPlusPlus)
5284     return false;
5285 
5286   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5287   if (!RD)
5288     return false;
5289 
5290   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5291   // class template specialization here, but doing so breaks a lot of code.
5292 
5293   // We can't answer whether something is abstract until it has a
5294   // definition. If it's currently being defined, we'll walk back
5295   // over all the declarations when we have a full definition.
5296   const CXXRecordDecl *Def = RD->getDefinition();
5297   if (!Def || Def->isBeingDefined())
5298     return false;
5299 
5300   return RD->isAbstract();
5301 }
5302 
5303 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5304                                   TypeDiagnoser &Diagnoser) {
5305   if (!isAbstractType(Loc, T))
5306     return false;
5307 
5308   T = Context.getBaseElementType(T);
5309   Diagnoser.diagnose(*this, Loc, T);
5310   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5311   return true;
5312 }
5313 
5314 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5315   // Check if we've already emitted the list of pure virtual functions
5316   // for this class.
5317   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5318     return;
5319 
5320   // If the diagnostic is suppressed, don't emit the notes. We're only
5321   // going to emit them once, so try to attach them to a diagnostic we're
5322   // actually going to show.
5323   if (Diags.isLastDiagnosticIgnored())
5324     return;
5325 
5326   CXXFinalOverriderMap FinalOverriders;
5327   RD->getFinalOverriders(FinalOverriders);
5328 
5329   // Keep a set of seen pure methods so we won't diagnose the same method
5330   // more than once.
5331   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5332 
5333   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5334                                    MEnd = FinalOverriders.end();
5335        M != MEnd;
5336        ++M) {
5337     for (OverridingMethods::iterator SO = M->second.begin(),
5338                                   SOEnd = M->second.end();
5339          SO != SOEnd; ++SO) {
5340       // C++ [class.abstract]p4:
5341       //   A class is abstract if it contains or inherits at least one
5342       //   pure virtual function for which the final overrider is pure
5343       //   virtual.
5344 
5345       //
5346       if (SO->second.size() != 1)
5347         continue;
5348 
5349       if (!SO->second.front().Method->isPure())
5350         continue;
5351 
5352       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5353         continue;
5354 
5355       Diag(SO->second.front().Method->getLocation(),
5356            diag::note_pure_virtual_function)
5357         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5358     }
5359   }
5360 
5361   if (!PureVirtualClassDiagSet)
5362     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5363   PureVirtualClassDiagSet->insert(RD);
5364 }
5365 
5366 namespace {
5367 struct AbstractUsageInfo {
5368   Sema &S;
5369   CXXRecordDecl *Record;
5370   CanQualType AbstractType;
5371   bool Invalid;
5372 
5373   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5374     : S(S), Record(Record),
5375       AbstractType(S.Context.getCanonicalType(
5376                    S.Context.getTypeDeclType(Record))),
5377       Invalid(false) {}
5378 
5379   void DiagnoseAbstractType() {
5380     if (Invalid) return;
5381     S.DiagnoseAbstractType(Record);
5382     Invalid = true;
5383   }
5384 
5385   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5386 };
5387 
5388 struct CheckAbstractUsage {
5389   AbstractUsageInfo &Info;
5390   const NamedDecl *Ctx;
5391 
5392   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5393     : Info(Info), Ctx(Ctx) {}
5394 
5395   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5396     switch (TL.getTypeLocClass()) {
5397 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5398 #define TYPELOC(CLASS, PARENT) \
5399     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5400 #include "clang/AST/TypeLocNodes.def"
5401     }
5402   }
5403 
5404   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5405     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5406     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5407       if (!TL.getParam(I))
5408         continue;
5409 
5410       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5411       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5412     }
5413   }
5414 
5415   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5416     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5417   }
5418 
5419   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5420     // Visit the type parameters from a permissive context.
5421     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5422       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5423       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5424         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5425           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5426       // TODO: other template argument types?
5427     }
5428   }
5429 
5430   // Visit pointee types from a permissive context.
5431 #define CheckPolymorphic(Type) \
5432   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5433     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5434   }
5435   CheckPolymorphic(PointerTypeLoc)
5436   CheckPolymorphic(ReferenceTypeLoc)
5437   CheckPolymorphic(MemberPointerTypeLoc)
5438   CheckPolymorphic(BlockPointerTypeLoc)
5439   CheckPolymorphic(AtomicTypeLoc)
5440 
5441   /// Handle all the types we haven't given a more specific
5442   /// implementation for above.
5443   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5444     // Every other kind of type that we haven't called out already
5445     // that has an inner type is either (1) sugar or (2) contains that
5446     // inner type in some way as a subobject.
5447     if (TypeLoc Next = TL.getNextTypeLoc())
5448       return Visit(Next, Sel);
5449 
5450     // If there's no inner type and we're in a permissive context,
5451     // don't diagnose.
5452     if (Sel == Sema::AbstractNone) return;
5453 
5454     // Check whether the type matches the abstract type.
5455     QualType T = TL.getType();
5456     if (T->isArrayType()) {
5457       Sel = Sema::AbstractArrayType;
5458       T = Info.S.Context.getBaseElementType(T);
5459     }
5460     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5461     if (CT != Info.AbstractType) return;
5462 
5463     // It matched; do some magic.
5464     if (Sel == Sema::AbstractArrayType) {
5465       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5466         << T << TL.getSourceRange();
5467     } else {
5468       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5469         << Sel << T << TL.getSourceRange();
5470     }
5471     Info.DiagnoseAbstractType();
5472   }
5473 };
5474 
5475 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5476                                   Sema::AbstractDiagSelID Sel) {
5477   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5478 }
5479 
5480 }
5481 
5482 /// Check for invalid uses of an abstract type in a method declaration.
5483 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5484                                     CXXMethodDecl *MD) {
5485   // No need to do the check on definitions, which require that
5486   // the return/param types be complete.
5487   if (MD->doesThisDeclarationHaveABody())
5488     return;
5489 
5490   // For safety's sake, just ignore it if we don't have type source
5491   // information.  This should never happen for non-implicit methods,
5492   // but...
5493   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5494     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5495 }
5496 
5497 /// Check for invalid uses of an abstract type within a class definition.
5498 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5499                                     CXXRecordDecl *RD) {
5500   for (auto *D : RD->decls()) {
5501     if (D->isImplicit()) continue;
5502 
5503     // Methods and method templates.
5504     if (isa<CXXMethodDecl>(D)) {
5505       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5506     } else if (isa<FunctionTemplateDecl>(D)) {
5507       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5508       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5509 
5510     // Fields and static variables.
5511     } else if (isa<FieldDecl>(D)) {
5512       FieldDecl *FD = cast<FieldDecl>(D);
5513       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5514         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5515     } else if (isa<VarDecl>(D)) {
5516       VarDecl *VD = cast<VarDecl>(D);
5517       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5518         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5519 
5520     // Nested classes and class templates.
5521     } else if (isa<CXXRecordDecl>(D)) {
5522       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5523     } else if (isa<ClassTemplateDecl>(D)) {
5524       CheckAbstractClassUsage(Info,
5525                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5526     }
5527   }
5528 }
5529 
5530 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5531   Attr *ClassAttr = getDLLAttr(Class);
5532   if (!ClassAttr)
5533     return;
5534 
5535   assert(ClassAttr->getKind() == attr::DLLExport);
5536 
5537   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5538 
5539   if (TSK == TSK_ExplicitInstantiationDeclaration)
5540     // Don't go any further if this is just an explicit instantiation
5541     // declaration.
5542     return;
5543 
5544   for (Decl *Member : Class->decls()) {
5545     // Defined static variables that are members of an exported base
5546     // class must be marked export too.
5547     auto *VD = dyn_cast<VarDecl>(Member);
5548     if (VD && Member->getAttr<DLLExportAttr>() &&
5549         VD->getStorageClass() == SC_Static &&
5550         TSK == TSK_ImplicitInstantiation)
5551       S.MarkVariableReferenced(VD->getLocation(), VD);
5552 
5553     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5554     if (!MD)
5555       continue;
5556 
5557     if (Member->getAttr<DLLExportAttr>()) {
5558       if (MD->isUserProvided()) {
5559         // Instantiate non-default class member functions ...
5560 
5561         // .. except for certain kinds of template specializations.
5562         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5563           continue;
5564 
5565         S.MarkFunctionReferenced(Class->getLocation(), MD);
5566 
5567         // The function will be passed to the consumer when its definition is
5568         // encountered.
5569       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5570                  MD->isCopyAssignmentOperator() ||
5571                  MD->isMoveAssignmentOperator()) {
5572         // Synthesize and instantiate non-trivial implicit methods, explicitly
5573         // defaulted methods, and the copy and move assignment operators. The
5574         // latter are exported even if they are trivial, because the address of
5575         // an operator can be taken and should compare equal across libraries.
5576         DiagnosticErrorTrap Trap(S.Diags);
5577         S.MarkFunctionReferenced(Class->getLocation(), MD);
5578         if (Trap.hasErrorOccurred()) {
5579           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5580               << Class << !S.getLangOpts().CPlusPlus11;
5581           break;
5582         }
5583 
5584         // There is no later point when we will see the definition of this
5585         // function, so pass it to the consumer now.
5586         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5587       }
5588     }
5589   }
5590 }
5591 
5592 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5593                                                         CXXRecordDecl *Class) {
5594   // Only the MS ABI has default constructor closures, so we don't need to do
5595   // this semantic checking anywhere else.
5596   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5597     return;
5598 
5599   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5600   for (Decl *Member : Class->decls()) {
5601     // Look for exported default constructors.
5602     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5603     if (!CD || !CD->isDefaultConstructor())
5604       continue;
5605     auto *Attr = CD->getAttr<DLLExportAttr>();
5606     if (!Attr)
5607       continue;
5608 
5609     // If the class is non-dependent, mark the default arguments as ODR-used so
5610     // that we can properly codegen the constructor closure.
5611     if (!Class->isDependentContext()) {
5612       for (ParmVarDecl *PD : CD->parameters()) {
5613         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5614         S.DiscardCleanupsInEvaluationContext();
5615       }
5616     }
5617 
5618     if (LastExportedDefaultCtor) {
5619       S.Diag(LastExportedDefaultCtor->getLocation(),
5620              diag::err_attribute_dll_ambiguous_default_ctor)
5621           << Class;
5622       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5623           << CD->getDeclName();
5624       return;
5625     }
5626     LastExportedDefaultCtor = CD;
5627   }
5628 }
5629 
5630 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5631   // Mark any compiler-generated routines with the implicit code_seg attribute.
5632   for (auto *Method : Class->methods()) {
5633     if (Method->isUserProvided())
5634       continue;
5635     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5636       Method->addAttr(A);
5637   }
5638 }
5639 
5640 /// Check class-level dllimport/dllexport attribute.
5641 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5642   Attr *ClassAttr = getDLLAttr(Class);
5643 
5644   // MSVC inherits DLL attributes to partial class template specializations.
5645   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5646     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5647       if (Attr *TemplateAttr =
5648               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5649         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5650         A->setInherited(true);
5651         ClassAttr = A;
5652       }
5653     }
5654   }
5655 
5656   if (!ClassAttr)
5657     return;
5658 
5659   if (!Class->isExternallyVisible()) {
5660     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5661         << Class << ClassAttr;
5662     return;
5663   }
5664 
5665   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5666       !ClassAttr->isInherited()) {
5667     // Diagnose dll attributes on members of class with dll attribute.
5668     for (Decl *Member : Class->decls()) {
5669       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5670         continue;
5671       InheritableAttr *MemberAttr = getDLLAttr(Member);
5672       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5673         continue;
5674 
5675       Diag(MemberAttr->getLocation(),
5676              diag::err_attribute_dll_member_of_dll_class)
5677           << MemberAttr << ClassAttr;
5678       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5679       Member->setInvalidDecl();
5680     }
5681   }
5682 
5683   if (Class->getDescribedClassTemplate())
5684     // Don't inherit dll attribute until the template is instantiated.
5685     return;
5686 
5687   // The class is either imported or exported.
5688   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5689 
5690   // Check if this was a dllimport attribute propagated from a derived class to
5691   // a base class template specialization. We don't apply these attributes to
5692   // static data members.
5693   const bool PropagatedImport =
5694       !ClassExported &&
5695       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5696 
5697   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5698 
5699   // Ignore explicit dllexport on explicit class template instantiation declarations.
5700   if (ClassExported && !ClassAttr->isInherited() &&
5701       TSK == TSK_ExplicitInstantiationDeclaration) {
5702     Class->dropAttr<DLLExportAttr>();
5703     return;
5704   }
5705 
5706   // Force declaration of implicit members so they can inherit the attribute.
5707   ForceDeclarationOfImplicitMembers(Class);
5708 
5709   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5710   // seem to be true in practice?
5711 
5712   for (Decl *Member : Class->decls()) {
5713     VarDecl *VD = dyn_cast<VarDecl>(Member);
5714     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5715 
5716     // Only methods and static fields inherit the attributes.
5717     if (!VD && !MD)
5718       continue;
5719 
5720     if (MD) {
5721       // Don't process deleted methods.
5722       if (MD->isDeleted())
5723         continue;
5724 
5725       if (MD->isInlined()) {
5726         // MinGW does not import or export inline methods.
5727         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5728             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5729           continue;
5730 
5731         // MSVC versions before 2015 don't export the move assignment operators
5732         // and move constructor, so don't attempt to import/export them if
5733         // we have a definition.
5734         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5735         if ((MD->isMoveAssignmentOperator() ||
5736              (Ctor && Ctor->isMoveConstructor())) &&
5737             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5738           continue;
5739 
5740         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5741         // operator is exported anyway.
5742         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5743             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5744           continue;
5745       }
5746     }
5747 
5748     // Don't apply dllimport attributes to static data members of class template
5749     // instantiations when the attribute is propagated from a derived class.
5750     if (VD && PropagatedImport)
5751       continue;
5752 
5753     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5754       continue;
5755 
5756     if (!getDLLAttr(Member)) {
5757       auto *NewAttr =
5758           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5759       NewAttr->setInherited(true);
5760       Member->addAttr(NewAttr);
5761 
5762       if (MD) {
5763         // Propagate DLLAttr to friend re-declarations of MD that have already
5764         // been constructed.
5765         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5766              FD = FD->getPreviousDecl()) {
5767           if (FD->getFriendObjectKind() == Decl::FOK_None)
5768             continue;
5769           assert(!getDLLAttr(FD) &&
5770                  "friend re-decl should not already have a DLLAttr");
5771           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5772           NewAttr->setInherited(true);
5773           FD->addAttr(NewAttr);
5774         }
5775       }
5776     }
5777   }
5778 
5779   if (ClassExported)
5780     DelayedDllExportClasses.push_back(Class);
5781 }
5782 
5783 /// Perform propagation of DLL attributes from a derived class to a
5784 /// templated base class for MS compatibility.
5785 void Sema::propagateDLLAttrToBaseClassTemplate(
5786     CXXRecordDecl *Class, Attr *ClassAttr,
5787     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5788   if (getDLLAttr(
5789           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5790     // If the base class template has a DLL attribute, don't try to change it.
5791     return;
5792   }
5793 
5794   auto TSK = BaseTemplateSpec->getSpecializationKind();
5795   if (!getDLLAttr(BaseTemplateSpec) &&
5796       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5797        TSK == TSK_ImplicitInstantiation)) {
5798     // The template hasn't been instantiated yet (or it has, but only as an
5799     // explicit instantiation declaration or implicit instantiation, which means
5800     // we haven't codegenned any members yet), so propagate the attribute.
5801     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5802     NewAttr->setInherited(true);
5803     BaseTemplateSpec->addAttr(NewAttr);
5804 
5805     // If this was an import, mark that we propagated it from a derived class to
5806     // a base class template specialization.
5807     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5808       ImportAttr->setPropagatedToBaseTemplate();
5809 
5810     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5811     // needs to be run again to work see the new attribute. Otherwise this will
5812     // get run whenever the template is instantiated.
5813     if (TSK != TSK_Undeclared)
5814       checkClassLevelDLLAttribute(BaseTemplateSpec);
5815 
5816     return;
5817   }
5818 
5819   if (getDLLAttr(BaseTemplateSpec)) {
5820     // The template has already been specialized or instantiated with an
5821     // attribute, explicitly or through propagation. We should not try to change
5822     // it.
5823     return;
5824   }
5825 
5826   // The template was previously instantiated or explicitly specialized without
5827   // a dll attribute, It's too late for us to add an attribute, so warn that
5828   // this is unsupported.
5829   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5830       << BaseTemplateSpec->isExplicitSpecialization();
5831   Diag(ClassAttr->getLocation(), diag::note_attribute);
5832   if (BaseTemplateSpec->isExplicitSpecialization()) {
5833     Diag(BaseTemplateSpec->getLocation(),
5834            diag::note_template_class_explicit_specialization_was_here)
5835         << BaseTemplateSpec;
5836   } else {
5837     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5838            diag::note_template_class_instantiation_was_here)
5839         << BaseTemplateSpec;
5840   }
5841 }
5842 
5843 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5844                                         SourceLocation DefaultLoc) {
5845   switch (S.getSpecialMember(MD)) {
5846   case Sema::CXXDefaultConstructor:
5847     S.DefineImplicitDefaultConstructor(DefaultLoc,
5848                                        cast<CXXConstructorDecl>(MD));
5849     break;
5850   case Sema::CXXCopyConstructor:
5851     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5852     break;
5853   case Sema::CXXCopyAssignment:
5854     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5855     break;
5856   case Sema::CXXDestructor:
5857     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5858     break;
5859   case Sema::CXXMoveConstructor:
5860     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5861     break;
5862   case Sema::CXXMoveAssignment:
5863     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5864     break;
5865   case Sema::CXXInvalid:
5866     llvm_unreachable("Invalid special member.");
5867   }
5868 }
5869 
5870 /// Determine whether a type is permitted to be passed or returned in
5871 /// registers, per C++ [class.temporary]p3.
5872 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5873                                TargetInfo::CallingConvKind CCK) {
5874   if (D->isDependentType() || D->isInvalidDecl())
5875     return false;
5876 
5877   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5878   // The PS4 platform ABI follows the behavior of Clang 3.2.
5879   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5880     return !D->hasNonTrivialDestructorForCall() &&
5881            !D->hasNonTrivialCopyConstructorForCall();
5882 
5883   if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
5884     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5885     bool DtorIsTrivialForCall = false;
5886 
5887     // If a class has at least one non-deleted, trivial copy constructor, it
5888     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5889     //
5890     // Note: This permits classes with non-trivial copy or move ctors to be
5891     // passed in registers, so long as they *also* have a trivial copy ctor,
5892     // which is non-conforming.
5893     if (D->needsImplicitCopyConstructor()) {
5894       if (!D->defaultedCopyConstructorIsDeleted()) {
5895         if (D->hasTrivialCopyConstructor())
5896           CopyCtorIsTrivial = true;
5897         if (D->hasTrivialCopyConstructorForCall())
5898           CopyCtorIsTrivialForCall = true;
5899       }
5900     } else {
5901       for (const CXXConstructorDecl *CD : D->ctors()) {
5902         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5903           if (CD->isTrivial())
5904             CopyCtorIsTrivial = true;
5905           if (CD->isTrivialForCall())
5906             CopyCtorIsTrivialForCall = true;
5907         }
5908       }
5909     }
5910 
5911     if (D->needsImplicitDestructor()) {
5912       if (!D->defaultedDestructorIsDeleted() &&
5913           D->hasTrivialDestructorForCall())
5914         DtorIsTrivialForCall = true;
5915     } else if (const auto *DD = D->getDestructor()) {
5916       if (!DD->isDeleted() && DD->isTrivialForCall())
5917         DtorIsTrivialForCall = true;
5918     }
5919 
5920     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5921     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5922       return true;
5923 
5924     // If a class has a destructor, we'd really like to pass it indirectly
5925     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5926     // impossible for small types, which it will pass in a single register or
5927     // stack slot. Most objects with dtors are large-ish, so handle that early.
5928     // We can't call out all large objects as being indirect because there are
5929     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5930     // how we pass large POD types.
5931 
5932     // Note: This permits small classes with nontrivial destructors to be
5933     // passed in registers, which is non-conforming.
5934     if (CopyCtorIsTrivial &&
5935         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5936       return true;
5937     return false;
5938   }
5939 
5940   // Per C++ [class.temporary]p3, the relevant condition is:
5941   //   each copy constructor, move constructor, and destructor of X is
5942   //   either trivial or deleted, and X has at least one non-deleted copy
5943   //   or move constructor
5944   bool HasNonDeletedCopyOrMove = false;
5945 
5946   if (D->needsImplicitCopyConstructor() &&
5947       !D->defaultedCopyConstructorIsDeleted()) {
5948     if (!D->hasTrivialCopyConstructorForCall())
5949       return false;
5950     HasNonDeletedCopyOrMove = true;
5951   }
5952 
5953   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5954       !D->defaultedMoveConstructorIsDeleted()) {
5955     if (!D->hasTrivialMoveConstructorForCall())
5956       return false;
5957     HasNonDeletedCopyOrMove = true;
5958   }
5959 
5960   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5961       !D->hasTrivialDestructorForCall())
5962     return false;
5963 
5964   for (const CXXMethodDecl *MD : D->methods()) {
5965     if (MD->isDeleted())
5966       continue;
5967 
5968     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5969     if (CD && CD->isCopyOrMoveConstructor())
5970       HasNonDeletedCopyOrMove = true;
5971     else if (!isa<CXXDestructorDecl>(MD))
5972       continue;
5973 
5974     if (!MD->isTrivialForCall())
5975       return false;
5976   }
5977 
5978   return HasNonDeletedCopyOrMove;
5979 }
5980 
5981 /// Perform semantic checks on a class definition that has been
5982 /// completing, introducing implicitly-declared members, checking for
5983 /// abstract types, etc.
5984 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5985   if (!Record)
5986     return;
5987 
5988   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5989     AbstractUsageInfo Info(*this, Record);
5990     CheckAbstractClassUsage(Info, Record);
5991   }
5992 
5993   // If this is not an aggregate type and has no user-declared constructor,
5994   // complain about any non-static data members of reference or const scalar
5995   // type, since they will never get initializers.
5996   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5997       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5998       !Record->isLambda()) {
5999     bool Complained = false;
6000     for (const auto *F : Record->fields()) {
6001       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6002         continue;
6003 
6004       if (F->getType()->isReferenceType() ||
6005           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6006         if (!Complained) {
6007           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6008             << Record->getTagKind() << Record;
6009           Complained = true;
6010         }
6011 
6012         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6013           << F->getType()->isReferenceType()
6014           << F->getDeclName();
6015       }
6016     }
6017   }
6018 
6019   if (Record->getIdentifier()) {
6020     // C++ [class.mem]p13:
6021     //   If T is the name of a class, then each of the following shall have a
6022     //   name different from T:
6023     //     - every member of every anonymous union that is a member of class T.
6024     //
6025     // C++ [class.mem]p14:
6026     //   In addition, if class T has a user-declared constructor (12.1), every
6027     //   non-static data member of class T shall have a name different from T.
6028     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6029     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6030          ++I) {
6031       NamedDecl *D = (*I)->getUnderlyingDecl();
6032       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6033            Record->hasUserDeclaredConstructor()) ||
6034           isa<IndirectFieldDecl>(D)) {
6035         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6036           << D->getDeclName();
6037         break;
6038       }
6039     }
6040   }
6041 
6042   // Warn if the class has virtual methods but non-virtual public destructor.
6043   if (Record->isPolymorphic() && !Record->isDependentType()) {
6044     CXXDestructorDecl *dtor = Record->getDestructor();
6045     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6046         !Record->hasAttr<FinalAttr>())
6047       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6048            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6049   }
6050 
6051   if (Record->isAbstract()) {
6052     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6053       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6054         << FA->isSpelledAsSealed();
6055       DiagnoseAbstractType(Record);
6056     }
6057   }
6058 
6059   // See if trivial_abi has to be dropped.
6060   if (Record->hasAttr<TrivialABIAttr>())
6061     checkIllFormedTrivialABIStruct(*Record);
6062 
6063   // Set HasTrivialSpecialMemberForCall if the record has attribute
6064   // "trivial_abi".
6065   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6066 
6067   if (HasTrivialABI)
6068     Record->setHasTrivialSpecialMemberForCall();
6069 
6070   bool HasMethodWithOverrideControl = false,
6071        HasOverridingMethodWithoutOverrideControl = false;
6072   if (!Record->isDependentType()) {
6073     for (auto *M : Record->methods()) {
6074       // See if a method overloads virtual methods in a base
6075       // class without overriding any.
6076       if (!M->isStatic())
6077         DiagnoseHiddenVirtualMethods(M);
6078       if (M->hasAttr<OverrideAttr>())
6079         HasMethodWithOverrideControl = true;
6080       else if (M->size_overridden_methods() > 0)
6081         HasOverridingMethodWithoutOverrideControl = true;
6082       // Check whether the explicitly-defaulted special members are valid.
6083       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6084         CheckExplicitlyDefaultedSpecialMember(M);
6085 
6086       // For an explicitly defaulted or deleted special member, we defer
6087       // determining triviality until the class is complete. That time is now!
6088       CXXSpecialMember CSM = getSpecialMember(M);
6089       if (!M->isImplicit() && !M->isUserProvided()) {
6090         if (CSM != CXXInvalid) {
6091           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6092           // Inform the class that we've finished declaring this member.
6093           Record->finishedDefaultedOrDeletedMember(M);
6094           M->setTrivialForCall(
6095               HasTrivialABI ||
6096               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6097           Record->setTrivialForCallFlags(M);
6098         }
6099       }
6100 
6101       // Set triviality for the purpose of calls if this is a user-provided
6102       // copy/move constructor or destructor.
6103       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6104            CSM == CXXDestructor) && M->isUserProvided()) {
6105         M->setTrivialForCall(HasTrivialABI);
6106         Record->setTrivialForCallFlags(M);
6107       }
6108 
6109       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6110           M->hasAttr<DLLExportAttr>()) {
6111         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6112             M->isTrivial() &&
6113             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6114              CSM == CXXDestructor))
6115           M->dropAttr<DLLExportAttr>();
6116 
6117         if (M->hasAttr<DLLExportAttr>()) {
6118           DefineImplicitSpecialMember(*this, M, M->getLocation());
6119           ActOnFinishInlineFunctionDef(M);
6120         }
6121       }
6122     }
6123   }
6124 
6125   if (HasMethodWithOverrideControl &&
6126       HasOverridingMethodWithoutOverrideControl) {
6127     // At least one method has the 'override' control declared.
6128     // Diagnose all other overridden methods which do not have 'override' specified on them.
6129     for (auto *M : Record->methods())
6130       DiagnoseAbsenceOfOverrideControl(M);
6131   }
6132 
6133   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6134   // whether this class uses any C++ features that are implemented
6135   // completely differently in MSVC, and if so, emit a diagnostic.
6136   // That diagnostic defaults to an error, but we allow projects to
6137   // map it down to a warning (or ignore it).  It's a fairly common
6138   // practice among users of the ms_struct pragma to mass-annotate
6139   // headers, sweeping up a bunch of types that the project doesn't
6140   // really rely on MSVC-compatible layout for.  We must therefore
6141   // support "ms_struct except for C++ stuff" as a secondary ABI.
6142   if (Record->isMsStruct(Context) &&
6143       (Record->isPolymorphic() || Record->getNumBases())) {
6144     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6145   }
6146 
6147   checkClassLevelDLLAttribute(Record);
6148   checkClassLevelCodeSegAttribute(Record);
6149 
6150   bool ClangABICompat4 =
6151       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6152   TargetInfo::CallingConvKind CCK =
6153       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6154   bool CanPass = canPassInRegisters(*this, Record, CCK);
6155 
6156   // Do not change ArgPassingRestrictions if it has already been set to
6157   // APK_CanNeverPassInRegs.
6158   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6159     Record->setArgPassingRestrictions(CanPass
6160                                           ? RecordDecl::APK_CanPassInRegs
6161                                           : RecordDecl::APK_CannotPassInRegs);
6162 
6163   // If canPassInRegisters returns true despite the record having a non-trivial
6164   // destructor, the record is destructed in the callee. This happens only when
6165   // the record or one of its subobjects has a field annotated with trivial_abi
6166   // or a field qualified with ObjC __strong/__weak.
6167   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6168     Record->setParamDestroyedInCallee(true);
6169   else if (Record->hasNonTrivialDestructor())
6170     Record->setParamDestroyedInCallee(CanPass);
6171 
6172   if (getLangOpts().ForceEmitVTables) {
6173     // If we want to emit all the vtables, we need to mark it as used.  This
6174     // is especially required for cases like vtable assumption loads.
6175     MarkVTableUsed(Record->getInnerLocStart(), Record);
6176   }
6177 }
6178 
6179 /// Look up the special member function that would be called by a special
6180 /// member function for a subobject of class type.
6181 ///
6182 /// \param Class The class type of the subobject.
6183 /// \param CSM The kind of special member function.
6184 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6185 /// \param ConstRHS True if this is a copy operation with a const object
6186 ///        on its RHS, that is, if the argument to the outer special member
6187 ///        function is 'const' and this is not a field marked 'mutable'.
6188 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6189     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6190     unsigned FieldQuals, bool ConstRHS) {
6191   unsigned LHSQuals = 0;
6192   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6193     LHSQuals = FieldQuals;
6194 
6195   unsigned RHSQuals = FieldQuals;
6196   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6197     RHSQuals = 0;
6198   else if (ConstRHS)
6199     RHSQuals |= Qualifiers::Const;
6200 
6201   return S.LookupSpecialMember(Class, CSM,
6202                                RHSQuals & Qualifiers::Const,
6203                                RHSQuals & Qualifiers::Volatile,
6204                                false,
6205                                LHSQuals & Qualifiers::Const,
6206                                LHSQuals & Qualifiers::Volatile);
6207 }
6208 
6209 class Sema::InheritedConstructorInfo {
6210   Sema &S;
6211   SourceLocation UseLoc;
6212 
6213   /// A mapping from the base classes through which the constructor was
6214   /// inherited to the using shadow declaration in that base class (or a null
6215   /// pointer if the constructor was declared in that base class).
6216   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6217       InheritedFromBases;
6218 
6219 public:
6220   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6221                            ConstructorUsingShadowDecl *Shadow)
6222       : S(S), UseLoc(UseLoc) {
6223     bool DiagnosedMultipleConstructedBases = false;
6224     CXXRecordDecl *ConstructedBase = nullptr;
6225     UsingDecl *ConstructedBaseUsing = nullptr;
6226 
6227     // Find the set of such base class subobjects and check that there's a
6228     // unique constructed subobject.
6229     for (auto *D : Shadow->redecls()) {
6230       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6231       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6232       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6233 
6234       InheritedFromBases.insert(
6235           std::make_pair(DNominatedBase->getCanonicalDecl(),
6236                          DShadow->getNominatedBaseClassShadowDecl()));
6237       if (DShadow->constructsVirtualBase())
6238         InheritedFromBases.insert(
6239             std::make_pair(DConstructedBase->getCanonicalDecl(),
6240                            DShadow->getConstructedBaseClassShadowDecl()));
6241       else
6242         assert(DNominatedBase == DConstructedBase);
6243 
6244       // [class.inhctor.init]p2:
6245       //   If the constructor was inherited from multiple base class subobjects
6246       //   of type B, the program is ill-formed.
6247       if (!ConstructedBase) {
6248         ConstructedBase = DConstructedBase;
6249         ConstructedBaseUsing = D->getUsingDecl();
6250       } else if (ConstructedBase != DConstructedBase &&
6251                  !Shadow->isInvalidDecl()) {
6252         if (!DiagnosedMultipleConstructedBases) {
6253           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6254               << Shadow->getTargetDecl();
6255           S.Diag(ConstructedBaseUsing->getLocation(),
6256                diag::note_ambiguous_inherited_constructor_using)
6257               << ConstructedBase;
6258           DiagnosedMultipleConstructedBases = true;
6259         }
6260         S.Diag(D->getUsingDecl()->getLocation(),
6261                diag::note_ambiguous_inherited_constructor_using)
6262             << DConstructedBase;
6263       }
6264     }
6265 
6266     if (DiagnosedMultipleConstructedBases)
6267       Shadow->setInvalidDecl();
6268   }
6269 
6270   /// Find the constructor to use for inherited construction of a base class,
6271   /// and whether that base class constructor inherits the constructor from a
6272   /// virtual base class (in which case it won't actually invoke it).
6273   std::pair<CXXConstructorDecl *, bool>
6274   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6275     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6276     if (It == InheritedFromBases.end())
6277       return std::make_pair(nullptr, false);
6278 
6279     // This is an intermediary class.
6280     if (It->second)
6281       return std::make_pair(
6282           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6283           It->second->constructsVirtualBase());
6284 
6285     // This is the base class from which the constructor was inherited.
6286     return std::make_pair(Ctor, false);
6287   }
6288 };
6289 
6290 /// Is the special member function which would be selected to perform the
6291 /// specified operation on the specified class type a constexpr constructor?
6292 static bool
6293 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6294                          Sema::CXXSpecialMember CSM, unsigned Quals,
6295                          bool ConstRHS,
6296                          CXXConstructorDecl *InheritedCtor = nullptr,
6297                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6298   // If we're inheriting a constructor, see if we need to call it for this base
6299   // class.
6300   if (InheritedCtor) {
6301     assert(CSM == Sema::CXXDefaultConstructor);
6302     auto BaseCtor =
6303         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6304     if (BaseCtor)
6305       return BaseCtor->isConstexpr();
6306   }
6307 
6308   if (CSM == Sema::CXXDefaultConstructor)
6309     return ClassDecl->hasConstexprDefaultConstructor();
6310 
6311   Sema::SpecialMemberOverloadResult SMOR =
6312       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6313   if (!SMOR.getMethod())
6314     // A constructor we wouldn't select can't be "involved in initializing"
6315     // anything.
6316     return true;
6317   return SMOR.getMethod()->isConstexpr();
6318 }
6319 
6320 /// Determine whether the specified special member function would be constexpr
6321 /// if it were implicitly defined.
6322 static bool defaultedSpecialMemberIsConstexpr(
6323     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6324     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6325     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6326   if (!S.getLangOpts().CPlusPlus11)
6327     return false;
6328 
6329   // C++11 [dcl.constexpr]p4:
6330   // In the definition of a constexpr constructor [...]
6331   bool Ctor = true;
6332   switch (CSM) {
6333   case Sema::CXXDefaultConstructor:
6334     if (Inherited)
6335       break;
6336     // Since default constructor lookup is essentially trivial (and cannot
6337     // involve, for instance, template instantiation), we compute whether a
6338     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6339     //
6340     // This is important for performance; we need to know whether the default
6341     // constructor is constexpr to determine whether the type is a literal type.
6342     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6343 
6344   case Sema::CXXCopyConstructor:
6345   case Sema::CXXMoveConstructor:
6346     // For copy or move constructors, we need to perform overload resolution.
6347     break;
6348 
6349   case Sema::CXXCopyAssignment:
6350   case Sema::CXXMoveAssignment:
6351     if (!S.getLangOpts().CPlusPlus14)
6352       return false;
6353     // In C++1y, we need to perform overload resolution.
6354     Ctor = false;
6355     break;
6356 
6357   case Sema::CXXDestructor:
6358   case Sema::CXXInvalid:
6359     return false;
6360   }
6361 
6362   //   -- if the class is a non-empty union, or for each non-empty anonymous
6363   //      union member of a non-union class, exactly one non-static data member
6364   //      shall be initialized; [DR1359]
6365   //
6366   // If we squint, this is guaranteed, since exactly one non-static data member
6367   // will be initialized (if the constructor isn't deleted), we just don't know
6368   // which one.
6369   if (Ctor && ClassDecl->isUnion())
6370     return CSM == Sema::CXXDefaultConstructor
6371                ? ClassDecl->hasInClassInitializer() ||
6372                      !ClassDecl->hasVariantMembers()
6373                : true;
6374 
6375   //   -- the class shall not have any virtual base classes;
6376   if (Ctor && ClassDecl->getNumVBases())
6377     return false;
6378 
6379   // C++1y [class.copy]p26:
6380   //   -- [the class] is a literal type, and
6381   if (!Ctor && !ClassDecl->isLiteral())
6382     return false;
6383 
6384   //   -- every constructor involved in initializing [...] base class
6385   //      sub-objects shall be a constexpr constructor;
6386   //   -- the assignment operator selected to copy/move each direct base
6387   //      class is a constexpr function, and
6388   for (const auto &B : ClassDecl->bases()) {
6389     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6390     if (!BaseType) continue;
6391 
6392     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6393     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6394                                   InheritedCtor, Inherited))
6395       return false;
6396   }
6397 
6398   //   -- every constructor involved in initializing non-static data members
6399   //      [...] shall be a constexpr constructor;
6400   //   -- every non-static data member and base class sub-object shall be
6401   //      initialized
6402   //   -- for each non-static data member of X that is of class type (or array
6403   //      thereof), the assignment operator selected to copy/move that member is
6404   //      a constexpr function
6405   for (const auto *F : ClassDecl->fields()) {
6406     if (F->isInvalidDecl())
6407       continue;
6408     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6409       continue;
6410     QualType BaseType = S.Context.getBaseElementType(F->getType());
6411     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6412       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6413       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6414                                     BaseType.getCVRQualifiers(),
6415                                     ConstArg && !F->isMutable()))
6416         return false;
6417     } else if (CSM == Sema::CXXDefaultConstructor) {
6418       return false;
6419     }
6420   }
6421 
6422   // All OK, it's constexpr!
6423   return true;
6424 }
6425 
6426 static Sema::ImplicitExceptionSpecification
6427 ComputeDefaultedSpecialMemberExceptionSpec(
6428     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6429     Sema::InheritedConstructorInfo *ICI);
6430 
6431 static Sema::ImplicitExceptionSpecification
6432 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6433   auto CSM = S.getSpecialMember(MD);
6434   if (CSM != Sema::CXXInvalid)
6435     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6436 
6437   auto *CD = cast<CXXConstructorDecl>(MD);
6438   assert(CD->getInheritedConstructor() &&
6439          "only special members have implicit exception specs");
6440   Sema::InheritedConstructorInfo ICI(
6441       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6442   return ComputeDefaultedSpecialMemberExceptionSpec(
6443       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6444 }
6445 
6446 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6447                                                             CXXMethodDecl *MD) {
6448   FunctionProtoType::ExtProtoInfo EPI;
6449 
6450   // Build an exception specification pointing back at this member.
6451   EPI.ExceptionSpec.Type = EST_Unevaluated;
6452   EPI.ExceptionSpec.SourceDecl = MD;
6453 
6454   // Set the calling convention to the default for C++ instance methods.
6455   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6456       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6457                                             /*IsCXXMethod=*/true));
6458   return EPI;
6459 }
6460 
6461 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6462   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6463   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6464     return;
6465 
6466   // Evaluate the exception specification.
6467   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6468   auto ESI = IES.getExceptionSpec();
6469 
6470   // Update the type of the special member to use it.
6471   UpdateExceptionSpec(MD, ESI);
6472 
6473   // A user-provided destructor can be defined outside the class. When that
6474   // happens, be sure to update the exception specification on both
6475   // declarations.
6476   const FunctionProtoType *CanonicalFPT =
6477     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6478   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6479     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6480 }
6481 
6482 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6483   CXXRecordDecl *RD = MD->getParent();
6484   CXXSpecialMember CSM = getSpecialMember(MD);
6485 
6486   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6487          "not an explicitly-defaulted special member");
6488 
6489   // Whether this was the first-declared instance of the constructor.
6490   // This affects whether we implicitly add an exception spec and constexpr.
6491   bool First = MD == MD->getCanonicalDecl();
6492 
6493   bool HadError = false;
6494 
6495   // C++11 [dcl.fct.def.default]p1:
6496   //   A function that is explicitly defaulted shall
6497   //     -- be a special member function (checked elsewhere),
6498   //     -- have the same type (except for ref-qualifiers, and except that a
6499   //        copy operation can take a non-const reference) as an implicit
6500   //        declaration, and
6501   //     -- not have default arguments.
6502   unsigned ExpectedParams = 1;
6503   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6504     ExpectedParams = 0;
6505   if (MD->getNumParams() != ExpectedParams) {
6506     // This also checks for default arguments: a copy or move constructor with a
6507     // default argument is classified as a default constructor, and assignment
6508     // operations and destructors can't have default arguments.
6509     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6510       << CSM << MD->getSourceRange();
6511     HadError = true;
6512   } else if (MD->isVariadic()) {
6513     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6514       << CSM << MD->getSourceRange();
6515     HadError = true;
6516   }
6517 
6518   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6519 
6520   bool CanHaveConstParam = false;
6521   if (CSM == CXXCopyConstructor)
6522     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6523   else if (CSM == CXXCopyAssignment)
6524     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6525 
6526   QualType ReturnType = Context.VoidTy;
6527   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6528     // Check for return type matching.
6529     ReturnType = Type->getReturnType();
6530     QualType ExpectedReturnType =
6531         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6532     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6533       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6534         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6535       HadError = true;
6536     }
6537 
6538     // A defaulted special member cannot have cv-qualifiers.
6539     if (Type->getTypeQuals()) {
6540       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6541         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6542       HadError = true;
6543     }
6544   }
6545 
6546   // Check for parameter type matching.
6547   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6548   bool HasConstParam = false;
6549   if (ExpectedParams && ArgType->isReferenceType()) {
6550     // Argument must be reference to possibly-const T.
6551     QualType ReferentType = ArgType->getPointeeType();
6552     HasConstParam = ReferentType.isConstQualified();
6553 
6554     if (ReferentType.isVolatileQualified()) {
6555       Diag(MD->getLocation(),
6556            diag::err_defaulted_special_member_volatile_param) << CSM;
6557       HadError = true;
6558     }
6559 
6560     if (HasConstParam && !CanHaveConstParam) {
6561       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6562         Diag(MD->getLocation(),
6563              diag::err_defaulted_special_member_copy_const_param)
6564           << (CSM == CXXCopyAssignment);
6565         // FIXME: Explain why this special member can't be const.
6566       } else {
6567         Diag(MD->getLocation(),
6568              diag::err_defaulted_special_member_move_const_param)
6569           << (CSM == CXXMoveAssignment);
6570       }
6571       HadError = true;
6572     }
6573   } else if (ExpectedParams) {
6574     // A copy assignment operator can take its argument by value, but a
6575     // defaulted one cannot.
6576     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6577     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6578     HadError = true;
6579   }
6580 
6581   // C++11 [dcl.fct.def.default]p2:
6582   //   An explicitly-defaulted function may be declared constexpr only if it
6583   //   would have been implicitly declared as constexpr,
6584   // Do not apply this rule to members of class templates, since core issue 1358
6585   // makes such functions always instantiate to constexpr functions. For
6586   // functions which cannot be constexpr (for non-constructors in C++11 and for
6587   // destructors in C++1y), this is checked elsewhere.
6588   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6589                                                      HasConstParam);
6590   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6591                                  : isa<CXXConstructorDecl>(MD)) &&
6592       MD->isConstexpr() && !Constexpr &&
6593       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6594     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6595     // FIXME: Explain why the special member can't be constexpr.
6596     HadError = true;
6597   }
6598 
6599   //   and may have an explicit exception-specification only if it is compatible
6600   //   with the exception-specification on the implicit declaration.
6601   if (Type->hasExceptionSpec()) {
6602     // Delay the check if this is the first declaration of the special member,
6603     // since we may not have parsed some necessary in-class initializers yet.
6604     if (First) {
6605       // If the exception specification needs to be instantiated, do so now,
6606       // before we clobber it with an EST_Unevaluated specification below.
6607       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6608         InstantiateExceptionSpec(MD->getLocStart(), MD);
6609         Type = MD->getType()->getAs<FunctionProtoType>();
6610       }
6611       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6612     } else
6613       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6614   }
6615 
6616   //   If a function is explicitly defaulted on its first declaration,
6617   if (First) {
6618     //  -- it is implicitly considered to be constexpr if the implicit
6619     //     definition would be,
6620     MD->setConstexpr(Constexpr);
6621 
6622     //  -- it is implicitly considered to have the same exception-specification
6623     //     as if it had been implicitly declared,
6624     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6625     EPI.ExceptionSpec.Type = EST_Unevaluated;
6626     EPI.ExceptionSpec.SourceDecl = MD;
6627     MD->setType(Context.getFunctionType(ReturnType,
6628                                         llvm::makeArrayRef(&ArgType,
6629                                                            ExpectedParams),
6630                                         EPI));
6631   }
6632 
6633   if (ShouldDeleteSpecialMember(MD, CSM)) {
6634     if (First) {
6635       SetDeclDeleted(MD, MD->getLocation());
6636     } else {
6637       // C++11 [dcl.fct.def.default]p4:
6638       //   [For a] user-provided explicitly-defaulted function [...] if such a
6639       //   function is implicitly defined as deleted, the program is ill-formed.
6640       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6641       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6642       HadError = true;
6643     }
6644   }
6645 
6646   if (HadError)
6647     MD->setInvalidDecl();
6648 }
6649 
6650 /// Check whether the exception specification provided for an
6651 /// explicitly-defaulted special member matches the exception specification
6652 /// that would have been generated for an implicit special member, per
6653 /// C++11 [dcl.fct.def.default]p2.
6654 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6655     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6656   // If the exception specification was explicitly specified but hadn't been
6657   // parsed when the method was defaulted, grab it now.
6658   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6659     SpecifiedType =
6660         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6661 
6662   // Compute the implicit exception specification.
6663   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6664                                                        /*IsCXXMethod=*/true);
6665   FunctionProtoType::ExtProtoInfo EPI(CC);
6666   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6667   EPI.ExceptionSpec = IES.getExceptionSpec();
6668   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6669     Context.getFunctionType(Context.VoidTy, None, EPI));
6670 
6671   // Ensure that it matches.
6672   CheckEquivalentExceptionSpec(
6673     PDiag(diag::err_incorrect_defaulted_exception_spec)
6674       << getSpecialMember(MD), PDiag(),
6675     ImplicitType, SourceLocation(),
6676     SpecifiedType, MD->getLocation());
6677 }
6678 
6679 void Sema::CheckDelayedMemberExceptionSpecs() {
6680   decltype(DelayedExceptionSpecChecks) Checks;
6681   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6682 
6683   std::swap(Checks, DelayedExceptionSpecChecks);
6684   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6685 
6686   // Perform any deferred checking of exception specifications for virtual
6687   // destructors.
6688   for (auto &Check : Checks)
6689     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6690 
6691   // Check that any explicitly-defaulted methods have exception specifications
6692   // compatible with their implicit exception specifications.
6693   for (auto &Spec : Specs)
6694     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6695 }
6696 
6697 namespace {
6698 /// CRTP base class for visiting operations performed by a special member
6699 /// function (or inherited constructor).
6700 template<typename Derived>
6701 struct SpecialMemberVisitor {
6702   Sema &S;
6703   CXXMethodDecl *MD;
6704   Sema::CXXSpecialMember CSM;
6705   Sema::InheritedConstructorInfo *ICI;
6706 
6707   // Properties of the special member, computed for convenience.
6708   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6709 
6710   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6711                        Sema::InheritedConstructorInfo *ICI)
6712       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6713     switch (CSM) {
6714     case Sema::CXXDefaultConstructor:
6715     case Sema::CXXCopyConstructor:
6716     case Sema::CXXMoveConstructor:
6717       IsConstructor = true;
6718       break;
6719     case Sema::CXXCopyAssignment:
6720     case Sema::CXXMoveAssignment:
6721       IsAssignment = true;
6722       break;
6723     case Sema::CXXDestructor:
6724       break;
6725     case Sema::CXXInvalid:
6726       llvm_unreachable("invalid special member kind");
6727     }
6728 
6729     if (MD->getNumParams()) {
6730       if (const ReferenceType *RT =
6731               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6732         ConstArg = RT->getPointeeType().isConstQualified();
6733     }
6734   }
6735 
6736   Derived &getDerived() { return static_cast<Derived&>(*this); }
6737 
6738   /// Is this a "move" special member?
6739   bool isMove() const {
6740     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6741   }
6742 
6743   /// Look up the corresponding special member in the given class.
6744   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6745                                              unsigned Quals, bool IsMutable) {
6746     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6747                                        ConstArg && !IsMutable);
6748   }
6749 
6750   /// Look up the constructor for the specified base class to see if it's
6751   /// overridden due to this being an inherited constructor.
6752   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6753     if (!ICI)
6754       return {};
6755     assert(CSM == Sema::CXXDefaultConstructor);
6756     auto *BaseCtor =
6757       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6758     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6759       return MD;
6760     return {};
6761   }
6762 
6763   /// A base or member subobject.
6764   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6765 
6766   /// Get the location to use for a subobject in diagnostics.
6767   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6768     // FIXME: For an indirect virtual base, the direct base leading to
6769     // the indirect virtual base would be a more useful choice.
6770     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6771       return B->getBaseTypeLoc();
6772     else
6773       return Subobj.get<FieldDecl*>()->getLocation();
6774   }
6775 
6776   enum BasesToVisit {
6777     /// Visit all non-virtual (direct) bases.
6778     VisitNonVirtualBases,
6779     /// Visit all direct bases, virtual or not.
6780     VisitDirectBases,
6781     /// Visit all non-virtual bases, and all virtual bases if the class
6782     /// is not abstract.
6783     VisitPotentiallyConstructedBases,
6784     /// Visit all direct or virtual bases.
6785     VisitAllBases
6786   };
6787 
6788   // Visit the bases and members of the class.
6789   bool visit(BasesToVisit Bases) {
6790     CXXRecordDecl *RD = MD->getParent();
6791 
6792     if (Bases == VisitPotentiallyConstructedBases)
6793       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6794 
6795     for (auto &B : RD->bases())
6796       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6797           getDerived().visitBase(&B))
6798         return true;
6799 
6800     if (Bases == VisitAllBases)
6801       for (auto &B : RD->vbases())
6802         if (getDerived().visitBase(&B))
6803           return true;
6804 
6805     for (auto *F : RD->fields())
6806       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6807           getDerived().visitField(F))
6808         return true;
6809 
6810     return false;
6811   }
6812 };
6813 }
6814 
6815 namespace {
6816 struct SpecialMemberDeletionInfo
6817     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6818   bool Diagnose;
6819 
6820   SourceLocation Loc;
6821 
6822   bool AllFieldsAreConst;
6823 
6824   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6825                             Sema::CXXSpecialMember CSM,
6826                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6827       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6828         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6829 
6830   bool inUnion() const { return MD->getParent()->isUnion(); }
6831 
6832   Sema::CXXSpecialMember getEffectiveCSM() {
6833     return ICI ? Sema::CXXInvalid : CSM;
6834   }
6835 
6836   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6837   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6838 
6839   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6840   bool shouldDeleteForField(FieldDecl *FD);
6841   bool shouldDeleteForAllConstMembers();
6842 
6843   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6844                                      unsigned Quals);
6845   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6846                                     Sema::SpecialMemberOverloadResult SMOR,
6847                                     bool IsDtorCallInCtor);
6848 
6849   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6850 };
6851 }
6852 
6853 /// Is the given special member inaccessible when used on the given
6854 /// sub-object.
6855 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6856                                              CXXMethodDecl *target) {
6857   /// If we're operating on a base class, the object type is the
6858   /// type of this special member.
6859   QualType objectTy;
6860   AccessSpecifier access = target->getAccess();
6861   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6862     objectTy = S.Context.getTypeDeclType(MD->getParent());
6863     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6864 
6865   // If we're operating on a field, the object type is the type of the field.
6866   } else {
6867     objectTy = S.Context.getTypeDeclType(target->getParent());
6868   }
6869 
6870   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6871 }
6872 
6873 /// Check whether we should delete a special member due to the implicit
6874 /// definition containing a call to a special member of a subobject.
6875 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6876     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6877     bool IsDtorCallInCtor) {
6878   CXXMethodDecl *Decl = SMOR.getMethod();
6879   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6880 
6881   int DiagKind = -1;
6882 
6883   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6884     DiagKind = !Decl ? 0 : 1;
6885   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6886     DiagKind = 2;
6887   else if (!isAccessible(Subobj, Decl))
6888     DiagKind = 3;
6889   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6890            !Decl->isTrivial()) {
6891     // A member of a union must have a trivial corresponding special member.
6892     // As a weird special case, a destructor call from a union's constructor
6893     // must be accessible and non-deleted, but need not be trivial. Such a
6894     // destructor is never actually called, but is semantically checked as
6895     // if it were.
6896     DiagKind = 4;
6897   }
6898 
6899   if (DiagKind == -1)
6900     return false;
6901 
6902   if (Diagnose) {
6903     if (Field) {
6904       S.Diag(Field->getLocation(),
6905              diag::note_deleted_special_member_class_subobject)
6906         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6907         << Field << DiagKind << IsDtorCallInCtor;
6908     } else {
6909       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6910       S.Diag(Base->getLocStart(),
6911              diag::note_deleted_special_member_class_subobject)
6912         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6913         << Base->getType() << DiagKind << IsDtorCallInCtor;
6914     }
6915 
6916     if (DiagKind == 1)
6917       S.NoteDeletedFunction(Decl);
6918     // FIXME: Explain inaccessibility if DiagKind == 3.
6919   }
6920 
6921   return true;
6922 }
6923 
6924 /// Check whether we should delete a special member function due to having a
6925 /// direct or virtual base class or non-static data member of class type M.
6926 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6927     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6928   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6929   bool IsMutable = Field && Field->isMutable();
6930 
6931   // C++11 [class.ctor]p5:
6932   // -- any direct or virtual base class, or non-static data member with no
6933   //    brace-or-equal-initializer, has class type M (or array thereof) and
6934   //    either M has no default constructor or overload resolution as applied
6935   //    to M's default constructor results in an ambiguity or in a function
6936   //    that is deleted or inaccessible
6937   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6938   // -- a direct or virtual base class B that cannot be copied/moved because
6939   //    overload resolution, as applied to B's corresponding special member,
6940   //    results in an ambiguity or a function that is deleted or inaccessible
6941   //    from the defaulted special member
6942   // C++11 [class.dtor]p5:
6943   // -- any direct or virtual base class [...] has a type with a destructor
6944   //    that is deleted or inaccessible
6945   if (!(CSM == Sema::CXXDefaultConstructor &&
6946         Field && Field->hasInClassInitializer()) &&
6947       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6948                                    false))
6949     return true;
6950 
6951   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6952   // -- any direct or virtual base class or non-static data member has a
6953   //    type with a destructor that is deleted or inaccessible
6954   if (IsConstructor) {
6955     Sema::SpecialMemberOverloadResult SMOR =
6956         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6957                               false, false, false, false, false);
6958     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6959       return true;
6960   }
6961 
6962   return false;
6963 }
6964 
6965 /// Check whether we should delete a special member function due to the class
6966 /// having a particular direct or virtual base class.
6967 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6968   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6969   // If program is correct, BaseClass cannot be null, but if it is, the error
6970   // must be reported elsewhere.
6971   if (!BaseClass)
6972     return false;
6973   // If we have an inheriting constructor, check whether we're calling an
6974   // inherited constructor instead of a default constructor.
6975   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6976   if (auto *BaseCtor = SMOR.getMethod()) {
6977     // Note that we do not check access along this path; other than that,
6978     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6979     // FIXME: Check that the base has a usable destructor! Sink this into
6980     // shouldDeleteForClassSubobject.
6981     if (BaseCtor->isDeleted() && Diagnose) {
6982       S.Diag(Base->getLocStart(),
6983              diag::note_deleted_special_member_class_subobject)
6984         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6985         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6986       S.NoteDeletedFunction(BaseCtor);
6987     }
6988     return BaseCtor->isDeleted();
6989   }
6990   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6991 }
6992 
6993 /// Check whether we should delete a special member function due to the class
6994 /// having a particular non-static data member.
6995 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6996   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6997   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6998 
6999   if (CSM == Sema::CXXDefaultConstructor) {
7000     // For a default constructor, all references must be initialized in-class
7001     // and, if a union, it must have a non-const member.
7002     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7003       if (Diagnose)
7004         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7005           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7006       return true;
7007     }
7008     // C++11 [class.ctor]p5: any non-variant non-static data member of
7009     // const-qualified type (or array thereof) with no
7010     // brace-or-equal-initializer does not have a user-provided default
7011     // constructor.
7012     if (!inUnion() && FieldType.isConstQualified() &&
7013         !FD->hasInClassInitializer() &&
7014         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7015       if (Diagnose)
7016         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7017           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7018       return true;
7019     }
7020 
7021     if (inUnion() && !FieldType.isConstQualified())
7022       AllFieldsAreConst = false;
7023   } else if (CSM == Sema::CXXCopyConstructor) {
7024     // For a copy constructor, data members must not be of rvalue reference
7025     // type.
7026     if (FieldType->isRValueReferenceType()) {
7027       if (Diagnose)
7028         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7029           << MD->getParent() << FD << FieldType;
7030       return true;
7031     }
7032   } else if (IsAssignment) {
7033     // For an assignment operator, data members must not be of reference type.
7034     if (FieldType->isReferenceType()) {
7035       if (Diagnose)
7036         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7037           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7038       return true;
7039     }
7040     if (!FieldRecord && FieldType.isConstQualified()) {
7041       // C++11 [class.copy]p23:
7042       // -- a non-static data member of const non-class type (or array thereof)
7043       if (Diagnose)
7044         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7045           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7046       return true;
7047     }
7048   }
7049 
7050   if (FieldRecord) {
7051     // Some additional restrictions exist on the variant members.
7052     if (!inUnion() && FieldRecord->isUnion() &&
7053         FieldRecord->isAnonymousStructOrUnion()) {
7054       bool AllVariantFieldsAreConst = true;
7055 
7056       // FIXME: Handle anonymous unions declared within anonymous unions.
7057       for (auto *UI : FieldRecord->fields()) {
7058         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7059 
7060         if (!UnionFieldType.isConstQualified())
7061           AllVariantFieldsAreConst = false;
7062 
7063         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7064         if (UnionFieldRecord &&
7065             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7066                                           UnionFieldType.getCVRQualifiers()))
7067           return true;
7068       }
7069 
7070       // At least one member in each anonymous union must be non-const
7071       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7072           !FieldRecord->field_empty()) {
7073         if (Diagnose)
7074           S.Diag(FieldRecord->getLocation(),
7075                  diag::note_deleted_default_ctor_all_const)
7076             << !!ICI << MD->getParent() << /*anonymous union*/1;
7077         return true;
7078       }
7079 
7080       // Don't check the implicit member of the anonymous union type.
7081       // This is technically non-conformant, but sanity demands it.
7082       return false;
7083     }
7084 
7085     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7086                                       FieldType.getCVRQualifiers()))
7087       return true;
7088   }
7089 
7090   return false;
7091 }
7092 
7093 /// C++11 [class.ctor] p5:
7094 ///   A defaulted default constructor for a class X is defined as deleted if
7095 /// X is a union and all of its variant members are of const-qualified type.
7096 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7097   // This is a silly definition, because it gives an empty union a deleted
7098   // default constructor. Don't do that.
7099   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7100     bool AnyFields = false;
7101     for (auto *F : MD->getParent()->fields())
7102       if ((AnyFields = !F->isUnnamedBitfield()))
7103         break;
7104     if (!AnyFields)
7105       return false;
7106     if (Diagnose)
7107       S.Diag(MD->getParent()->getLocation(),
7108              diag::note_deleted_default_ctor_all_const)
7109         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7110     return true;
7111   }
7112   return false;
7113 }
7114 
7115 /// Determine whether a defaulted special member function should be defined as
7116 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7117 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7118 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7119                                      InheritedConstructorInfo *ICI,
7120                                      bool Diagnose) {
7121   if (MD->isInvalidDecl())
7122     return false;
7123   CXXRecordDecl *RD = MD->getParent();
7124   assert(!RD->isDependentType() && "do deletion after instantiation");
7125   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7126     return false;
7127 
7128   // C++11 [expr.lambda.prim]p19:
7129   //   The closure type associated with a lambda-expression has a
7130   //   deleted (8.4.3) default constructor and a deleted copy
7131   //   assignment operator.
7132   if (RD->isLambda() &&
7133       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7134     if (Diagnose)
7135       Diag(RD->getLocation(), diag::note_lambda_decl);
7136     return true;
7137   }
7138 
7139   // For an anonymous struct or union, the copy and assignment special members
7140   // will never be used, so skip the check. For an anonymous union declared at
7141   // namespace scope, the constructor and destructor are used.
7142   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7143       RD->isAnonymousStructOrUnion())
7144     return false;
7145 
7146   // C++11 [class.copy]p7, p18:
7147   //   If the class definition declares a move constructor or move assignment
7148   //   operator, an implicitly declared copy constructor or copy assignment
7149   //   operator is defined as deleted.
7150   if (MD->isImplicit() &&
7151       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7152     CXXMethodDecl *UserDeclaredMove = nullptr;
7153 
7154     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7155     // deletion of the corresponding copy operation, not both copy operations.
7156     // MSVC 2015 has adopted the standards conforming behavior.
7157     bool DeletesOnlyMatchingCopy =
7158         getLangOpts().MSVCCompat &&
7159         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7160 
7161     if (RD->hasUserDeclaredMoveConstructor() &&
7162         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7163       if (!Diagnose) return true;
7164 
7165       // Find any user-declared move constructor.
7166       for (auto *I : RD->ctors()) {
7167         if (I->isMoveConstructor()) {
7168           UserDeclaredMove = I;
7169           break;
7170         }
7171       }
7172       assert(UserDeclaredMove);
7173     } else if (RD->hasUserDeclaredMoveAssignment() &&
7174                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7175       if (!Diagnose) return true;
7176 
7177       // Find any user-declared move assignment operator.
7178       for (auto *I : RD->methods()) {
7179         if (I->isMoveAssignmentOperator()) {
7180           UserDeclaredMove = I;
7181           break;
7182         }
7183       }
7184       assert(UserDeclaredMove);
7185     }
7186 
7187     if (UserDeclaredMove) {
7188       Diag(UserDeclaredMove->getLocation(),
7189            diag::note_deleted_copy_user_declared_move)
7190         << (CSM == CXXCopyAssignment) << RD
7191         << UserDeclaredMove->isMoveAssignmentOperator();
7192       return true;
7193     }
7194   }
7195 
7196   // Do access control from the special member function
7197   ContextRAII MethodContext(*this, MD);
7198 
7199   // C++11 [class.dtor]p5:
7200   // -- for a virtual destructor, lookup of the non-array deallocation function
7201   //    results in an ambiguity or in a function that is deleted or inaccessible
7202   if (CSM == CXXDestructor && MD->isVirtual()) {
7203     FunctionDecl *OperatorDelete = nullptr;
7204     DeclarationName Name =
7205       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7206     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7207                                  OperatorDelete, /*Diagnose*/false)) {
7208       if (Diagnose)
7209         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7210       return true;
7211     }
7212   }
7213 
7214   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7215 
7216   // Per DR1611, do not consider virtual bases of constructors of abstract
7217   // classes, since we are not going to construct them.
7218   // Per DR1658, do not consider virtual bases of destructors of abstract
7219   // classes either.
7220   // Per DR2180, for assignment operators we only assign (and thus only
7221   // consider) direct bases.
7222   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7223                                  : SMI.VisitPotentiallyConstructedBases))
7224     return true;
7225 
7226   if (SMI.shouldDeleteForAllConstMembers())
7227     return true;
7228 
7229   if (getLangOpts().CUDA) {
7230     // We should delete the special member in CUDA mode if target inference
7231     // failed.
7232     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7233                                                    Diagnose);
7234   }
7235 
7236   return false;
7237 }
7238 
7239 /// Perform lookup for a special member of the specified kind, and determine
7240 /// whether it is trivial. If the triviality can be determined without the
7241 /// lookup, skip it. This is intended for use when determining whether a
7242 /// special member of a containing object is trivial, and thus does not ever
7243 /// perform overload resolution for default constructors.
7244 ///
7245 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7246 /// member that was most likely to be intended to be trivial, if any.
7247 ///
7248 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7249 /// determine whether the special member is trivial.
7250 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7251                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7252                                      bool ConstRHS,
7253                                      Sema::TrivialABIHandling TAH,
7254                                      CXXMethodDecl **Selected) {
7255   if (Selected)
7256     *Selected = nullptr;
7257 
7258   switch (CSM) {
7259   case Sema::CXXInvalid:
7260     llvm_unreachable("not a special member");
7261 
7262   case Sema::CXXDefaultConstructor:
7263     // C++11 [class.ctor]p5:
7264     //   A default constructor is trivial if:
7265     //    - all the [direct subobjects] have trivial default constructors
7266     //
7267     // Note, no overload resolution is performed in this case.
7268     if (RD->hasTrivialDefaultConstructor())
7269       return true;
7270 
7271     if (Selected) {
7272       // If there's a default constructor which could have been trivial, dig it
7273       // out. Otherwise, if there's any user-provided default constructor, point
7274       // to that as an example of why there's not a trivial one.
7275       CXXConstructorDecl *DefCtor = nullptr;
7276       if (RD->needsImplicitDefaultConstructor())
7277         S.DeclareImplicitDefaultConstructor(RD);
7278       for (auto *CI : RD->ctors()) {
7279         if (!CI->isDefaultConstructor())
7280           continue;
7281         DefCtor = CI;
7282         if (!DefCtor->isUserProvided())
7283           break;
7284       }
7285 
7286       *Selected = DefCtor;
7287     }
7288 
7289     return false;
7290 
7291   case Sema::CXXDestructor:
7292     // C++11 [class.dtor]p5:
7293     //   A destructor is trivial if:
7294     //    - all the direct [subobjects] have trivial destructors
7295     if (RD->hasTrivialDestructor() ||
7296         (TAH == Sema::TAH_ConsiderTrivialABI &&
7297          RD->hasTrivialDestructorForCall()))
7298       return true;
7299 
7300     if (Selected) {
7301       if (RD->needsImplicitDestructor())
7302         S.DeclareImplicitDestructor(RD);
7303       *Selected = RD->getDestructor();
7304     }
7305 
7306     return false;
7307 
7308   case Sema::CXXCopyConstructor:
7309     // C++11 [class.copy]p12:
7310     //   A copy constructor is trivial if:
7311     //    - the constructor selected to copy each direct [subobject] is trivial
7312     if (RD->hasTrivialCopyConstructor() ||
7313         (TAH == Sema::TAH_ConsiderTrivialABI &&
7314          RD->hasTrivialCopyConstructorForCall())) {
7315       if (Quals == Qualifiers::Const)
7316         // We must either select the trivial copy constructor or reach an
7317         // ambiguity; no need to actually perform overload resolution.
7318         return true;
7319     } else if (!Selected) {
7320       return false;
7321     }
7322     // In C++98, we are not supposed to perform overload resolution here, but we
7323     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7324     // cases like B as having a non-trivial copy constructor:
7325     //   struct A { template<typename T> A(T&); };
7326     //   struct B { mutable A a; };
7327     goto NeedOverloadResolution;
7328 
7329   case Sema::CXXCopyAssignment:
7330     // C++11 [class.copy]p25:
7331     //   A copy assignment operator is trivial if:
7332     //    - the assignment operator selected to copy each direct [subobject] is
7333     //      trivial
7334     if (RD->hasTrivialCopyAssignment()) {
7335       if (Quals == Qualifiers::Const)
7336         return true;
7337     } else if (!Selected) {
7338       return false;
7339     }
7340     // In C++98, we are not supposed to perform overload resolution here, but we
7341     // treat that as a language defect.
7342     goto NeedOverloadResolution;
7343 
7344   case Sema::CXXMoveConstructor:
7345   case Sema::CXXMoveAssignment:
7346   NeedOverloadResolution:
7347     Sema::SpecialMemberOverloadResult SMOR =
7348         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7349 
7350     // The standard doesn't describe how to behave if the lookup is ambiguous.
7351     // We treat it as not making the member non-trivial, just like the standard
7352     // mandates for the default constructor. This should rarely matter, because
7353     // the member will also be deleted.
7354     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7355       return true;
7356 
7357     if (!SMOR.getMethod()) {
7358       assert(SMOR.getKind() ==
7359              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7360       return false;
7361     }
7362 
7363     // We deliberately don't check if we found a deleted special member. We're
7364     // not supposed to!
7365     if (Selected)
7366       *Selected = SMOR.getMethod();
7367 
7368     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7369         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7370       return SMOR.getMethod()->isTrivialForCall();
7371     return SMOR.getMethod()->isTrivial();
7372   }
7373 
7374   llvm_unreachable("unknown special method kind");
7375 }
7376 
7377 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7378   for (auto *CI : RD->ctors())
7379     if (!CI->isImplicit())
7380       return CI;
7381 
7382   // Look for constructor templates.
7383   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7384   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7385     if (CXXConstructorDecl *CD =
7386           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7387       return CD;
7388   }
7389 
7390   return nullptr;
7391 }
7392 
7393 /// The kind of subobject we are checking for triviality. The values of this
7394 /// enumeration are used in diagnostics.
7395 enum TrivialSubobjectKind {
7396   /// The subobject is a base class.
7397   TSK_BaseClass,
7398   /// The subobject is a non-static data member.
7399   TSK_Field,
7400   /// The object is actually the complete object.
7401   TSK_CompleteObject
7402 };
7403 
7404 /// Check whether the special member selected for a given type would be trivial.
7405 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7406                                       QualType SubType, bool ConstRHS,
7407                                       Sema::CXXSpecialMember CSM,
7408                                       TrivialSubobjectKind Kind,
7409                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7410   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7411   if (!SubRD)
7412     return true;
7413 
7414   CXXMethodDecl *Selected;
7415   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7416                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7417     return true;
7418 
7419   if (Diagnose) {
7420     if (ConstRHS)
7421       SubType.addConst();
7422 
7423     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7424       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7425         << Kind << SubType.getUnqualifiedType();
7426       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7427         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7428     } else if (!Selected)
7429       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7430         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7431     else if (Selected->isUserProvided()) {
7432       if (Kind == TSK_CompleteObject)
7433         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7434           << Kind << SubType.getUnqualifiedType() << CSM;
7435       else {
7436         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7437           << Kind << SubType.getUnqualifiedType() << CSM;
7438         S.Diag(Selected->getLocation(), diag::note_declared_at);
7439       }
7440     } else {
7441       if (Kind != TSK_CompleteObject)
7442         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7443           << Kind << SubType.getUnqualifiedType() << CSM;
7444 
7445       // Explain why the defaulted or deleted special member isn't trivial.
7446       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7447                                Diagnose);
7448     }
7449   }
7450 
7451   return false;
7452 }
7453 
7454 /// Check whether the members of a class type allow a special member to be
7455 /// trivial.
7456 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7457                                      Sema::CXXSpecialMember CSM,
7458                                      bool ConstArg,
7459                                      Sema::TrivialABIHandling TAH,
7460                                      bool Diagnose) {
7461   for (const auto *FI : RD->fields()) {
7462     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7463       continue;
7464 
7465     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7466 
7467     // Pretend anonymous struct or union members are members of this class.
7468     if (FI->isAnonymousStructOrUnion()) {
7469       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7470                                     CSM, ConstArg, TAH, Diagnose))
7471         return false;
7472       continue;
7473     }
7474 
7475     // C++11 [class.ctor]p5:
7476     //   A default constructor is trivial if [...]
7477     //    -- no non-static data member of its class has a
7478     //       brace-or-equal-initializer
7479     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7480       if (Diagnose)
7481         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7482       return false;
7483     }
7484 
7485     // Objective C ARC 4.3.5:
7486     //   [...] nontrivally ownership-qualified types are [...] not trivially
7487     //   default constructible, copy constructible, move constructible, copy
7488     //   assignable, move assignable, or destructible [...]
7489     if (FieldType.hasNonTrivialObjCLifetime()) {
7490       if (Diagnose)
7491         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7492           << RD << FieldType.getObjCLifetime();
7493       return false;
7494     }
7495 
7496     bool ConstRHS = ConstArg && !FI->isMutable();
7497     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7498                                    CSM, TSK_Field, TAH, Diagnose))
7499       return false;
7500   }
7501 
7502   return true;
7503 }
7504 
7505 /// Diagnose why the specified class does not have a trivial special member of
7506 /// the given kind.
7507 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7508   QualType Ty = Context.getRecordType(RD);
7509 
7510   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7511   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7512                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7513                             /*Diagnose*/true);
7514 }
7515 
7516 /// Determine whether a defaulted or deleted special member function is trivial,
7517 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7518 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7519 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7520                                   TrivialABIHandling TAH, bool Diagnose) {
7521   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7522 
7523   CXXRecordDecl *RD = MD->getParent();
7524 
7525   bool ConstArg = false;
7526 
7527   // C++11 [class.copy]p12, p25: [DR1593]
7528   //   A [special member] is trivial if [...] its parameter-type-list is
7529   //   equivalent to the parameter-type-list of an implicit declaration [...]
7530   switch (CSM) {
7531   case CXXDefaultConstructor:
7532   case CXXDestructor:
7533     // Trivial default constructors and destructors cannot have parameters.
7534     break;
7535 
7536   case CXXCopyConstructor:
7537   case CXXCopyAssignment: {
7538     // Trivial copy operations always have const, non-volatile parameter types.
7539     ConstArg = true;
7540     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7541     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7542     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7543       if (Diagnose)
7544         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7545           << Param0->getSourceRange() << Param0->getType()
7546           << Context.getLValueReferenceType(
7547                Context.getRecordType(RD).withConst());
7548       return false;
7549     }
7550     break;
7551   }
7552 
7553   case CXXMoveConstructor:
7554   case CXXMoveAssignment: {
7555     // Trivial move operations always have non-cv-qualified parameters.
7556     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7557     const RValueReferenceType *RT =
7558       Param0->getType()->getAs<RValueReferenceType>();
7559     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7560       if (Diagnose)
7561         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7562           << Param0->getSourceRange() << Param0->getType()
7563           << Context.getRValueReferenceType(Context.getRecordType(RD));
7564       return false;
7565     }
7566     break;
7567   }
7568 
7569   case CXXInvalid:
7570     llvm_unreachable("not a special member");
7571   }
7572 
7573   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7574     if (Diagnose)
7575       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7576            diag::note_nontrivial_default_arg)
7577         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7578     return false;
7579   }
7580   if (MD->isVariadic()) {
7581     if (Diagnose)
7582       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7583     return false;
7584   }
7585 
7586   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7587   //   A copy/move [constructor or assignment operator] is trivial if
7588   //    -- the [member] selected to copy/move each direct base class subobject
7589   //       is trivial
7590   //
7591   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7592   //   A [default constructor or destructor] is trivial if
7593   //    -- all the direct base classes have trivial [default constructors or
7594   //       destructors]
7595   for (const auto &BI : RD->bases())
7596     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7597                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7598       return false;
7599 
7600   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7601   //   A copy/move [constructor or assignment operator] for a class X is
7602   //   trivial if
7603   //    -- for each non-static data member of X that is of class type (or array
7604   //       thereof), the constructor selected to copy/move that member is
7605   //       trivial
7606   //
7607   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7608   //   A [default constructor or destructor] is trivial if
7609   //    -- for all of the non-static data members of its class that are of class
7610   //       type (or array thereof), each such class has a trivial [default
7611   //       constructor or destructor]
7612   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7613     return false;
7614 
7615   // C++11 [class.dtor]p5:
7616   //   A destructor is trivial if [...]
7617   //    -- the destructor is not virtual
7618   if (CSM == CXXDestructor && MD->isVirtual()) {
7619     if (Diagnose)
7620       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7621     return false;
7622   }
7623 
7624   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7625   //   A [special member] for class X is trivial if [...]
7626   //    -- class X has no virtual functions and no virtual base classes
7627   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7628     if (!Diagnose)
7629       return false;
7630 
7631     if (RD->getNumVBases()) {
7632       // Check for virtual bases. We already know that the corresponding
7633       // member in all bases is trivial, so vbases must all be direct.
7634       CXXBaseSpecifier &BS = *RD->vbases_begin();
7635       assert(BS.isVirtual());
7636       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7637       return false;
7638     }
7639 
7640     // Must have a virtual method.
7641     for (const auto *MI : RD->methods()) {
7642       if (MI->isVirtual()) {
7643         SourceLocation MLoc = MI->getLocStart();
7644         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7645         return false;
7646       }
7647     }
7648 
7649     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7650   }
7651 
7652   // Looks like it's trivial!
7653   return true;
7654 }
7655 
7656 namespace {
7657 struct FindHiddenVirtualMethod {
7658   Sema *S;
7659   CXXMethodDecl *Method;
7660   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7661   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7662 
7663 private:
7664   /// Check whether any most overriden method from MD in Methods
7665   static bool CheckMostOverridenMethods(
7666       const CXXMethodDecl *MD,
7667       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7668     if (MD->size_overridden_methods() == 0)
7669       return Methods.count(MD->getCanonicalDecl());
7670     for (const CXXMethodDecl *O : MD->overridden_methods())
7671       if (CheckMostOverridenMethods(O, Methods))
7672         return true;
7673     return false;
7674   }
7675 
7676 public:
7677   /// Member lookup function that determines whether a given C++
7678   /// method overloads virtual methods in a base class without overriding any,
7679   /// to be used with CXXRecordDecl::lookupInBases().
7680   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7681     RecordDecl *BaseRecord =
7682         Specifier->getType()->getAs<RecordType>()->getDecl();
7683 
7684     DeclarationName Name = Method->getDeclName();
7685     assert(Name.getNameKind() == DeclarationName::Identifier);
7686 
7687     bool foundSameNameMethod = false;
7688     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7689     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7690          Path.Decls = Path.Decls.slice(1)) {
7691       NamedDecl *D = Path.Decls.front();
7692       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7693         MD = MD->getCanonicalDecl();
7694         foundSameNameMethod = true;
7695         // Interested only in hidden virtual methods.
7696         if (!MD->isVirtual())
7697           continue;
7698         // If the method we are checking overrides a method from its base
7699         // don't warn about the other overloaded methods. Clang deviates from
7700         // GCC by only diagnosing overloads of inherited virtual functions that
7701         // do not override any other virtual functions in the base. GCC's
7702         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7703         // function from a base class. These cases may be better served by a
7704         // warning (not specific to virtual functions) on call sites when the
7705         // call would select a different function from the base class, were it
7706         // visible.
7707         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7708         if (!S->IsOverload(Method, MD, false))
7709           return true;
7710         // Collect the overload only if its hidden.
7711         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7712           overloadedMethods.push_back(MD);
7713       }
7714     }
7715 
7716     if (foundSameNameMethod)
7717       OverloadedMethods.append(overloadedMethods.begin(),
7718                                overloadedMethods.end());
7719     return foundSameNameMethod;
7720   }
7721 };
7722 } // end anonymous namespace
7723 
7724 /// Add the most overriden methods from MD to Methods
7725 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7726                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7727   if (MD->size_overridden_methods() == 0)
7728     Methods.insert(MD->getCanonicalDecl());
7729   else
7730     for (const CXXMethodDecl *O : MD->overridden_methods())
7731       AddMostOverridenMethods(O, Methods);
7732 }
7733 
7734 /// Check if a method overloads virtual methods in a base class without
7735 /// overriding any.
7736 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7737                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7738   if (!MD->getDeclName().isIdentifier())
7739     return;
7740 
7741   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7742                      /*bool RecordPaths=*/false,
7743                      /*bool DetectVirtual=*/false);
7744   FindHiddenVirtualMethod FHVM;
7745   FHVM.Method = MD;
7746   FHVM.S = this;
7747 
7748   // Keep the base methods that were overriden or introduced in the subclass
7749   // by 'using' in a set. A base method not in this set is hidden.
7750   CXXRecordDecl *DC = MD->getParent();
7751   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7752   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7753     NamedDecl *ND = *I;
7754     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7755       ND = shad->getTargetDecl();
7756     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7757       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7758   }
7759 
7760   if (DC->lookupInBases(FHVM, Paths))
7761     OverloadedMethods = FHVM.OverloadedMethods;
7762 }
7763 
7764 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7765                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7766   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7767     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7768     PartialDiagnostic PD = PDiag(
7769          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7770     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7771     Diag(overloadedMD->getLocation(), PD);
7772   }
7773 }
7774 
7775 /// Diagnose methods which overload virtual methods in a base class
7776 /// without overriding any.
7777 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7778   if (MD->isInvalidDecl())
7779     return;
7780 
7781   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7782     return;
7783 
7784   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7785   FindHiddenVirtualMethods(MD, OverloadedMethods);
7786   if (!OverloadedMethods.empty()) {
7787     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7788       << MD << (OverloadedMethods.size() > 1);
7789 
7790     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7791   }
7792 }
7793 
7794 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7795   auto PrintDiagAndRemoveAttr = [&]() {
7796     // No diagnostics if this is a template instantiation.
7797     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7798       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7799            diag::ext_cannot_use_trivial_abi) << &RD;
7800     RD.dropAttr<TrivialABIAttr>();
7801   };
7802 
7803   // Ill-formed if the struct has virtual functions.
7804   if (RD.isPolymorphic()) {
7805     PrintDiagAndRemoveAttr();
7806     return;
7807   }
7808 
7809   for (const auto &B : RD.bases()) {
7810     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7811     // virtual base.
7812     if ((!B.getType()->isDependentType() &&
7813          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7814         B.isVirtual()) {
7815       PrintDiagAndRemoveAttr();
7816       return;
7817     }
7818   }
7819 
7820   for (const auto *FD : RD.fields()) {
7821     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7822     // non-trivial for the purpose of calls.
7823     QualType FT = FD->getType();
7824     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7825       PrintDiagAndRemoveAttr();
7826       return;
7827     }
7828 
7829     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7830       if (!RT->isDependentType() &&
7831           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7832         PrintDiagAndRemoveAttr();
7833         return;
7834       }
7835   }
7836 }
7837 
7838 void Sema::ActOnFinishCXXMemberSpecification(
7839     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7840     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7841   if (!TagDecl)
7842     return;
7843 
7844   AdjustDeclIfTemplate(TagDecl);
7845 
7846   for (const ParsedAttr &AL : AttrList) {
7847     if (AL.getKind() != ParsedAttr::AT_Visibility)
7848       continue;
7849     AL.setInvalid();
7850     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7851         << AL.getName();
7852   }
7853 
7854   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7855               // strict aliasing violation!
7856               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7857               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7858 
7859   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7860 }
7861 
7862 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7863 /// special functions, such as the default constructor, copy
7864 /// constructor, or destructor, to the given C++ class (C++
7865 /// [special]p1).  This routine can only be executed just before the
7866 /// definition of the class is complete.
7867 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7868   if (ClassDecl->needsImplicitDefaultConstructor()) {
7869     ++ASTContext::NumImplicitDefaultConstructors;
7870 
7871     if (ClassDecl->hasInheritedConstructor())
7872       DeclareImplicitDefaultConstructor(ClassDecl);
7873   }
7874 
7875   if (ClassDecl->needsImplicitCopyConstructor()) {
7876     ++ASTContext::NumImplicitCopyConstructors;
7877 
7878     // If the properties or semantics of the copy constructor couldn't be
7879     // determined while the class was being declared, force a declaration
7880     // of it now.
7881     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7882         ClassDecl->hasInheritedConstructor())
7883       DeclareImplicitCopyConstructor(ClassDecl);
7884     // For the MS ABI we need to know whether the copy ctor is deleted. A
7885     // prerequisite for deleting the implicit copy ctor is that the class has a
7886     // move ctor or move assignment that is either user-declared or whose
7887     // semantics are inherited from a subobject. FIXME: We should provide a more
7888     // direct way for CodeGen to ask whether the constructor was deleted.
7889     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7890              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7891               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7892               ClassDecl->hasUserDeclaredMoveAssignment() ||
7893               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7894       DeclareImplicitCopyConstructor(ClassDecl);
7895   }
7896 
7897   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7898     ++ASTContext::NumImplicitMoveConstructors;
7899 
7900     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7901         ClassDecl->hasInheritedConstructor())
7902       DeclareImplicitMoveConstructor(ClassDecl);
7903   }
7904 
7905   if (ClassDecl->needsImplicitCopyAssignment()) {
7906     ++ASTContext::NumImplicitCopyAssignmentOperators;
7907 
7908     // If we have a dynamic class, then the copy assignment operator may be
7909     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7910     // it shows up in the right place in the vtable and that we diagnose
7911     // problems with the implicit exception specification.
7912     if (ClassDecl->isDynamicClass() ||
7913         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7914         ClassDecl->hasInheritedAssignment())
7915       DeclareImplicitCopyAssignment(ClassDecl);
7916   }
7917 
7918   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7919     ++ASTContext::NumImplicitMoveAssignmentOperators;
7920 
7921     // Likewise for the move assignment operator.
7922     if (ClassDecl->isDynamicClass() ||
7923         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7924         ClassDecl->hasInheritedAssignment())
7925       DeclareImplicitMoveAssignment(ClassDecl);
7926   }
7927 
7928   if (ClassDecl->needsImplicitDestructor()) {
7929     ++ASTContext::NumImplicitDestructors;
7930 
7931     // If we have a dynamic class, then the destructor may be virtual, so we
7932     // have to declare the destructor immediately. This ensures that, e.g., it
7933     // shows up in the right place in the vtable and that we diagnose problems
7934     // with the implicit exception specification.
7935     if (ClassDecl->isDynamicClass() ||
7936         ClassDecl->needsOverloadResolutionForDestructor())
7937       DeclareImplicitDestructor(ClassDecl);
7938   }
7939 }
7940 
7941 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7942   if (!D)
7943     return 0;
7944 
7945   // The order of template parameters is not important here. All names
7946   // get added to the same scope.
7947   SmallVector<TemplateParameterList *, 4> ParameterLists;
7948 
7949   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7950     D = TD->getTemplatedDecl();
7951 
7952   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7953     ParameterLists.push_back(PSD->getTemplateParameters());
7954 
7955   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7956     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7957       ParameterLists.push_back(DD->getTemplateParameterList(i));
7958 
7959     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7960       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7961         ParameterLists.push_back(FTD->getTemplateParameters());
7962     }
7963   }
7964 
7965   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7966     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7967       ParameterLists.push_back(TD->getTemplateParameterList(i));
7968 
7969     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7970       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7971         ParameterLists.push_back(CTD->getTemplateParameters());
7972     }
7973   }
7974 
7975   unsigned Count = 0;
7976   for (TemplateParameterList *Params : ParameterLists) {
7977     if (Params->size() > 0)
7978       // Ignore explicit specializations; they don't contribute to the template
7979       // depth.
7980       ++Count;
7981     for (NamedDecl *Param : *Params) {
7982       if (Param->getDeclName()) {
7983         S->AddDecl(Param);
7984         IdResolver.AddDecl(Param);
7985       }
7986     }
7987   }
7988 
7989   return Count;
7990 }
7991 
7992 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7993   if (!RecordD) return;
7994   AdjustDeclIfTemplate(RecordD);
7995   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7996   PushDeclContext(S, Record);
7997 }
7998 
7999 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8000   if (!RecordD) return;
8001   PopDeclContext();
8002 }
8003 
8004 /// This is used to implement the constant expression evaluation part of the
8005 /// attribute enable_if extension. There is nothing in standard C++ which would
8006 /// require reentering parameters.
8007 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8008   if (!Param)
8009     return;
8010 
8011   S->AddDecl(Param);
8012   if (Param->getDeclName())
8013     IdResolver.AddDecl(Param);
8014 }
8015 
8016 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8017 /// parsing a top-level (non-nested) C++ class, and we are now
8018 /// parsing those parts of the given Method declaration that could
8019 /// not be parsed earlier (C++ [class.mem]p2), such as default
8020 /// arguments. This action should enter the scope of the given
8021 /// Method declaration as if we had just parsed the qualified method
8022 /// name. However, it should not bring the parameters into scope;
8023 /// that will be performed by ActOnDelayedCXXMethodParameter.
8024 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8025 }
8026 
8027 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8028 /// C++ method declaration. We're (re-)introducing the given
8029 /// function parameter into scope for use in parsing later parts of
8030 /// the method declaration. For example, we could see an
8031 /// ActOnParamDefaultArgument event for this parameter.
8032 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8033   if (!ParamD)
8034     return;
8035 
8036   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8037 
8038   // If this parameter has an unparsed default argument, clear it out
8039   // to make way for the parsed default argument.
8040   if (Param->hasUnparsedDefaultArg())
8041     Param->setDefaultArg(nullptr);
8042 
8043   S->AddDecl(Param);
8044   if (Param->getDeclName())
8045     IdResolver.AddDecl(Param);
8046 }
8047 
8048 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8049 /// processing the delayed method declaration for Method. The method
8050 /// declaration is now considered finished. There may be a separate
8051 /// ActOnStartOfFunctionDef action later (not necessarily
8052 /// immediately!) for this method, if it was also defined inside the
8053 /// class body.
8054 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8055   if (!MethodD)
8056     return;
8057 
8058   AdjustDeclIfTemplate(MethodD);
8059 
8060   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8061 
8062   // Now that we have our default arguments, check the constructor
8063   // again. It could produce additional diagnostics or affect whether
8064   // the class has implicitly-declared destructors, among other
8065   // things.
8066   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8067     CheckConstructor(Constructor);
8068 
8069   // Check the default arguments, which we may have added.
8070   if (!Method->isInvalidDecl())
8071     CheckCXXDefaultArguments(Method);
8072 }
8073 
8074 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8075 /// the well-formedness of the constructor declarator @p D with type @p
8076 /// R. If there are any errors in the declarator, this routine will
8077 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8078 /// will be updated to reflect a well-formed type for the constructor and
8079 /// returned.
8080 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8081                                           StorageClass &SC) {
8082   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8083 
8084   // C++ [class.ctor]p3:
8085   //   A constructor shall not be virtual (10.3) or static (9.4). A
8086   //   constructor can be invoked for a const, volatile or const
8087   //   volatile object. A constructor shall not be declared const,
8088   //   volatile, or const volatile (9.3.2).
8089   if (isVirtual) {
8090     if (!D.isInvalidType())
8091       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8092         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8093         << SourceRange(D.getIdentifierLoc());
8094     D.setInvalidType();
8095   }
8096   if (SC == SC_Static) {
8097     if (!D.isInvalidType())
8098       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8099         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8100         << SourceRange(D.getIdentifierLoc());
8101     D.setInvalidType();
8102     SC = SC_None;
8103   }
8104 
8105   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8106     diagnoseIgnoredQualifiers(
8107         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8108         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8109         D.getDeclSpec().getRestrictSpecLoc(),
8110         D.getDeclSpec().getAtomicSpecLoc());
8111     D.setInvalidType();
8112   }
8113 
8114   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8115   if (FTI.TypeQuals != 0) {
8116     if (FTI.TypeQuals & Qualifiers::Const)
8117       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8118         << "const" << SourceRange(D.getIdentifierLoc());
8119     if (FTI.TypeQuals & Qualifiers::Volatile)
8120       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8121         << "volatile" << SourceRange(D.getIdentifierLoc());
8122     if (FTI.TypeQuals & Qualifiers::Restrict)
8123       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8124         << "restrict" << SourceRange(D.getIdentifierLoc());
8125     D.setInvalidType();
8126   }
8127 
8128   // C++0x [class.ctor]p4:
8129   //   A constructor shall not be declared with a ref-qualifier.
8130   if (FTI.hasRefQualifier()) {
8131     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8132       << FTI.RefQualifierIsLValueRef
8133       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8134     D.setInvalidType();
8135   }
8136 
8137   // Rebuild the function type "R" without any type qualifiers (in
8138   // case any of the errors above fired) and with "void" as the
8139   // return type, since constructors don't have return types.
8140   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8141   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8142     return R;
8143 
8144   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8145   EPI.TypeQuals = 0;
8146   EPI.RefQualifier = RQ_None;
8147 
8148   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8149 }
8150 
8151 /// CheckConstructor - Checks a fully-formed constructor for
8152 /// well-formedness, issuing any diagnostics required. Returns true if
8153 /// the constructor declarator is invalid.
8154 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8155   CXXRecordDecl *ClassDecl
8156     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8157   if (!ClassDecl)
8158     return Constructor->setInvalidDecl();
8159 
8160   // C++ [class.copy]p3:
8161   //   A declaration of a constructor for a class X is ill-formed if
8162   //   its first parameter is of type (optionally cv-qualified) X and
8163   //   either there are no other parameters or else all other
8164   //   parameters have default arguments.
8165   if (!Constructor->isInvalidDecl() &&
8166       ((Constructor->getNumParams() == 1) ||
8167        (Constructor->getNumParams() > 1 &&
8168         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8169       Constructor->getTemplateSpecializationKind()
8170                                               != TSK_ImplicitInstantiation) {
8171     QualType ParamType = Constructor->getParamDecl(0)->getType();
8172     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8173     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8174       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8175       const char *ConstRef
8176         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8177                                                         : " const &";
8178       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8179         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8180 
8181       // FIXME: Rather that making the constructor invalid, we should endeavor
8182       // to fix the type.
8183       Constructor->setInvalidDecl();
8184     }
8185   }
8186 }
8187 
8188 /// CheckDestructor - Checks a fully-formed destructor definition for
8189 /// well-formedness, issuing any diagnostics required.  Returns true
8190 /// on error.
8191 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8192   CXXRecordDecl *RD = Destructor->getParent();
8193 
8194   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8195     SourceLocation Loc;
8196 
8197     if (!Destructor->isImplicit())
8198       Loc = Destructor->getLocation();
8199     else
8200       Loc = RD->getLocation();
8201 
8202     // If we have a virtual destructor, look up the deallocation function
8203     if (FunctionDecl *OperatorDelete =
8204             FindDeallocationFunctionForDestructor(Loc, RD)) {
8205       Expr *ThisArg = nullptr;
8206 
8207       // If the notional 'delete this' expression requires a non-trivial
8208       // conversion from 'this' to the type of a destroying operator delete's
8209       // first parameter, perform that conversion now.
8210       if (OperatorDelete->isDestroyingOperatorDelete()) {
8211         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8212         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8213           // C++ [class.dtor]p13:
8214           //   ... as if for the expression 'delete this' appearing in a
8215           //   non-virtual destructor of the destructor's class.
8216           ContextRAII SwitchContext(*this, Destructor);
8217           ExprResult This =
8218               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8219           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8220           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8221           if (This.isInvalid()) {
8222             // FIXME: Register this as a context note so that it comes out
8223             // in the right order.
8224             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8225             return true;
8226           }
8227           ThisArg = This.get();
8228         }
8229       }
8230 
8231       MarkFunctionReferenced(Loc, OperatorDelete);
8232       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8233     }
8234   }
8235 
8236   return false;
8237 }
8238 
8239 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8240 /// the well-formednes of the destructor declarator @p D with type @p
8241 /// R. If there are any errors in the declarator, this routine will
8242 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8243 /// will be updated to reflect a well-formed type for the destructor and
8244 /// returned.
8245 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8246                                          StorageClass& SC) {
8247   // C++ [class.dtor]p1:
8248   //   [...] A typedef-name that names a class is a class-name
8249   //   (7.1.3); however, a typedef-name that names a class shall not
8250   //   be used as the identifier in the declarator for a destructor
8251   //   declaration.
8252   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8253   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8254     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8255       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8256   else if (const TemplateSpecializationType *TST =
8257              DeclaratorType->getAs<TemplateSpecializationType>())
8258     if (TST->isTypeAlias())
8259       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8260         << DeclaratorType << 1;
8261 
8262   // C++ [class.dtor]p2:
8263   //   A destructor is used to destroy objects of its class type. A
8264   //   destructor takes no parameters, and no return type can be
8265   //   specified for it (not even void). The address of a destructor
8266   //   shall not be taken. A destructor shall not be static. A
8267   //   destructor can be invoked for a const, volatile or const
8268   //   volatile object. A destructor shall not be declared const,
8269   //   volatile or const volatile (9.3.2).
8270   if (SC == SC_Static) {
8271     if (!D.isInvalidType())
8272       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8273         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8274         << SourceRange(D.getIdentifierLoc())
8275         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8276 
8277     SC = SC_None;
8278   }
8279   if (!D.isInvalidType()) {
8280     // Destructors don't have return types, but the parser will
8281     // happily parse something like:
8282     //
8283     //   class X {
8284     //     float ~X();
8285     //   };
8286     //
8287     // The return type will be eliminated later.
8288     if (D.getDeclSpec().hasTypeSpecifier())
8289       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8290         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8291         << SourceRange(D.getIdentifierLoc());
8292     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8293       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8294                                 SourceLocation(),
8295                                 D.getDeclSpec().getConstSpecLoc(),
8296                                 D.getDeclSpec().getVolatileSpecLoc(),
8297                                 D.getDeclSpec().getRestrictSpecLoc(),
8298                                 D.getDeclSpec().getAtomicSpecLoc());
8299       D.setInvalidType();
8300     }
8301   }
8302 
8303   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8304   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8305     if (FTI.TypeQuals & Qualifiers::Const)
8306       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8307         << "const" << SourceRange(D.getIdentifierLoc());
8308     if (FTI.TypeQuals & Qualifiers::Volatile)
8309       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8310         << "volatile" << SourceRange(D.getIdentifierLoc());
8311     if (FTI.TypeQuals & Qualifiers::Restrict)
8312       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8313         << "restrict" << SourceRange(D.getIdentifierLoc());
8314     D.setInvalidType();
8315   }
8316 
8317   // C++0x [class.dtor]p2:
8318   //   A destructor shall not be declared with a ref-qualifier.
8319   if (FTI.hasRefQualifier()) {
8320     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8321       << FTI.RefQualifierIsLValueRef
8322       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8323     D.setInvalidType();
8324   }
8325 
8326   // Make sure we don't have any parameters.
8327   if (FTIHasNonVoidParameters(FTI)) {
8328     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8329 
8330     // Delete the parameters.
8331     FTI.freeParams();
8332     D.setInvalidType();
8333   }
8334 
8335   // Make sure the destructor isn't variadic.
8336   if (FTI.isVariadic) {
8337     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8338     D.setInvalidType();
8339   }
8340 
8341   // Rebuild the function type "R" without any type qualifiers or
8342   // parameters (in case any of the errors above fired) and with
8343   // "void" as the return type, since destructors don't have return
8344   // types.
8345   if (!D.isInvalidType())
8346     return R;
8347 
8348   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8349   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8350   EPI.Variadic = false;
8351   EPI.TypeQuals = 0;
8352   EPI.RefQualifier = RQ_None;
8353   return Context.getFunctionType(Context.VoidTy, None, EPI);
8354 }
8355 
8356 static void extendLeft(SourceRange &R, SourceRange Before) {
8357   if (Before.isInvalid())
8358     return;
8359   R.setBegin(Before.getBegin());
8360   if (R.getEnd().isInvalid())
8361     R.setEnd(Before.getEnd());
8362 }
8363 
8364 static void extendRight(SourceRange &R, SourceRange After) {
8365   if (After.isInvalid())
8366     return;
8367   if (R.getBegin().isInvalid())
8368     R.setBegin(After.getBegin());
8369   R.setEnd(After.getEnd());
8370 }
8371 
8372 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8373 /// well-formednes of the conversion function declarator @p D with
8374 /// type @p R. If there are any errors in the declarator, this routine
8375 /// will emit diagnostics and return true. Otherwise, it will return
8376 /// false. Either way, the type @p R will be updated to reflect a
8377 /// well-formed type for the conversion operator.
8378 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8379                                      StorageClass& SC) {
8380   // C++ [class.conv.fct]p1:
8381   //   Neither parameter types nor return type can be specified. The
8382   //   type of a conversion function (8.3.5) is "function taking no
8383   //   parameter returning conversion-type-id."
8384   if (SC == SC_Static) {
8385     if (!D.isInvalidType())
8386       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8387         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8388         << D.getName().getSourceRange();
8389     D.setInvalidType();
8390     SC = SC_None;
8391   }
8392 
8393   TypeSourceInfo *ConvTSI = nullptr;
8394   QualType ConvType =
8395       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8396 
8397   const DeclSpec &DS = D.getDeclSpec();
8398   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8399     // Conversion functions don't have return types, but the parser will
8400     // happily parse something like:
8401     //
8402     //   class X {
8403     //     float operator bool();
8404     //   };
8405     //
8406     // The return type will be changed later anyway.
8407     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8408       << SourceRange(DS.getTypeSpecTypeLoc())
8409       << SourceRange(D.getIdentifierLoc());
8410     D.setInvalidType();
8411   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8412     // It's also plausible that the user writes type qualifiers in the wrong
8413     // place, such as:
8414     //   struct S { const operator int(); };
8415     // FIXME: we could provide a fixit to move the qualifiers onto the
8416     // conversion type.
8417     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8418         << SourceRange(D.getIdentifierLoc()) << 0;
8419     D.setInvalidType();
8420   }
8421 
8422   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8423 
8424   // Make sure we don't have any parameters.
8425   if (Proto->getNumParams() > 0) {
8426     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8427 
8428     // Delete the parameters.
8429     D.getFunctionTypeInfo().freeParams();
8430     D.setInvalidType();
8431   } else if (Proto->isVariadic()) {
8432     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8433     D.setInvalidType();
8434   }
8435 
8436   // Diagnose "&operator bool()" and other such nonsense.  This
8437   // is actually a gcc extension which we don't support.
8438   if (Proto->getReturnType() != ConvType) {
8439     bool NeedsTypedef = false;
8440     SourceRange Before, After;
8441 
8442     // Walk the chunks and extract information on them for our diagnostic.
8443     bool PastFunctionChunk = false;
8444     for (auto &Chunk : D.type_objects()) {
8445       switch (Chunk.Kind) {
8446       case DeclaratorChunk::Function:
8447         if (!PastFunctionChunk) {
8448           if (Chunk.Fun.HasTrailingReturnType) {
8449             TypeSourceInfo *TRT = nullptr;
8450             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8451             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8452           }
8453           PastFunctionChunk = true;
8454           break;
8455         }
8456         LLVM_FALLTHROUGH;
8457       case DeclaratorChunk::Array:
8458         NeedsTypedef = true;
8459         extendRight(After, Chunk.getSourceRange());
8460         break;
8461 
8462       case DeclaratorChunk::Pointer:
8463       case DeclaratorChunk::BlockPointer:
8464       case DeclaratorChunk::Reference:
8465       case DeclaratorChunk::MemberPointer:
8466       case DeclaratorChunk::Pipe:
8467         extendLeft(Before, Chunk.getSourceRange());
8468         break;
8469 
8470       case DeclaratorChunk::Paren:
8471         extendLeft(Before, Chunk.Loc);
8472         extendRight(After, Chunk.EndLoc);
8473         break;
8474       }
8475     }
8476 
8477     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8478                          After.isValid()  ? After.getBegin() :
8479                                             D.getIdentifierLoc();
8480     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8481     DB << Before << After;
8482 
8483     if (!NeedsTypedef) {
8484       DB << /*don't need a typedef*/0;
8485 
8486       // If we can provide a correct fix-it hint, do so.
8487       if (After.isInvalid() && ConvTSI) {
8488         SourceLocation InsertLoc =
8489             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8490         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8491            << FixItHint::CreateInsertionFromRange(
8492                   InsertLoc, CharSourceRange::getTokenRange(Before))
8493            << FixItHint::CreateRemoval(Before);
8494       }
8495     } else if (!Proto->getReturnType()->isDependentType()) {
8496       DB << /*typedef*/1 << Proto->getReturnType();
8497     } else if (getLangOpts().CPlusPlus11) {
8498       DB << /*alias template*/2 << Proto->getReturnType();
8499     } else {
8500       DB << /*might not be fixable*/3;
8501     }
8502 
8503     // Recover by incorporating the other type chunks into the result type.
8504     // Note, this does *not* change the name of the function. This is compatible
8505     // with the GCC extension:
8506     //   struct S { &operator int(); } s;
8507     //   int &r = s.operator int(); // ok in GCC
8508     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8509     ConvType = Proto->getReturnType();
8510   }
8511 
8512   // C++ [class.conv.fct]p4:
8513   //   The conversion-type-id shall not represent a function type nor
8514   //   an array type.
8515   if (ConvType->isArrayType()) {
8516     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8517     ConvType = Context.getPointerType(ConvType);
8518     D.setInvalidType();
8519   } else if (ConvType->isFunctionType()) {
8520     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8521     ConvType = Context.getPointerType(ConvType);
8522     D.setInvalidType();
8523   }
8524 
8525   // Rebuild the function type "R" without any parameters (in case any
8526   // of the errors above fired) and with the conversion type as the
8527   // return type.
8528   if (D.isInvalidType())
8529     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8530 
8531   // C++0x explicit conversion operators.
8532   if (DS.isExplicitSpecified())
8533     Diag(DS.getExplicitSpecLoc(),
8534          getLangOpts().CPlusPlus11
8535              ? diag::warn_cxx98_compat_explicit_conversion_functions
8536              : diag::ext_explicit_conversion_functions)
8537         << SourceRange(DS.getExplicitSpecLoc());
8538 }
8539 
8540 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8541 /// the declaration of the given C++ conversion function. This routine
8542 /// is responsible for recording the conversion function in the C++
8543 /// class, if possible.
8544 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8545   assert(Conversion && "Expected to receive a conversion function declaration");
8546 
8547   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8548 
8549   // Make sure we aren't redeclaring the conversion function.
8550   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8551 
8552   // C++ [class.conv.fct]p1:
8553   //   [...] A conversion function is never used to convert a
8554   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8555   //   same object type (or a reference to it), to a (possibly
8556   //   cv-qualified) base class of that type (or a reference to it),
8557   //   or to (possibly cv-qualified) void.
8558   // FIXME: Suppress this warning if the conversion function ends up being a
8559   // virtual function that overrides a virtual function in a base class.
8560   QualType ClassType
8561     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8562   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8563     ConvType = ConvTypeRef->getPointeeType();
8564   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8565       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8566     /* Suppress diagnostics for instantiations. */;
8567   else if (ConvType->isRecordType()) {
8568     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8569     if (ConvType == ClassType)
8570       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8571         << ClassType;
8572     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8573       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8574         <<  ClassType << ConvType;
8575   } else if (ConvType->isVoidType()) {
8576     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8577       << ClassType << ConvType;
8578   }
8579 
8580   if (FunctionTemplateDecl *ConversionTemplate
8581                                 = Conversion->getDescribedFunctionTemplate())
8582     return ConversionTemplate;
8583 
8584   return Conversion;
8585 }
8586 
8587 namespace {
8588 /// Utility class to accumulate and print a diagnostic listing the invalid
8589 /// specifier(s) on a declaration.
8590 struct BadSpecifierDiagnoser {
8591   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8592       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8593   ~BadSpecifierDiagnoser() {
8594     Diagnostic << Specifiers;
8595   }
8596 
8597   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8598     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8599   }
8600   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8601     return check(SpecLoc,
8602                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8603   }
8604   void check(SourceLocation SpecLoc, const char *Spec) {
8605     if (SpecLoc.isInvalid()) return;
8606     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8607     if (!Specifiers.empty()) Specifiers += " ";
8608     Specifiers += Spec;
8609   }
8610 
8611   Sema &S;
8612   Sema::SemaDiagnosticBuilder Diagnostic;
8613   std::string Specifiers;
8614 };
8615 }
8616 
8617 /// Check the validity of a declarator that we parsed for a deduction-guide.
8618 /// These aren't actually declarators in the grammar, so we need to check that
8619 /// the user didn't specify any pieces that are not part of the deduction-guide
8620 /// grammar.
8621 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8622                                          StorageClass &SC) {
8623   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8624   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8625   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8626 
8627   // C++ [temp.deduct.guide]p3:
8628   //   A deduction-gide shall be declared in the same scope as the
8629   //   corresponding class template.
8630   if (!CurContext->getRedeclContext()->Equals(
8631           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8632     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8633       << GuidedTemplateDecl;
8634     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8635   }
8636 
8637   auto &DS = D.getMutableDeclSpec();
8638   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8639   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8640       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8641       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8642     BadSpecifierDiagnoser Diagnoser(
8643         *this, D.getIdentifierLoc(),
8644         diag::err_deduction_guide_invalid_specifier);
8645 
8646     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8647     DS.ClearStorageClassSpecs();
8648     SC = SC_None;
8649 
8650     // 'explicit' is permitted.
8651     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8652     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8653     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8654     DS.ClearConstexprSpec();
8655 
8656     Diagnoser.check(DS.getConstSpecLoc(), "const");
8657     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8658     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8659     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8660     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8661     DS.ClearTypeQualifiers();
8662 
8663     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8664     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8665     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8666     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8667     DS.ClearTypeSpecType();
8668   }
8669 
8670   if (D.isInvalidType())
8671     return;
8672 
8673   // Check the declarator is simple enough.
8674   bool FoundFunction = false;
8675   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8676     if (Chunk.Kind == DeclaratorChunk::Paren)
8677       continue;
8678     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8679       Diag(D.getDeclSpec().getLocStart(),
8680           diag::err_deduction_guide_with_complex_decl)
8681         << D.getSourceRange();
8682       break;
8683     }
8684     if (!Chunk.Fun.hasTrailingReturnType()) {
8685       Diag(D.getName().getLocStart(),
8686            diag::err_deduction_guide_no_trailing_return_type);
8687       break;
8688     }
8689 
8690     // Check that the return type is written as a specialization of
8691     // the template specified as the deduction-guide's name.
8692     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8693     TypeSourceInfo *TSI = nullptr;
8694     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8695     assert(TSI && "deduction guide has valid type but invalid return type?");
8696     bool AcceptableReturnType = false;
8697     bool MightInstantiateToSpecialization = false;
8698     if (auto RetTST =
8699             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8700       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8701       bool TemplateMatches =
8702           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8703       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8704         AcceptableReturnType = true;
8705       else {
8706         // This could still instantiate to the right type, unless we know it
8707         // names the wrong class template.
8708         auto *TD = SpecifiedName.getAsTemplateDecl();
8709         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8710                                              !TemplateMatches);
8711       }
8712     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8713       MightInstantiateToSpecialization = true;
8714     }
8715 
8716     if (!AcceptableReturnType) {
8717       Diag(TSI->getTypeLoc().getLocStart(),
8718            diag::err_deduction_guide_bad_trailing_return_type)
8719         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8720         << TSI->getTypeLoc().getSourceRange();
8721     }
8722 
8723     // Keep going to check that we don't have any inner declarator pieces (we
8724     // could still have a function returning a pointer to a function).
8725     FoundFunction = true;
8726   }
8727 
8728   if (D.isFunctionDefinition())
8729     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8730 }
8731 
8732 //===----------------------------------------------------------------------===//
8733 // Namespace Handling
8734 //===----------------------------------------------------------------------===//
8735 
8736 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8737 /// reopened.
8738 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8739                                             SourceLocation Loc,
8740                                             IdentifierInfo *II, bool *IsInline,
8741                                             NamespaceDecl *PrevNS) {
8742   assert(*IsInline != PrevNS->isInline());
8743 
8744   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8745   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8746   // inline namespaces, with the intention of bringing names into namespace std.
8747   //
8748   // We support this just well enough to get that case working; this is not
8749   // sufficient to support reopening namespaces as inline in general.
8750   if (*IsInline && II && II->getName().startswith("__atomic") &&
8751       S.getSourceManager().isInSystemHeader(Loc)) {
8752     // Mark all prior declarations of the namespace as inline.
8753     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8754          NS = NS->getPreviousDecl())
8755       NS->setInline(*IsInline);
8756     // Patch up the lookup table for the containing namespace. This isn't really
8757     // correct, but it's good enough for this particular case.
8758     for (auto *I : PrevNS->decls())
8759       if (auto *ND = dyn_cast<NamedDecl>(I))
8760         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8761     return;
8762   }
8763 
8764   if (PrevNS->isInline())
8765     // The user probably just forgot the 'inline', so suggest that it
8766     // be added back.
8767     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8768       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8769   else
8770     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8771 
8772   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8773   *IsInline = PrevNS->isInline();
8774 }
8775 
8776 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8777 /// definition.
8778 Decl *Sema::ActOnStartNamespaceDef(
8779     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8780     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8781     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8782   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8783   // For anonymous namespace, take the location of the left brace.
8784   SourceLocation Loc = II ? IdentLoc : LBrace;
8785   bool IsInline = InlineLoc.isValid();
8786   bool IsInvalid = false;
8787   bool IsStd = false;
8788   bool AddToKnown = false;
8789   Scope *DeclRegionScope = NamespcScope->getParent();
8790 
8791   NamespaceDecl *PrevNS = nullptr;
8792   if (II) {
8793     // C++ [namespace.def]p2:
8794     //   The identifier in an original-namespace-definition shall not
8795     //   have been previously defined in the declarative region in
8796     //   which the original-namespace-definition appears. The
8797     //   identifier in an original-namespace-definition is the name of
8798     //   the namespace. Subsequently in that declarative region, it is
8799     //   treated as an original-namespace-name.
8800     //
8801     // Since namespace names are unique in their scope, and we don't
8802     // look through using directives, just look for any ordinary names
8803     // as if by qualified name lookup.
8804     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8805                    ForExternalRedeclaration);
8806     LookupQualifiedName(R, CurContext->getRedeclContext());
8807     NamedDecl *PrevDecl =
8808         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8809     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8810 
8811     if (PrevNS) {
8812       // This is an extended namespace definition.
8813       if (IsInline != PrevNS->isInline())
8814         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8815                                         &IsInline, PrevNS);
8816     } else if (PrevDecl) {
8817       // This is an invalid name redefinition.
8818       Diag(Loc, diag::err_redefinition_different_kind)
8819         << II;
8820       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8821       IsInvalid = true;
8822       // Continue on to push Namespc as current DeclContext and return it.
8823     } else if (II->isStr("std") &&
8824                CurContext->getRedeclContext()->isTranslationUnit()) {
8825       // This is the first "real" definition of the namespace "std", so update
8826       // our cache of the "std" namespace to point at this definition.
8827       PrevNS = getStdNamespace();
8828       IsStd = true;
8829       AddToKnown = !IsInline;
8830     } else {
8831       // We've seen this namespace for the first time.
8832       AddToKnown = !IsInline;
8833     }
8834   } else {
8835     // Anonymous namespaces.
8836 
8837     // Determine whether the parent already has an anonymous namespace.
8838     DeclContext *Parent = CurContext->getRedeclContext();
8839     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8840       PrevNS = TU->getAnonymousNamespace();
8841     } else {
8842       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8843       PrevNS = ND->getAnonymousNamespace();
8844     }
8845 
8846     if (PrevNS && IsInline != PrevNS->isInline())
8847       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8848                                       &IsInline, PrevNS);
8849   }
8850 
8851   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8852                                                  StartLoc, Loc, II, PrevNS);
8853   if (IsInvalid)
8854     Namespc->setInvalidDecl();
8855 
8856   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8857   AddPragmaAttributes(DeclRegionScope, Namespc);
8858 
8859   // FIXME: Should we be merging attributes?
8860   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8861     PushNamespaceVisibilityAttr(Attr, Loc);
8862 
8863   if (IsStd)
8864     StdNamespace = Namespc;
8865   if (AddToKnown)
8866     KnownNamespaces[Namespc] = false;
8867 
8868   if (II) {
8869     PushOnScopeChains(Namespc, DeclRegionScope);
8870   } else {
8871     // Link the anonymous namespace into its parent.
8872     DeclContext *Parent = CurContext->getRedeclContext();
8873     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8874       TU->setAnonymousNamespace(Namespc);
8875     } else {
8876       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8877     }
8878 
8879     CurContext->addDecl(Namespc);
8880 
8881     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8882     //   behaves as if it were replaced by
8883     //     namespace unique { /* empty body */ }
8884     //     using namespace unique;
8885     //     namespace unique { namespace-body }
8886     //   where all occurrences of 'unique' in a translation unit are
8887     //   replaced by the same identifier and this identifier differs
8888     //   from all other identifiers in the entire program.
8889 
8890     // We just create the namespace with an empty name and then add an
8891     // implicit using declaration, just like the standard suggests.
8892     //
8893     // CodeGen enforces the "universally unique" aspect by giving all
8894     // declarations semantically contained within an anonymous
8895     // namespace internal linkage.
8896 
8897     if (!PrevNS) {
8898       UD = UsingDirectiveDecl::Create(Context, Parent,
8899                                       /* 'using' */ LBrace,
8900                                       /* 'namespace' */ SourceLocation(),
8901                                       /* qualifier */ NestedNameSpecifierLoc(),
8902                                       /* identifier */ SourceLocation(),
8903                                       Namespc,
8904                                       /* Ancestor */ Parent);
8905       UD->setImplicit();
8906       Parent->addDecl(UD);
8907     }
8908   }
8909 
8910   ActOnDocumentableDecl(Namespc);
8911 
8912   // Although we could have an invalid decl (i.e. the namespace name is a
8913   // redefinition), push it as current DeclContext and try to continue parsing.
8914   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8915   // for the namespace has the declarations that showed up in that particular
8916   // namespace definition.
8917   PushDeclContext(NamespcScope, Namespc);
8918   return Namespc;
8919 }
8920 
8921 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8922 /// is a namespace alias, returns the namespace it points to.
8923 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8924   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8925     return AD->getNamespace();
8926   return dyn_cast_or_null<NamespaceDecl>(D);
8927 }
8928 
8929 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8930 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8931 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8932   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8933   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8934   Namespc->setRBraceLoc(RBrace);
8935   PopDeclContext();
8936   if (Namespc->hasAttr<VisibilityAttr>())
8937     PopPragmaVisibility(true, RBrace);
8938 }
8939 
8940 CXXRecordDecl *Sema::getStdBadAlloc() const {
8941   return cast_or_null<CXXRecordDecl>(
8942                                   StdBadAlloc.get(Context.getExternalSource()));
8943 }
8944 
8945 EnumDecl *Sema::getStdAlignValT() const {
8946   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8947 }
8948 
8949 NamespaceDecl *Sema::getStdNamespace() const {
8950   return cast_or_null<NamespaceDecl>(
8951                                  StdNamespace.get(Context.getExternalSource()));
8952 }
8953 
8954 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8955   if (!StdExperimentalNamespaceCache) {
8956     if (auto Std = getStdNamespace()) {
8957       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8958                           SourceLocation(), LookupNamespaceName);
8959       if (!LookupQualifiedName(Result, Std) ||
8960           !(StdExperimentalNamespaceCache =
8961                 Result.getAsSingle<NamespaceDecl>()))
8962         Result.suppressDiagnostics();
8963     }
8964   }
8965   return StdExperimentalNamespaceCache;
8966 }
8967 
8968 namespace {
8969 
8970 enum UnsupportedSTLSelect {
8971   USS_InvalidMember,
8972   USS_MissingMember,
8973   USS_NonTrivial,
8974   USS_Other
8975 };
8976 
8977 struct InvalidSTLDiagnoser {
8978   Sema &S;
8979   SourceLocation Loc;
8980   QualType TyForDiags;
8981 
8982   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8983                       const VarDecl *VD = nullptr) {
8984     {
8985       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8986                << TyForDiags << ((int)Sel);
8987       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8988         assert(!Name.empty());
8989         D << Name;
8990       }
8991     }
8992     if (Sel == USS_InvalidMember) {
8993       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8994           << VD << VD->getSourceRange();
8995     }
8996     return QualType();
8997   }
8998 };
8999 } // namespace
9000 
9001 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9002                                            SourceLocation Loc) {
9003   assert(getLangOpts().CPlusPlus &&
9004          "Looking for comparison category type outside of C++.");
9005 
9006   // Check if we've already successfully checked the comparison category type
9007   // before. If so, skip checking it again.
9008   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9009   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9010     return Info->getType();
9011 
9012   // If lookup failed
9013   if (!Info) {
9014     std::string NameForDiags = "std::";
9015     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9016     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9017         << NameForDiags;
9018     return QualType();
9019   }
9020 
9021   assert(Info->Kind == Kind);
9022   assert(Info->Record);
9023 
9024   // Update the Record decl in case we encountered a forward declaration on our
9025   // first pass. FIXME: This is a bit of a hack.
9026   if (Info->Record->hasDefinition())
9027     Info->Record = Info->Record->getDefinition();
9028 
9029   // Use an elaborated type for diagnostics which has a name containing the
9030   // prepended 'std' namespace but not any inline namespace names.
9031   QualType TyForDiags = [&]() {
9032     auto *NNS =
9033         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9034     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9035   }();
9036 
9037   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9038     return QualType();
9039 
9040   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9041 
9042   if (!Info->Record->isTriviallyCopyable())
9043     return UnsupportedSTLError(USS_NonTrivial);
9044 
9045   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9046     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9047     // Tolerate empty base classes.
9048     if (Base->isEmpty())
9049       continue;
9050     // Reject STL implementations which have at least one non-empty base.
9051     return UnsupportedSTLError();
9052   }
9053 
9054   // Check that the STL has implemented the types using a single integer field.
9055   // This expectation allows better codegen for builtin operators. We require:
9056   //   (1) The class has exactly one field.
9057   //   (2) The field is an integral or enumeration type.
9058   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9059   if (std::distance(FIt, FEnd) != 1 ||
9060       !FIt->getType()->isIntegralOrEnumerationType()) {
9061     return UnsupportedSTLError();
9062   }
9063 
9064   // Build each of the require values and store them in Info.
9065   for (ComparisonCategoryResult CCR :
9066        ComparisonCategories::getPossibleResultsForType(Kind)) {
9067     StringRef MemName = ComparisonCategories::getResultString(CCR);
9068     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9069 
9070     if (!ValInfo)
9071       return UnsupportedSTLError(USS_MissingMember, MemName);
9072 
9073     VarDecl *VD = ValInfo->VD;
9074     assert(VD && "should not be null!");
9075 
9076     // Attempt to diagnose reasons why the STL definition of this type
9077     // might be foobar, including it failing to be a constant expression.
9078     // TODO Handle more ways the lookup or result can be invalid.
9079     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9080         !VD->checkInitIsICE())
9081       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9082 
9083     // Attempt to evaluate the var decl as a constant expression and extract
9084     // the value of its first field as a ICE. If this fails, the STL
9085     // implementation is not supported.
9086     if (!ValInfo->hasValidIntValue())
9087       return UnsupportedSTLError();
9088 
9089     MarkVariableReferenced(Loc, VD);
9090   }
9091 
9092   // We've successfully built the required types and expressions. Update
9093   // the cache and return the newly cached value.
9094   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9095   return Info->getType();
9096 }
9097 
9098 /// Retrieve the special "std" namespace, which may require us to
9099 /// implicitly define the namespace.
9100 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9101   if (!StdNamespace) {
9102     // The "std" namespace has not yet been defined, so build one implicitly.
9103     StdNamespace = NamespaceDecl::Create(Context,
9104                                          Context.getTranslationUnitDecl(),
9105                                          /*Inline=*/false,
9106                                          SourceLocation(), SourceLocation(),
9107                                          &PP.getIdentifierTable().get("std"),
9108                                          /*PrevDecl=*/nullptr);
9109     getStdNamespace()->setImplicit(true);
9110   }
9111 
9112   return getStdNamespace();
9113 }
9114 
9115 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9116   assert(getLangOpts().CPlusPlus &&
9117          "Looking for std::initializer_list outside of C++.");
9118 
9119   // We're looking for implicit instantiations of
9120   // template <typename E> class std::initializer_list.
9121 
9122   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9123     return false;
9124 
9125   ClassTemplateDecl *Template = nullptr;
9126   const TemplateArgument *Arguments = nullptr;
9127 
9128   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9129 
9130     ClassTemplateSpecializationDecl *Specialization =
9131         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9132     if (!Specialization)
9133       return false;
9134 
9135     Template = Specialization->getSpecializedTemplate();
9136     Arguments = Specialization->getTemplateArgs().data();
9137   } else if (const TemplateSpecializationType *TST =
9138                  Ty->getAs<TemplateSpecializationType>()) {
9139     Template = dyn_cast_or_null<ClassTemplateDecl>(
9140         TST->getTemplateName().getAsTemplateDecl());
9141     Arguments = TST->getArgs();
9142   }
9143   if (!Template)
9144     return false;
9145 
9146   if (!StdInitializerList) {
9147     // Haven't recognized std::initializer_list yet, maybe this is it.
9148     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9149     if (TemplateClass->getIdentifier() !=
9150             &PP.getIdentifierTable().get("initializer_list") ||
9151         !getStdNamespace()->InEnclosingNamespaceSetOf(
9152             TemplateClass->getDeclContext()))
9153       return false;
9154     // This is a template called std::initializer_list, but is it the right
9155     // template?
9156     TemplateParameterList *Params = Template->getTemplateParameters();
9157     if (Params->getMinRequiredArguments() != 1)
9158       return false;
9159     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9160       return false;
9161 
9162     // It's the right template.
9163     StdInitializerList = Template;
9164   }
9165 
9166   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9167     return false;
9168 
9169   // This is an instance of std::initializer_list. Find the argument type.
9170   if (Element)
9171     *Element = Arguments[0].getAsType();
9172   return true;
9173 }
9174 
9175 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9176   NamespaceDecl *Std = S.getStdNamespace();
9177   if (!Std) {
9178     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9179     return nullptr;
9180   }
9181 
9182   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9183                       Loc, Sema::LookupOrdinaryName);
9184   if (!S.LookupQualifiedName(Result, Std)) {
9185     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9186     return nullptr;
9187   }
9188   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9189   if (!Template) {
9190     Result.suppressDiagnostics();
9191     // We found something weird. Complain about the first thing we found.
9192     NamedDecl *Found = *Result.begin();
9193     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9194     return nullptr;
9195   }
9196 
9197   // We found some template called std::initializer_list. Now verify that it's
9198   // correct.
9199   TemplateParameterList *Params = Template->getTemplateParameters();
9200   if (Params->getMinRequiredArguments() != 1 ||
9201       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9202     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9203     return nullptr;
9204   }
9205 
9206   return Template;
9207 }
9208 
9209 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9210   if (!StdInitializerList) {
9211     StdInitializerList = LookupStdInitializerList(*this, Loc);
9212     if (!StdInitializerList)
9213       return QualType();
9214   }
9215 
9216   TemplateArgumentListInfo Args(Loc, Loc);
9217   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9218                                        Context.getTrivialTypeSourceInfo(Element,
9219                                                                         Loc)));
9220   return Context.getCanonicalType(
9221       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9222 }
9223 
9224 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9225   // C++ [dcl.init.list]p2:
9226   //   A constructor is an initializer-list constructor if its first parameter
9227   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9228   //   std::initializer_list<E> for some type E, and either there are no other
9229   //   parameters or else all other parameters have default arguments.
9230   if (Ctor->getNumParams() < 1 ||
9231       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9232     return false;
9233 
9234   QualType ArgType = Ctor->getParamDecl(0)->getType();
9235   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9236     ArgType = RT->getPointeeType().getUnqualifiedType();
9237 
9238   return isStdInitializerList(ArgType, nullptr);
9239 }
9240 
9241 /// Determine whether a using statement is in a context where it will be
9242 /// apply in all contexts.
9243 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9244   switch (CurContext->getDeclKind()) {
9245     case Decl::TranslationUnit:
9246       return true;
9247     case Decl::LinkageSpec:
9248       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9249     default:
9250       return false;
9251   }
9252 }
9253 
9254 namespace {
9255 
9256 // Callback to only accept typo corrections that are namespaces.
9257 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9258 public:
9259   bool ValidateCandidate(const TypoCorrection &candidate) override {
9260     if (NamedDecl *ND = candidate.getCorrectionDecl())
9261       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9262     return false;
9263   }
9264 };
9265 
9266 }
9267 
9268 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9269                                        CXXScopeSpec &SS,
9270                                        SourceLocation IdentLoc,
9271                                        IdentifierInfo *Ident) {
9272   R.clear();
9273   if (TypoCorrection Corrected =
9274           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9275                         llvm::make_unique<NamespaceValidatorCCC>(),
9276                         Sema::CTK_ErrorRecovery)) {
9277     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9278       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9279       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9280                               Ident->getName().equals(CorrectedStr);
9281       S.diagnoseTypo(Corrected,
9282                      S.PDiag(diag::err_using_directive_member_suggest)
9283                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9284                      S.PDiag(diag::note_namespace_defined_here));
9285     } else {
9286       S.diagnoseTypo(Corrected,
9287                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9288                      S.PDiag(diag::note_namespace_defined_here));
9289     }
9290     R.addDecl(Corrected.getFoundDecl());
9291     return true;
9292   }
9293   return false;
9294 }
9295 
9296 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9297                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9298                                 SourceLocation IdentLoc,
9299                                 IdentifierInfo *NamespcName,
9300                                 const ParsedAttributesView &AttrList) {
9301   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9302   assert(NamespcName && "Invalid NamespcName.");
9303   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9304 
9305   // This can only happen along a recovery path.
9306   while (S->isTemplateParamScope())
9307     S = S->getParent();
9308   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9309 
9310   UsingDirectiveDecl *UDir = nullptr;
9311   NestedNameSpecifier *Qualifier = nullptr;
9312   if (SS.isSet())
9313     Qualifier = SS.getScopeRep();
9314 
9315   // Lookup namespace name.
9316   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9317   LookupParsedName(R, S, &SS);
9318   if (R.isAmbiguous())
9319     return nullptr;
9320 
9321   if (R.empty()) {
9322     R.clear();
9323     // Allow "using namespace std;" or "using namespace ::std;" even if
9324     // "std" hasn't been defined yet, for GCC compatibility.
9325     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9326         NamespcName->isStr("std")) {
9327       Diag(IdentLoc, diag::ext_using_undefined_std);
9328       R.addDecl(getOrCreateStdNamespace());
9329       R.resolveKind();
9330     }
9331     // Otherwise, attempt typo correction.
9332     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9333   }
9334 
9335   if (!R.empty()) {
9336     NamedDecl *Named = R.getRepresentativeDecl();
9337     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9338     assert(NS && "expected namespace decl");
9339 
9340     // The use of a nested name specifier may trigger deprecation warnings.
9341     DiagnoseUseOfDecl(Named, IdentLoc);
9342 
9343     // C++ [namespace.udir]p1:
9344     //   A using-directive specifies that the names in the nominated
9345     //   namespace can be used in the scope in which the
9346     //   using-directive appears after the using-directive. During
9347     //   unqualified name lookup (3.4.1), the names appear as if they
9348     //   were declared in the nearest enclosing namespace which
9349     //   contains both the using-directive and the nominated
9350     //   namespace. [Note: in this context, "contains" means "contains
9351     //   directly or indirectly". ]
9352 
9353     // Find enclosing context containing both using-directive and
9354     // nominated namespace.
9355     DeclContext *CommonAncestor = NS;
9356     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9357       CommonAncestor = CommonAncestor->getParent();
9358 
9359     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9360                                       SS.getWithLocInContext(Context),
9361                                       IdentLoc, Named, CommonAncestor);
9362 
9363     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9364         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9365       Diag(IdentLoc, diag::warn_using_directive_in_header);
9366     }
9367 
9368     PushUsingDirective(S, UDir);
9369   } else {
9370     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9371   }
9372 
9373   if (UDir)
9374     ProcessDeclAttributeList(S, UDir, AttrList);
9375 
9376   return UDir;
9377 }
9378 
9379 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9380   // If the scope has an associated entity and the using directive is at
9381   // namespace or translation unit scope, add the UsingDirectiveDecl into
9382   // its lookup structure so qualified name lookup can find it.
9383   DeclContext *Ctx = S->getEntity();
9384   if (Ctx && !Ctx->isFunctionOrMethod())
9385     Ctx->addDecl(UDir);
9386   else
9387     // Otherwise, it is at block scope. The using-directives will affect lookup
9388     // only to the end of the scope.
9389     S->PushUsingDirective(UDir);
9390 }
9391 
9392 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9393                                   SourceLocation UsingLoc,
9394                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9395                                   UnqualifiedId &Name,
9396                                   SourceLocation EllipsisLoc,
9397                                   const ParsedAttributesView &AttrList) {
9398   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9399 
9400   if (SS.isEmpty()) {
9401     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9402     return nullptr;
9403   }
9404 
9405   switch (Name.getKind()) {
9406   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9407   case UnqualifiedIdKind::IK_Identifier:
9408   case UnqualifiedIdKind::IK_OperatorFunctionId:
9409   case UnqualifiedIdKind::IK_LiteralOperatorId:
9410   case UnqualifiedIdKind::IK_ConversionFunctionId:
9411     break;
9412 
9413   case UnqualifiedIdKind::IK_ConstructorName:
9414   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9415     // C++11 inheriting constructors.
9416     Diag(Name.getLocStart(),
9417          getLangOpts().CPlusPlus11 ?
9418            diag::warn_cxx98_compat_using_decl_constructor :
9419            diag::err_using_decl_constructor)
9420       << SS.getRange();
9421 
9422     if (getLangOpts().CPlusPlus11) break;
9423 
9424     return nullptr;
9425 
9426   case UnqualifiedIdKind::IK_DestructorName:
9427     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9428       << SS.getRange();
9429     return nullptr;
9430 
9431   case UnqualifiedIdKind::IK_TemplateId:
9432     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9433       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9434     return nullptr;
9435 
9436   case UnqualifiedIdKind::IK_DeductionGuideName:
9437     llvm_unreachable("cannot parse qualified deduction guide name");
9438   }
9439 
9440   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9441   DeclarationName TargetName = TargetNameInfo.getName();
9442   if (!TargetName)
9443     return nullptr;
9444 
9445   // Warn about access declarations.
9446   if (UsingLoc.isInvalid()) {
9447     Diag(Name.getLocStart(),
9448          getLangOpts().CPlusPlus11 ? diag::err_access_decl
9449                                    : diag::warn_access_decl_deprecated)
9450       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9451   }
9452 
9453   if (EllipsisLoc.isInvalid()) {
9454     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9455         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9456       return nullptr;
9457   } else {
9458     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9459         !TargetNameInfo.containsUnexpandedParameterPack()) {
9460       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9461         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9462       EllipsisLoc = SourceLocation();
9463     }
9464   }
9465 
9466   NamedDecl *UD =
9467       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9468                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9469                             /*IsInstantiation*/false);
9470   if (UD)
9471     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9472 
9473   return UD;
9474 }
9475 
9476 /// Determine whether a using declaration considers the given
9477 /// declarations as "equivalent", e.g., if they are redeclarations of
9478 /// the same entity or are both typedefs of the same type.
9479 static bool
9480 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9481   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9482     return true;
9483 
9484   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9485     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9486       return Context.hasSameType(TD1->getUnderlyingType(),
9487                                  TD2->getUnderlyingType());
9488 
9489   return false;
9490 }
9491 
9492 
9493 /// Determines whether to create a using shadow decl for a particular
9494 /// decl, given the set of decls existing prior to this using lookup.
9495 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9496                                 const LookupResult &Previous,
9497                                 UsingShadowDecl *&PrevShadow) {
9498   // Diagnose finding a decl which is not from a base class of the
9499   // current class.  We do this now because there are cases where this
9500   // function will silently decide not to build a shadow decl, which
9501   // will pre-empt further diagnostics.
9502   //
9503   // We don't need to do this in C++11 because we do the check once on
9504   // the qualifier.
9505   //
9506   // FIXME: diagnose the following if we care enough:
9507   //   struct A { int foo; };
9508   //   struct B : A { using A::foo; };
9509   //   template <class T> struct C : A {};
9510   //   template <class T> struct D : C<T> { using B::foo; } // <---
9511   // This is invalid (during instantiation) in C++03 because B::foo
9512   // resolves to the using decl in B, which is not a base class of D<T>.
9513   // We can't diagnose it immediately because C<T> is an unknown
9514   // specialization.  The UsingShadowDecl in D<T> then points directly
9515   // to A::foo, which will look well-formed when we instantiate.
9516   // The right solution is to not collapse the shadow-decl chain.
9517   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9518     DeclContext *OrigDC = Orig->getDeclContext();
9519 
9520     // Handle enums and anonymous structs.
9521     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9522     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9523     while (OrigRec->isAnonymousStructOrUnion())
9524       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9525 
9526     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9527       if (OrigDC == CurContext) {
9528         Diag(Using->getLocation(),
9529              diag::err_using_decl_nested_name_specifier_is_current_class)
9530           << Using->getQualifierLoc().getSourceRange();
9531         Diag(Orig->getLocation(), diag::note_using_decl_target);
9532         Using->setInvalidDecl();
9533         return true;
9534       }
9535 
9536       Diag(Using->getQualifierLoc().getBeginLoc(),
9537            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9538         << Using->getQualifier()
9539         << cast<CXXRecordDecl>(CurContext)
9540         << Using->getQualifierLoc().getSourceRange();
9541       Diag(Orig->getLocation(), diag::note_using_decl_target);
9542       Using->setInvalidDecl();
9543       return true;
9544     }
9545   }
9546 
9547   if (Previous.empty()) return false;
9548 
9549   NamedDecl *Target = Orig;
9550   if (isa<UsingShadowDecl>(Target))
9551     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9552 
9553   // If the target happens to be one of the previous declarations, we
9554   // don't have a conflict.
9555   //
9556   // FIXME: but we might be increasing its access, in which case we
9557   // should redeclare it.
9558   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9559   bool FoundEquivalentDecl = false;
9560   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9561          I != E; ++I) {
9562     NamedDecl *D = (*I)->getUnderlyingDecl();
9563     // We can have UsingDecls in our Previous results because we use the same
9564     // LookupResult for checking whether the UsingDecl itself is a valid
9565     // redeclaration.
9566     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9567       continue;
9568 
9569     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9570       // C++ [class.mem]p19:
9571       //   If T is the name of a class, then [every named member other than
9572       //   a non-static data member] shall have a name different from T
9573       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9574           !isa<IndirectFieldDecl>(Target) &&
9575           !isa<UnresolvedUsingValueDecl>(Target) &&
9576           DiagnoseClassNameShadow(
9577               CurContext,
9578               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9579         return true;
9580     }
9581 
9582     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9583       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9584         PrevShadow = Shadow;
9585       FoundEquivalentDecl = true;
9586     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9587       // We don't conflict with an existing using shadow decl of an equivalent
9588       // declaration, but we're not a redeclaration of it.
9589       FoundEquivalentDecl = true;
9590     }
9591 
9592     if (isVisible(D))
9593       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9594   }
9595 
9596   if (FoundEquivalentDecl)
9597     return false;
9598 
9599   if (FunctionDecl *FD = Target->getAsFunction()) {
9600     NamedDecl *OldDecl = nullptr;
9601     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9602                           /*IsForUsingDecl*/ true)) {
9603     case Ovl_Overload:
9604       return false;
9605 
9606     case Ovl_NonFunction:
9607       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9608       break;
9609 
9610     // We found a decl with the exact signature.
9611     case Ovl_Match:
9612       // If we're in a record, we want to hide the target, so we
9613       // return true (without a diagnostic) to tell the caller not to
9614       // build a shadow decl.
9615       if (CurContext->isRecord())
9616         return true;
9617 
9618       // If we're not in a record, this is an error.
9619       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9620       break;
9621     }
9622 
9623     Diag(Target->getLocation(), diag::note_using_decl_target);
9624     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9625     Using->setInvalidDecl();
9626     return true;
9627   }
9628 
9629   // Target is not a function.
9630 
9631   if (isa<TagDecl>(Target)) {
9632     // No conflict between a tag and a non-tag.
9633     if (!Tag) return false;
9634 
9635     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9636     Diag(Target->getLocation(), diag::note_using_decl_target);
9637     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9638     Using->setInvalidDecl();
9639     return true;
9640   }
9641 
9642   // No conflict between a tag and a non-tag.
9643   if (!NonTag) return false;
9644 
9645   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9646   Diag(Target->getLocation(), diag::note_using_decl_target);
9647   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9648   Using->setInvalidDecl();
9649   return true;
9650 }
9651 
9652 /// Determine whether a direct base class is a virtual base class.
9653 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9654   if (!Derived->getNumVBases())
9655     return false;
9656   for (auto &B : Derived->bases())
9657     if (B.getType()->getAsCXXRecordDecl() == Base)
9658       return B.isVirtual();
9659   llvm_unreachable("not a direct base class");
9660 }
9661 
9662 /// Builds a shadow declaration corresponding to a 'using' declaration.
9663 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9664                                             UsingDecl *UD,
9665                                             NamedDecl *Orig,
9666                                             UsingShadowDecl *PrevDecl) {
9667   // If we resolved to another shadow declaration, just coalesce them.
9668   NamedDecl *Target = Orig;
9669   if (isa<UsingShadowDecl>(Target)) {
9670     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9671     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9672   }
9673 
9674   NamedDecl *NonTemplateTarget = Target;
9675   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9676     NonTemplateTarget = TargetTD->getTemplatedDecl();
9677 
9678   UsingShadowDecl *Shadow;
9679   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9680     bool IsVirtualBase =
9681         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9682                             UD->getQualifier()->getAsRecordDecl());
9683     Shadow = ConstructorUsingShadowDecl::Create(
9684         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9685   } else {
9686     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9687                                      Target);
9688   }
9689   UD->addShadowDecl(Shadow);
9690 
9691   Shadow->setAccess(UD->getAccess());
9692   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9693     Shadow->setInvalidDecl();
9694 
9695   Shadow->setPreviousDecl(PrevDecl);
9696 
9697   if (S)
9698     PushOnScopeChains(Shadow, S);
9699   else
9700     CurContext->addDecl(Shadow);
9701 
9702 
9703   return Shadow;
9704 }
9705 
9706 /// Hides a using shadow declaration.  This is required by the current
9707 /// using-decl implementation when a resolvable using declaration in a
9708 /// class is followed by a declaration which would hide or override
9709 /// one or more of the using decl's targets; for example:
9710 ///
9711 ///   struct Base { void foo(int); };
9712 ///   struct Derived : Base {
9713 ///     using Base::foo;
9714 ///     void foo(int);
9715 ///   };
9716 ///
9717 /// The governing language is C++03 [namespace.udecl]p12:
9718 ///
9719 ///   When a using-declaration brings names from a base class into a
9720 ///   derived class scope, member functions in the derived class
9721 ///   override and/or hide member functions with the same name and
9722 ///   parameter types in a base class (rather than conflicting).
9723 ///
9724 /// There are two ways to implement this:
9725 ///   (1) optimistically create shadow decls when they're not hidden
9726 ///       by existing declarations, or
9727 ///   (2) don't create any shadow decls (or at least don't make them
9728 ///       visible) until we've fully parsed/instantiated the class.
9729 /// The problem with (1) is that we might have to retroactively remove
9730 /// a shadow decl, which requires several O(n) operations because the
9731 /// decl structures are (very reasonably) not designed for removal.
9732 /// (2) avoids this but is very fiddly and phase-dependent.
9733 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9734   if (Shadow->getDeclName().getNameKind() ==
9735         DeclarationName::CXXConversionFunctionName)
9736     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9737 
9738   // Remove it from the DeclContext...
9739   Shadow->getDeclContext()->removeDecl(Shadow);
9740 
9741   // ...and the scope, if applicable...
9742   if (S) {
9743     S->RemoveDecl(Shadow);
9744     IdResolver.RemoveDecl(Shadow);
9745   }
9746 
9747   // ...and the using decl.
9748   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9749 
9750   // TODO: complain somehow if Shadow was used.  It shouldn't
9751   // be possible for this to happen, because...?
9752 }
9753 
9754 /// Find the base specifier for a base class with the given type.
9755 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9756                                                 QualType DesiredBase,
9757                                                 bool &AnyDependentBases) {
9758   // Check whether the named type is a direct base class.
9759   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9760   for (auto &Base : Derived->bases()) {
9761     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9762     if (CanonicalDesiredBase == BaseType)
9763       return &Base;
9764     if (BaseType->isDependentType())
9765       AnyDependentBases = true;
9766   }
9767   return nullptr;
9768 }
9769 
9770 namespace {
9771 class UsingValidatorCCC : public CorrectionCandidateCallback {
9772 public:
9773   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9774                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9775       : HasTypenameKeyword(HasTypenameKeyword),
9776         IsInstantiation(IsInstantiation), OldNNS(NNS),
9777         RequireMemberOf(RequireMemberOf) {}
9778 
9779   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9780     NamedDecl *ND = Candidate.getCorrectionDecl();
9781 
9782     // Keywords are not valid here.
9783     if (!ND || isa<NamespaceDecl>(ND))
9784       return false;
9785 
9786     // Completely unqualified names are invalid for a 'using' declaration.
9787     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9788       return false;
9789 
9790     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9791     // reject.
9792 
9793     if (RequireMemberOf) {
9794       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9795       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9796         // No-one ever wants a using-declaration to name an injected-class-name
9797         // of a base class, unless they're declaring an inheriting constructor.
9798         ASTContext &Ctx = ND->getASTContext();
9799         if (!Ctx.getLangOpts().CPlusPlus11)
9800           return false;
9801         QualType FoundType = Ctx.getRecordType(FoundRecord);
9802 
9803         // Check that the injected-class-name is named as a member of its own
9804         // type; we don't want to suggest 'using Derived::Base;', since that
9805         // means something else.
9806         NestedNameSpecifier *Specifier =
9807             Candidate.WillReplaceSpecifier()
9808                 ? Candidate.getCorrectionSpecifier()
9809                 : OldNNS;
9810         if (!Specifier->getAsType() ||
9811             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9812           return false;
9813 
9814         // Check that this inheriting constructor declaration actually names a
9815         // direct base class of the current class.
9816         bool AnyDependentBases = false;
9817         if (!findDirectBaseWithType(RequireMemberOf,
9818                                     Ctx.getRecordType(FoundRecord),
9819                                     AnyDependentBases) &&
9820             !AnyDependentBases)
9821           return false;
9822       } else {
9823         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9824         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9825           return false;
9826 
9827         // FIXME: Check that the base class member is accessible?
9828       }
9829     } else {
9830       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9831       if (FoundRecord && FoundRecord->isInjectedClassName())
9832         return false;
9833     }
9834 
9835     if (isa<TypeDecl>(ND))
9836       return HasTypenameKeyword || !IsInstantiation;
9837 
9838     return !HasTypenameKeyword;
9839   }
9840 
9841 private:
9842   bool HasTypenameKeyword;
9843   bool IsInstantiation;
9844   NestedNameSpecifier *OldNNS;
9845   CXXRecordDecl *RequireMemberOf;
9846 };
9847 } // end anonymous namespace
9848 
9849 /// Builds a using declaration.
9850 ///
9851 /// \param IsInstantiation - Whether this call arises from an
9852 ///   instantiation of an unresolved using declaration.  We treat
9853 ///   the lookup differently for these declarations.
9854 NamedDecl *Sema::BuildUsingDeclaration(
9855     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9856     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9857     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9858     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9859   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9860   SourceLocation IdentLoc = NameInfo.getLoc();
9861   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9862 
9863   // FIXME: We ignore attributes for now.
9864 
9865   // For an inheriting constructor declaration, the name of the using
9866   // declaration is the name of a constructor in this class, not in the
9867   // base class.
9868   DeclarationNameInfo UsingName = NameInfo;
9869   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9870     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9871       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9872           Context.getCanonicalType(Context.getRecordType(RD))));
9873 
9874   // Do the redeclaration lookup in the current scope.
9875   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9876                         ForVisibleRedeclaration);
9877   Previous.setHideTags(false);
9878   if (S) {
9879     LookupName(Previous, S);
9880 
9881     // It is really dumb that we have to do this.
9882     LookupResult::Filter F = Previous.makeFilter();
9883     while (F.hasNext()) {
9884       NamedDecl *D = F.next();
9885       if (!isDeclInScope(D, CurContext, S))
9886         F.erase();
9887       // If we found a local extern declaration that's not ordinarily visible,
9888       // and this declaration is being added to a non-block scope, ignore it.
9889       // We're only checking for scope conflicts here, not also for violations
9890       // of the linkage rules.
9891       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9892                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9893         F.erase();
9894     }
9895     F.done();
9896   } else {
9897     assert(IsInstantiation && "no scope in non-instantiation");
9898     if (CurContext->isRecord())
9899       LookupQualifiedName(Previous, CurContext);
9900     else {
9901       // No redeclaration check is needed here; in non-member contexts we
9902       // diagnosed all possible conflicts with other using-declarations when
9903       // building the template:
9904       //
9905       // For a dependent non-type using declaration, the only valid case is
9906       // if we instantiate to a single enumerator. We check for conflicts
9907       // between shadow declarations we introduce, and we check in the template
9908       // definition for conflicts between a non-type using declaration and any
9909       // other declaration, which together covers all cases.
9910       //
9911       // A dependent typename using declaration will never successfully
9912       // instantiate, since it will always name a class member, so we reject
9913       // that in the template definition.
9914     }
9915   }
9916 
9917   // Check for invalid redeclarations.
9918   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9919                                   SS, IdentLoc, Previous))
9920     return nullptr;
9921 
9922   // Check for bad qualifiers.
9923   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9924                               IdentLoc))
9925     return nullptr;
9926 
9927   DeclContext *LookupContext = computeDeclContext(SS);
9928   NamedDecl *D;
9929   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9930   if (!LookupContext || EllipsisLoc.isValid()) {
9931     if (HasTypenameKeyword) {
9932       // FIXME: not all declaration name kinds are legal here
9933       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9934                                               UsingLoc, TypenameLoc,
9935                                               QualifierLoc,
9936                                               IdentLoc, NameInfo.getName(),
9937                                               EllipsisLoc);
9938     } else {
9939       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9940                                            QualifierLoc, NameInfo, EllipsisLoc);
9941     }
9942     D->setAccess(AS);
9943     CurContext->addDecl(D);
9944     return D;
9945   }
9946 
9947   auto Build = [&](bool Invalid) {
9948     UsingDecl *UD =
9949         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9950                           UsingName, HasTypenameKeyword);
9951     UD->setAccess(AS);
9952     CurContext->addDecl(UD);
9953     UD->setInvalidDecl(Invalid);
9954     return UD;
9955   };
9956   auto BuildInvalid = [&]{ return Build(true); };
9957   auto BuildValid = [&]{ return Build(false); };
9958 
9959   if (RequireCompleteDeclContext(SS, LookupContext))
9960     return BuildInvalid();
9961 
9962   // Look up the target name.
9963   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9964 
9965   // Unlike most lookups, we don't always want to hide tag
9966   // declarations: tag names are visible through the using declaration
9967   // even if hidden by ordinary names, *except* in a dependent context
9968   // where it's important for the sanity of two-phase lookup.
9969   if (!IsInstantiation)
9970     R.setHideTags(false);
9971 
9972   // For the purposes of this lookup, we have a base object type
9973   // equal to that of the current context.
9974   if (CurContext->isRecord()) {
9975     R.setBaseObjectType(
9976                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9977   }
9978 
9979   LookupQualifiedName(R, LookupContext);
9980 
9981   // Try to correct typos if possible. If constructor name lookup finds no
9982   // results, that means the named class has no explicit constructors, and we
9983   // suppressed declaring implicit ones (probably because it's dependent or
9984   // invalid).
9985   if (R.empty() &&
9986       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9987     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9988     // it will believe that glibc provides a ::gets in cases where it does not,
9989     // and will try to pull it into namespace std with a using-declaration.
9990     // Just ignore the using-declaration in that case.
9991     auto *II = NameInfo.getName().getAsIdentifierInfo();
9992     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9993         CurContext->isStdNamespace() &&
9994         isa<TranslationUnitDecl>(LookupContext) &&
9995         getSourceManager().isInSystemHeader(UsingLoc))
9996       return nullptr;
9997     if (TypoCorrection Corrected = CorrectTypo(
9998             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9999             llvm::make_unique<UsingValidatorCCC>(
10000                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10001                 dyn_cast<CXXRecordDecl>(CurContext)),
10002             CTK_ErrorRecovery)) {
10003       // We reject candidates where DroppedSpecifier == true, hence the
10004       // literal '0' below.
10005       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10006                                 << NameInfo.getName() << LookupContext << 0
10007                                 << SS.getRange());
10008 
10009       // If we picked a correction with no attached Decl we can't do anything
10010       // useful with it, bail out.
10011       NamedDecl *ND = Corrected.getCorrectionDecl();
10012       if (!ND)
10013         return BuildInvalid();
10014 
10015       // If we corrected to an inheriting constructor, handle it as one.
10016       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10017       if (RD && RD->isInjectedClassName()) {
10018         // The parent of the injected class name is the class itself.
10019         RD = cast<CXXRecordDecl>(RD->getParent());
10020 
10021         // Fix up the information we'll use to build the using declaration.
10022         if (Corrected.WillReplaceSpecifier()) {
10023           NestedNameSpecifierLocBuilder Builder;
10024           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10025                               QualifierLoc.getSourceRange());
10026           QualifierLoc = Builder.getWithLocInContext(Context);
10027         }
10028 
10029         // In this case, the name we introduce is the name of a derived class
10030         // constructor.
10031         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10032         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10033             Context.getCanonicalType(Context.getRecordType(CurClass))));
10034         UsingName.setNamedTypeInfo(nullptr);
10035         for (auto *Ctor : LookupConstructors(RD))
10036           R.addDecl(Ctor);
10037         R.resolveKind();
10038       } else {
10039         // FIXME: Pick up all the declarations if we found an overloaded
10040         // function.
10041         UsingName.setName(ND->getDeclName());
10042         R.addDecl(ND);
10043       }
10044     } else {
10045       Diag(IdentLoc, diag::err_no_member)
10046         << NameInfo.getName() << LookupContext << SS.getRange();
10047       return BuildInvalid();
10048     }
10049   }
10050 
10051   if (R.isAmbiguous())
10052     return BuildInvalid();
10053 
10054   if (HasTypenameKeyword) {
10055     // If we asked for a typename and got a non-type decl, error out.
10056     if (!R.getAsSingle<TypeDecl>()) {
10057       Diag(IdentLoc, diag::err_using_typename_non_type);
10058       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10059         Diag((*I)->getUnderlyingDecl()->getLocation(),
10060              diag::note_using_decl_target);
10061       return BuildInvalid();
10062     }
10063   } else {
10064     // If we asked for a non-typename and we got a type, error out,
10065     // but only if this is an instantiation of an unresolved using
10066     // decl.  Otherwise just silently find the type name.
10067     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10068       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10069       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10070       return BuildInvalid();
10071     }
10072   }
10073 
10074   // C++14 [namespace.udecl]p6:
10075   // A using-declaration shall not name a namespace.
10076   if (R.getAsSingle<NamespaceDecl>()) {
10077     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10078       << SS.getRange();
10079     return BuildInvalid();
10080   }
10081 
10082   // C++14 [namespace.udecl]p7:
10083   // A using-declaration shall not name a scoped enumerator.
10084   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10085     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10086       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10087         << SS.getRange();
10088       return BuildInvalid();
10089     }
10090   }
10091 
10092   UsingDecl *UD = BuildValid();
10093 
10094   // Some additional rules apply to inheriting constructors.
10095   if (UsingName.getName().getNameKind() ==
10096         DeclarationName::CXXConstructorName) {
10097     // Suppress access diagnostics; the access check is instead performed at the
10098     // point of use for an inheriting constructor.
10099     R.suppressDiagnostics();
10100     if (CheckInheritingConstructorUsingDecl(UD))
10101       return UD;
10102   }
10103 
10104   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10105     UsingShadowDecl *PrevDecl = nullptr;
10106     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10107       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10108   }
10109 
10110   return UD;
10111 }
10112 
10113 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10114                                     ArrayRef<NamedDecl *> Expansions) {
10115   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10116          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10117          isa<UsingPackDecl>(InstantiatedFrom));
10118 
10119   auto *UPD =
10120       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10121   UPD->setAccess(InstantiatedFrom->getAccess());
10122   CurContext->addDecl(UPD);
10123   return UPD;
10124 }
10125 
10126 /// Additional checks for a using declaration referring to a constructor name.
10127 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10128   assert(!UD->hasTypename() && "expecting a constructor name");
10129 
10130   const Type *SourceType = UD->getQualifier()->getAsType();
10131   assert(SourceType &&
10132          "Using decl naming constructor doesn't have type in scope spec.");
10133   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10134 
10135   // Check whether the named type is a direct base class.
10136   bool AnyDependentBases = false;
10137   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10138                                       AnyDependentBases);
10139   if (!Base && !AnyDependentBases) {
10140     Diag(UD->getUsingLoc(),
10141          diag::err_using_decl_constructor_not_in_direct_base)
10142       << UD->getNameInfo().getSourceRange()
10143       << QualType(SourceType, 0) << TargetClass;
10144     UD->setInvalidDecl();
10145     return true;
10146   }
10147 
10148   if (Base)
10149     Base->setInheritConstructors();
10150 
10151   return false;
10152 }
10153 
10154 /// Checks that the given using declaration is not an invalid
10155 /// redeclaration.  Note that this is checking only for the using decl
10156 /// itself, not for any ill-formedness among the UsingShadowDecls.
10157 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10158                                        bool HasTypenameKeyword,
10159                                        const CXXScopeSpec &SS,
10160                                        SourceLocation NameLoc,
10161                                        const LookupResult &Prev) {
10162   NestedNameSpecifier *Qual = SS.getScopeRep();
10163 
10164   // C++03 [namespace.udecl]p8:
10165   // C++0x [namespace.udecl]p10:
10166   //   A using-declaration is a declaration and can therefore be used
10167   //   repeatedly where (and only where) multiple declarations are
10168   //   allowed.
10169   //
10170   // That's in non-member contexts.
10171   if (!CurContext->getRedeclContext()->isRecord()) {
10172     // A dependent qualifier outside a class can only ever resolve to an
10173     // enumeration type. Therefore it conflicts with any other non-type
10174     // declaration in the same scope.
10175     // FIXME: How should we check for dependent type-type conflicts at block
10176     // scope?
10177     if (Qual->isDependent() && !HasTypenameKeyword) {
10178       for (auto *D : Prev) {
10179         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10180           bool OldCouldBeEnumerator =
10181               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10182           Diag(NameLoc,
10183                OldCouldBeEnumerator ? diag::err_redefinition
10184                                     : diag::err_redefinition_different_kind)
10185               << Prev.getLookupName();
10186           Diag(D->getLocation(), diag::note_previous_definition);
10187           return true;
10188         }
10189       }
10190     }
10191     return false;
10192   }
10193 
10194   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10195     NamedDecl *D = *I;
10196 
10197     bool DTypename;
10198     NestedNameSpecifier *DQual;
10199     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10200       DTypename = UD->hasTypename();
10201       DQual = UD->getQualifier();
10202     } else if (UnresolvedUsingValueDecl *UD
10203                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10204       DTypename = false;
10205       DQual = UD->getQualifier();
10206     } else if (UnresolvedUsingTypenameDecl *UD
10207                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10208       DTypename = true;
10209       DQual = UD->getQualifier();
10210     } else continue;
10211 
10212     // using decls differ if one says 'typename' and the other doesn't.
10213     // FIXME: non-dependent using decls?
10214     if (HasTypenameKeyword != DTypename) continue;
10215 
10216     // using decls differ if they name different scopes (but note that
10217     // template instantiation can cause this check to trigger when it
10218     // didn't before instantiation).
10219     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10220         Context.getCanonicalNestedNameSpecifier(DQual))
10221       continue;
10222 
10223     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10224     Diag(D->getLocation(), diag::note_using_decl) << 1;
10225     return true;
10226   }
10227 
10228   return false;
10229 }
10230 
10231 
10232 /// Checks that the given nested-name qualifier used in a using decl
10233 /// in the current context is appropriately related to the current
10234 /// scope.  If an error is found, diagnoses it and returns true.
10235 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10236                                    bool HasTypename,
10237                                    const CXXScopeSpec &SS,
10238                                    const DeclarationNameInfo &NameInfo,
10239                                    SourceLocation NameLoc) {
10240   DeclContext *NamedContext = computeDeclContext(SS);
10241 
10242   if (!CurContext->isRecord()) {
10243     // C++03 [namespace.udecl]p3:
10244     // C++0x [namespace.udecl]p8:
10245     //   A using-declaration for a class member shall be a member-declaration.
10246 
10247     // If we weren't able to compute a valid scope, it might validly be a
10248     // dependent class scope or a dependent enumeration unscoped scope. If
10249     // we have a 'typename' keyword, the scope must resolve to a class type.
10250     if ((HasTypename && !NamedContext) ||
10251         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10252       auto *RD = NamedContext
10253                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10254                      : nullptr;
10255       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10256         RD = nullptr;
10257 
10258       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10259         << SS.getRange();
10260 
10261       // If we have a complete, non-dependent source type, try to suggest a
10262       // way to get the same effect.
10263       if (!RD)
10264         return true;
10265 
10266       // Find what this using-declaration was referring to.
10267       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10268       R.setHideTags(false);
10269       R.suppressDiagnostics();
10270       LookupQualifiedName(R, RD);
10271 
10272       if (R.getAsSingle<TypeDecl>()) {
10273         if (getLangOpts().CPlusPlus11) {
10274           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10275           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10276             << 0 // alias declaration
10277             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10278                                           NameInfo.getName().getAsString() +
10279                                               " = ");
10280         } else {
10281           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10282           SourceLocation InsertLoc =
10283               getLocForEndOfToken(NameInfo.getLocEnd());
10284           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10285             << 1 // typedef declaration
10286             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10287             << FixItHint::CreateInsertion(
10288                    InsertLoc, " " + NameInfo.getName().getAsString());
10289         }
10290       } else if (R.getAsSingle<VarDecl>()) {
10291         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10292         // repeating the type of the static data member here.
10293         FixItHint FixIt;
10294         if (getLangOpts().CPlusPlus11) {
10295           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10296           FixIt = FixItHint::CreateReplacement(
10297               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10298         }
10299 
10300         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10301           << 2 // reference declaration
10302           << FixIt;
10303       } else if (R.getAsSingle<EnumConstantDecl>()) {
10304         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10305         // repeating the type of the enumeration here, and we can't do so if
10306         // the type is anonymous.
10307         FixItHint FixIt;
10308         if (getLangOpts().CPlusPlus11) {
10309           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10310           FixIt = FixItHint::CreateReplacement(
10311               UsingLoc,
10312               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10313         }
10314 
10315         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10316           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10317           << FixIt;
10318       }
10319       return true;
10320     }
10321 
10322     // Otherwise, this might be valid.
10323     return false;
10324   }
10325 
10326   // The current scope is a record.
10327 
10328   // If the named context is dependent, we can't decide much.
10329   if (!NamedContext) {
10330     // FIXME: in C++0x, we can diagnose if we can prove that the
10331     // nested-name-specifier does not refer to a base class, which is
10332     // still possible in some cases.
10333 
10334     // Otherwise we have to conservatively report that things might be
10335     // okay.
10336     return false;
10337   }
10338 
10339   if (!NamedContext->isRecord()) {
10340     // Ideally this would point at the last name in the specifier,
10341     // but we don't have that level of source info.
10342     Diag(SS.getRange().getBegin(),
10343          diag::err_using_decl_nested_name_specifier_is_not_class)
10344       << SS.getScopeRep() << SS.getRange();
10345     return true;
10346   }
10347 
10348   if (!NamedContext->isDependentContext() &&
10349       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10350     return true;
10351 
10352   if (getLangOpts().CPlusPlus11) {
10353     // C++11 [namespace.udecl]p3:
10354     //   In a using-declaration used as a member-declaration, the
10355     //   nested-name-specifier shall name a base class of the class
10356     //   being defined.
10357 
10358     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10359                                  cast<CXXRecordDecl>(NamedContext))) {
10360       if (CurContext == NamedContext) {
10361         Diag(NameLoc,
10362              diag::err_using_decl_nested_name_specifier_is_current_class)
10363           << SS.getRange();
10364         return true;
10365       }
10366 
10367       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10368         Diag(SS.getRange().getBegin(),
10369              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10370           << SS.getScopeRep()
10371           << cast<CXXRecordDecl>(CurContext)
10372           << SS.getRange();
10373       }
10374       return true;
10375     }
10376 
10377     return false;
10378   }
10379 
10380   // C++03 [namespace.udecl]p4:
10381   //   A using-declaration used as a member-declaration shall refer
10382   //   to a member of a base class of the class being defined [etc.].
10383 
10384   // Salient point: SS doesn't have to name a base class as long as
10385   // lookup only finds members from base classes.  Therefore we can
10386   // diagnose here only if we can prove that that can't happen,
10387   // i.e. if the class hierarchies provably don't intersect.
10388 
10389   // TODO: it would be nice if "definitely valid" results were cached
10390   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10391   // need to be repeated.
10392 
10393   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10394   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10395     Bases.insert(Base);
10396     return true;
10397   };
10398 
10399   // Collect all bases. Return false if we find a dependent base.
10400   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10401     return false;
10402 
10403   // Returns true if the base is dependent or is one of the accumulated base
10404   // classes.
10405   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10406     return !Bases.count(Base);
10407   };
10408 
10409   // Return false if the class has a dependent base or if it or one
10410   // of its bases is present in the base set of the current context.
10411   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10412       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10413     return false;
10414 
10415   Diag(SS.getRange().getBegin(),
10416        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10417     << SS.getScopeRep()
10418     << cast<CXXRecordDecl>(CurContext)
10419     << SS.getRange();
10420 
10421   return true;
10422 }
10423 
10424 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10425                                   MultiTemplateParamsArg TemplateParamLists,
10426                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10427                                   const ParsedAttributesView &AttrList,
10428                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10429   // Skip up to the relevant declaration scope.
10430   while (S->isTemplateParamScope())
10431     S = S->getParent();
10432   assert((S->getFlags() & Scope::DeclScope) &&
10433          "got alias-declaration outside of declaration scope");
10434 
10435   if (Type.isInvalid())
10436     return nullptr;
10437 
10438   bool Invalid = false;
10439   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10440   TypeSourceInfo *TInfo = nullptr;
10441   GetTypeFromParser(Type.get(), &TInfo);
10442 
10443   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10444     return nullptr;
10445 
10446   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10447                                       UPPC_DeclarationType)) {
10448     Invalid = true;
10449     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10450                                              TInfo->getTypeLoc().getBeginLoc());
10451   }
10452 
10453   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10454                         TemplateParamLists.size()
10455                             ? forRedeclarationInCurContext()
10456                             : ForVisibleRedeclaration);
10457   LookupName(Previous, S);
10458 
10459   // Warn about shadowing the name of a template parameter.
10460   if (Previous.isSingleResult() &&
10461       Previous.getFoundDecl()->isTemplateParameter()) {
10462     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10463     Previous.clear();
10464   }
10465 
10466   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10467          "name in alias declaration must be an identifier");
10468   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10469                                                Name.StartLocation,
10470                                                Name.Identifier, TInfo);
10471 
10472   NewTD->setAccess(AS);
10473 
10474   if (Invalid)
10475     NewTD->setInvalidDecl();
10476 
10477   ProcessDeclAttributeList(S, NewTD, AttrList);
10478   AddPragmaAttributes(S, NewTD);
10479 
10480   CheckTypedefForVariablyModifiedType(S, NewTD);
10481   Invalid |= NewTD->isInvalidDecl();
10482 
10483   bool Redeclaration = false;
10484 
10485   NamedDecl *NewND;
10486   if (TemplateParamLists.size()) {
10487     TypeAliasTemplateDecl *OldDecl = nullptr;
10488     TemplateParameterList *OldTemplateParams = nullptr;
10489 
10490     if (TemplateParamLists.size() != 1) {
10491       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10492         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10493          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10494     }
10495     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10496 
10497     // Check that we can declare a template here.
10498     if (CheckTemplateDeclScope(S, TemplateParams))
10499       return nullptr;
10500 
10501     // Only consider previous declarations in the same scope.
10502     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10503                          /*ExplicitInstantiationOrSpecialization*/false);
10504     if (!Previous.empty()) {
10505       Redeclaration = true;
10506 
10507       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10508       if (!OldDecl && !Invalid) {
10509         Diag(UsingLoc, diag::err_redefinition_different_kind)
10510           << Name.Identifier;
10511 
10512         NamedDecl *OldD = Previous.getRepresentativeDecl();
10513         if (OldD->getLocation().isValid())
10514           Diag(OldD->getLocation(), diag::note_previous_definition);
10515 
10516         Invalid = true;
10517       }
10518 
10519       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10520         if (TemplateParameterListsAreEqual(TemplateParams,
10521                                            OldDecl->getTemplateParameters(),
10522                                            /*Complain=*/true,
10523                                            TPL_TemplateMatch))
10524           OldTemplateParams = OldDecl->getTemplateParameters();
10525         else
10526           Invalid = true;
10527 
10528         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10529         if (!Invalid &&
10530             !Context.hasSameType(OldTD->getUnderlyingType(),
10531                                  NewTD->getUnderlyingType())) {
10532           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10533           // but we can't reasonably accept it.
10534           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10535             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10536           if (OldTD->getLocation().isValid())
10537             Diag(OldTD->getLocation(), diag::note_previous_definition);
10538           Invalid = true;
10539         }
10540       }
10541     }
10542 
10543     // Merge any previous default template arguments into our parameters,
10544     // and check the parameter list.
10545     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10546                                    TPC_TypeAliasTemplate))
10547       return nullptr;
10548 
10549     TypeAliasTemplateDecl *NewDecl =
10550       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10551                                     Name.Identifier, TemplateParams,
10552                                     NewTD);
10553     NewTD->setDescribedAliasTemplate(NewDecl);
10554 
10555     NewDecl->setAccess(AS);
10556 
10557     if (Invalid)
10558       NewDecl->setInvalidDecl();
10559     else if (OldDecl) {
10560       NewDecl->setPreviousDecl(OldDecl);
10561       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10562     }
10563 
10564     NewND = NewDecl;
10565   } else {
10566     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10567       setTagNameForLinkagePurposes(TD, NewTD);
10568       handleTagNumbering(TD, S);
10569     }
10570     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10571     NewND = NewTD;
10572   }
10573 
10574   PushOnScopeChains(NewND, S);
10575   ActOnDocumentableDecl(NewND);
10576   return NewND;
10577 }
10578 
10579 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10580                                    SourceLocation AliasLoc,
10581                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10582                                    SourceLocation IdentLoc,
10583                                    IdentifierInfo *Ident) {
10584 
10585   // Lookup the namespace name.
10586   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10587   LookupParsedName(R, S, &SS);
10588 
10589   if (R.isAmbiguous())
10590     return nullptr;
10591 
10592   if (R.empty()) {
10593     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10594       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10595       return nullptr;
10596     }
10597   }
10598   assert(!R.isAmbiguous() && !R.empty());
10599   NamedDecl *ND = R.getRepresentativeDecl();
10600 
10601   // Check if we have a previous declaration with the same name.
10602   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10603                      ForVisibleRedeclaration);
10604   LookupName(PrevR, S);
10605 
10606   // Check we're not shadowing a template parameter.
10607   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10608     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10609     PrevR.clear();
10610   }
10611 
10612   // Filter out any other lookup result from an enclosing scope.
10613   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10614                        /*AllowInlineNamespace*/false);
10615 
10616   // Find the previous declaration and check that we can redeclare it.
10617   NamespaceAliasDecl *Prev = nullptr;
10618   if (PrevR.isSingleResult()) {
10619     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10620     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10621       // We already have an alias with the same name that points to the same
10622       // namespace; check that it matches.
10623       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10624         Prev = AD;
10625       } else if (isVisible(PrevDecl)) {
10626         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10627           << Alias;
10628         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10629           << AD->getNamespace();
10630         return nullptr;
10631       }
10632     } else if (isVisible(PrevDecl)) {
10633       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10634                             ? diag::err_redefinition
10635                             : diag::err_redefinition_different_kind;
10636       Diag(AliasLoc, DiagID) << Alias;
10637       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10638       return nullptr;
10639     }
10640   }
10641 
10642   // The use of a nested name specifier may trigger deprecation warnings.
10643   DiagnoseUseOfDecl(ND, IdentLoc);
10644 
10645   NamespaceAliasDecl *AliasDecl =
10646     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10647                                Alias, SS.getWithLocInContext(Context),
10648                                IdentLoc, ND);
10649   if (Prev)
10650     AliasDecl->setPreviousDecl(Prev);
10651 
10652   PushOnScopeChains(AliasDecl, S);
10653   return AliasDecl;
10654 }
10655 
10656 namespace {
10657 struct SpecialMemberExceptionSpecInfo
10658     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10659   SourceLocation Loc;
10660   Sema::ImplicitExceptionSpecification ExceptSpec;
10661 
10662   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10663                                  Sema::CXXSpecialMember CSM,
10664                                  Sema::InheritedConstructorInfo *ICI,
10665                                  SourceLocation Loc)
10666       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10667 
10668   bool visitBase(CXXBaseSpecifier *Base);
10669   bool visitField(FieldDecl *FD);
10670 
10671   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10672                            unsigned Quals);
10673 
10674   void visitSubobjectCall(Subobject Subobj,
10675                           Sema::SpecialMemberOverloadResult SMOR);
10676 };
10677 }
10678 
10679 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10680   auto *RT = Base->getType()->getAs<RecordType>();
10681   if (!RT)
10682     return false;
10683 
10684   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10685   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10686   if (auto *BaseCtor = SMOR.getMethod()) {
10687     visitSubobjectCall(Base, BaseCtor);
10688     return false;
10689   }
10690 
10691   visitClassSubobject(BaseClass, Base, 0);
10692   return false;
10693 }
10694 
10695 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10696   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10697     Expr *E = FD->getInClassInitializer();
10698     if (!E)
10699       // FIXME: It's a little wasteful to build and throw away a
10700       // CXXDefaultInitExpr here.
10701       // FIXME: We should have a single context note pointing at Loc, and
10702       // this location should be MD->getLocation() instead, since that's
10703       // the location where we actually use the default init expression.
10704       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10705     if (E)
10706       ExceptSpec.CalledExpr(E);
10707   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10708                             ->getAs<RecordType>()) {
10709     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10710                         FD->getType().getCVRQualifiers());
10711   }
10712   return false;
10713 }
10714 
10715 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10716                                                          Subobject Subobj,
10717                                                          unsigned Quals) {
10718   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10719   bool IsMutable = Field && Field->isMutable();
10720   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10721 }
10722 
10723 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10724     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10725   // Note, if lookup fails, it doesn't matter what exception specification we
10726   // choose because the special member will be deleted.
10727   if (CXXMethodDecl *MD = SMOR.getMethod())
10728     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10729 }
10730 
10731 static Sema::ImplicitExceptionSpecification
10732 ComputeDefaultedSpecialMemberExceptionSpec(
10733     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10734     Sema::InheritedConstructorInfo *ICI) {
10735   CXXRecordDecl *ClassDecl = MD->getParent();
10736 
10737   // C++ [except.spec]p14:
10738   //   An implicitly declared special member function (Clause 12) shall have an
10739   //   exception-specification. [...]
10740   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10741   if (ClassDecl->isInvalidDecl())
10742     return Info.ExceptSpec;
10743 
10744   // C++1z [except.spec]p7:
10745   //   [Look for exceptions thrown by] a constructor selected [...] to
10746   //   initialize a potentially constructed subobject,
10747   // C++1z [except.spec]p8:
10748   //   The exception specification for an implicitly-declared destructor, or a
10749   //   destructor without a noexcept-specifier, is potentially-throwing if and
10750   //   only if any of the destructors for any of its potentially constructed
10751   //   subojects is potentially throwing.
10752   // FIXME: We respect the first rule but ignore the "potentially constructed"
10753   // in the second rule to resolve a core issue (no number yet) that would have
10754   // us reject:
10755   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10756   //   struct B : A {};
10757   //   struct C : B { void f(); };
10758   // ... due to giving B::~B() a non-throwing exception specification.
10759   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10760                                 : Info.VisitAllBases);
10761 
10762   return Info.ExceptSpec;
10763 }
10764 
10765 namespace {
10766 /// RAII object to register a special member as being currently declared.
10767 struct DeclaringSpecialMember {
10768   Sema &S;
10769   Sema::SpecialMemberDecl D;
10770   Sema::ContextRAII SavedContext;
10771   bool WasAlreadyBeingDeclared;
10772 
10773   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10774       : S(S), D(RD, CSM), SavedContext(S, RD) {
10775     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10776     if (WasAlreadyBeingDeclared)
10777       // This almost never happens, but if it does, ensure that our cache
10778       // doesn't contain a stale result.
10779       S.SpecialMemberCache.clear();
10780     else {
10781       // Register a note to be produced if we encounter an error while
10782       // declaring the special member.
10783       Sema::CodeSynthesisContext Ctx;
10784       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10785       // FIXME: We don't have a location to use here. Using the class's
10786       // location maintains the fiction that we declare all special members
10787       // with the class, but (1) it's not clear that lying about that helps our
10788       // users understand what's going on, and (2) there may be outer contexts
10789       // on the stack (some of which are relevant) and printing them exposes
10790       // our lies.
10791       Ctx.PointOfInstantiation = RD->getLocation();
10792       Ctx.Entity = RD;
10793       Ctx.SpecialMember = CSM;
10794       S.pushCodeSynthesisContext(Ctx);
10795     }
10796   }
10797   ~DeclaringSpecialMember() {
10798     if (!WasAlreadyBeingDeclared) {
10799       S.SpecialMembersBeingDeclared.erase(D);
10800       S.popCodeSynthesisContext();
10801     }
10802   }
10803 
10804   /// Are we already trying to declare this special member?
10805   bool isAlreadyBeingDeclared() const {
10806     return WasAlreadyBeingDeclared;
10807   }
10808 };
10809 }
10810 
10811 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10812   // Look up any existing declarations, but don't trigger declaration of all
10813   // implicit special members with this name.
10814   DeclarationName Name = FD->getDeclName();
10815   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10816                  ForExternalRedeclaration);
10817   for (auto *D : FD->getParent()->lookup(Name))
10818     if (auto *Acceptable = R.getAcceptableDecl(D))
10819       R.addDecl(Acceptable);
10820   R.resolveKind();
10821   R.suppressDiagnostics();
10822 
10823   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10824 }
10825 
10826 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10827                                                      CXXRecordDecl *ClassDecl) {
10828   // C++ [class.ctor]p5:
10829   //   A default constructor for a class X is a constructor of class X
10830   //   that can be called without an argument. If there is no
10831   //   user-declared constructor for class X, a default constructor is
10832   //   implicitly declared. An implicitly-declared default constructor
10833   //   is an inline public member of its class.
10834   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10835          "Should not build implicit default constructor!");
10836 
10837   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10838   if (DSM.isAlreadyBeingDeclared())
10839     return nullptr;
10840 
10841   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10842                                                      CXXDefaultConstructor,
10843                                                      false);
10844 
10845   // Create the actual constructor declaration.
10846   CanQualType ClassType
10847     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10848   SourceLocation ClassLoc = ClassDecl->getLocation();
10849   DeclarationName Name
10850     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10851   DeclarationNameInfo NameInfo(Name, ClassLoc);
10852   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10853       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10854       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10855       /*isImplicitlyDeclared=*/true, Constexpr);
10856   DefaultCon->setAccess(AS_public);
10857   DefaultCon->setDefaulted();
10858 
10859   if (getLangOpts().CUDA) {
10860     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10861                                             DefaultCon,
10862                                             /* ConstRHS */ false,
10863                                             /* Diagnose */ false);
10864   }
10865 
10866   // Build an exception specification pointing back at this constructor.
10867   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10868   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10869 
10870   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10871   // constructors is easy to compute.
10872   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10873 
10874   // Note that we have declared this constructor.
10875   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10876 
10877   Scope *S = getScopeForContext(ClassDecl);
10878   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10879 
10880   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10881     SetDeclDeleted(DefaultCon, ClassLoc);
10882 
10883   if (S)
10884     PushOnScopeChains(DefaultCon, S, false);
10885   ClassDecl->addDecl(DefaultCon);
10886 
10887   return DefaultCon;
10888 }
10889 
10890 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10891                                             CXXConstructorDecl *Constructor) {
10892   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10893           !Constructor->doesThisDeclarationHaveABody() &&
10894           !Constructor->isDeleted()) &&
10895     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10896   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10897     return;
10898 
10899   CXXRecordDecl *ClassDecl = Constructor->getParent();
10900   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10901 
10902   SynthesizedFunctionScope Scope(*this, Constructor);
10903 
10904   // The exception specification is needed because we are defining the
10905   // function.
10906   ResolveExceptionSpec(CurrentLocation,
10907                        Constructor->getType()->castAs<FunctionProtoType>());
10908   MarkVTableUsed(CurrentLocation, ClassDecl);
10909 
10910   // Add a context note for diagnostics produced after this point.
10911   Scope.addContextNote(CurrentLocation);
10912 
10913   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10914     Constructor->setInvalidDecl();
10915     return;
10916   }
10917 
10918   SourceLocation Loc = Constructor->getLocEnd().isValid()
10919                            ? Constructor->getLocEnd()
10920                            : Constructor->getLocation();
10921   Constructor->setBody(new (Context) CompoundStmt(Loc));
10922   Constructor->markUsed(Context);
10923 
10924   if (ASTMutationListener *L = getASTMutationListener()) {
10925     L->CompletedImplicitDefinition(Constructor);
10926   }
10927 
10928   DiagnoseUninitializedFields(*this, Constructor);
10929 }
10930 
10931 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10932   // Perform any delayed checks on exception specifications.
10933   CheckDelayedMemberExceptionSpecs();
10934 }
10935 
10936 /// Find or create the fake constructor we synthesize to model constructing an
10937 /// object of a derived class via a constructor of a base class.
10938 CXXConstructorDecl *
10939 Sema::findInheritingConstructor(SourceLocation Loc,
10940                                 CXXConstructorDecl *BaseCtor,
10941                                 ConstructorUsingShadowDecl *Shadow) {
10942   CXXRecordDecl *Derived = Shadow->getParent();
10943   SourceLocation UsingLoc = Shadow->getLocation();
10944 
10945   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10946   // For now we use the name of the base class constructor as a member of the
10947   // derived class to indicate a (fake) inherited constructor name.
10948   DeclarationName Name = BaseCtor->getDeclName();
10949 
10950   // Check to see if we already have a fake constructor for this inherited
10951   // constructor call.
10952   for (NamedDecl *Ctor : Derived->lookup(Name))
10953     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10954                                ->getInheritedConstructor()
10955                                .getConstructor(),
10956                            BaseCtor))
10957       return cast<CXXConstructorDecl>(Ctor);
10958 
10959   DeclarationNameInfo NameInfo(Name, UsingLoc);
10960   TypeSourceInfo *TInfo =
10961       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10962   FunctionProtoTypeLoc ProtoLoc =
10963       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10964 
10965   // Check the inherited constructor is valid and find the list of base classes
10966   // from which it was inherited.
10967   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10968 
10969   bool Constexpr =
10970       BaseCtor->isConstexpr() &&
10971       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10972                                         false, BaseCtor, &ICI);
10973 
10974   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10975       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10976       BaseCtor->isExplicit(), /*Inline=*/true,
10977       /*ImplicitlyDeclared=*/true, Constexpr,
10978       InheritedConstructor(Shadow, BaseCtor));
10979   if (Shadow->isInvalidDecl())
10980     DerivedCtor->setInvalidDecl();
10981 
10982   // Build an unevaluated exception specification for this fake constructor.
10983   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10984   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10985   EPI.ExceptionSpec.Type = EST_Unevaluated;
10986   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10987   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10988                                                FPT->getParamTypes(), EPI));
10989 
10990   // Build the parameter declarations.
10991   SmallVector<ParmVarDecl *, 16> ParamDecls;
10992   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10993     TypeSourceInfo *TInfo =
10994         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10995     ParmVarDecl *PD = ParmVarDecl::Create(
10996         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10997         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10998     PD->setScopeInfo(0, I);
10999     PD->setImplicit();
11000     // Ensure attributes are propagated onto parameters (this matters for
11001     // format, pass_object_size, ...).
11002     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11003     ParamDecls.push_back(PD);
11004     ProtoLoc.setParam(I, PD);
11005   }
11006 
11007   // Set up the new constructor.
11008   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11009   DerivedCtor->setAccess(BaseCtor->getAccess());
11010   DerivedCtor->setParams(ParamDecls);
11011   Derived->addDecl(DerivedCtor);
11012 
11013   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11014     SetDeclDeleted(DerivedCtor, UsingLoc);
11015 
11016   return DerivedCtor;
11017 }
11018 
11019 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11020   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11021                                Ctor->getInheritedConstructor().getShadowDecl());
11022   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11023                             /*Diagnose*/true);
11024 }
11025 
11026 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11027                                        CXXConstructorDecl *Constructor) {
11028   CXXRecordDecl *ClassDecl = Constructor->getParent();
11029   assert(Constructor->getInheritedConstructor() &&
11030          !Constructor->doesThisDeclarationHaveABody() &&
11031          !Constructor->isDeleted());
11032   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11033     return;
11034 
11035   // Initializations are performed "as if by a defaulted default constructor",
11036   // so enter the appropriate scope.
11037   SynthesizedFunctionScope Scope(*this, Constructor);
11038 
11039   // The exception specification is needed because we are defining the
11040   // function.
11041   ResolveExceptionSpec(CurrentLocation,
11042                        Constructor->getType()->castAs<FunctionProtoType>());
11043   MarkVTableUsed(CurrentLocation, ClassDecl);
11044 
11045   // Add a context note for diagnostics produced after this point.
11046   Scope.addContextNote(CurrentLocation);
11047 
11048   ConstructorUsingShadowDecl *Shadow =
11049       Constructor->getInheritedConstructor().getShadowDecl();
11050   CXXConstructorDecl *InheritedCtor =
11051       Constructor->getInheritedConstructor().getConstructor();
11052 
11053   // [class.inhctor.init]p1:
11054   //   initialization proceeds as if a defaulted default constructor is used to
11055   //   initialize the D object and each base class subobject from which the
11056   //   constructor was inherited
11057 
11058   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11059   CXXRecordDecl *RD = Shadow->getParent();
11060   SourceLocation InitLoc = Shadow->getLocation();
11061 
11062   // Build explicit initializers for all base classes from which the
11063   // constructor was inherited.
11064   SmallVector<CXXCtorInitializer*, 8> Inits;
11065   for (bool VBase : {false, true}) {
11066     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11067       if (B.isVirtual() != VBase)
11068         continue;
11069 
11070       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11071       if (!BaseRD)
11072         continue;
11073 
11074       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11075       if (!BaseCtor.first)
11076         continue;
11077 
11078       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11079       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11080           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11081 
11082       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11083       Inits.push_back(new (Context) CXXCtorInitializer(
11084           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11085           SourceLocation()));
11086     }
11087   }
11088 
11089   // We now proceed as if for a defaulted default constructor, with the relevant
11090   // initializers replaced.
11091 
11092   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11093     Constructor->setInvalidDecl();
11094     return;
11095   }
11096 
11097   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11098   Constructor->markUsed(Context);
11099 
11100   if (ASTMutationListener *L = getASTMutationListener()) {
11101     L->CompletedImplicitDefinition(Constructor);
11102   }
11103 
11104   DiagnoseUninitializedFields(*this, Constructor);
11105 }
11106 
11107 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11108   // C++ [class.dtor]p2:
11109   //   If a class has no user-declared destructor, a destructor is
11110   //   declared implicitly. An implicitly-declared destructor is an
11111   //   inline public member of its class.
11112   assert(ClassDecl->needsImplicitDestructor());
11113 
11114   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11115   if (DSM.isAlreadyBeingDeclared())
11116     return nullptr;
11117 
11118   // Create the actual destructor declaration.
11119   CanQualType ClassType
11120     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11121   SourceLocation ClassLoc = ClassDecl->getLocation();
11122   DeclarationName Name
11123     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11124   DeclarationNameInfo NameInfo(Name, ClassLoc);
11125   CXXDestructorDecl *Destructor
11126       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11127                                   QualType(), nullptr, /*isInline=*/true,
11128                                   /*isImplicitlyDeclared=*/true);
11129   Destructor->setAccess(AS_public);
11130   Destructor->setDefaulted();
11131 
11132   if (getLangOpts().CUDA) {
11133     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11134                                             Destructor,
11135                                             /* ConstRHS */ false,
11136                                             /* Diagnose */ false);
11137   }
11138 
11139   // Build an exception specification pointing back at this destructor.
11140   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11141   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11142 
11143   // We don't need to use SpecialMemberIsTrivial here; triviality for
11144   // destructors is easy to compute.
11145   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11146   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11147                                 ClassDecl->hasTrivialDestructorForCall());
11148 
11149   // Note that we have declared this destructor.
11150   ++ASTContext::NumImplicitDestructorsDeclared;
11151 
11152   Scope *S = getScopeForContext(ClassDecl);
11153   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11154 
11155   // We can't check whether an implicit destructor is deleted before we complete
11156   // the definition of the class, because its validity depends on the alignment
11157   // of the class. We'll check this from ActOnFields once the class is complete.
11158   if (ClassDecl->isCompleteDefinition() &&
11159       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11160     SetDeclDeleted(Destructor, ClassLoc);
11161 
11162   // Introduce this destructor into its scope.
11163   if (S)
11164     PushOnScopeChains(Destructor, S, false);
11165   ClassDecl->addDecl(Destructor);
11166 
11167   return Destructor;
11168 }
11169 
11170 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11171                                     CXXDestructorDecl *Destructor) {
11172   assert((Destructor->isDefaulted() &&
11173           !Destructor->doesThisDeclarationHaveABody() &&
11174           !Destructor->isDeleted()) &&
11175          "DefineImplicitDestructor - call it for implicit default dtor");
11176   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11177     return;
11178 
11179   CXXRecordDecl *ClassDecl = Destructor->getParent();
11180   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11181 
11182   SynthesizedFunctionScope Scope(*this, Destructor);
11183 
11184   // The exception specification is needed because we are defining the
11185   // function.
11186   ResolveExceptionSpec(CurrentLocation,
11187                        Destructor->getType()->castAs<FunctionProtoType>());
11188   MarkVTableUsed(CurrentLocation, ClassDecl);
11189 
11190   // Add a context note for diagnostics produced after this point.
11191   Scope.addContextNote(CurrentLocation);
11192 
11193   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11194                                          Destructor->getParent());
11195 
11196   if (CheckDestructor(Destructor)) {
11197     Destructor->setInvalidDecl();
11198     return;
11199   }
11200 
11201   SourceLocation Loc = Destructor->getLocEnd().isValid()
11202                            ? Destructor->getLocEnd()
11203                            : Destructor->getLocation();
11204   Destructor->setBody(new (Context) CompoundStmt(Loc));
11205   Destructor->markUsed(Context);
11206 
11207   if (ASTMutationListener *L = getASTMutationListener()) {
11208     L->CompletedImplicitDefinition(Destructor);
11209   }
11210 }
11211 
11212 /// Perform any semantic analysis which needs to be delayed until all
11213 /// pending class member declarations have been parsed.
11214 void Sema::ActOnFinishCXXMemberDecls() {
11215   // If the context is an invalid C++ class, just suppress these checks.
11216   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11217     if (Record->isInvalidDecl()) {
11218       DelayedDefaultedMemberExceptionSpecs.clear();
11219       DelayedExceptionSpecChecks.clear();
11220       return;
11221     }
11222     checkForMultipleExportedDefaultConstructors(*this, Record);
11223   }
11224 }
11225 
11226 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11227   referenceDLLExportedClassMethods();
11228 }
11229 
11230 void Sema::referenceDLLExportedClassMethods() {
11231   if (!DelayedDllExportClasses.empty()) {
11232     // Calling ReferenceDllExportedMembers might cause the current function to
11233     // be called again, so use a local copy of DelayedDllExportClasses.
11234     SmallVector<CXXRecordDecl *, 4> WorkList;
11235     std::swap(DelayedDllExportClasses, WorkList);
11236     for (CXXRecordDecl *Class : WorkList)
11237       ReferenceDllExportedMembers(*this, Class);
11238   }
11239 }
11240 
11241 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11242                                          CXXDestructorDecl *Destructor) {
11243   assert(getLangOpts().CPlusPlus11 &&
11244          "adjusting dtor exception specs was introduced in c++11");
11245 
11246   // C++11 [class.dtor]p3:
11247   //   A declaration of a destructor that does not have an exception-
11248   //   specification is implicitly considered to have the same exception-
11249   //   specification as an implicit declaration.
11250   const FunctionProtoType *DtorType = Destructor->getType()->
11251                                         getAs<FunctionProtoType>();
11252   if (DtorType->hasExceptionSpec())
11253     return;
11254 
11255   // Replace the destructor's type, building off the existing one. Fortunately,
11256   // the only thing of interest in the destructor type is its extended info.
11257   // The return and arguments are fixed.
11258   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11259   EPI.ExceptionSpec.Type = EST_Unevaluated;
11260   EPI.ExceptionSpec.SourceDecl = Destructor;
11261   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11262 
11263   // FIXME: If the destructor has a body that could throw, and the newly created
11264   // spec doesn't allow exceptions, we should emit a warning, because this
11265   // change in behavior can break conforming C++03 programs at runtime.
11266   // However, we don't have a body or an exception specification yet, so it
11267   // needs to be done somewhere else.
11268 }
11269 
11270 namespace {
11271 /// An abstract base class for all helper classes used in building the
11272 //  copy/move operators. These classes serve as factory functions and help us
11273 //  avoid using the same Expr* in the AST twice.
11274 class ExprBuilder {
11275   ExprBuilder(const ExprBuilder&) = delete;
11276   ExprBuilder &operator=(const ExprBuilder&) = delete;
11277 
11278 protected:
11279   static Expr *assertNotNull(Expr *E) {
11280     assert(E && "Expression construction must not fail.");
11281     return E;
11282   }
11283 
11284 public:
11285   ExprBuilder() {}
11286   virtual ~ExprBuilder() {}
11287 
11288   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11289 };
11290 
11291 class RefBuilder: public ExprBuilder {
11292   VarDecl *Var;
11293   QualType VarType;
11294 
11295 public:
11296   Expr *build(Sema &S, SourceLocation Loc) const override {
11297     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11298   }
11299 
11300   RefBuilder(VarDecl *Var, QualType VarType)
11301       : Var(Var), VarType(VarType) {}
11302 };
11303 
11304 class ThisBuilder: public ExprBuilder {
11305 public:
11306   Expr *build(Sema &S, SourceLocation Loc) const override {
11307     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11308   }
11309 };
11310 
11311 class CastBuilder: public ExprBuilder {
11312   const ExprBuilder &Builder;
11313   QualType Type;
11314   ExprValueKind Kind;
11315   const CXXCastPath &Path;
11316 
11317 public:
11318   Expr *build(Sema &S, SourceLocation Loc) const override {
11319     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11320                                              CK_UncheckedDerivedToBase, Kind,
11321                                              &Path).get());
11322   }
11323 
11324   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11325               const CXXCastPath &Path)
11326       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11327 };
11328 
11329 class DerefBuilder: public ExprBuilder {
11330   const ExprBuilder &Builder;
11331 
11332 public:
11333   Expr *build(Sema &S, SourceLocation Loc) const override {
11334     return assertNotNull(
11335         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11336   }
11337 
11338   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11339 };
11340 
11341 class MemberBuilder: public ExprBuilder {
11342   const ExprBuilder &Builder;
11343   QualType Type;
11344   CXXScopeSpec SS;
11345   bool IsArrow;
11346   LookupResult &MemberLookup;
11347 
11348 public:
11349   Expr *build(Sema &S, SourceLocation Loc) const override {
11350     return assertNotNull(S.BuildMemberReferenceExpr(
11351         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11352         nullptr, MemberLookup, nullptr, nullptr).get());
11353   }
11354 
11355   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11356                 LookupResult &MemberLookup)
11357       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11358         MemberLookup(MemberLookup) {}
11359 };
11360 
11361 class MoveCastBuilder: public ExprBuilder {
11362   const ExprBuilder &Builder;
11363 
11364 public:
11365   Expr *build(Sema &S, SourceLocation Loc) const override {
11366     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11367   }
11368 
11369   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11370 };
11371 
11372 class LvalueConvBuilder: public ExprBuilder {
11373   const ExprBuilder &Builder;
11374 
11375 public:
11376   Expr *build(Sema &S, SourceLocation Loc) const override {
11377     return assertNotNull(
11378         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11379   }
11380 
11381   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11382 };
11383 
11384 class SubscriptBuilder: public ExprBuilder {
11385   const ExprBuilder &Base;
11386   const ExprBuilder &Index;
11387 
11388 public:
11389   Expr *build(Sema &S, SourceLocation Loc) const override {
11390     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11391         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11392   }
11393 
11394   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11395       : Base(Base), Index(Index) {}
11396 };
11397 
11398 } // end anonymous namespace
11399 
11400 /// When generating a defaulted copy or move assignment operator, if a field
11401 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11402 /// do so. This optimization only applies for arrays of scalars, and for arrays
11403 /// of class type where the selected copy/move-assignment operator is trivial.
11404 static StmtResult
11405 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11406                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11407   // Compute the size of the memory buffer to be copied.
11408   QualType SizeType = S.Context.getSizeType();
11409   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11410                    S.Context.getTypeSizeInChars(T).getQuantity());
11411 
11412   // Take the address of the field references for "from" and "to". We
11413   // directly construct UnaryOperators here because semantic analysis
11414   // does not permit us to take the address of an xvalue.
11415   Expr *From = FromB.build(S, Loc);
11416   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11417                          S.Context.getPointerType(From->getType()),
11418                          VK_RValue, OK_Ordinary, Loc, false);
11419   Expr *To = ToB.build(S, Loc);
11420   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11421                        S.Context.getPointerType(To->getType()),
11422                        VK_RValue, OK_Ordinary, Loc, false);
11423 
11424   const Type *E = T->getBaseElementTypeUnsafe();
11425   bool NeedsCollectableMemCpy =
11426     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11427 
11428   // Create a reference to the __builtin_objc_memmove_collectable function
11429   StringRef MemCpyName = NeedsCollectableMemCpy ?
11430     "__builtin_objc_memmove_collectable" :
11431     "__builtin_memcpy";
11432   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11433                  Sema::LookupOrdinaryName);
11434   S.LookupName(R, S.TUScope, true);
11435 
11436   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11437   if (!MemCpy)
11438     // Something went horribly wrong earlier, and we will have complained
11439     // about it.
11440     return StmtError();
11441 
11442   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11443                                             VK_RValue, Loc, nullptr);
11444   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11445 
11446   Expr *CallArgs[] = {
11447     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11448   };
11449   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11450                                     Loc, CallArgs, Loc);
11451 
11452   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11453   return Call.getAs<Stmt>();
11454 }
11455 
11456 /// Builds a statement that copies/moves the given entity from \p From to
11457 /// \c To.
11458 ///
11459 /// This routine is used to copy/move the members of a class with an
11460 /// implicitly-declared copy/move assignment operator. When the entities being
11461 /// copied are arrays, this routine builds for loops to copy them.
11462 ///
11463 /// \param S The Sema object used for type-checking.
11464 ///
11465 /// \param Loc The location where the implicit copy/move is being generated.
11466 ///
11467 /// \param T The type of the expressions being copied/moved. Both expressions
11468 /// must have this type.
11469 ///
11470 /// \param To The expression we are copying/moving to.
11471 ///
11472 /// \param From The expression we are copying/moving from.
11473 ///
11474 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11475 /// Otherwise, it's a non-static member subobject.
11476 ///
11477 /// \param Copying Whether we're copying or moving.
11478 ///
11479 /// \param Depth Internal parameter recording the depth of the recursion.
11480 ///
11481 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11482 /// if a memcpy should be used instead.
11483 static StmtResult
11484 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11485                                  const ExprBuilder &To, const ExprBuilder &From,
11486                                  bool CopyingBaseSubobject, bool Copying,
11487                                  unsigned Depth = 0) {
11488   // C++11 [class.copy]p28:
11489   //   Each subobject is assigned in the manner appropriate to its type:
11490   //
11491   //     - if the subobject is of class type, as if by a call to operator= with
11492   //       the subobject as the object expression and the corresponding
11493   //       subobject of x as a single function argument (as if by explicit
11494   //       qualification; that is, ignoring any possible virtual overriding
11495   //       functions in more derived classes);
11496   //
11497   // C++03 [class.copy]p13:
11498   //     - if the subobject is of class type, the copy assignment operator for
11499   //       the class is used (as if by explicit qualification; that is,
11500   //       ignoring any possible virtual overriding functions in more derived
11501   //       classes);
11502   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11503     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11504 
11505     // Look for operator=.
11506     DeclarationName Name
11507       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11508     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11509     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11510 
11511     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11512     // operator.
11513     if (!S.getLangOpts().CPlusPlus11) {
11514       LookupResult::Filter F = OpLookup.makeFilter();
11515       while (F.hasNext()) {
11516         NamedDecl *D = F.next();
11517         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11518           if (Method->isCopyAssignmentOperator() ||
11519               (!Copying && Method->isMoveAssignmentOperator()))
11520             continue;
11521 
11522         F.erase();
11523       }
11524       F.done();
11525     }
11526 
11527     // Suppress the protected check (C++ [class.protected]) for each of the
11528     // assignment operators we found. This strange dance is required when
11529     // we're assigning via a base classes's copy-assignment operator. To
11530     // ensure that we're getting the right base class subobject (without
11531     // ambiguities), we need to cast "this" to that subobject type; to
11532     // ensure that we don't go through the virtual call mechanism, we need
11533     // to qualify the operator= name with the base class (see below). However,
11534     // this means that if the base class has a protected copy assignment
11535     // operator, the protected member access check will fail. So, we
11536     // rewrite "protected" access to "public" access in this case, since we
11537     // know by construction that we're calling from a derived class.
11538     if (CopyingBaseSubobject) {
11539       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11540            L != LEnd; ++L) {
11541         if (L.getAccess() == AS_protected)
11542           L.setAccess(AS_public);
11543       }
11544     }
11545 
11546     // Create the nested-name-specifier that will be used to qualify the
11547     // reference to operator=; this is required to suppress the virtual
11548     // call mechanism.
11549     CXXScopeSpec SS;
11550     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11551     SS.MakeTrivial(S.Context,
11552                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11553                                                CanonicalT),
11554                    Loc);
11555 
11556     // Create the reference to operator=.
11557     ExprResult OpEqualRef
11558       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11559                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11560                                    /*FirstQualifierInScope=*/nullptr,
11561                                    OpLookup,
11562                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11563                                    /*SuppressQualifierCheck=*/true);
11564     if (OpEqualRef.isInvalid())
11565       return StmtError();
11566 
11567     // Build the call to the assignment operator.
11568 
11569     Expr *FromInst = From.build(S, Loc);
11570     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11571                                                   OpEqualRef.getAs<Expr>(),
11572                                                   Loc, FromInst, Loc);
11573     if (Call.isInvalid())
11574       return StmtError();
11575 
11576     // If we built a call to a trivial 'operator=' while copying an array,
11577     // bail out. We'll replace the whole shebang with a memcpy.
11578     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11579     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11580       return StmtResult((Stmt*)nullptr);
11581 
11582     // Convert to an expression-statement, and clean up any produced
11583     // temporaries.
11584     return S.ActOnExprStmt(Call);
11585   }
11586 
11587   //     - if the subobject is of scalar type, the built-in assignment
11588   //       operator is used.
11589   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11590   if (!ArrayTy) {
11591     ExprResult Assignment = S.CreateBuiltinBinOp(
11592         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11593     if (Assignment.isInvalid())
11594       return StmtError();
11595     return S.ActOnExprStmt(Assignment);
11596   }
11597 
11598   //     - if the subobject is an array, each element is assigned, in the
11599   //       manner appropriate to the element type;
11600 
11601   // Construct a loop over the array bounds, e.g.,
11602   //
11603   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11604   //
11605   // that will copy each of the array elements.
11606   QualType SizeType = S.Context.getSizeType();
11607 
11608   // Create the iteration variable.
11609   IdentifierInfo *IterationVarName = nullptr;
11610   {
11611     SmallString<8> Str;
11612     llvm::raw_svector_ostream OS(Str);
11613     OS << "__i" << Depth;
11614     IterationVarName = &S.Context.Idents.get(OS.str());
11615   }
11616   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11617                                           IterationVarName, SizeType,
11618                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11619                                           SC_None);
11620 
11621   // Initialize the iteration variable to zero.
11622   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11623   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11624 
11625   // Creates a reference to the iteration variable.
11626   RefBuilder IterationVarRef(IterationVar, SizeType);
11627   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11628 
11629   // Create the DeclStmt that holds the iteration variable.
11630   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11631 
11632   // Subscript the "from" and "to" expressions with the iteration variable.
11633   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11634   MoveCastBuilder FromIndexMove(FromIndexCopy);
11635   const ExprBuilder *FromIndex;
11636   if (Copying)
11637     FromIndex = &FromIndexCopy;
11638   else
11639     FromIndex = &FromIndexMove;
11640 
11641   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11642 
11643   // Build the copy/move for an individual element of the array.
11644   StmtResult Copy =
11645     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11646                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11647                                      Copying, Depth + 1);
11648   // Bail out if copying fails or if we determined that we should use memcpy.
11649   if (Copy.isInvalid() || !Copy.get())
11650     return Copy;
11651 
11652   // Create the comparison against the array bound.
11653   llvm::APInt Upper
11654     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11655   Expr *Comparison
11656     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11657                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11658                                      BO_NE, S.Context.BoolTy,
11659                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11660 
11661   // Create the pre-increment of the iteration variable. We can determine
11662   // whether the increment will overflow based on the value of the array
11663   // bound.
11664   Expr *Increment = new (S.Context)
11665       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11666                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11667 
11668   // Construct the loop that copies all elements of this array.
11669   return S.ActOnForStmt(
11670       Loc, Loc, InitStmt,
11671       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11672       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11673 }
11674 
11675 static StmtResult
11676 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11677                       const ExprBuilder &To, const ExprBuilder &From,
11678                       bool CopyingBaseSubobject, bool Copying) {
11679   // Maybe we should use a memcpy?
11680   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11681       T.isTriviallyCopyableType(S.Context))
11682     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11683 
11684   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11685                                                      CopyingBaseSubobject,
11686                                                      Copying, 0));
11687 
11688   // If we ended up picking a trivial assignment operator for an array of a
11689   // non-trivially-copyable class type, just emit a memcpy.
11690   if (!Result.isInvalid() && !Result.get())
11691     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11692 
11693   return Result;
11694 }
11695 
11696 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11697   // Note: The following rules are largely analoguous to the copy
11698   // constructor rules. Note that virtual bases are not taken into account
11699   // for determining the argument type of the operator. Note also that
11700   // operators taking an object instead of a reference are allowed.
11701   assert(ClassDecl->needsImplicitCopyAssignment());
11702 
11703   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11704   if (DSM.isAlreadyBeingDeclared())
11705     return nullptr;
11706 
11707   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11708   QualType RetType = Context.getLValueReferenceType(ArgType);
11709   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11710   if (Const)
11711     ArgType = ArgType.withConst();
11712   ArgType = Context.getLValueReferenceType(ArgType);
11713 
11714   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11715                                                      CXXCopyAssignment,
11716                                                      Const);
11717 
11718   //   An implicitly-declared copy assignment operator is an inline public
11719   //   member of its class.
11720   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11721   SourceLocation ClassLoc = ClassDecl->getLocation();
11722   DeclarationNameInfo NameInfo(Name, ClassLoc);
11723   CXXMethodDecl *CopyAssignment =
11724       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11725                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11726                             /*isInline=*/true, Constexpr, SourceLocation());
11727   CopyAssignment->setAccess(AS_public);
11728   CopyAssignment->setDefaulted();
11729   CopyAssignment->setImplicit();
11730 
11731   if (getLangOpts().CUDA) {
11732     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11733                                             CopyAssignment,
11734                                             /* ConstRHS */ Const,
11735                                             /* Diagnose */ false);
11736   }
11737 
11738   // Build an exception specification pointing back at this member.
11739   FunctionProtoType::ExtProtoInfo EPI =
11740       getImplicitMethodEPI(*this, CopyAssignment);
11741   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11742 
11743   // Add the parameter to the operator.
11744   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11745                                                ClassLoc, ClassLoc,
11746                                                /*Id=*/nullptr, ArgType,
11747                                                /*TInfo=*/nullptr, SC_None,
11748                                                nullptr);
11749   CopyAssignment->setParams(FromParam);
11750 
11751   CopyAssignment->setTrivial(
11752     ClassDecl->needsOverloadResolutionForCopyAssignment()
11753       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11754       : ClassDecl->hasTrivialCopyAssignment());
11755 
11756   // Note that we have added this copy-assignment operator.
11757   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11758 
11759   Scope *S = getScopeForContext(ClassDecl);
11760   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11761 
11762   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11763     SetDeclDeleted(CopyAssignment, ClassLoc);
11764 
11765   if (S)
11766     PushOnScopeChains(CopyAssignment, S, false);
11767   ClassDecl->addDecl(CopyAssignment);
11768 
11769   return CopyAssignment;
11770 }
11771 
11772 /// Diagnose an implicit copy operation for a class which is odr-used, but
11773 /// which is deprecated because the class has a user-declared copy constructor,
11774 /// copy assignment operator, or destructor.
11775 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11776   assert(CopyOp->isImplicit());
11777 
11778   CXXRecordDecl *RD = CopyOp->getParent();
11779   CXXMethodDecl *UserDeclaredOperation = nullptr;
11780 
11781   // In Microsoft mode, assignment operations don't affect constructors and
11782   // vice versa.
11783   if (RD->hasUserDeclaredDestructor()) {
11784     UserDeclaredOperation = RD->getDestructor();
11785   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11786              RD->hasUserDeclaredCopyConstructor() &&
11787              !S.getLangOpts().MSVCCompat) {
11788     // Find any user-declared copy constructor.
11789     for (auto *I : RD->ctors()) {
11790       if (I->isCopyConstructor()) {
11791         UserDeclaredOperation = I;
11792         break;
11793       }
11794     }
11795     assert(UserDeclaredOperation);
11796   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11797              RD->hasUserDeclaredCopyAssignment() &&
11798              !S.getLangOpts().MSVCCompat) {
11799     // Find any user-declared move assignment operator.
11800     for (auto *I : RD->methods()) {
11801       if (I->isCopyAssignmentOperator()) {
11802         UserDeclaredOperation = I;
11803         break;
11804       }
11805     }
11806     assert(UserDeclaredOperation);
11807   }
11808 
11809   if (UserDeclaredOperation) {
11810     S.Diag(UserDeclaredOperation->getLocation(),
11811          diag::warn_deprecated_copy_operation)
11812       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11813       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11814   }
11815 }
11816 
11817 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11818                                         CXXMethodDecl *CopyAssignOperator) {
11819   assert((CopyAssignOperator->isDefaulted() &&
11820           CopyAssignOperator->isOverloadedOperator() &&
11821           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11822           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11823           !CopyAssignOperator->isDeleted()) &&
11824          "DefineImplicitCopyAssignment called for wrong function");
11825   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11826     return;
11827 
11828   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11829   if (ClassDecl->isInvalidDecl()) {
11830     CopyAssignOperator->setInvalidDecl();
11831     return;
11832   }
11833 
11834   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11835 
11836   // The exception specification is needed because we are defining the
11837   // function.
11838   ResolveExceptionSpec(CurrentLocation,
11839                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11840 
11841   // Add a context note for diagnostics produced after this point.
11842   Scope.addContextNote(CurrentLocation);
11843 
11844   // C++11 [class.copy]p18:
11845   //   The [definition of an implicitly declared copy assignment operator] is
11846   //   deprecated if the class has a user-declared copy constructor or a
11847   //   user-declared destructor.
11848   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11849     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11850 
11851   // C++0x [class.copy]p30:
11852   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11853   //   for a non-union class X performs memberwise copy assignment of its
11854   //   subobjects. The direct base classes of X are assigned first, in the
11855   //   order of their declaration in the base-specifier-list, and then the
11856   //   immediate non-static data members of X are assigned, in the order in
11857   //   which they were declared in the class definition.
11858 
11859   // The statements that form the synthesized function body.
11860   SmallVector<Stmt*, 8> Statements;
11861 
11862   // The parameter for the "other" object, which we are copying from.
11863   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11864   Qualifiers OtherQuals = Other->getType().getQualifiers();
11865   QualType OtherRefType = Other->getType();
11866   if (const LValueReferenceType *OtherRef
11867                                 = OtherRefType->getAs<LValueReferenceType>()) {
11868     OtherRefType = OtherRef->getPointeeType();
11869     OtherQuals = OtherRefType.getQualifiers();
11870   }
11871 
11872   // Our location for everything implicitly-generated.
11873   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11874                            ? CopyAssignOperator->getLocEnd()
11875                            : CopyAssignOperator->getLocation();
11876 
11877   // Builds a DeclRefExpr for the "other" object.
11878   RefBuilder OtherRef(Other, OtherRefType);
11879 
11880   // Builds the "this" pointer.
11881   ThisBuilder This;
11882 
11883   // Assign base classes.
11884   bool Invalid = false;
11885   for (auto &Base : ClassDecl->bases()) {
11886     // Form the assignment:
11887     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11888     QualType BaseType = Base.getType().getUnqualifiedType();
11889     if (!BaseType->isRecordType()) {
11890       Invalid = true;
11891       continue;
11892     }
11893 
11894     CXXCastPath BasePath;
11895     BasePath.push_back(&Base);
11896 
11897     // Construct the "from" expression, which is an implicit cast to the
11898     // appropriately-qualified base type.
11899     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11900                      VK_LValue, BasePath);
11901 
11902     // Dereference "this".
11903     DerefBuilder DerefThis(This);
11904     CastBuilder To(DerefThis,
11905                    Context.getCVRQualifiedType(
11906                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11907                    VK_LValue, BasePath);
11908 
11909     // Build the copy.
11910     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11911                                             To, From,
11912                                             /*CopyingBaseSubobject=*/true,
11913                                             /*Copying=*/true);
11914     if (Copy.isInvalid()) {
11915       CopyAssignOperator->setInvalidDecl();
11916       return;
11917     }
11918 
11919     // Success! Record the copy.
11920     Statements.push_back(Copy.getAs<Expr>());
11921   }
11922 
11923   // Assign non-static members.
11924   for (auto *Field : ClassDecl->fields()) {
11925     // FIXME: We should form some kind of AST representation for the implied
11926     // memcpy in a union copy operation.
11927     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11928       continue;
11929 
11930     if (Field->isInvalidDecl()) {
11931       Invalid = true;
11932       continue;
11933     }
11934 
11935     // Check for members of reference type; we can't copy those.
11936     if (Field->getType()->isReferenceType()) {
11937       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11938         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11939       Diag(Field->getLocation(), diag::note_declared_at);
11940       Invalid = true;
11941       continue;
11942     }
11943 
11944     // Check for members of const-qualified, non-class type.
11945     QualType BaseType = Context.getBaseElementType(Field->getType());
11946     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11947       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11948         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11949       Diag(Field->getLocation(), diag::note_declared_at);
11950       Invalid = true;
11951       continue;
11952     }
11953 
11954     // Suppress assigning zero-width bitfields.
11955     if (Field->isZeroLengthBitField(Context))
11956       continue;
11957 
11958     QualType FieldType = Field->getType().getNonReferenceType();
11959     if (FieldType->isIncompleteArrayType()) {
11960       assert(ClassDecl->hasFlexibleArrayMember() &&
11961              "Incomplete array type is not valid");
11962       continue;
11963     }
11964 
11965     // Build references to the field in the object we're copying from and to.
11966     CXXScopeSpec SS; // Intentionally empty
11967     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11968                               LookupMemberName);
11969     MemberLookup.addDecl(Field);
11970     MemberLookup.resolveKind();
11971 
11972     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11973 
11974     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11975 
11976     // Build the copy of this field.
11977     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11978                                             To, From,
11979                                             /*CopyingBaseSubobject=*/false,
11980                                             /*Copying=*/true);
11981     if (Copy.isInvalid()) {
11982       CopyAssignOperator->setInvalidDecl();
11983       return;
11984     }
11985 
11986     // Success! Record the copy.
11987     Statements.push_back(Copy.getAs<Stmt>());
11988   }
11989 
11990   if (!Invalid) {
11991     // Add a "return *this;"
11992     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11993 
11994     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11995     if (Return.isInvalid())
11996       Invalid = true;
11997     else
11998       Statements.push_back(Return.getAs<Stmt>());
11999   }
12000 
12001   if (Invalid) {
12002     CopyAssignOperator->setInvalidDecl();
12003     return;
12004   }
12005 
12006   StmtResult Body;
12007   {
12008     CompoundScopeRAII CompoundScope(*this);
12009     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12010                              /*isStmtExpr=*/false);
12011     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12012   }
12013   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12014   CopyAssignOperator->markUsed(Context);
12015 
12016   if (ASTMutationListener *L = getASTMutationListener()) {
12017     L->CompletedImplicitDefinition(CopyAssignOperator);
12018   }
12019 }
12020 
12021 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12022   assert(ClassDecl->needsImplicitMoveAssignment());
12023 
12024   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12025   if (DSM.isAlreadyBeingDeclared())
12026     return nullptr;
12027 
12028   // Note: The following rules are largely analoguous to the move
12029   // constructor rules.
12030 
12031   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12032   QualType RetType = Context.getLValueReferenceType(ArgType);
12033   ArgType = Context.getRValueReferenceType(ArgType);
12034 
12035   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12036                                                      CXXMoveAssignment,
12037                                                      false);
12038 
12039   //   An implicitly-declared move assignment operator is an inline public
12040   //   member of its class.
12041   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12042   SourceLocation ClassLoc = ClassDecl->getLocation();
12043   DeclarationNameInfo NameInfo(Name, ClassLoc);
12044   CXXMethodDecl *MoveAssignment =
12045       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12046                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12047                             /*isInline=*/true, Constexpr, SourceLocation());
12048   MoveAssignment->setAccess(AS_public);
12049   MoveAssignment->setDefaulted();
12050   MoveAssignment->setImplicit();
12051 
12052   if (getLangOpts().CUDA) {
12053     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12054                                             MoveAssignment,
12055                                             /* ConstRHS */ false,
12056                                             /* Diagnose */ false);
12057   }
12058 
12059   // Build an exception specification pointing back at this member.
12060   FunctionProtoType::ExtProtoInfo EPI =
12061       getImplicitMethodEPI(*this, MoveAssignment);
12062   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12063 
12064   // Add the parameter to the operator.
12065   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12066                                                ClassLoc, ClassLoc,
12067                                                /*Id=*/nullptr, ArgType,
12068                                                /*TInfo=*/nullptr, SC_None,
12069                                                nullptr);
12070   MoveAssignment->setParams(FromParam);
12071 
12072   MoveAssignment->setTrivial(
12073     ClassDecl->needsOverloadResolutionForMoveAssignment()
12074       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12075       : ClassDecl->hasTrivialMoveAssignment());
12076 
12077   // Note that we have added this copy-assignment operator.
12078   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12079 
12080   Scope *S = getScopeForContext(ClassDecl);
12081   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12082 
12083   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12084     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12085     SetDeclDeleted(MoveAssignment, ClassLoc);
12086   }
12087 
12088   if (S)
12089     PushOnScopeChains(MoveAssignment, S, false);
12090   ClassDecl->addDecl(MoveAssignment);
12091 
12092   return MoveAssignment;
12093 }
12094 
12095 /// Check if we're implicitly defining a move assignment operator for a class
12096 /// with virtual bases. Such a move assignment might move-assign the virtual
12097 /// base multiple times.
12098 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12099                                                SourceLocation CurrentLocation) {
12100   assert(!Class->isDependentContext() && "should not define dependent move");
12101 
12102   // Only a virtual base could get implicitly move-assigned multiple times.
12103   // Only a non-trivial move assignment can observe this. We only want to
12104   // diagnose if we implicitly define an assignment operator that assigns
12105   // two base classes, both of which move-assign the same virtual base.
12106   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12107       Class->getNumBases() < 2)
12108     return;
12109 
12110   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12111   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12112   VBaseMap VBases;
12113 
12114   for (auto &BI : Class->bases()) {
12115     Worklist.push_back(&BI);
12116     while (!Worklist.empty()) {
12117       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12118       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12119 
12120       // If the base has no non-trivial move assignment operators,
12121       // we don't care about moves from it.
12122       if (!Base->hasNonTrivialMoveAssignment())
12123         continue;
12124 
12125       // If there's nothing virtual here, skip it.
12126       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12127         continue;
12128 
12129       // If we're not actually going to call a move assignment for this base,
12130       // or the selected move assignment is trivial, skip it.
12131       Sema::SpecialMemberOverloadResult SMOR =
12132         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12133                               /*ConstArg*/false, /*VolatileArg*/false,
12134                               /*RValueThis*/true, /*ConstThis*/false,
12135                               /*VolatileThis*/false);
12136       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12137           !SMOR.getMethod()->isMoveAssignmentOperator())
12138         continue;
12139 
12140       if (BaseSpec->isVirtual()) {
12141         // We're going to move-assign this virtual base, and its move
12142         // assignment operator is not trivial. If this can happen for
12143         // multiple distinct direct bases of Class, diagnose it. (If it
12144         // only happens in one base, we'll diagnose it when synthesizing
12145         // that base class's move assignment operator.)
12146         CXXBaseSpecifier *&Existing =
12147             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12148                 .first->second;
12149         if (Existing && Existing != &BI) {
12150           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12151             << Class << Base;
12152           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
12153             << (Base->getCanonicalDecl() ==
12154                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12155             << Base << Existing->getType() << Existing->getSourceRange();
12156           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
12157             << (Base->getCanonicalDecl() ==
12158                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12159             << Base << BI.getType() << BaseSpec->getSourceRange();
12160 
12161           // Only diagnose each vbase once.
12162           Existing = nullptr;
12163         }
12164       } else {
12165         // Only walk over bases that have defaulted move assignment operators.
12166         // We assume that any user-provided move assignment operator handles
12167         // the multiple-moves-of-vbase case itself somehow.
12168         if (!SMOR.getMethod()->isDefaulted())
12169           continue;
12170 
12171         // We're going to move the base classes of Base. Add them to the list.
12172         for (auto &BI : Base->bases())
12173           Worklist.push_back(&BI);
12174       }
12175     }
12176   }
12177 }
12178 
12179 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12180                                         CXXMethodDecl *MoveAssignOperator) {
12181   assert((MoveAssignOperator->isDefaulted() &&
12182           MoveAssignOperator->isOverloadedOperator() &&
12183           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12184           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12185           !MoveAssignOperator->isDeleted()) &&
12186          "DefineImplicitMoveAssignment called for wrong function");
12187   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12188     return;
12189 
12190   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12191   if (ClassDecl->isInvalidDecl()) {
12192     MoveAssignOperator->setInvalidDecl();
12193     return;
12194   }
12195 
12196   // C++0x [class.copy]p28:
12197   //   The implicitly-defined or move assignment operator for a non-union class
12198   //   X performs memberwise move assignment of its subobjects. The direct base
12199   //   classes of X are assigned first, in the order of their declaration in the
12200   //   base-specifier-list, and then the immediate non-static data members of X
12201   //   are assigned, in the order in which they were declared in the class
12202   //   definition.
12203 
12204   // Issue a warning if our implicit move assignment operator will move
12205   // from a virtual base more than once.
12206   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12207 
12208   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12209 
12210   // The exception specification is needed because we are defining the
12211   // function.
12212   ResolveExceptionSpec(CurrentLocation,
12213                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12214 
12215   // Add a context note for diagnostics produced after this point.
12216   Scope.addContextNote(CurrentLocation);
12217 
12218   // The statements that form the synthesized function body.
12219   SmallVector<Stmt*, 8> Statements;
12220 
12221   // The parameter for the "other" object, which we are move from.
12222   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12223   QualType OtherRefType = Other->getType()->
12224       getAs<RValueReferenceType>()->getPointeeType();
12225   assert(!OtherRefType.getQualifiers() &&
12226          "Bad argument type of defaulted move assignment");
12227 
12228   // Our location for everything implicitly-generated.
12229   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
12230                            ? MoveAssignOperator->getLocEnd()
12231                            : MoveAssignOperator->getLocation();
12232 
12233   // Builds a reference to the "other" object.
12234   RefBuilder OtherRef(Other, OtherRefType);
12235   // Cast to rvalue.
12236   MoveCastBuilder MoveOther(OtherRef);
12237 
12238   // Builds the "this" pointer.
12239   ThisBuilder This;
12240 
12241   // Assign base classes.
12242   bool Invalid = false;
12243   for (auto &Base : ClassDecl->bases()) {
12244     // C++11 [class.copy]p28:
12245     //   It is unspecified whether subobjects representing virtual base classes
12246     //   are assigned more than once by the implicitly-defined copy assignment
12247     //   operator.
12248     // FIXME: Do not assign to a vbase that will be assigned by some other base
12249     // class. For a move-assignment, this can result in the vbase being moved
12250     // multiple times.
12251 
12252     // Form the assignment:
12253     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12254     QualType BaseType = Base.getType().getUnqualifiedType();
12255     if (!BaseType->isRecordType()) {
12256       Invalid = true;
12257       continue;
12258     }
12259 
12260     CXXCastPath BasePath;
12261     BasePath.push_back(&Base);
12262 
12263     // Construct the "from" expression, which is an implicit cast to the
12264     // appropriately-qualified base type.
12265     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12266 
12267     // Dereference "this".
12268     DerefBuilder DerefThis(This);
12269 
12270     // Implicitly cast "this" to the appropriately-qualified base type.
12271     CastBuilder To(DerefThis,
12272                    Context.getCVRQualifiedType(
12273                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12274                    VK_LValue, BasePath);
12275 
12276     // Build the move.
12277     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12278                                             To, From,
12279                                             /*CopyingBaseSubobject=*/true,
12280                                             /*Copying=*/false);
12281     if (Move.isInvalid()) {
12282       MoveAssignOperator->setInvalidDecl();
12283       return;
12284     }
12285 
12286     // Success! Record the move.
12287     Statements.push_back(Move.getAs<Expr>());
12288   }
12289 
12290   // Assign non-static members.
12291   for (auto *Field : ClassDecl->fields()) {
12292     // FIXME: We should form some kind of AST representation for the implied
12293     // memcpy in a union copy operation.
12294     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12295       continue;
12296 
12297     if (Field->isInvalidDecl()) {
12298       Invalid = true;
12299       continue;
12300     }
12301 
12302     // Check for members of reference type; we can't move those.
12303     if (Field->getType()->isReferenceType()) {
12304       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12305         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12306       Diag(Field->getLocation(), diag::note_declared_at);
12307       Invalid = true;
12308       continue;
12309     }
12310 
12311     // Check for members of const-qualified, non-class type.
12312     QualType BaseType = Context.getBaseElementType(Field->getType());
12313     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12314       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12315         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12316       Diag(Field->getLocation(), diag::note_declared_at);
12317       Invalid = true;
12318       continue;
12319     }
12320 
12321     // Suppress assigning zero-width bitfields.
12322     if (Field->isZeroLengthBitField(Context))
12323       continue;
12324 
12325     QualType FieldType = Field->getType().getNonReferenceType();
12326     if (FieldType->isIncompleteArrayType()) {
12327       assert(ClassDecl->hasFlexibleArrayMember() &&
12328              "Incomplete array type is not valid");
12329       continue;
12330     }
12331 
12332     // Build references to the field in the object we're copying from and to.
12333     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12334                               LookupMemberName);
12335     MemberLookup.addDecl(Field);
12336     MemberLookup.resolveKind();
12337     MemberBuilder From(MoveOther, OtherRefType,
12338                        /*IsArrow=*/false, MemberLookup);
12339     MemberBuilder To(This, getCurrentThisType(),
12340                      /*IsArrow=*/true, MemberLookup);
12341 
12342     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12343         "Member reference with rvalue base must be rvalue except for reference "
12344         "members, which aren't allowed for move assignment.");
12345 
12346     // Build the move of this field.
12347     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12348                                             To, From,
12349                                             /*CopyingBaseSubobject=*/false,
12350                                             /*Copying=*/false);
12351     if (Move.isInvalid()) {
12352       MoveAssignOperator->setInvalidDecl();
12353       return;
12354     }
12355 
12356     // Success! Record the copy.
12357     Statements.push_back(Move.getAs<Stmt>());
12358   }
12359 
12360   if (!Invalid) {
12361     // Add a "return *this;"
12362     ExprResult ThisObj =
12363         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12364 
12365     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12366     if (Return.isInvalid())
12367       Invalid = true;
12368     else
12369       Statements.push_back(Return.getAs<Stmt>());
12370   }
12371 
12372   if (Invalid) {
12373     MoveAssignOperator->setInvalidDecl();
12374     return;
12375   }
12376 
12377   StmtResult Body;
12378   {
12379     CompoundScopeRAII CompoundScope(*this);
12380     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12381                              /*isStmtExpr=*/false);
12382     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12383   }
12384   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12385   MoveAssignOperator->markUsed(Context);
12386 
12387   if (ASTMutationListener *L = getASTMutationListener()) {
12388     L->CompletedImplicitDefinition(MoveAssignOperator);
12389   }
12390 }
12391 
12392 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12393                                                     CXXRecordDecl *ClassDecl) {
12394   // C++ [class.copy]p4:
12395   //   If the class definition does not explicitly declare a copy
12396   //   constructor, one is declared implicitly.
12397   assert(ClassDecl->needsImplicitCopyConstructor());
12398 
12399   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12400   if (DSM.isAlreadyBeingDeclared())
12401     return nullptr;
12402 
12403   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12404   QualType ArgType = ClassType;
12405   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12406   if (Const)
12407     ArgType = ArgType.withConst();
12408   ArgType = Context.getLValueReferenceType(ArgType);
12409 
12410   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12411                                                      CXXCopyConstructor,
12412                                                      Const);
12413 
12414   DeclarationName Name
12415     = Context.DeclarationNames.getCXXConstructorName(
12416                                            Context.getCanonicalType(ClassType));
12417   SourceLocation ClassLoc = ClassDecl->getLocation();
12418   DeclarationNameInfo NameInfo(Name, ClassLoc);
12419 
12420   //   An implicitly-declared copy constructor is an inline public
12421   //   member of its class.
12422   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12423       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12424       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12425       Constexpr);
12426   CopyConstructor->setAccess(AS_public);
12427   CopyConstructor->setDefaulted();
12428 
12429   if (getLangOpts().CUDA) {
12430     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12431                                             CopyConstructor,
12432                                             /* ConstRHS */ Const,
12433                                             /* Diagnose */ false);
12434   }
12435 
12436   // Build an exception specification pointing back at this member.
12437   FunctionProtoType::ExtProtoInfo EPI =
12438       getImplicitMethodEPI(*this, CopyConstructor);
12439   CopyConstructor->setType(
12440       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12441 
12442   // Add the parameter to the constructor.
12443   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12444                                                ClassLoc, ClassLoc,
12445                                                /*IdentifierInfo=*/nullptr,
12446                                                ArgType, /*TInfo=*/nullptr,
12447                                                SC_None, nullptr);
12448   CopyConstructor->setParams(FromParam);
12449 
12450   CopyConstructor->setTrivial(
12451       ClassDecl->needsOverloadResolutionForCopyConstructor()
12452           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12453           : ClassDecl->hasTrivialCopyConstructor());
12454 
12455   CopyConstructor->setTrivialForCall(
12456       ClassDecl->hasAttr<TrivialABIAttr>() ||
12457       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12458            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12459              TAH_ConsiderTrivialABI)
12460            : ClassDecl->hasTrivialCopyConstructorForCall()));
12461 
12462   // Note that we have declared this constructor.
12463   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12464 
12465   Scope *S = getScopeForContext(ClassDecl);
12466   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12467 
12468   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12469     ClassDecl->setImplicitCopyConstructorIsDeleted();
12470     SetDeclDeleted(CopyConstructor, ClassLoc);
12471   }
12472 
12473   if (S)
12474     PushOnScopeChains(CopyConstructor, S, false);
12475   ClassDecl->addDecl(CopyConstructor);
12476 
12477   return CopyConstructor;
12478 }
12479 
12480 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12481                                          CXXConstructorDecl *CopyConstructor) {
12482   assert((CopyConstructor->isDefaulted() &&
12483           CopyConstructor->isCopyConstructor() &&
12484           !CopyConstructor->doesThisDeclarationHaveABody() &&
12485           !CopyConstructor->isDeleted()) &&
12486          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12487   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12488     return;
12489 
12490   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12491   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12492 
12493   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12494 
12495   // The exception specification is needed because we are defining the
12496   // function.
12497   ResolveExceptionSpec(CurrentLocation,
12498                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12499   MarkVTableUsed(CurrentLocation, ClassDecl);
12500 
12501   // Add a context note for diagnostics produced after this point.
12502   Scope.addContextNote(CurrentLocation);
12503 
12504   // C++11 [class.copy]p7:
12505   //   The [definition of an implicitly declared copy constructor] is
12506   //   deprecated if the class has a user-declared copy assignment operator
12507   //   or a user-declared destructor.
12508   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12509     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12510 
12511   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12512     CopyConstructor->setInvalidDecl();
12513   }  else {
12514     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12515                              ? CopyConstructor->getLocEnd()
12516                              : CopyConstructor->getLocation();
12517     Sema::CompoundScopeRAII CompoundScope(*this);
12518     CopyConstructor->setBody(
12519         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12520     CopyConstructor->markUsed(Context);
12521   }
12522 
12523   if (ASTMutationListener *L = getASTMutationListener()) {
12524     L->CompletedImplicitDefinition(CopyConstructor);
12525   }
12526 }
12527 
12528 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12529                                                     CXXRecordDecl *ClassDecl) {
12530   assert(ClassDecl->needsImplicitMoveConstructor());
12531 
12532   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12533   if (DSM.isAlreadyBeingDeclared())
12534     return nullptr;
12535 
12536   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12537   QualType ArgType = Context.getRValueReferenceType(ClassType);
12538 
12539   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12540                                                      CXXMoveConstructor,
12541                                                      false);
12542 
12543   DeclarationName Name
12544     = Context.DeclarationNames.getCXXConstructorName(
12545                                            Context.getCanonicalType(ClassType));
12546   SourceLocation ClassLoc = ClassDecl->getLocation();
12547   DeclarationNameInfo NameInfo(Name, ClassLoc);
12548 
12549   // C++11 [class.copy]p11:
12550   //   An implicitly-declared copy/move constructor is an inline public
12551   //   member of its class.
12552   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12553       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12554       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12555       Constexpr);
12556   MoveConstructor->setAccess(AS_public);
12557   MoveConstructor->setDefaulted();
12558 
12559   if (getLangOpts().CUDA) {
12560     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12561                                             MoveConstructor,
12562                                             /* ConstRHS */ false,
12563                                             /* Diagnose */ false);
12564   }
12565 
12566   // Build an exception specification pointing back at this member.
12567   FunctionProtoType::ExtProtoInfo EPI =
12568       getImplicitMethodEPI(*this, MoveConstructor);
12569   MoveConstructor->setType(
12570       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12571 
12572   // Add the parameter to the constructor.
12573   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12574                                                ClassLoc, ClassLoc,
12575                                                /*IdentifierInfo=*/nullptr,
12576                                                ArgType, /*TInfo=*/nullptr,
12577                                                SC_None, nullptr);
12578   MoveConstructor->setParams(FromParam);
12579 
12580   MoveConstructor->setTrivial(
12581       ClassDecl->needsOverloadResolutionForMoveConstructor()
12582           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12583           : ClassDecl->hasTrivialMoveConstructor());
12584 
12585   MoveConstructor->setTrivialForCall(
12586       ClassDecl->hasAttr<TrivialABIAttr>() ||
12587       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12588            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12589                                     TAH_ConsiderTrivialABI)
12590            : ClassDecl->hasTrivialMoveConstructorForCall()));
12591 
12592   // Note that we have declared this constructor.
12593   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12594 
12595   Scope *S = getScopeForContext(ClassDecl);
12596   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12597 
12598   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12599     ClassDecl->setImplicitMoveConstructorIsDeleted();
12600     SetDeclDeleted(MoveConstructor, ClassLoc);
12601   }
12602 
12603   if (S)
12604     PushOnScopeChains(MoveConstructor, S, false);
12605   ClassDecl->addDecl(MoveConstructor);
12606 
12607   return MoveConstructor;
12608 }
12609 
12610 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12611                                          CXXConstructorDecl *MoveConstructor) {
12612   assert((MoveConstructor->isDefaulted() &&
12613           MoveConstructor->isMoveConstructor() &&
12614           !MoveConstructor->doesThisDeclarationHaveABody() &&
12615           !MoveConstructor->isDeleted()) &&
12616          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12617   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12618     return;
12619 
12620   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12621   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12622 
12623   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12624 
12625   // The exception specification is needed because we are defining the
12626   // function.
12627   ResolveExceptionSpec(CurrentLocation,
12628                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12629   MarkVTableUsed(CurrentLocation, ClassDecl);
12630 
12631   // Add a context note for diagnostics produced after this point.
12632   Scope.addContextNote(CurrentLocation);
12633 
12634   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12635     MoveConstructor->setInvalidDecl();
12636   } else {
12637     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12638                              ? MoveConstructor->getLocEnd()
12639                              : MoveConstructor->getLocation();
12640     Sema::CompoundScopeRAII CompoundScope(*this);
12641     MoveConstructor->setBody(ActOnCompoundStmt(
12642         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12643     MoveConstructor->markUsed(Context);
12644   }
12645 
12646   if (ASTMutationListener *L = getASTMutationListener()) {
12647     L->CompletedImplicitDefinition(MoveConstructor);
12648   }
12649 }
12650 
12651 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12652   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12653 }
12654 
12655 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12656                             SourceLocation CurrentLocation,
12657                             CXXConversionDecl *Conv) {
12658   SynthesizedFunctionScope Scope(*this, Conv);
12659   assert(!Conv->getReturnType()->isUndeducedType());
12660 
12661   CXXRecordDecl *Lambda = Conv->getParent();
12662   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12663   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12664 
12665   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12666     CallOp = InstantiateFunctionDeclaration(
12667         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12668     if (!CallOp)
12669       return;
12670 
12671     Invoker = InstantiateFunctionDeclaration(
12672         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12673     if (!Invoker)
12674       return;
12675   }
12676 
12677   if (CallOp->isInvalidDecl())
12678     return;
12679 
12680   // Mark the call operator referenced (and add to pending instantiations
12681   // if necessary).
12682   // For both the conversion and static-invoker template specializations
12683   // we construct their body's in this function, so no need to add them
12684   // to the PendingInstantiations.
12685   MarkFunctionReferenced(CurrentLocation, CallOp);
12686 
12687   // Fill in the __invoke function with a dummy implementation. IR generation
12688   // will fill in the actual details. Update its type in case it contained
12689   // an 'auto'.
12690   Invoker->markUsed(Context);
12691   Invoker->setReferenced();
12692   Invoker->setType(Conv->getReturnType()->getPointeeType());
12693   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12694 
12695   // Construct the body of the conversion function { return __invoke; }.
12696   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12697                                        VK_LValue, Conv->getLocation()).get();
12698   assert(FunctionRef && "Can't refer to __invoke function?");
12699   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12700   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12701                                      Conv->getLocation()));
12702   Conv->markUsed(Context);
12703   Conv->setReferenced();
12704 
12705   if (ASTMutationListener *L = getASTMutationListener()) {
12706     L->CompletedImplicitDefinition(Conv);
12707     L->CompletedImplicitDefinition(Invoker);
12708   }
12709 }
12710 
12711 
12712 
12713 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12714        SourceLocation CurrentLocation,
12715        CXXConversionDecl *Conv)
12716 {
12717   assert(!Conv->getParent()->isGenericLambda());
12718 
12719   SynthesizedFunctionScope Scope(*this, Conv);
12720 
12721   // Copy-initialize the lambda object as needed to capture it.
12722   Expr *This = ActOnCXXThis(CurrentLocation).get();
12723   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12724 
12725   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12726                                                         Conv->getLocation(),
12727                                                         Conv, DerefThis);
12728 
12729   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12730   // behavior.  Note that only the general conversion function does this
12731   // (since it's unusable otherwise); in the case where we inline the
12732   // block literal, it has block literal lifetime semantics.
12733   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12734     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12735                                           CK_CopyAndAutoreleaseBlockObject,
12736                                           BuildBlock.get(), nullptr, VK_RValue);
12737 
12738   if (BuildBlock.isInvalid()) {
12739     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12740     Conv->setInvalidDecl();
12741     return;
12742   }
12743 
12744   // Create the return statement that returns the block from the conversion
12745   // function.
12746   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12747   if (Return.isInvalid()) {
12748     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12749     Conv->setInvalidDecl();
12750     return;
12751   }
12752 
12753   // Set the body of the conversion function.
12754   Stmt *ReturnS = Return.get();
12755   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12756                                      Conv->getLocation()));
12757   Conv->markUsed(Context);
12758 
12759   // We're done; notify the mutation listener, if any.
12760   if (ASTMutationListener *L = getASTMutationListener()) {
12761     L->CompletedImplicitDefinition(Conv);
12762   }
12763 }
12764 
12765 /// Determine whether the given list arguments contains exactly one
12766 /// "real" (non-default) argument.
12767 static bool hasOneRealArgument(MultiExprArg Args) {
12768   switch (Args.size()) {
12769   case 0:
12770     return false;
12771 
12772   default:
12773     if (!Args[1]->isDefaultArgument())
12774       return false;
12775 
12776     LLVM_FALLTHROUGH;
12777   case 1:
12778     return !Args[0]->isDefaultArgument();
12779   }
12780 
12781   return false;
12782 }
12783 
12784 ExprResult
12785 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12786                             NamedDecl *FoundDecl,
12787                             CXXConstructorDecl *Constructor,
12788                             MultiExprArg ExprArgs,
12789                             bool HadMultipleCandidates,
12790                             bool IsListInitialization,
12791                             bool IsStdInitListInitialization,
12792                             bool RequiresZeroInit,
12793                             unsigned ConstructKind,
12794                             SourceRange ParenRange) {
12795   bool Elidable = false;
12796 
12797   // C++0x [class.copy]p34:
12798   //   When certain criteria are met, an implementation is allowed to
12799   //   omit the copy/move construction of a class object, even if the
12800   //   copy/move constructor and/or destructor for the object have
12801   //   side effects. [...]
12802   //     - when a temporary class object that has not been bound to a
12803   //       reference (12.2) would be copied/moved to a class object
12804   //       with the same cv-unqualified type, the copy/move operation
12805   //       can be omitted by constructing the temporary object
12806   //       directly into the target of the omitted copy/move
12807   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12808       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12809     Expr *SubExpr = ExprArgs[0];
12810     Elidable = SubExpr->isTemporaryObject(
12811         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12812   }
12813 
12814   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12815                                FoundDecl, Constructor,
12816                                Elidable, ExprArgs, HadMultipleCandidates,
12817                                IsListInitialization,
12818                                IsStdInitListInitialization, RequiresZeroInit,
12819                                ConstructKind, ParenRange);
12820 }
12821 
12822 ExprResult
12823 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12824                             NamedDecl *FoundDecl,
12825                             CXXConstructorDecl *Constructor,
12826                             bool Elidable,
12827                             MultiExprArg ExprArgs,
12828                             bool HadMultipleCandidates,
12829                             bool IsListInitialization,
12830                             bool IsStdInitListInitialization,
12831                             bool RequiresZeroInit,
12832                             unsigned ConstructKind,
12833                             SourceRange ParenRange) {
12834   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12835     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12836     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12837       return ExprError();
12838   }
12839 
12840   return BuildCXXConstructExpr(
12841       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12842       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12843       RequiresZeroInit, ConstructKind, ParenRange);
12844 }
12845 
12846 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12847 /// including handling of its default argument expressions.
12848 ExprResult
12849 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12850                             CXXConstructorDecl *Constructor,
12851                             bool Elidable,
12852                             MultiExprArg ExprArgs,
12853                             bool HadMultipleCandidates,
12854                             bool IsListInitialization,
12855                             bool IsStdInitListInitialization,
12856                             bool RequiresZeroInit,
12857                             unsigned ConstructKind,
12858                             SourceRange ParenRange) {
12859   assert(declaresSameEntity(
12860              Constructor->getParent(),
12861              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12862          "given constructor for wrong type");
12863   MarkFunctionReferenced(ConstructLoc, Constructor);
12864   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12865     return ExprError();
12866 
12867   return CXXConstructExpr::Create(
12868       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12869       ExprArgs, HadMultipleCandidates, IsListInitialization,
12870       IsStdInitListInitialization, RequiresZeroInit,
12871       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12872       ParenRange);
12873 }
12874 
12875 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12876   assert(Field->hasInClassInitializer());
12877 
12878   // If we already have the in-class initializer nothing needs to be done.
12879   if (Field->getInClassInitializer())
12880     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12881 
12882   // If we might have already tried and failed to instantiate, don't try again.
12883   if (Field->isInvalidDecl())
12884     return ExprError();
12885 
12886   // Maybe we haven't instantiated the in-class initializer. Go check the
12887   // pattern FieldDecl to see if it has one.
12888   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12889 
12890   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12891     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12892     DeclContext::lookup_result Lookup =
12893         ClassPattern->lookup(Field->getDeclName());
12894 
12895     // Lookup can return at most two results: the pattern for the field, or the
12896     // injected class name of the parent record. No other member can have the
12897     // same name as the field.
12898     // In modules mode, lookup can return multiple results (coming from
12899     // different modules).
12900     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12901            "more than two lookup results for field name");
12902     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12903     if (!Pattern) {
12904       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12905              "cannot have other non-field member with same name");
12906       for (auto L : Lookup)
12907         if (isa<FieldDecl>(L)) {
12908           Pattern = cast<FieldDecl>(L);
12909           break;
12910         }
12911       assert(Pattern && "We must have set the Pattern!");
12912     }
12913 
12914     if (!Pattern->hasInClassInitializer() ||
12915         InstantiateInClassInitializer(Loc, Field, Pattern,
12916                                       getTemplateInstantiationArgs(Field))) {
12917       // Don't diagnose this again.
12918       Field->setInvalidDecl();
12919       return ExprError();
12920     }
12921     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12922   }
12923 
12924   // DR1351:
12925   //   If the brace-or-equal-initializer of a non-static data member
12926   //   invokes a defaulted default constructor of its class or of an
12927   //   enclosing class in a potentially evaluated subexpression, the
12928   //   program is ill-formed.
12929   //
12930   // This resolution is unworkable: the exception specification of the
12931   // default constructor can be needed in an unevaluated context, in
12932   // particular, in the operand of a noexcept-expression, and we can be
12933   // unable to compute an exception specification for an enclosed class.
12934   //
12935   // Any attempt to resolve the exception specification of a defaulted default
12936   // constructor before the initializer is lexically complete will ultimately
12937   // come here at which point we can diagnose it.
12938   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12939   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12940       << OutermostClass << Field;
12941   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12942   // Recover by marking the field invalid, unless we're in a SFINAE context.
12943   if (!isSFINAEContext())
12944     Field->setInvalidDecl();
12945   return ExprError();
12946 }
12947 
12948 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12949   if (VD->isInvalidDecl()) return;
12950 
12951   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12952   if (ClassDecl->isInvalidDecl()) return;
12953   if (ClassDecl->hasIrrelevantDestructor()) return;
12954   if (ClassDecl->isDependentContext()) return;
12955 
12956   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12957   MarkFunctionReferenced(VD->getLocation(), Destructor);
12958   CheckDestructorAccess(VD->getLocation(), Destructor,
12959                         PDiag(diag::err_access_dtor_var)
12960                         << VD->getDeclName()
12961                         << VD->getType());
12962   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12963 
12964   if (Destructor->isTrivial()) return;
12965   if (!VD->hasGlobalStorage()) return;
12966 
12967   // Emit warning for non-trivial dtor in global scope (a real global,
12968   // class-static, function-static).
12969   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12970 
12971   // TODO: this should be re-enabled for static locals by !CXAAtExit
12972   if (!VD->isStaticLocal())
12973     Diag(VD->getLocation(), diag::warn_global_destructor);
12974 }
12975 
12976 /// Given a constructor and the set of arguments provided for the
12977 /// constructor, convert the arguments and add any required default arguments
12978 /// to form a proper call to this constructor.
12979 ///
12980 /// \returns true if an error occurred, false otherwise.
12981 bool
12982 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12983                               MultiExprArg ArgsPtr,
12984                               SourceLocation Loc,
12985                               SmallVectorImpl<Expr*> &ConvertedArgs,
12986                               bool AllowExplicit,
12987                               bool IsListInitialization) {
12988   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12989   unsigned NumArgs = ArgsPtr.size();
12990   Expr **Args = ArgsPtr.data();
12991 
12992   const FunctionProtoType *Proto
12993     = Constructor->getType()->getAs<FunctionProtoType>();
12994   assert(Proto && "Constructor without a prototype?");
12995   unsigned NumParams = Proto->getNumParams();
12996 
12997   // If too few arguments are available, we'll fill in the rest with defaults.
12998   if (NumArgs < NumParams)
12999     ConvertedArgs.reserve(NumParams);
13000   else
13001     ConvertedArgs.reserve(NumArgs);
13002 
13003   VariadicCallType CallType =
13004     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13005   SmallVector<Expr *, 8> AllArgs;
13006   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13007                                         Proto, 0,
13008                                         llvm::makeArrayRef(Args, NumArgs),
13009                                         AllArgs,
13010                                         CallType, AllowExplicit,
13011                                         IsListInitialization);
13012   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13013 
13014   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13015 
13016   CheckConstructorCall(Constructor,
13017                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13018                        Proto, Loc);
13019 
13020   return Invalid;
13021 }
13022 
13023 static inline bool
13024 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13025                                        const FunctionDecl *FnDecl) {
13026   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13027   if (isa<NamespaceDecl>(DC)) {
13028     return SemaRef.Diag(FnDecl->getLocation(),
13029                         diag::err_operator_new_delete_declared_in_namespace)
13030       << FnDecl->getDeclName();
13031   }
13032 
13033   if (isa<TranslationUnitDecl>(DC) &&
13034       FnDecl->getStorageClass() == SC_Static) {
13035     return SemaRef.Diag(FnDecl->getLocation(),
13036                         diag::err_operator_new_delete_declared_static)
13037       << FnDecl->getDeclName();
13038   }
13039 
13040   return false;
13041 }
13042 
13043 static QualType
13044 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13045   QualType QTy = PtrTy->getPointeeType();
13046   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13047   return SemaRef.Context.getPointerType(QTy);
13048 }
13049 
13050 static inline bool
13051 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13052                             CanQualType ExpectedResultType,
13053                             CanQualType ExpectedFirstParamType,
13054                             unsigned DependentParamTypeDiag,
13055                             unsigned InvalidParamTypeDiag) {
13056   QualType ResultType =
13057       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13058 
13059   // Check that the result type is not dependent.
13060   if (ResultType->isDependentType())
13061     return SemaRef.Diag(FnDecl->getLocation(),
13062                         diag::err_operator_new_delete_dependent_result_type)
13063     << FnDecl->getDeclName() << ExpectedResultType;
13064 
13065   // OpenCL C++: the operator is valid on any address space.
13066   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13067     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13068       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13069     }
13070   }
13071 
13072   // Check that the result type is what we expect.
13073   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13074     return SemaRef.Diag(FnDecl->getLocation(),
13075                         diag::err_operator_new_delete_invalid_result_type)
13076     << FnDecl->getDeclName() << ExpectedResultType;
13077 
13078   // A function template must have at least 2 parameters.
13079   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13080     return SemaRef.Diag(FnDecl->getLocation(),
13081                       diag::err_operator_new_delete_template_too_few_parameters)
13082         << FnDecl->getDeclName();
13083 
13084   // The function decl must have at least 1 parameter.
13085   if (FnDecl->getNumParams() == 0)
13086     return SemaRef.Diag(FnDecl->getLocation(),
13087                         diag::err_operator_new_delete_too_few_parameters)
13088       << FnDecl->getDeclName();
13089 
13090   // Check the first parameter type is not dependent.
13091   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13092   if (FirstParamType->isDependentType())
13093     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13094       << FnDecl->getDeclName() << ExpectedFirstParamType;
13095 
13096   // Check that the first parameter type is what we expect.
13097   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13098     // OpenCL C++: the operator is valid on any address space.
13099     if (auto *PtrTy =
13100             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13101       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13102     }
13103   }
13104   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13105       ExpectedFirstParamType)
13106     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13107     << FnDecl->getDeclName() << ExpectedFirstParamType;
13108 
13109   return false;
13110 }
13111 
13112 static bool
13113 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13114   // C++ [basic.stc.dynamic.allocation]p1:
13115   //   A program is ill-formed if an allocation function is declared in a
13116   //   namespace scope other than global scope or declared static in global
13117   //   scope.
13118   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13119     return true;
13120 
13121   CanQualType SizeTy =
13122     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13123 
13124   // C++ [basic.stc.dynamic.allocation]p1:
13125   //  The return type shall be void*. The first parameter shall have type
13126   //  std::size_t.
13127   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13128                                   SizeTy,
13129                                   diag::err_operator_new_dependent_param_type,
13130                                   diag::err_operator_new_param_type))
13131     return true;
13132 
13133   // C++ [basic.stc.dynamic.allocation]p1:
13134   //  The first parameter shall not have an associated default argument.
13135   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13136     return SemaRef.Diag(FnDecl->getLocation(),
13137                         diag::err_operator_new_default_arg)
13138       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13139 
13140   return false;
13141 }
13142 
13143 static bool
13144 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13145   // C++ [basic.stc.dynamic.deallocation]p1:
13146   //   A program is ill-formed if deallocation functions are declared in a
13147   //   namespace scope other than global scope or declared static in global
13148   //   scope.
13149   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13150     return true;
13151 
13152   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13153 
13154   // C++ P0722:
13155   //   Within a class C, the first parameter of a destroying operator delete
13156   //   shall be of type C *. The first parameter of any other deallocation
13157   //   function shall be of type void *.
13158   CanQualType ExpectedFirstParamType =
13159       MD && MD->isDestroyingOperatorDelete()
13160           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13161                 SemaRef.Context.getRecordType(MD->getParent())))
13162           : SemaRef.Context.VoidPtrTy;
13163 
13164   // C++ [basic.stc.dynamic.deallocation]p2:
13165   //   Each deallocation function shall return void
13166   if (CheckOperatorNewDeleteTypes(
13167           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13168           diag::err_operator_delete_dependent_param_type,
13169           diag::err_operator_delete_param_type))
13170     return true;
13171 
13172   // C++ P0722:
13173   //   A destroying operator delete shall be a usual deallocation function.
13174   if (MD && !MD->getParent()->isDependentContext() &&
13175       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13176     SemaRef.Diag(MD->getLocation(),
13177                  diag::err_destroying_operator_delete_not_usual);
13178     return true;
13179   }
13180 
13181   return false;
13182 }
13183 
13184 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13185 /// of this overloaded operator is well-formed. If so, returns false;
13186 /// otherwise, emits appropriate diagnostics and returns true.
13187 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13188   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13189          "Expected an overloaded operator declaration");
13190 
13191   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13192 
13193   // C++ [over.oper]p5:
13194   //   The allocation and deallocation functions, operator new,
13195   //   operator new[], operator delete and operator delete[], are
13196   //   described completely in 3.7.3. The attributes and restrictions
13197   //   found in the rest of this subclause do not apply to them unless
13198   //   explicitly stated in 3.7.3.
13199   if (Op == OO_Delete || Op == OO_Array_Delete)
13200     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13201 
13202   if (Op == OO_New || Op == OO_Array_New)
13203     return CheckOperatorNewDeclaration(*this, FnDecl);
13204 
13205   // C++ [over.oper]p6:
13206   //   An operator function shall either be a non-static member
13207   //   function or be a non-member function and have at least one
13208   //   parameter whose type is a class, a reference to a class, an
13209   //   enumeration, or a reference to an enumeration.
13210   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13211     if (MethodDecl->isStatic())
13212       return Diag(FnDecl->getLocation(),
13213                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13214   } else {
13215     bool ClassOrEnumParam = false;
13216     for (auto Param : FnDecl->parameters()) {
13217       QualType ParamType = Param->getType().getNonReferenceType();
13218       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13219           ParamType->isEnumeralType()) {
13220         ClassOrEnumParam = true;
13221         break;
13222       }
13223     }
13224 
13225     if (!ClassOrEnumParam)
13226       return Diag(FnDecl->getLocation(),
13227                   diag::err_operator_overload_needs_class_or_enum)
13228         << FnDecl->getDeclName();
13229   }
13230 
13231   // C++ [over.oper]p8:
13232   //   An operator function cannot have default arguments (8.3.6),
13233   //   except where explicitly stated below.
13234   //
13235   // Only the function-call operator allows default arguments
13236   // (C++ [over.call]p1).
13237   if (Op != OO_Call) {
13238     for (auto Param : FnDecl->parameters()) {
13239       if (Param->hasDefaultArg())
13240         return Diag(Param->getLocation(),
13241                     diag::err_operator_overload_default_arg)
13242           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13243     }
13244   }
13245 
13246   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13247     { false, false, false }
13248 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13249     , { Unary, Binary, MemberOnly }
13250 #include "clang/Basic/OperatorKinds.def"
13251   };
13252 
13253   bool CanBeUnaryOperator = OperatorUses[Op][0];
13254   bool CanBeBinaryOperator = OperatorUses[Op][1];
13255   bool MustBeMemberOperator = OperatorUses[Op][2];
13256 
13257   // C++ [over.oper]p8:
13258   //   [...] Operator functions cannot have more or fewer parameters
13259   //   than the number required for the corresponding operator, as
13260   //   described in the rest of this subclause.
13261   unsigned NumParams = FnDecl->getNumParams()
13262                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13263   if (Op != OO_Call &&
13264       ((NumParams == 1 && !CanBeUnaryOperator) ||
13265        (NumParams == 2 && !CanBeBinaryOperator) ||
13266        (NumParams < 1) || (NumParams > 2))) {
13267     // We have the wrong number of parameters.
13268     unsigned ErrorKind;
13269     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13270       ErrorKind = 2;  // 2 -> unary or binary.
13271     } else if (CanBeUnaryOperator) {
13272       ErrorKind = 0;  // 0 -> unary
13273     } else {
13274       assert(CanBeBinaryOperator &&
13275              "All non-call overloaded operators are unary or binary!");
13276       ErrorKind = 1;  // 1 -> binary
13277     }
13278 
13279     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13280       << FnDecl->getDeclName() << NumParams << ErrorKind;
13281   }
13282 
13283   // Overloaded operators other than operator() cannot be variadic.
13284   if (Op != OO_Call &&
13285       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13286     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13287       << FnDecl->getDeclName();
13288   }
13289 
13290   // Some operators must be non-static member functions.
13291   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13292     return Diag(FnDecl->getLocation(),
13293                 diag::err_operator_overload_must_be_member)
13294       << FnDecl->getDeclName();
13295   }
13296 
13297   // C++ [over.inc]p1:
13298   //   The user-defined function called operator++ implements the
13299   //   prefix and postfix ++ operator. If this function is a member
13300   //   function with no parameters, or a non-member function with one
13301   //   parameter of class or enumeration type, it defines the prefix
13302   //   increment operator ++ for objects of that type. If the function
13303   //   is a member function with one parameter (which shall be of type
13304   //   int) or a non-member function with two parameters (the second
13305   //   of which shall be of type int), it defines the postfix
13306   //   increment operator ++ for objects of that type.
13307   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13308     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13309     QualType ParamType = LastParam->getType();
13310 
13311     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13312         !ParamType->isDependentType())
13313       return Diag(LastParam->getLocation(),
13314                   diag::err_operator_overload_post_incdec_must_be_int)
13315         << LastParam->getType() << (Op == OO_MinusMinus);
13316   }
13317 
13318   return false;
13319 }
13320 
13321 static bool
13322 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13323                                           FunctionTemplateDecl *TpDecl) {
13324   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13325 
13326   // Must have one or two template parameters.
13327   if (TemplateParams->size() == 1) {
13328     NonTypeTemplateParmDecl *PmDecl =
13329         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13330 
13331     // The template parameter must be a char parameter pack.
13332     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13333         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13334       return false;
13335 
13336   } else if (TemplateParams->size() == 2) {
13337     TemplateTypeParmDecl *PmType =
13338         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13339     NonTypeTemplateParmDecl *PmArgs =
13340         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13341 
13342     // The second template parameter must be a parameter pack with the
13343     // first template parameter as its type.
13344     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13345         PmArgs->isTemplateParameterPack()) {
13346       const TemplateTypeParmType *TArgs =
13347           PmArgs->getType()->getAs<TemplateTypeParmType>();
13348       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13349           TArgs->getIndex() == PmType->getIndex()) {
13350         if (!SemaRef.inTemplateInstantiation())
13351           SemaRef.Diag(TpDecl->getLocation(),
13352                        diag::ext_string_literal_operator_template);
13353         return false;
13354       }
13355     }
13356   }
13357 
13358   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13359                diag::err_literal_operator_template)
13360       << TpDecl->getTemplateParameters()->getSourceRange();
13361   return true;
13362 }
13363 
13364 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13365 /// of this literal operator function is well-formed. If so, returns
13366 /// false; otherwise, emits appropriate diagnostics and returns true.
13367 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13368   if (isa<CXXMethodDecl>(FnDecl)) {
13369     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13370       << FnDecl->getDeclName();
13371     return true;
13372   }
13373 
13374   if (FnDecl->isExternC()) {
13375     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13376     if (const LinkageSpecDecl *LSD =
13377             FnDecl->getDeclContext()->getExternCContext())
13378       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13379     return true;
13380   }
13381 
13382   // This might be the definition of a literal operator template.
13383   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13384 
13385   // This might be a specialization of a literal operator template.
13386   if (!TpDecl)
13387     TpDecl = FnDecl->getPrimaryTemplate();
13388 
13389   // template <char...> type operator "" name() and
13390   // template <class T, T...> type operator "" name() are the only valid
13391   // template signatures, and the only valid signatures with no parameters.
13392   if (TpDecl) {
13393     if (FnDecl->param_size() != 0) {
13394       Diag(FnDecl->getLocation(),
13395            diag::err_literal_operator_template_with_params);
13396       return true;
13397     }
13398 
13399     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13400       return true;
13401 
13402   } else if (FnDecl->param_size() == 1) {
13403     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13404 
13405     QualType ParamType = Param->getType().getUnqualifiedType();
13406 
13407     // Only unsigned long long int, long double, any character type, and const
13408     // char * are allowed as the only parameters.
13409     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13410         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13411         Context.hasSameType(ParamType, Context.CharTy) ||
13412         Context.hasSameType(ParamType, Context.WideCharTy) ||
13413         Context.hasSameType(ParamType, Context.Char8Ty) ||
13414         Context.hasSameType(ParamType, Context.Char16Ty) ||
13415         Context.hasSameType(ParamType, Context.Char32Ty)) {
13416     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13417       QualType InnerType = Ptr->getPointeeType();
13418 
13419       // Pointer parameter must be a const char *.
13420       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13421                                 Context.CharTy) &&
13422             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13423         Diag(Param->getSourceRange().getBegin(),
13424              diag::err_literal_operator_param)
13425             << ParamType << "'const char *'" << Param->getSourceRange();
13426         return true;
13427       }
13428 
13429     } else if (ParamType->isRealFloatingType()) {
13430       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13431           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13432       return true;
13433 
13434     } else if (ParamType->isIntegerType()) {
13435       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13436           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13437       return true;
13438 
13439     } else {
13440       Diag(Param->getSourceRange().getBegin(),
13441            diag::err_literal_operator_invalid_param)
13442           << ParamType << Param->getSourceRange();
13443       return true;
13444     }
13445 
13446   } else if (FnDecl->param_size() == 2) {
13447     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13448 
13449     // First, verify that the first parameter is correct.
13450 
13451     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13452 
13453     // Two parameter function must have a pointer to const as a
13454     // first parameter; let's strip those qualifiers.
13455     const PointerType *PT = FirstParamType->getAs<PointerType>();
13456 
13457     if (!PT) {
13458       Diag((*Param)->getSourceRange().getBegin(),
13459            diag::err_literal_operator_param)
13460           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13461       return true;
13462     }
13463 
13464     QualType PointeeType = PT->getPointeeType();
13465     // First parameter must be const
13466     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13467       Diag((*Param)->getSourceRange().getBegin(),
13468            diag::err_literal_operator_param)
13469           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13470       return true;
13471     }
13472 
13473     QualType InnerType = PointeeType.getUnqualifiedType();
13474     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13475     // const char32_t* are allowed as the first parameter to a two-parameter
13476     // function
13477     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13478           Context.hasSameType(InnerType, Context.WideCharTy) ||
13479           Context.hasSameType(InnerType, Context.Char8Ty) ||
13480           Context.hasSameType(InnerType, Context.Char16Ty) ||
13481           Context.hasSameType(InnerType, Context.Char32Ty))) {
13482       Diag((*Param)->getSourceRange().getBegin(),
13483            diag::err_literal_operator_param)
13484           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13485       return true;
13486     }
13487 
13488     // Move on to the second and final parameter.
13489     ++Param;
13490 
13491     // The second parameter must be a std::size_t.
13492     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13493     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13494       Diag((*Param)->getSourceRange().getBegin(),
13495            diag::err_literal_operator_param)
13496           << SecondParamType << Context.getSizeType()
13497           << (*Param)->getSourceRange();
13498       return true;
13499     }
13500   } else {
13501     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13502     return true;
13503   }
13504 
13505   // Parameters are good.
13506 
13507   // A parameter-declaration-clause containing a default argument is not
13508   // equivalent to any of the permitted forms.
13509   for (auto Param : FnDecl->parameters()) {
13510     if (Param->hasDefaultArg()) {
13511       Diag(Param->getDefaultArgRange().getBegin(),
13512            diag::err_literal_operator_default_argument)
13513         << Param->getDefaultArgRange();
13514       break;
13515     }
13516   }
13517 
13518   StringRef LiteralName
13519     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13520   if (LiteralName[0] != '_' &&
13521       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13522     // C++11 [usrlit.suffix]p1:
13523     //   Literal suffix identifiers that do not start with an underscore
13524     //   are reserved for future standardization.
13525     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13526       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13527   }
13528 
13529   return false;
13530 }
13531 
13532 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13533 /// linkage specification, including the language and (if present)
13534 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13535 /// language string literal. LBraceLoc, if valid, provides the location of
13536 /// the '{' brace. Otherwise, this linkage specification does not
13537 /// have any braces.
13538 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13539                                            Expr *LangStr,
13540                                            SourceLocation LBraceLoc) {
13541   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13542   if (!Lit->isAscii()) {
13543     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13544       << LangStr->getSourceRange();
13545     return nullptr;
13546   }
13547 
13548   StringRef Lang = Lit->getString();
13549   LinkageSpecDecl::LanguageIDs Language;
13550   if (Lang == "C")
13551     Language = LinkageSpecDecl::lang_c;
13552   else if (Lang == "C++")
13553     Language = LinkageSpecDecl::lang_cxx;
13554   else {
13555     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13556       << LangStr->getSourceRange();
13557     return nullptr;
13558   }
13559 
13560   // FIXME: Add all the various semantics of linkage specifications
13561 
13562   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13563                                                LangStr->getExprLoc(), Language,
13564                                                LBraceLoc.isValid());
13565   CurContext->addDecl(D);
13566   PushDeclContext(S, D);
13567   return D;
13568 }
13569 
13570 /// ActOnFinishLinkageSpecification - Complete the definition of
13571 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13572 /// valid, it's the position of the closing '}' brace in a linkage
13573 /// specification that uses braces.
13574 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13575                                             Decl *LinkageSpec,
13576                                             SourceLocation RBraceLoc) {
13577   if (RBraceLoc.isValid()) {
13578     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13579     LSDecl->setRBraceLoc(RBraceLoc);
13580   }
13581   PopDeclContext();
13582   return LinkageSpec;
13583 }
13584 
13585 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13586                                   const ParsedAttributesView &AttrList,
13587                                   SourceLocation SemiLoc) {
13588   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13589   // Attribute declarations appertain to empty declaration so we handle
13590   // them here.
13591   ProcessDeclAttributeList(S, ED, AttrList);
13592 
13593   CurContext->addDecl(ED);
13594   return ED;
13595 }
13596 
13597 /// Perform semantic analysis for the variable declaration that
13598 /// occurs within a C++ catch clause, returning the newly-created
13599 /// variable.
13600 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13601                                          TypeSourceInfo *TInfo,
13602                                          SourceLocation StartLoc,
13603                                          SourceLocation Loc,
13604                                          IdentifierInfo *Name) {
13605   bool Invalid = false;
13606   QualType ExDeclType = TInfo->getType();
13607 
13608   // Arrays and functions decay.
13609   if (ExDeclType->isArrayType())
13610     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13611   else if (ExDeclType->isFunctionType())
13612     ExDeclType = Context.getPointerType(ExDeclType);
13613 
13614   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13615   // The exception-declaration shall not denote a pointer or reference to an
13616   // incomplete type, other than [cv] void*.
13617   // N2844 forbids rvalue references.
13618   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13619     Diag(Loc, diag::err_catch_rvalue_ref);
13620     Invalid = true;
13621   }
13622 
13623   if (ExDeclType->isVariablyModifiedType()) {
13624     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13625     Invalid = true;
13626   }
13627 
13628   QualType BaseType = ExDeclType;
13629   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13630   unsigned DK = diag::err_catch_incomplete;
13631   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13632     BaseType = Ptr->getPointeeType();
13633     Mode = 1;
13634     DK = diag::err_catch_incomplete_ptr;
13635   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13636     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13637     BaseType = Ref->getPointeeType();
13638     Mode = 2;
13639     DK = diag::err_catch_incomplete_ref;
13640   }
13641   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13642       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13643     Invalid = true;
13644 
13645   if (!Invalid && !ExDeclType->isDependentType() &&
13646       RequireNonAbstractType(Loc, ExDeclType,
13647                              diag::err_abstract_type_in_decl,
13648                              AbstractVariableType))
13649     Invalid = true;
13650 
13651   // Only the non-fragile NeXT runtime currently supports C++ catches
13652   // of ObjC types, and no runtime supports catching ObjC types by value.
13653   if (!Invalid && getLangOpts().ObjC1) {
13654     QualType T = ExDeclType;
13655     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13656       T = RT->getPointeeType();
13657 
13658     if (T->isObjCObjectType()) {
13659       Diag(Loc, diag::err_objc_object_catch);
13660       Invalid = true;
13661     } else if (T->isObjCObjectPointerType()) {
13662       // FIXME: should this be a test for macosx-fragile specifically?
13663       if (getLangOpts().ObjCRuntime.isFragile())
13664         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13665     }
13666   }
13667 
13668   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13669                                     ExDeclType, TInfo, SC_None);
13670   ExDecl->setExceptionVariable(true);
13671 
13672   // In ARC, infer 'retaining' for variables of retainable type.
13673   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13674     Invalid = true;
13675 
13676   if (!Invalid && !ExDeclType->isDependentType()) {
13677     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13678       // Insulate this from anything else we might currently be parsing.
13679       EnterExpressionEvaluationContext scope(
13680           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13681 
13682       // C++ [except.handle]p16:
13683       //   The object declared in an exception-declaration or, if the
13684       //   exception-declaration does not specify a name, a temporary (12.2) is
13685       //   copy-initialized (8.5) from the exception object. [...]
13686       //   The object is destroyed when the handler exits, after the destruction
13687       //   of any automatic objects initialized within the handler.
13688       //
13689       // We just pretend to initialize the object with itself, then make sure
13690       // it can be destroyed later.
13691       QualType initType = Context.getExceptionObjectType(ExDeclType);
13692 
13693       InitializedEntity entity =
13694         InitializedEntity::InitializeVariable(ExDecl);
13695       InitializationKind initKind =
13696         InitializationKind::CreateCopy(Loc, SourceLocation());
13697 
13698       Expr *opaqueValue =
13699         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13700       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13701       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13702       if (result.isInvalid())
13703         Invalid = true;
13704       else {
13705         // If the constructor used was non-trivial, set this as the
13706         // "initializer".
13707         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13708         if (!construct->getConstructor()->isTrivial()) {
13709           Expr *init = MaybeCreateExprWithCleanups(construct);
13710           ExDecl->setInit(init);
13711         }
13712 
13713         // And make sure it's destructable.
13714         FinalizeVarWithDestructor(ExDecl, recordType);
13715       }
13716     }
13717   }
13718 
13719   if (Invalid)
13720     ExDecl->setInvalidDecl();
13721 
13722   return ExDecl;
13723 }
13724 
13725 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13726 /// handler.
13727 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13728   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13729   bool Invalid = D.isInvalidType();
13730 
13731   // Check for unexpanded parameter packs.
13732   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13733                                       UPPC_ExceptionType)) {
13734     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13735                                              D.getIdentifierLoc());
13736     Invalid = true;
13737   }
13738 
13739   IdentifierInfo *II = D.getIdentifier();
13740   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13741                                              LookupOrdinaryName,
13742                                              ForVisibleRedeclaration)) {
13743     // The scope should be freshly made just for us. There is just no way
13744     // it contains any previous declaration, except for function parameters in
13745     // a function-try-block's catch statement.
13746     assert(!S->isDeclScope(PrevDecl));
13747     if (isDeclInScope(PrevDecl, CurContext, S)) {
13748       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13749         << D.getIdentifier();
13750       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13751       Invalid = true;
13752     } else if (PrevDecl->isTemplateParameter())
13753       // Maybe we will complain about the shadowed template parameter.
13754       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13755   }
13756 
13757   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13758     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13759       << D.getCXXScopeSpec().getRange();
13760     Invalid = true;
13761   }
13762 
13763   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13764                                               D.getLocStart(),
13765                                               D.getIdentifierLoc(),
13766                                               D.getIdentifier());
13767   if (Invalid)
13768     ExDecl->setInvalidDecl();
13769 
13770   // Add the exception declaration into this scope.
13771   if (II)
13772     PushOnScopeChains(ExDecl, S);
13773   else
13774     CurContext->addDecl(ExDecl);
13775 
13776   ProcessDeclAttributes(S, ExDecl, D);
13777   return ExDecl;
13778 }
13779 
13780 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13781                                          Expr *AssertExpr,
13782                                          Expr *AssertMessageExpr,
13783                                          SourceLocation RParenLoc) {
13784   StringLiteral *AssertMessage =
13785       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13786 
13787   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13788     return nullptr;
13789 
13790   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13791                                       AssertMessage, RParenLoc, false);
13792 }
13793 
13794 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13795                                          Expr *AssertExpr,
13796                                          StringLiteral *AssertMessage,
13797                                          SourceLocation RParenLoc,
13798                                          bool Failed) {
13799   assert(AssertExpr != nullptr && "Expected non-null condition");
13800   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13801       !Failed) {
13802     // In a static_assert-declaration, the constant-expression shall be a
13803     // constant expression that can be contextually converted to bool.
13804     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13805     if (Converted.isInvalid())
13806       Failed = true;
13807 
13808     llvm::APSInt Cond;
13809     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13810           diag::err_static_assert_expression_is_not_constant,
13811           /*AllowFold=*/false).isInvalid())
13812       Failed = true;
13813 
13814     if (!Failed && !Cond) {
13815       SmallString<256> MsgBuffer;
13816       llvm::raw_svector_ostream Msg(MsgBuffer);
13817       if (AssertMessage)
13818         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13819 
13820       Expr *InnerCond = nullptr;
13821       std::string InnerCondDescription;
13822       std::tie(InnerCond, InnerCondDescription) =
13823         findFailedBooleanCondition(Converted.get(),
13824                                    /*AllowTopLevelCond=*/false);
13825       if (InnerCond) {
13826         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13827           << InnerCondDescription << !AssertMessage
13828           << Msg.str() << InnerCond->getSourceRange();
13829       } else {
13830         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13831           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13832       }
13833       Failed = true;
13834     }
13835   }
13836 
13837   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13838                                                   /*DiscardedValue*/false,
13839                                                   /*IsConstexpr*/true);
13840   if (FullAssertExpr.isInvalid())
13841     Failed = true;
13842   else
13843     AssertExpr = FullAssertExpr.get();
13844 
13845   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13846                                         AssertExpr, AssertMessage, RParenLoc,
13847                                         Failed);
13848 
13849   CurContext->addDecl(Decl);
13850   return Decl;
13851 }
13852 
13853 /// Perform semantic analysis of the given friend type declaration.
13854 ///
13855 /// \returns A friend declaration that.
13856 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13857                                       SourceLocation FriendLoc,
13858                                       TypeSourceInfo *TSInfo) {
13859   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13860 
13861   QualType T = TSInfo->getType();
13862   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13863 
13864   // C++03 [class.friend]p2:
13865   //   An elaborated-type-specifier shall be used in a friend declaration
13866   //   for a class.*
13867   //
13868   //   * The class-key of the elaborated-type-specifier is required.
13869   if (!CodeSynthesisContexts.empty()) {
13870     // Do not complain about the form of friend template types during any kind
13871     // of code synthesis. For template instantiation, we will have complained
13872     // when the template was defined.
13873   } else {
13874     if (!T->isElaboratedTypeSpecifier()) {
13875       // If we evaluated the type to a record type, suggest putting
13876       // a tag in front.
13877       if (const RecordType *RT = T->getAs<RecordType>()) {
13878         RecordDecl *RD = RT->getDecl();
13879 
13880         SmallString<16> InsertionText(" ");
13881         InsertionText += RD->getKindName();
13882 
13883         Diag(TypeRange.getBegin(),
13884              getLangOpts().CPlusPlus11 ?
13885                diag::warn_cxx98_compat_unelaborated_friend_type :
13886                diag::ext_unelaborated_friend_type)
13887           << (unsigned) RD->getTagKind()
13888           << T
13889           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13890                                         InsertionText);
13891       } else {
13892         Diag(FriendLoc,
13893              getLangOpts().CPlusPlus11 ?
13894                diag::warn_cxx98_compat_nonclass_type_friend :
13895                diag::ext_nonclass_type_friend)
13896           << T
13897           << TypeRange;
13898       }
13899     } else if (T->getAs<EnumType>()) {
13900       Diag(FriendLoc,
13901            getLangOpts().CPlusPlus11 ?
13902              diag::warn_cxx98_compat_enum_friend :
13903              diag::ext_enum_friend)
13904         << T
13905         << TypeRange;
13906     }
13907 
13908     // C++11 [class.friend]p3:
13909     //   A friend declaration that does not declare a function shall have one
13910     //   of the following forms:
13911     //     friend elaborated-type-specifier ;
13912     //     friend simple-type-specifier ;
13913     //     friend typename-specifier ;
13914     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13915       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13916   }
13917 
13918   //   If the type specifier in a friend declaration designates a (possibly
13919   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13920   //   the friend declaration is ignored.
13921   return FriendDecl::Create(Context, CurContext,
13922                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13923                             FriendLoc);
13924 }
13925 
13926 /// Handle a friend tag declaration where the scope specifier was
13927 /// templated.
13928 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13929                                     unsigned TagSpec, SourceLocation TagLoc,
13930                                     CXXScopeSpec &SS, IdentifierInfo *Name,
13931                                     SourceLocation NameLoc,
13932                                     const ParsedAttributesView &Attr,
13933                                     MultiTemplateParamsArg TempParamLists) {
13934   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13935 
13936   bool IsMemberSpecialization = false;
13937   bool Invalid = false;
13938 
13939   if (TemplateParameterList *TemplateParams =
13940           MatchTemplateParametersToScopeSpecifier(
13941               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13942               IsMemberSpecialization, Invalid)) {
13943     if (TemplateParams->size() > 0) {
13944       // This is a declaration of a class template.
13945       if (Invalid)
13946         return nullptr;
13947 
13948       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13949                                 NameLoc, Attr, TemplateParams, AS_public,
13950                                 /*ModulePrivateLoc=*/SourceLocation(),
13951                                 FriendLoc, TempParamLists.size() - 1,
13952                                 TempParamLists.data()).get();
13953     } else {
13954       // The "template<>" header is extraneous.
13955       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13956         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13957       IsMemberSpecialization = true;
13958     }
13959   }
13960 
13961   if (Invalid) return nullptr;
13962 
13963   bool isAllExplicitSpecializations = true;
13964   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13965     if (TempParamLists[I]->size()) {
13966       isAllExplicitSpecializations = false;
13967       break;
13968     }
13969   }
13970 
13971   // FIXME: don't ignore attributes.
13972 
13973   // If it's explicit specializations all the way down, just forget
13974   // about the template header and build an appropriate non-templated
13975   // friend.  TODO: for source fidelity, remember the headers.
13976   if (isAllExplicitSpecializations) {
13977     if (SS.isEmpty()) {
13978       bool Owned = false;
13979       bool IsDependent = false;
13980       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13981                       Attr, AS_public,
13982                       /*ModulePrivateLoc=*/SourceLocation(),
13983                       MultiTemplateParamsArg(), Owned, IsDependent,
13984                       /*ScopedEnumKWLoc=*/SourceLocation(),
13985                       /*ScopedEnumUsesClassTag=*/false,
13986                       /*UnderlyingType=*/TypeResult(),
13987                       /*IsTypeSpecifier=*/false,
13988                       /*IsTemplateParamOrArg=*/false);
13989     }
13990 
13991     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13992     ElaboratedTypeKeyword Keyword
13993       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13994     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13995                                    *Name, NameLoc);
13996     if (T.isNull())
13997       return nullptr;
13998 
13999     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14000     if (isa<DependentNameType>(T)) {
14001       DependentNameTypeLoc TL =
14002           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14003       TL.setElaboratedKeywordLoc(TagLoc);
14004       TL.setQualifierLoc(QualifierLoc);
14005       TL.setNameLoc(NameLoc);
14006     } else {
14007       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14008       TL.setElaboratedKeywordLoc(TagLoc);
14009       TL.setQualifierLoc(QualifierLoc);
14010       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14011     }
14012 
14013     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14014                                             TSI, FriendLoc, TempParamLists);
14015     Friend->setAccess(AS_public);
14016     CurContext->addDecl(Friend);
14017     return Friend;
14018   }
14019 
14020   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14021 
14022 
14023 
14024   // Handle the case of a templated-scope friend class.  e.g.
14025   //   template <class T> class A<T>::B;
14026   // FIXME: we don't support these right now.
14027   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14028     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14029   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14030   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14031   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14032   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14033   TL.setElaboratedKeywordLoc(TagLoc);
14034   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14035   TL.setNameLoc(NameLoc);
14036 
14037   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14038                                           TSI, FriendLoc, TempParamLists);
14039   Friend->setAccess(AS_public);
14040   Friend->setUnsupportedFriend(true);
14041   CurContext->addDecl(Friend);
14042   return Friend;
14043 }
14044 
14045 /// Handle a friend type declaration.  This works in tandem with
14046 /// ActOnTag.
14047 ///
14048 /// Notes on friend class templates:
14049 ///
14050 /// We generally treat friend class declarations as if they were
14051 /// declaring a class.  So, for example, the elaborated type specifier
14052 /// in a friend declaration is required to obey the restrictions of a
14053 /// class-head (i.e. no typedefs in the scope chain), template
14054 /// parameters are required to match up with simple template-ids, &c.
14055 /// However, unlike when declaring a template specialization, it's
14056 /// okay to refer to a template specialization without an empty
14057 /// template parameter declaration, e.g.
14058 ///   friend class A<T>::B<unsigned>;
14059 /// We permit this as a special case; if there are any template
14060 /// parameters present at all, require proper matching, i.e.
14061 ///   template <> template \<class T> friend class A<int>::B;
14062 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14063                                 MultiTemplateParamsArg TempParams) {
14064   SourceLocation Loc = DS.getLocStart();
14065 
14066   assert(DS.isFriendSpecified());
14067   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14068 
14069   // Try to convert the decl specifier to a type.  This works for
14070   // friend templates because ActOnTag never produces a ClassTemplateDecl
14071   // for a TUK_Friend.
14072   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14073   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14074   QualType T = TSI->getType();
14075   if (TheDeclarator.isInvalidType())
14076     return nullptr;
14077 
14078   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14079     return nullptr;
14080 
14081   // This is definitely an error in C++98.  It's probably meant to
14082   // be forbidden in C++0x, too, but the specification is just
14083   // poorly written.
14084   //
14085   // The problem is with declarations like the following:
14086   //   template <T> friend A<T>::foo;
14087   // where deciding whether a class C is a friend or not now hinges
14088   // on whether there exists an instantiation of A that causes
14089   // 'foo' to equal C.  There are restrictions on class-heads
14090   // (which we declare (by fiat) elaborated friend declarations to
14091   // be) that makes this tractable.
14092   //
14093   // FIXME: handle "template <> friend class A<T>;", which
14094   // is possibly well-formed?  Who even knows?
14095   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14096     Diag(Loc, diag::err_tagless_friend_type_template)
14097       << DS.getSourceRange();
14098     return nullptr;
14099   }
14100 
14101   // C++98 [class.friend]p1: A friend of a class is a function
14102   //   or class that is not a member of the class . . .
14103   // This is fixed in DR77, which just barely didn't make the C++03
14104   // deadline.  It's also a very silly restriction that seriously
14105   // affects inner classes and which nobody else seems to implement;
14106   // thus we never diagnose it, not even in -pedantic.
14107   //
14108   // But note that we could warn about it: it's always useless to
14109   // friend one of your own members (it's not, however, worthless to
14110   // friend a member of an arbitrary specialization of your template).
14111 
14112   Decl *D;
14113   if (!TempParams.empty())
14114     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14115                                    TempParams,
14116                                    TSI,
14117                                    DS.getFriendSpecLoc());
14118   else
14119     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14120 
14121   if (!D)
14122     return nullptr;
14123 
14124   D->setAccess(AS_public);
14125   CurContext->addDecl(D);
14126 
14127   return D;
14128 }
14129 
14130 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14131                                         MultiTemplateParamsArg TemplateParams) {
14132   const DeclSpec &DS = D.getDeclSpec();
14133 
14134   assert(DS.isFriendSpecified());
14135   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14136 
14137   SourceLocation Loc = D.getIdentifierLoc();
14138   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14139 
14140   // C++ [class.friend]p1
14141   //   A friend of a class is a function or class....
14142   // Note that this sees through typedefs, which is intended.
14143   // It *doesn't* see through dependent types, which is correct
14144   // according to [temp.arg.type]p3:
14145   //   If a declaration acquires a function type through a
14146   //   type dependent on a template-parameter and this causes
14147   //   a declaration that does not use the syntactic form of a
14148   //   function declarator to have a function type, the program
14149   //   is ill-formed.
14150   if (!TInfo->getType()->isFunctionType()) {
14151     Diag(Loc, diag::err_unexpected_friend);
14152 
14153     // It might be worthwhile to try to recover by creating an
14154     // appropriate declaration.
14155     return nullptr;
14156   }
14157 
14158   // C++ [namespace.memdef]p3
14159   //  - If a friend declaration in a non-local class first declares a
14160   //    class or function, the friend class or function is a member
14161   //    of the innermost enclosing namespace.
14162   //  - The name of the friend is not found by simple name lookup
14163   //    until a matching declaration is provided in that namespace
14164   //    scope (either before or after the class declaration granting
14165   //    friendship).
14166   //  - If a friend function is called, its name may be found by the
14167   //    name lookup that considers functions from namespaces and
14168   //    classes associated with the types of the function arguments.
14169   //  - When looking for a prior declaration of a class or a function
14170   //    declared as a friend, scopes outside the innermost enclosing
14171   //    namespace scope are not considered.
14172 
14173   CXXScopeSpec &SS = D.getCXXScopeSpec();
14174   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14175   DeclarationName Name = NameInfo.getName();
14176   assert(Name);
14177 
14178   // Check for unexpanded parameter packs.
14179   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14180       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14181       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14182     return nullptr;
14183 
14184   // The context we found the declaration in, or in which we should
14185   // create the declaration.
14186   DeclContext *DC;
14187   Scope *DCScope = S;
14188   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14189                         ForExternalRedeclaration);
14190 
14191   // There are five cases here.
14192   //   - There's no scope specifier and we're in a local class. Only look
14193   //     for functions declared in the immediately-enclosing block scope.
14194   // We recover from invalid scope qualifiers as if they just weren't there.
14195   FunctionDecl *FunctionContainingLocalClass = nullptr;
14196   if ((SS.isInvalid() || !SS.isSet()) &&
14197       (FunctionContainingLocalClass =
14198            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14199     // C++11 [class.friend]p11:
14200     //   If a friend declaration appears in a local class and the name
14201     //   specified is an unqualified name, a prior declaration is
14202     //   looked up without considering scopes that are outside the
14203     //   innermost enclosing non-class scope. For a friend function
14204     //   declaration, if there is no prior declaration, the program is
14205     //   ill-formed.
14206 
14207     // Find the innermost enclosing non-class scope. This is the block
14208     // scope containing the local class definition (or for a nested class,
14209     // the outer local class).
14210     DCScope = S->getFnParent();
14211 
14212     // Look up the function name in the scope.
14213     Previous.clear(LookupLocalFriendName);
14214     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14215 
14216     if (!Previous.empty()) {
14217       // All possible previous declarations must have the same context:
14218       // either they were declared at block scope or they are members of
14219       // one of the enclosing local classes.
14220       DC = Previous.getRepresentativeDecl()->getDeclContext();
14221     } else {
14222       // This is ill-formed, but provide the context that we would have
14223       // declared the function in, if we were permitted to, for error recovery.
14224       DC = FunctionContainingLocalClass;
14225     }
14226     adjustContextForLocalExternDecl(DC);
14227 
14228     // C++ [class.friend]p6:
14229     //   A function can be defined in a friend declaration of a class if and
14230     //   only if the class is a non-local class (9.8), the function name is
14231     //   unqualified, and the function has namespace scope.
14232     if (D.isFunctionDefinition()) {
14233       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14234     }
14235 
14236   //   - There's no scope specifier, in which case we just go to the
14237   //     appropriate scope and look for a function or function template
14238   //     there as appropriate.
14239   } else if (SS.isInvalid() || !SS.isSet()) {
14240     // C++11 [namespace.memdef]p3:
14241     //   If the name in a friend declaration is neither qualified nor
14242     //   a template-id and the declaration is a function or an
14243     //   elaborated-type-specifier, the lookup to determine whether
14244     //   the entity has been previously declared shall not consider
14245     //   any scopes outside the innermost enclosing namespace.
14246     bool isTemplateId =
14247         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14248 
14249     // Find the appropriate context according to the above.
14250     DC = CurContext;
14251 
14252     // Skip class contexts.  If someone can cite chapter and verse
14253     // for this behavior, that would be nice --- it's what GCC and
14254     // EDG do, and it seems like a reasonable intent, but the spec
14255     // really only says that checks for unqualified existing
14256     // declarations should stop at the nearest enclosing namespace,
14257     // not that they should only consider the nearest enclosing
14258     // namespace.
14259     while (DC->isRecord())
14260       DC = DC->getParent();
14261 
14262     DeclContext *LookupDC = DC;
14263     while (LookupDC->isTransparentContext())
14264       LookupDC = LookupDC->getParent();
14265 
14266     while (true) {
14267       LookupQualifiedName(Previous, LookupDC);
14268 
14269       if (!Previous.empty()) {
14270         DC = LookupDC;
14271         break;
14272       }
14273 
14274       if (isTemplateId) {
14275         if (isa<TranslationUnitDecl>(LookupDC)) break;
14276       } else {
14277         if (LookupDC->isFileContext()) break;
14278       }
14279       LookupDC = LookupDC->getParent();
14280     }
14281 
14282     DCScope = getScopeForDeclContext(S, DC);
14283 
14284   //   - There's a non-dependent scope specifier, in which case we
14285   //     compute it and do a previous lookup there for a function
14286   //     or function template.
14287   } else if (!SS.getScopeRep()->isDependent()) {
14288     DC = computeDeclContext(SS);
14289     if (!DC) return nullptr;
14290 
14291     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14292 
14293     LookupQualifiedName(Previous, DC);
14294 
14295     // Ignore things found implicitly in the wrong scope.
14296     // TODO: better diagnostics for this case.  Suggesting the right
14297     // qualified scope would be nice...
14298     LookupResult::Filter F = Previous.makeFilter();
14299     while (F.hasNext()) {
14300       NamedDecl *D = F.next();
14301       if (!DC->InEnclosingNamespaceSetOf(
14302               D->getDeclContext()->getRedeclContext()))
14303         F.erase();
14304     }
14305     F.done();
14306 
14307     if (Previous.empty()) {
14308       D.setInvalidType();
14309       Diag(Loc, diag::err_qualified_friend_not_found)
14310           << Name << TInfo->getType();
14311       return nullptr;
14312     }
14313 
14314     // C++ [class.friend]p1: A friend of a class is a function or
14315     //   class that is not a member of the class . . .
14316     if (DC->Equals(CurContext))
14317       Diag(DS.getFriendSpecLoc(),
14318            getLangOpts().CPlusPlus11 ?
14319              diag::warn_cxx98_compat_friend_is_member :
14320              diag::err_friend_is_member);
14321 
14322     if (D.isFunctionDefinition()) {
14323       // C++ [class.friend]p6:
14324       //   A function can be defined in a friend declaration of a class if and
14325       //   only if the class is a non-local class (9.8), the function name is
14326       //   unqualified, and the function has namespace scope.
14327       SemaDiagnosticBuilder DB
14328         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14329 
14330       DB << SS.getScopeRep();
14331       if (DC->isFileContext())
14332         DB << FixItHint::CreateRemoval(SS.getRange());
14333       SS.clear();
14334     }
14335 
14336   //   - There's a scope specifier that does not match any template
14337   //     parameter lists, in which case we use some arbitrary context,
14338   //     create a method or method template, and wait for instantiation.
14339   //   - There's a scope specifier that does match some template
14340   //     parameter lists, which we don't handle right now.
14341   } else {
14342     if (D.isFunctionDefinition()) {
14343       // C++ [class.friend]p6:
14344       //   A function can be defined in a friend declaration of a class if and
14345       //   only if the class is a non-local class (9.8), the function name is
14346       //   unqualified, and the function has namespace scope.
14347       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14348         << SS.getScopeRep();
14349     }
14350 
14351     DC = CurContext;
14352     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14353   }
14354 
14355   if (!DC->isRecord()) {
14356     int DiagArg = -1;
14357     switch (D.getName().getKind()) {
14358     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14359     case UnqualifiedIdKind::IK_ConstructorName:
14360       DiagArg = 0;
14361       break;
14362     case UnqualifiedIdKind::IK_DestructorName:
14363       DiagArg = 1;
14364       break;
14365     case UnqualifiedIdKind::IK_ConversionFunctionId:
14366       DiagArg = 2;
14367       break;
14368     case UnqualifiedIdKind::IK_DeductionGuideName:
14369       DiagArg = 3;
14370       break;
14371     case UnqualifiedIdKind::IK_Identifier:
14372     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14373     case UnqualifiedIdKind::IK_LiteralOperatorId:
14374     case UnqualifiedIdKind::IK_OperatorFunctionId:
14375     case UnqualifiedIdKind::IK_TemplateId:
14376       break;
14377     }
14378     // This implies that it has to be an operator or function.
14379     if (DiagArg >= 0) {
14380       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14381       return nullptr;
14382     }
14383   }
14384 
14385   // FIXME: This is an egregious hack to cope with cases where the scope stack
14386   // does not contain the declaration context, i.e., in an out-of-line
14387   // definition of a class.
14388   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14389   if (!DCScope) {
14390     FakeDCScope.setEntity(DC);
14391     DCScope = &FakeDCScope;
14392   }
14393 
14394   bool AddToScope = true;
14395   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14396                                           TemplateParams, AddToScope);
14397   if (!ND) return nullptr;
14398 
14399   assert(ND->getLexicalDeclContext() == CurContext);
14400 
14401   // If we performed typo correction, we might have added a scope specifier
14402   // and changed the decl context.
14403   DC = ND->getDeclContext();
14404 
14405   // Add the function declaration to the appropriate lookup tables,
14406   // adjusting the redeclarations list as necessary.  We don't
14407   // want to do this yet if the friending class is dependent.
14408   //
14409   // Also update the scope-based lookup if the target context's
14410   // lookup context is in lexical scope.
14411   if (!CurContext->isDependentContext()) {
14412     DC = DC->getRedeclContext();
14413     DC->makeDeclVisibleInContext(ND);
14414     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14415       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14416   }
14417 
14418   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14419                                        D.getIdentifierLoc(), ND,
14420                                        DS.getFriendSpecLoc());
14421   FrD->setAccess(AS_public);
14422   CurContext->addDecl(FrD);
14423 
14424   if (ND->isInvalidDecl()) {
14425     FrD->setInvalidDecl();
14426   } else {
14427     if (DC->isRecord()) CheckFriendAccess(ND);
14428 
14429     FunctionDecl *FD;
14430     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14431       FD = FTD->getTemplatedDecl();
14432     else
14433       FD = cast<FunctionDecl>(ND);
14434 
14435     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14436     // default argument expression, that declaration shall be a definition
14437     // and shall be the only declaration of the function or function
14438     // template in the translation unit.
14439     if (functionDeclHasDefaultArgument(FD)) {
14440       // We can't look at FD->getPreviousDecl() because it may not have been set
14441       // if we're in a dependent context. If the function is known to be a
14442       // redeclaration, we will have narrowed Previous down to the right decl.
14443       if (D.isRedeclaration()) {
14444         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14445         Diag(Previous.getRepresentativeDecl()->getLocation(),
14446              diag::note_previous_declaration);
14447       } else if (!D.isFunctionDefinition())
14448         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14449     }
14450 
14451     // Mark templated-scope function declarations as unsupported.
14452     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14453       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14454         << SS.getScopeRep() << SS.getRange()
14455         << cast<CXXRecordDecl>(CurContext);
14456       FrD->setUnsupportedFriend(true);
14457     }
14458   }
14459 
14460   return ND;
14461 }
14462 
14463 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14464   AdjustDeclIfTemplate(Dcl);
14465 
14466   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14467   if (!Fn) {
14468     Diag(DelLoc, diag::err_deleted_non_function);
14469     return;
14470   }
14471 
14472   // Deleted function does not have a body.
14473   Fn->setWillHaveBody(false);
14474 
14475   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14476     // Don't consider the implicit declaration we generate for explicit
14477     // specializations. FIXME: Do not generate these implicit declarations.
14478     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14479          Prev->getPreviousDecl()) &&
14480         !Prev->isDefined()) {
14481       Diag(DelLoc, diag::err_deleted_decl_not_first);
14482       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14483            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14484                               : diag::note_previous_declaration);
14485     }
14486     // If the declaration wasn't the first, we delete the function anyway for
14487     // recovery.
14488     Fn = Fn->getCanonicalDecl();
14489   }
14490 
14491   // dllimport/dllexport cannot be deleted.
14492   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14493     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14494     Fn->setInvalidDecl();
14495   }
14496 
14497   if (Fn->isDeleted())
14498     return;
14499 
14500   // See if we're deleting a function which is already known to override a
14501   // non-deleted virtual function.
14502   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14503     bool IssuedDiagnostic = false;
14504     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14505       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14506         if (!IssuedDiagnostic) {
14507           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14508           IssuedDiagnostic = true;
14509         }
14510         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14511       }
14512     }
14513     // If this function was implicitly deleted because it was defaulted,
14514     // explain why it was deleted.
14515     if (IssuedDiagnostic && MD->isDefaulted())
14516       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14517                                 /*Diagnose*/true);
14518   }
14519 
14520   // C++11 [basic.start.main]p3:
14521   //   A program that defines main as deleted [...] is ill-formed.
14522   if (Fn->isMain())
14523     Diag(DelLoc, diag::err_deleted_main);
14524 
14525   // C++11 [dcl.fct.def.delete]p4:
14526   //  A deleted function is implicitly inline.
14527   Fn->setImplicitlyInline();
14528   Fn->setDeletedAsWritten();
14529 }
14530 
14531 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14532   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14533 
14534   if (MD) {
14535     if (MD->getParent()->isDependentType()) {
14536       MD->setDefaulted();
14537       MD->setExplicitlyDefaulted();
14538       return;
14539     }
14540 
14541     CXXSpecialMember Member = getSpecialMember(MD);
14542     if (Member == CXXInvalid) {
14543       if (!MD->isInvalidDecl())
14544         Diag(DefaultLoc, diag::err_default_special_members);
14545       return;
14546     }
14547 
14548     MD->setDefaulted();
14549     MD->setExplicitlyDefaulted();
14550 
14551     // Unset that we will have a body for this function. We might not,
14552     // if it turns out to be trivial, and we don't need this marking now
14553     // that we've marked it as defaulted.
14554     MD->setWillHaveBody(false);
14555 
14556     // If this definition appears within the record, do the checking when
14557     // the record is complete.
14558     const FunctionDecl *Primary = MD;
14559     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14560       // Ask the template instantiation pattern that actually had the
14561       // '= default' on it.
14562       Primary = Pattern;
14563 
14564     // If the method was defaulted on its first declaration, we will have
14565     // already performed the checking in CheckCompletedCXXClass. Such a
14566     // declaration doesn't trigger an implicit definition.
14567     if (Primary->getCanonicalDecl()->isDefaulted())
14568       return;
14569 
14570     CheckExplicitlyDefaultedSpecialMember(MD);
14571 
14572     if (!MD->isInvalidDecl())
14573       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14574   } else {
14575     Diag(DefaultLoc, diag::err_default_special_members);
14576   }
14577 }
14578 
14579 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14580   for (Stmt *SubStmt : S->children()) {
14581     if (!SubStmt)
14582       continue;
14583     if (isa<ReturnStmt>(SubStmt))
14584       Self.Diag(SubStmt->getLocStart(),
14585            diag::err_return_in_constructor_handler);
14586     if (!isa<Expr>(SubStmt))
14587       SearchForReturnInStmt(Self, SubStmt);
14588   }
14589 }
14590 
14591 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14592   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14593     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14594     SearchForReturnInStmt(*this, Handler);
14595   }
14596 }
14597 
14598 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14599                                              const CXXMethodDecl *Old) {
14600   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14601   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14602 
14603   if (OldFT->hasExtParameterInfos()) {
14604     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14605       // A parameter of the overriding method should be annotated with noescape
14606       // if the corresponding parameter of the overridden method is annotated.
14607       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14608           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14609         Diag(New->getParamDecl(I)->getLocation(),
14610              diag::warn_overriding_method_missing_noescape);
14611         Diag(Old->getParamDecl(I)->getLocation(),
14612              diag::note_overridden_marked_noescape);
14613       }
14614   }
14615 
14616   // Virtual overrides must have the same code_seg.
14617   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14618   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14619   if ((NewCSA || OldCSA) &&
14620       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14621     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14622     Diag(Old->getLocation(), diag::note_previous_declaration);
14623     return true;
14624   }
14625 
14626   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14627 
14628   // If the calling conventions match, everything is fine
14629   if (NewCC == OldCC)
14630     return false;
14631 
14632   // If the calling conventions mismatch because the new function is static,
14633   // suppress the calling convention mismatch error; the error about static
14634   // function override (err_static_overrides_virtual from
14635   // Sema::CheckFunctionDeclaration) is more clear.
14636   if (New->getStorageClass() == SC_Static)
14637     return false;
14638 
14639   Diag(New->getLocation(),
14640        diag::err_conflicting_overriding_cc_attributes)
14641     << New->getDeclName() << New->getType() << Old->getType();
14642   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14643   return true;
14644 }
14645 
14646 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14647                                              const CXXMethodDecl *Old) {
14648   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14649   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14650 
14651   if (Context.hasSameType(NewTy, OldTy) ||
14652       NewTy->isDependentType() || OldTy->isDependentType())
14653     return false;
14654 
14655   // Check if the return types are covariant
14656   QualType NewClassTy, OldClassTy;
14657 
14658   /// Both types must be pointers or references to classes.
14659   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14660     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14661       NewClassTy = NewPT->getPointeeType();
14662       OldClassTy = OldPT->getPointeeType();
14663     }
14664   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14665     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14666       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14667         NewClassTy = NewRT->getPointeeType();
14668         OldClassTy = OldRT->getPointeeType();
14669       }
14670     }
14671   }
14672 
14673   // The return types aren't either both pointers or references to a class type.
14674   if (NewClassTy.isNull()) {
14675     Diag(New->getLocation(),
14676          diag::err_different_return_type_for_overriding_virtual_function)
14677         << New->getDeclName() << NewTy << OldTy
14678         << New->getReturnTypeSourceRange();
14679     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14680         << Old->getReturnTypeSourceRange();
14681 
14682     return true;
14683   }
14684 
14685   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14686     // C++14 [class.virtual]p8:
14687     //   If the class type in the covariant return type of D::f differs from
14688     //   that of B::f, the class type in the return type of D::f shall be
14689     //   complete at the point of declaration of D::f or shall be the class
14690     //   type D.
14691     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14692       if (!RT->isBeingDefined() &&
14693           RequireCompleteType(New->getLocation(), NewClassTy,
14694                               diag::err_covariant_return_incomplete,
14695                               New->getDeclName()))
14696         return true;
14697     }
14698 
14699     // Check if the new class derives from the old class.
14700     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14701       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14702           << New->getDeclName() << NewTy << OldTy
14703           << New->getReturnTypeSourceRange();
14704       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14705           << Old->getReturnTypeSourceRange();
14706       return true;
14707     }
14708 
14709     // Check if we the conversion from derived to base is valid.
14710     if (CheckDerivedToBaseConversion(
14711             NewClassTy, OldClassTy,
14712             diag::err_covariant_return_inaccessible_base,
14713             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14714             New->getLocation(), New->getReturnTypeSourceRange(),
14715             New->getDeclName(), nullptr)) {
14716       // FIXME: this note won't trigger for delayed access control
14717       // diagnostics, and it's impossible to get an undelayed error
14718       // here from access control during the original parse because
14719       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14720       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14721           << Old->getReturnTypeSourceRange();
14722       return true;
14723     }
14724   }
14725 
14726   // The qualifiers of the return types must be the same.
14727   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14728     Diag(New->getLocation(),
14729          diag::err_covariant_return_type_different_qualifications)
14730         << New->getDeclName() << NewTy << OldTy
14731         << New->getReturnTypeSourceRange();
14732     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14733         << Old->getReturnTypeSourceRange();
14734     return true;
14735   }
14736 
14737 
14738   // The new class type must have the same or less qualifiers as the old type.
14739   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14740     Diag(New->getLocation(),
14741          diag::err_covariant_return_type_class_type_more_qualified)
14742         << New->getDeclName() << NewTy << OldTy
14743         << New->getReturnTypeSourceRange();
14744     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14745         << Old->getReturnTypeSourceRange();
14746     return true;
14747   }
14748 
14749   return false;
14750 }
14751 
14752 /// Mark the given method pure.
14753 ///
14754 /// \param Method the method to be marked pure.
14755 ///
14756 /// \param InitRange the source range that covers the "0" initializer.
14757 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14758   SourceLocation EndLoc = InitRange.getEnd();
14759   if (EndLoc.isValid())
14760     Method->setRangeEnd(EndLoc);
14761 
14762   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14763     Method->setPure();
14764     return false;
14765   }
14766 
14767   if (!Method->isInvalidDecl())
14768     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14769       << Method->getDeclName() << InitRange;
14770   return true;
14771 }
14772 
14773 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14774   if (D->getFriendObjectKind())
14775     Diag(D->getLocation(), diag::err_pure_friend);
14776   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14777     CheckPureMethod(M, ZeroLoc);
14778   else
14779     Diag(D->getLocation(), diag::err_illegal_initializer);
14780 }
14781 
14782 /// Determine whether the given declaration is a global variable or
14783 /// static data member.
14784 static bool isNonlocalVariable(const Decl *D) {
14785   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14786     return Var->hasGlobalStorage();
14787 
14788   return false;
14789 }
14790 
14791 /// Invoked when we are about to parse an initializer for the declaration
14792 /// 'Dcl'.
14793 ///
14794 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14795 /// static data member of class X, names should be looked up in the scope of
14796 /// class X. If the declaration had a scope specifier, a scope will have
14797 /// been created and passed in for this purpose. Otherwise, S will be null.
14798 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14799   // If there is no declaration, there was an error parsing it.
14800   if (!D || D->isInvalidDecl())
14801     return;
14802 
14803   // We will always have a nested name specifier here, but this declaration
14804   // might not be out of line if the specifier names the current namespace:
14805   //   extern int n;
14806   //   int ::n = 0;
14807   if (S && D->isOutOfLine())
14808     EnterDeclaratorContext(S, D->getDeclContext());
14809 
14810   // If we are parsing the initializer for a static data member, push a
14811   // new expression evaluation context that is associated with this static
14812   // data member.
14813   if (isNonlocalVariable(D))
14814     PushExpressionEvaluationContext(
14815         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14816 }
14817 
14818 /// Invoked after we are finished parsing an initializer for the declaration D.
14819 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14820   // If there is no declaration, there was an error parsing it.
14821   if (!D || D->isInvalidDecl())
14822     return;
14823 
14824   if (isNonlocalVariable(D))
14825     PopExpressionEvaluationContext();
14826 
14827   if (S && D->isOutOfLine())
14828     ExitDeclaratorContext(S);
14829 }
14830 
14831 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14832 /// C++ if/switch/while/for statement.
14833 /// e.g: "if (int x = f()) {...}"
14834 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14835   // C++ 6.4p2:
14836   // The declarator shall not specify a function or an array.
14837   // The type-specifier-seq shall not contain typedef and shall not declare a
14838   // new class or enumeration.
14839   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14840          "Parser allowed 'typedef' as storage class of condition decl.");
14841 
14842   Decl *Dcl = ActOnDeclarator(S, D);
14843   if (!Dcl)
14844     return true;
14845 
14846   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14847     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14848       << D.getSourceRange();
14849     return true;
14850   }
14851 
14852   return Dcl;
14853 }
14854 
14855 void Sema::LoadExternalVTableUses() {
14856   if (!ExternalSource)
14857     return;
14858 
14859   SmallVector<ExternalVTableUse, 4> VTables;
14860   ExternalSource->ReadUsedVTables(VTables);
14861   SmallVector<VTableUse, 4> NewUses;
14862   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14863     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14864       = VTablesUsed.find(VTables[I].Record);
14865     // Even if a definition wasn't required before, it may be required now.
14866     if (Pos != VTablesUsed.end()) {
14867       if (!Pos->second && VTables[I].DefinitionRequired)
14868         Pos->second = true;
14869       continue;
14870     }
14871 
14872     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14873     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14874   }
14875 
14876   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14877 }
14878 
14879 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14880                           bool DefinitionRequired) {
14881   // Ignore any vtable uses in unevaluated operands or for classes that do
14882   // not have a vtable.
14883   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14884       CurContext->isDependentContext() || isUnevaluatedContext())
14885     return;
14886 
14887   // Try to insert this class into the map.
14888   LoadExternalVTableUses();
14889   Class = Class->getCanonicalDecl();
14890   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14891     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14892   if (!Pos.second) {
14893     // If we already had an entry, check to see if we are promoting this vtable
14894     // to require a definition. If so, we need to reappend to the VTableUses
14895     // list, since we may have already processed the first entry.
14896     if (DefinitionRequired && !Pos.first->second) {
14897       Pos.first->second = true;
14898     } else {
14899       // Otherwise, we can early exit.
14900       return;
14901     }
14902   } else {
14903     // The Microsoft ABI requires that we perform the destructor body
14904     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14905     // the deleting destructor is emitted with the vtable, not with the
14906     // destructor definition as in the Itanium ABI.
14907     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14908       CXXDestructorDecl *DD = Class->getDestructor();
14909       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14910         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14911           // If this is an out-of-line declaration, marking it referenced will
14912           // not do anything. Manually call CheckDestructor to look up operator
14913           // delete().
14914           ContextRAII SavedContext(*this, DD);
14915           CheckDestructor(DD);
14916         } else {
14917           MarkFunctionReferenced(Loc, Class->getDestructor());
14918         }
14919       }
14920     }
14921   }
14922 
14923   // Local classes need to have their virtual members marked
14924   // immediately. For all other classes, we mark their virtual members
14925   // at the end of the translation unit.
14926   if (Class->isLocalClass())
14927     MarkVirtualMembersReferenced(Loc, Class);
14928   else
14929     VTableUses.push_back(std::make_pair(Class, Loc));
14930 }
14931 
14932 bool Sema::DefineUsedVTables() {
14933   LoadExternalVTableUses();
14934   if (VTableUses.empty())
14935     return false;
14936 
14937   // Note: The VTableUses vector could grow as a result of marking
14938   // the members of a class as "used", so we check the size each
14939   // time through the loop and prefer indices (which are stable) to
14940   // iterators (which are not).
14941   bool DefinedAnything = false;
14942   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14943     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14944     if (!Class)
14945       continue;
14946     TemplateSpecializationKind ClassTSK =
14947         Class->getTemplateSpecializationKind();
14948 
14949     SourceLocation Loc = VTableUses[I].second;
14950 
14951     bool DefineVTable = true;
14952 
14953     // If this class has a key function, but that key function is
14954     // defined in another translation unit, we don't need to emit the
14955     // vtable even though we're using it.
14956     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14957     if (KeyFunction && !KeyFunction->hasBody()) {
14958       // The key function is in another translation unit.
14959       DefineVTable = false;
14960       TemplateSpecializationKind TSK =
14961           KeyFunction->getTemplateSpecializationKind();
14962       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14963              TSK != TSK_ImplicitInstantiation &&
14964              "Instantiations don't have key functions");
14965       (void)TSK;
14966     } else if (!KeyFunction) {
14967       // If we have a class with no key function that is the subject
14968       // of an explicit instantiation declaration, suppress the
14969       // vtable; it will live with the explicit instantiation
14970       // definition.
14971       bool IsExplicitInstantiationDeclaration =
14972           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14973       for (auto R : Class->redecls()) {
14974         TemplateSpecializationKind TSK
14975           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14976         if (TSK == TSK_ExplicitInstantiationDeclaration)
14977           IsExplicitInstantiationDeclaration = true;
14978         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14979           IsExplicitInstantiationDeclaration = false;
14980           break;
14981         }
14982       }
14983 
14984       if (IsExplicitInstantiationDeclaration)
14985         DefineVTable = false;
14986     }
14987 
14988     // The exception specifications for all virtual members may be needed even
14989     // if we are not providing an authoritative form of the vtable in this TU.
14990     // We may choose to emit it available_externally anyway.
14991     if (!DefineVTable) {
14992       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14993       continue;
14994     }
14995 
14996     // Mark all of the virtual members of this class as referenced, so
14997     // that we can build a vtable. Then, tell the AST consumer that a
14998     // vtable for this class is required.
14999     DefinedAnything = true;
15000     MarkVirtualMembersReferenced(Loc, Class);
15001     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15002     if (VTablesUsed[Canonical])
15003       Consumer.HandleVTable(Class);
15004 
15005     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15006     // no key function or the key function is inlined. Don't warn in C++ ABIs
15007     // that lack key functions, since the user won't be able to make one.
15008     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15009         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15010       const FunctionDecl *KeyFunctionDef = nullptr;
15011       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15012                            KeyFunctionDef->isInlined())) {
15013         Diag(Class->getLocation(),
15014              ClassTSK == TSK_ExplicitInstantiationDefinition
15015                  ? diag::warn_weak_template_vtable
15016                  : diag::warn_weak_vtable)
15017             << Class;
15018       }
15019     }
15020   }
15021   VTableUses.clear();
15022 
15023   return DefinedAnything;
15024 }
15025 
15026 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15027                                                  const CXXRecordDecl *RD) {
15028   for (const auto *I : RD->methods())
15029     if (I->isVirtual() && !I->isPure())
15030       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15031 }
15032 
15033 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15034                                         const CXXRecordDecl *RD) {
15035   // Mark all functions which will appear in RD's vtable as used.
15036   CXXFinalOverriderMap FinalOverriders;
15037   RD->getFinalOverriders(FinalOverriders);
15038   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15039                                             E = FinalOverriders.end();
15040        I != E; ++I) {
15041     for (OverridingMethods::const_iterator OI = I->second.begin(),
15042                                            OE = I->second.end();
15043          OI != OE; ++OI) {
15044       assert(OI->second.size() > 0 && "no final overrider");
15045       CXXMethodDecl *Overrider = OI->second.front().Method;
15046 
15047       // C++ [basic.def.odr]p2:
15048       //   [...] A virtual member function is used if it is not pure. [...]
15049       if (!Overrider->isPure())
15050         MarkFunctionReferenced(Loc, Overrider);
15051     }
15052   }
15053 
15054   // Only classes that have virtual bases need a VTT.
15055   if (RD->getNumVBases() == 0)
15056     return;
15057 
15058   for (const auto &I : RD->bases()) {
15059     const CXXRecordDecl *Base =
15060         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15061     if (Base->getNumVBases() == 0)
15062       continue;
15063     MarkVirtualMembersReferenced(Loc, Base);
15064   }
15065 }
15066 
15067 /// SetIvarInitializers - This routine builds initialization ASTs for the
15068 /// Objective-C implementation whose ivars need be initialized.
15069 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15070   if (!getLangOpts().CPlusPlus)
15071     return;
15072   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15073     SmallVector<ObjCIvarDecl*, 8> ivars;
15074     CollectIvarsToConstructOrDestruct(OID, ivars);
15075     if (ivars.empty())
15076       return;
15077     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15078     for (unsigned i = 0; i < ivars.size(); i++) {
15079       FieldDecl *Field = ivars[i];
15080       if (Field->isInvalidDecl())
15081         continue;
15082 
15083       CXXCtorInitializer *Member;
15084       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15085       InitializationKind InitKind =
15086         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15087 
15088       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15089       ExprResult MemberInit =
15090         InitSeq.Perform(*this, InitEntity, InitKind, None);
15091       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15092       // Note, MemberInit could actually come back empty if no initialization
15093       // is required (e.g., because it would call a trivial default constructor)
15094       if (!MemberInit.get() || MemberInit.isInvalid())
15095         continue;
15096 
15097       Member =
15098         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15099                                          SourceLocation(),
15100                                          MemberInit.getAs<Expr>(),
15101                                          SourceLocation());
15102       AllToInit.push_back(Member);
15103 
15104       // Be sure that the destructor is accessible and is marked as referenced.
15105       if (const RecordType *RecordTy =
15106               Context.getBaseElementType(Field->getType())
15107                   ->getAs<RecordType>()) {
15108         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15109         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15110           MarkFunctionReferenced(Field->getLocation(), Destructor);
15111           CheckDestructorAccess(Field->getLocation(), Destructor,
15112                             PDiag(diag::err_access_dtor_ivar)
15113                               << Context.getBaseElementType(Field->getType()));
15114         }
15115       }
15116     }
15117     ObjCImplementation->setIvarInitializers(Context,
15118                                             AllToInit.data(), AllToInit.size());
15119   }
15120 }
15121 
15122 static
15123 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15124                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15125                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15126                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15127                            Sema &S) {
15128   if (Ctor->isInvalidDecl())
15129     return;
15130 
15131   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15132 
15133   // Target may not be determinable yet, for instance if this is a dependent
15134   // call in an uninstantiated template.
15135   if (Target) {
15136     const FunctionDecl *FNTarget = nullptr;
15137     (void)Target->hasBody(FNTarget);
15138     Target = const_cast<CXXConstructorDecl*>(
15139       cast_or_null<CXXConstructorDecl>(FNTarget));
15140   }
15141 
15142   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15143                      // Avoid dereferencing a null pointer here.
15144                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15145 
15146   if (!Current.insert(Canonical).second)
15147     return;
15148 
15149   // We know that beyond here, we aren't chaining into a cycle.
15150   if (!Target || !Target->isDelegatingConstructor() ||
15151       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15152     Valid.insert(Current.begin(), Current.end());
15153     Current.clear();
15154   // We've hit a cycle.
15155   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15156              Current.count(TCanonical)) {
15157     // If we haven't diagnosed this cycle yet, do so now.
15158     if (!Invalid.count(TCanonical)) {
15159       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15160              diag::warn_delegating_ctor_cycle)
15161         << Ctor;
15162 
15163       // Don't add a note for a function delegating directly to itself.
15164       if (TCanonical != Canonical)
15165         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15166 
15167       CXXConstructorDecl *C = Target;
15168       while (C->getCanonicalDecl() != Canonical) {
15169         const FunctionDecl *FNTarget = nullptr;
15170         (void)C->getTargetConstructor()->hasBody(FNTarget);
15171         assert(FNTarget && "Ctor cycle through bodiless function");
15172 
15173         C = const_cast<CXXConstructorDecl*>(
15174           cast<CXXConstructorDecl>(FNTarget));
15175         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15176       }
15177     }
15178 
15179     Invalid.insert(Current.begin(), Current.end());
15180     Current.clear();
15181   } else {
15182     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15183   }
15184 }
15185 
15186 
15187 void Sema::CheckDelegatingCtorCycles() {
15188   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15189 
15190   for (DelegatingCtorDeclsType::iterator
15191          I = DelegatingCtorDecls.begin(ExternalSource),
15192          E = DelegatingCtorDecls.end();
15193        I != E; ++I)
15194     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15195 
15196   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15197     (*CI)->setInvalidDecl();
15198 }
15199 
15200 namespace {
15201   /// AST visitor that finds references to the 'this' expression.
15202   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15203     Sema &S;
15204 
15205   public:
15206     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15207 
15208     bool VisitCXXThisExpr(CXXThisExpr *E) {
15209       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15210         << E->isImplicit();
15211       return false;
15212     }
15213   };
15214 }
15215 
15216 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15217   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15218   if (!TSInfo)
15219     return false;
15220 
15221   TypeLoc TL = TSInfo->getTypeLoc();
15222   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15223   if (!ProtoTL)
15224     return false;
15225 
15226   // C++11 [expr.prim.general]p3:
15227   //   [The expression this] shall not appear before the optional
15228   //   cv-qualifier-seq and it shall not appear within the declaration of a
15229   //   static member function (although its type and value category are defined
15230   //   within a static member function as they are within a non-static member
15231   //   function). [ Note: this is because declaration matching does not occur
15232   //  until the complete declarator is known. - end note ]
15233   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15234   FindCXXThisExpr Finder(*this);
15235 
15236   // If the return type came after the cv-qualifier-seq, check it now.
15237   if (Proto->hasTrailingReturn() &&
15238       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15239     return true;
15240 
15241   // Check the exception specification.
15242   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15243     return true;
15244 
15245   return checkThisInStaticMemberFunctionAttributes(Method);
15246 }
15247 
15248 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15249   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15250   if (!TSInfo)
15251     return false;
15252 
15253   TypeLoc TL = TSInfo->getTypeLoc();
15254   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15255   if (!ProtoTL)
15256     return false;
15257 
15258   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15259   FindCXXThisExpr Finder(*this);
15260 
15261   switch (Proto->getExceptionSpecType()) {
15262   case EST_Unparsed:
15263   case EST_Uninstantiated:
15264   case EST_Unevaluated:
15265   case EST_BasicNoexcept:
15266   case EST_DynamicNone:
15267   case EST_MSAny:
15268   case EST_None:
15269     break;
15270 
15271   case EST_DependentNoexcept:
15272   case EST_NoexceptFalse:
15273   case EST_NoexceptTrue:
15274     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15275       return true;
15276     LLVM_FALLTHROUGH;
15277 
15278   case EST_Dynamic:
15279     for (const auto &E : Proto->exceptions()) {
15280       if (!Finder.TraverseType(E))
15281         return true;
15282     }
15283     break;
15284   }
15285 
15286   return false;
15287 }
15288 
15289 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15290   FindCXXThisExpr Finder(*this);
15291 
15292   // Check attributes.
15293   for (const auto *A : Method->attrs()) {
15294     // FIXME: This should be emitted by tblgen.
15295     Expr *Arg = nullptr;
15296     ArrayRef<Expr *> Args;
15297     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15298       Arg = G->getArg();
15299     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15300       Arg = G->getArg();
15301     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15302       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15303     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15304       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15305     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15306       Arg = ETLF->getSuccessValue();
15307       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15308     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15309       Arg = STLF->getSuccessValue();
15310       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15311     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15312       Arg = LR->getArg();
15313     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15314       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15315     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15316       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15317     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15318       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15319     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15320       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15321     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15322       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15323 
15324     if (Arg && !Finder.TraverseStmt(Arg))
15325       return true;
15326 
15327     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15328       if (!Finder.TraverseStmt(Args[I]))
15329         return true;
15330     }
15331   }
15332 
15333   return false;
15334 }
15335 
15336 void Sema::checkExceptionSpecification(
15337     bool IsTopLevel, ExceptionSpecificationType EST,
15338     ArrayRef<ParsedType> DynamicExceptions,
15339     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15340     SmallVectorImpl<QualType> &Exceptions,
15341     FunctionProtoType::ExceptionSpecInfo &ESI) {
15342   Exceptions.clear();
15343   ESI.Type = EST;
15344   if (EST == EST_Dynamic) {
15345     Exceptions.reserve(DynamicExceptions.size());
15346     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15347       // FIXME: Preserve type source info.
15348       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15349 
15350       if (IsTopLevel) {
15351         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15352         collectUnexpandedParameterPacks(ET, Unexpanded);
15353         if (!Unexpanded.empty()) {
15354           DiagnoseUnexpandedParameterPacks(
15355               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15356               Unexpanded);
15357           continue;
15358         }
15359       }
15360 
15361       // Check that the type is valid for an exception spec, and
15362       // drop it if not.
15363       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15364         Exceptions.push_back(ET);
15365     }
15366     ESI.Exceptions = Exceptions;
15367     return;
15368   }
15369 
15370   if (isComputedNoexcept(EST)) {
15371     assert((NoexceptExpr->isTypeDependent() ||
15372             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15373             Context.BoolTy) &&
15374            "Parser should have made sure that the expression is boolean");
15375     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15376       ESI.Type = EST_BasicNoexcept;
15377       return;
15378     }
15379 
15380     ESI.NoexceptExpr = NoexceptExpr;
15381     return;
15382   }
15383 }
15384 
15385 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15386              ExceptionSpecificationType EST,
15387              SourceRange SpecificationRange,
15388              ArrayRef<ParsedType> DynamicExceptions,
15389              ArrayRef<SourceRange> DynamicExceptionRanges,
15390              Expr *NoexceptExpr) {
15391   if (!MethodD)
15392     return;
15393 
15394   // Dig out the method we're referring to.
15395   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15396     MethodD = FunTmpl->getTemplatedDecl();
15397 
15398   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15399   if (!Method)
15400     return;
15401 
15402   // Check the exception specification.
15403   llvm::SmallVector<QualType, 4> Exceptions;
15404   FunctionProtoType::ExceptionSpecInfo ESI;
15405   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15406                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15407                               ESI);
15408 
15409   // Update the exception specification on the function type.
15410   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15411 
15412   if (Method->isStatic())
15413     checkThisInStaticMemberFunctionExceptionSpec(Method);
15414 
15415   if (Method->isVirtual()) {
15416     // Check overrides, which we previously had to delay.
15417     for (const CXXMethodDecl *O : Method->overridden_methods())
15418       CheckOverridingFunctionExceptionSpec(Method, O);
15419   }
15420 }
15421 
15422 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15423 ///
15424 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15425                                        SourceLocation DeclStart, Declarator &D,
15426                                        Expr *BitWidth,
15427                                        InClassInitStyle InitStyle,
15428                                        AccessSpecifier AS,
15429                                        const ParsedAttr &MSPropertyAttr) {
15430   IdentifierInfo *II = D.getIdentifier();
15431   if (!II) {
15432     Diag(DeclStart, diag::err_anonymous_property);
15433     return nullptr;
15434   }
15435   SourceLocation Loc = D.getIdentifierLoc();
15436 
15437   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15438   QualType T = TInfo->getType();
15439   if (getLangOpts().CPlusPlus) {
15440     CheckExtraCXXDefaultArguments(D);
15441 
15442     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15443                                         UPPC_DataMemberType)) {
15444       D.setInvalidType();
15445       T = Context.IntTy;
15446       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15447     }
15448   }
15449 
15450   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15451 
15452   if (D.getDeclSpec().isInlineSpecified())
15453     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15454         << getLangOpts().CPlusPlus17;
15455   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15456     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15457          diag::err_invalid_thread)
15458       << DeclSpec::getSpecifierName(TSCS);
15459 
15460   // Check to see if this name was declared as a member previously
15461   NamedDecl *PrevDecl = nullptr;
15462   LookupResult Previous(*this, II, Loc, LookupMemberName,
15463                         ForVisibleRedeclaration);
15464   LookupName(Previous, S);
15465   switch (Previous.getResultKind()) {
15466   case LookupResult::Found:
15467   case LookupResult::FoundUnresolvedValue:
15468     PrevDecl = Previous.getAsSingle<NamedDecl>();
15469     break;
15470 
15471   case LookupResult::FoundOverloaded:
15472     PrevDecl = Previous.getRepresentativeDecl();
15473     break;
15474 
15475   case LookupResult::NotFound:
15476   case LookupResult::NotFoundInCurrentInstantiation:
15477   case LookupResult::Ambiguous:
15478     break;
15479   }
15480 
15481   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15482     // Maybe we will complain about the shadowed template parameter.
15483     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15484     // Just pretend that we didn't see the previous declaration.
15485     PrevDecl = nullptr;
15486   }
15487 
15488   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15489     PrevDecl = nullptr;
15490 
15491   SourceLocation TSSL = D.getLocStart();
15492   const ParsedAttr::PropertyData &Data = MSPropertyAttr.getPropertyData();
15493   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15494       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15495   ProcessDeclAttributes(TUScope, NewPD, D);
15496   NewPD->setAccess(AS);
15497 
15498   if (NewPD->isInvalidDecl())
15499     Record->setInvalidDecl();
15500 
15501   if (D.getDeclSpec().isModulePrivateSpecified())
15502     NewPD->setModulePrivate();
15503 
15504   if (NewPD->isInvalidDecl() && PrevDecl) {
15505     // Don't introduce NewFD into scope; there's already something
15506     // with the same name in the same scope.
15507   } else if (II) {
15508     PushOnScopeChains(NewPD, S);
15509   } else
15510     Record->addDecl(NewPD);
15511 
15512   return NewPD;
15513 }
15514