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 /// isCurrentClassName - Determine whether the identifier II is the
2063 /// name of the class type currently being defined. In the case of
2064 /// nested classes, this will only return true if II is the name of
2065 /// the innermost class.
2066 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2067                               const CXXScopeSpec *SS) {
2068   assert(getLangOpts().CPlusPlus && "No class names in C!");
2069 
2070   CXXRecordDecl *CurDecl;
2071   if (SS && SS->isSet() && !SS->isInvalid()) {
2072     DeclContext *DC = computeDeclContext(*SS, true);
2073     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2074   } else
2075     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2076 
2077   if (CurDecl && CurDecl->getIdentifier())
2078     return &II == CurDecl->getIdentifier();
2079   return false;
2080 }
2081 
2082 /// Determine whether the identifier II is a typo for the name of
2083 /// the class type currently being defined. If so, update it to the identifier
2084 /// that should have been used.
2085 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2086   assert(getLangOpts().CPlusPlus && "No class names in C!");
2087 
2088   if (!getLangOpts().SpellChecking)
2089     return false;
2090 
2091   CXXRecordDecl *CurDecl;
2092   if (SS && SS->isSet() && !SS->isInvalid()) {
2093     DeclContext *DC = computeDeclContext(*SS, true);
2094     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2095   } else
2096     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2097 
2098   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2099       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2100           < II->getLength()) {
2101     II = CurDecl->getIdentifier();
2102     return true;
2103   }
2104 
2105   return false;
2106 }
2107 
2108 /// Determine whether the given class is a base class of the given
2109 /// class, including looking at dependent bases.
2110 static bool findCircularInheritance(const CXXRecordDecl *Class,
2111                                     const CXXRecordDecl *Current) {
2112   SmallVector<const CXXRecordDecl*, 8> Queue;
2113 
2114   Class = Class->getCanonicalDecl();
2115   while (true) {
2116     for (const auto &I : Current->bases()) {
2117       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2118       if (!Base)
2119         continue;
2120 
2121       Base = Base->getDefinition();
2122       if (!Base)
2123         continue;
2124 
2125       if (Base->getCanonicalDecl() == Class)
2126         return true;
2127 
2128       Queue.push_back(Base);
2129     }
2130 
2131     if (Queue.empty())
2132       return false;
2133 
2134     Current = Queue.pop_back_val();
2135   }
2136 
2137   return false;
2138 }
2139 
2140 /// Check the validity of a C++ base class specifier.
2141 ///
2142 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2143 /// and returns NULL otherwise.
2144 CXXBaseSpecifier *
2145 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2146                          SourceRange SpecifierRange,
2147                          bool Virtual, AccessSpecifier Access,
2148                          TypeSourceInfo *TInfo,
2149                          SourceLocation EllipsisLoc) {
2150   QualType BaseType = TInfo->getType();
2151 
2152   // C++ [class.union]p1:
2153   //   A union shall not have base classes.
2154   if (Class->isUnion()) {
2155     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2156       << SpecifierRange;
2157     return nullptr;
2158   }
2159 
2160   if (EllipsisLoc.isValid() &&
2161       !TInfo->getType()->containsUnexpandedParameterPack()) {
2162     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2163       << TInfo->getTypeLoc().getSourceRange();
2164     EllipsisLoc = SourceLocation();
2165   }
2166 
2167   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2168 
2169   if (BaseType->isDependentType()) {
2170     // Make sure that we don't have circular inheritance among our dependent
2171     // bases. For non-dependent bases, the check for completeness below handles
2172     // this.
2173     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2174       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2175           ((BaseDecl = BaseDecl->getDefinition()) &&
2176            findCircularInheritance(Class, BaseDecl))) {
2177         Diag(BaseLoc, diag::err_circular_inheritance)
2178           << BaseType << Context.getTypeDeclType(Class);
2179 
2180         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2181           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2182             << BaseType;
2183 
2184         return nullptr;
2185       }
2186     }
2187 
2188     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2189                                           Class->getTagKind() == TTK_Class,
2190                                           Access, TInfo, EllipsisLoc);
2191   }
2192 
2193   // Base specifiers must be record types.
2194   if (!BaseType->isRecordType()) {
2195     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2196     return nullptr;
2197   }
2198 
2199   // C++ [class.union]p1:
2200   //   A union shall not be used as a base class.
2201   if (BaseType->isUnionType()) {
2202     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2203     return nullptr;
2204   }
2205 
2206   // For the MS ABI, propagate DLL attributes to base class templates.
2207   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2208     if (Attr *ClassAttr = getDLLAttr(Class)) {
2209       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2210               BaseType->getAsCXXRecordDecl())) {
2211         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2212                                             BaseLoc);
2213       }
2214     }
2215   }
2216 
2217   // C++ [class.derived]p2:
2218   //   The class-name in a base-specifier shall not be an incompletely
2219   //   defined class.
2220   if (RequireCompleteType(BaseLoc, BaseType,
2221                           diag::err_incomplete_base_class, SpecifierRange)) {
2222     Class->setInvalidDecl();
2223     return nullptr;
2224   }
2225 
2226   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2227   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2228   assert(BaseDecl && "Record type has no declaration");
2229   BaseDecl = BaseDecl->getDefinition();
2230   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2231   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2232   assert(CXXBaseDecl && "Base type is not a C++ type");
2233 
2234   // A class which contains a flexible array member is not suitable for use as a
2235   // base class:
2236   //   - If the layout determines that a base comes before another base,
2237   //     the flexible array member would index into the subsequent base.
2238   //   - If the layout determines that base comes before the derived class,
2239   //     the flexible array member would index into the derived class.
2240   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2241     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2242       << CXXBaseDecl->getDeclName();
2243     return nullptr;
2244   }
2245 
2246   // C++ [class]p3:
2247   //   If a class is marked final and it appears as a base-type-specifier in
2248   //   base-clause, the program is ill-formed.
2249   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2250     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2251       << CXXBaseDecl->getDeclName()
2252       << FA->isSpelledAsSealed();
2253     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2254         << CXXBaseDecl->getDeclName() << FA->getRange();
2255     return nullptr;
2256   }
2257 
2258   if (BaseDecl->isInvalidDecl())
2259     Class->setInvalidDecl();
2260 
2261   // Create the base specifier.
2262   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2263                                         Class->getTagKind() == TTK_Class,
2264                                         Access, TInfo, EllipsisLoc);
2265 }
2266 
2267 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2268 /// one entry in the base class list of a class specifier, for
2269 /// example:
2270 ///    class foo : public bar, virtual private baz {
2271 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2272 BaseResult
2273 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2274                          ParsedAttributes &Attributes,
2275                          bool Virtual, AccessSpecifier Access,
2276                          ParsedType basetype, SourceLocation BaseLoc,
2277                          SourceLocation EllipsisLoc) {
2278   if (!classdecl)
2279     return true;
2280 
2281   AdjustDeclIfTemplate(classdecl);
2282   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2283   if (!Class)
2284     return true;
2285 
2286   // We haven't yet attached the base specifiers.
2287   Class->setIsParsingBaseSpecifiers();
2288 
2289   // We do not support any C++11 attributes on base-specifiers yet.
2290   // Diagnose any attributes we see.
2291   if (!Attributes.empty()) {
2292     for (AttributeList *Attr = Attributes.getList(); Attr;
2293          Attr = Attr->getNext()) {
2294       if (Attr->isInvalid() ||
2295           Attr->getKind() == AttributeList::IgnoredAttribute)
2296         continue;
2297       Diag(Attr->getLoc(),
2298            Attr->getKind() == AttributeList::UnknownAttribute
2299              ? diag::warn_unknown_attribute_ignored
2300              : diag::err_base_specifier_attribute)
2301         << Attr->getName();
2302     }
2303   }
2304 
2305   TypeSourceInfo *TInfo = nullptr;
2306   GetTypeFromParser(basetype, &TInfo);
2307 
2308   if (EllipsisLoc.isInvalid() &&
2309       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2310                                       UPPC_BaseType))
2311     return true;
2312 
2313   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2314                                                       Virtual, Access, TInfo,
2315                                                       EllipsisLoc))
2316     return BaseSpec;
2317   else
2318     Class->setInvalidDecl();
2319 
2320   return true;
2321 }
2322 
2323 /// Use small set to collect indirect bases.  As this is only used
2324 /// locally, there's no need to abstract the small size parameter.
2325 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2326 
2327 /// Recursively add the bases of Type.  Don't add Type itself.
2328 static void
2329 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2330                   const QualType &Type)
2331 {
2332   // Even though the incoming type is a base, it might not be
2333   // a class -- it could be a template parm, for instance.
2334   if (auto Rec = Type->getAs<RecordType>()) {
2335     auto Decl = Rec->getAsCXXRecordDecl();
2336 
2337     // Iterate over its bases.
2338     for (const auto &BaseSpec : Decl->bases()) {
2339       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2340         .getUnqualifiedType();
2341       if (Set.insert(Base).second)
2342         // If we've not already seen it, recurse.
2343         NoteIndirectBases(Context, Set, Base);
2344     }
2345   }
2346 }
2347 
2348 /// Performs the actual work of attaching the given base class
2349 /// specifiers to a C++ class.
2350 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2351                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2352  if (Bases.empty())
2353     return false;
2354 
2355   // Used to keep track of which base types we have already seen, so
2356   // that we can properly diagnose redundant direct base types. Note
2357   // that the key is always the unqualified canonical type of the base
2358   // class.
2359   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2360 
2361   // Used to track indirect bases so we can see if a direct base is
2362   // ambiguous.
2363   IndirectBaseSet IndirectBaseTypes;
2364 
2365   // Copy non-redundant base specifiers into permanent storage.
2366   unsigned NumGoodBases = 0;
2367   bool Invalid = false;
2368   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2369     QualType NewBaseType
2370       = Context.getCanonicalType(Bases[idx]->getType());
2371     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2372 
2373     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2374     if (KnownBase) {
2375       // C++ [class.mi]p3:
2376       //   A class shall not be specified as a direct base class of a
2377       //   derived class more than once.
2378       Diag(Bases[idx]->getLocStart(),
2379            diag::err_duplicate_base_class)
2380         << KnownBase->getType()
2381         << Bases[idx]->getSourceRange();
2382 
2383       // Delete the duplicate base class specifier; we're going to
2384       // overwrite its pointer later.
2385       Context.Deallocate(Bases[idx]);
2386 
2387       Invalid = true;
2388     } else {
2389       // Okay, add this new base class.
2390       KnownBase = Bases[idx];
2391       Bases[NumGoodBases++] = Bases[idx];
2392 
2393       // Note this base's direct & indirect bases, if there could be ambiguity.
2394       if (Bases.size() > 1)
2395         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2396 
2397       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2398         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2399         if (Class->isInterface() &&
2400               (!RD->isInterfaceLike() ||
2401                KnownBase->getAccessSpecifier() != AS_public)) {
2402           // The Microsoft extension __interface does not permit bases that
2403           // are not themselves public interfaces.
2404           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2405             << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2406             << RD->getSourceRange();
2407           Invalid = true;
2408         }
2409         if (RD->hasAttr<WeakAttr>())
2410           Class->addAttr(WeakAttr::CreateImplicit(Context));
2411       }
2412     }
2413   }
2414 
2415   // Attach the remaining base class specifiers to the derived class.
2416   Class->setBases(Bases.data(), NumGoodBases);
2417 
2418   // Check that the only base classes that are duplicate are virtual.
2419   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2420     // Check whether this direct base is inaccessible due to ambiguity.
2421     QualType BaseType = Bases[idx]->getType();
2422 
2423     // Skip all dependent types in templates being used as base specifiers.
2424     // Checks below assume that the base specifier is a CXXRecord.
2425     if (BaseType->isDependentType())
2426       continue;
2427 
2428     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2429       .getUnqualifiedType();
2430 
2431     if (IndirectBaseTypes.count(CanonicalBase)) {
2432       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2433                          /*DetectVirtual=*/true);
2434       bool found
2435         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2436       assert(found);
2437       (void)found;
2438 
2439       if (Paths.isAmbiguous(CanonicalBase))
2440         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2441           << BaseType << getAmbiguousPathsDisplayString(Paths)
2442           << Bases[idx]->getSourceRange();
2443       else
2444         assert(Bases[idx]->isVirtual());
2445     }
2446 
2447     // Delete the base class specifier, since its data has been copied
2448     // into the CXXRecordDecl.
2449     Context.Deallocate(Bases[idx]);
2450   }
2451 
2452   return Invalid;
2453 }
2454 
2455 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2456 /// class, after checking whether there are any duplicate base
2457 /// classes.
2458 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2459                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2460   if (!ClassDecl || Bases.empty())
2461     return;
2462 
2463   AdjustDeclIfTemplate(ClassDecl);
2464   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2465 }
2466 
2467 /// Determine whether the type \p Derived is a C++ class that is
2468 /// derived from the type \p Base.
2469 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2470   if (!getLangOpts().CPlusPlus)
2471     return false;
2472 
2473   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2474   if (!DerivedRD)
2475     return false;
2476 
2477   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2478   if (!BaseRD)
2479     return false;
2480 
2481   // If either the base or the derived type is invalid, don't try to
2482   // check whether one is derived from the other.
2483   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2484     return false;
2485 
2486   // FIXME: In a modules build, do we need the entire path to be visible for us
2487   // to be able to use the inheritance relationship?
2488   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2489     return false;
2490 
2491   return DerivedRD->isDerivedFrom(BaseRD);
2492 }
2493 
2494 /// Determine whether the type \p Derived is a C++ class that is
2495 /// derived from the type \p Base.
2496 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2497                          CXXBasePaths &Paths) {
2498   if (!getLangOpts().CPlusPlus)
2499     return false;
2500 
2501   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2502   if (!DerivedRD)
2503     return false;
2504 
2505   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2506   if (!BaseRD)
2507     return false;
2508 
2509   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2510     return false;
2511 
2512   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2513 }
2514 
2515 static void BuildBasePathArray(const CXXBasePath &Path,
2516                                CXXCastPath &BasePathArray) {
2517   // We first go backward and check if we have a virtual base.
2518   // FIXME: It would be better if CXXBasePath had the base specifier for
2519   // the nearest virtual base.
2520   unsigned Start = 0;
2521   for (unsigned I = Path.size(); I != 0; --I) {
2522     if (Path[I - 1].Base->isVirtual()) {
2523       Start = I - 1;
2524       break;
2525     }
2526   }
2527 
2528   // Now add all bases.
2529   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2530     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2531 }
2532 
2533 
2534 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2535                               CXXCastPath &BasePathArray) {
2536   assert(BasePathArray.empty() && "Base path array must be empty!");
2537   assert(Paths.isRecordingPaths() && "Must record paths!");
2538   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2539 }
2540 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2541 /// conversion (where Derived and Base are class types) is
2542 /// well-formed, meaning that the conversion is unambiguous (and
2543 /// that all of the base classes are accessible). Returns true
2544 /// and emits a diagnostic if the code is ill-formed, returns false
2545 /// otherwise. Loc is the location where this routine should point to
2546 /// if there is an error, and Range is the source range to highlight
2547 /// if there is an error.
2548 ///
2549 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2550 /// diagnostic for the respective type of error will be suppressed, but the
2551 /// check for ill-formed code will still be performed.
2552 bool
2553 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2554                                    unsigned InaccessibleBaseID,
2555                                    unsigned AmbigiousBaseConvID,
2556                                    SourceLocation Loc, SourceRange Range,
2557                                    DeclarationName Name,
2558                                    CXXCastPath *BasePath,
2559                                    bool IgnoreAccess) {
2560   // First, determine whether the path from Derived to Base is
2561   // ambiguous. This is slightly more expensive than checking whether
2562   // the Derived to Base conversion exists, because here we need to
2563   // explore multiple paths to determine if there is an ambiguity.
2564   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2565                      /*DetectVirtual=*/false);
2566   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2567   if (!DerivationOkay)
2568     return true;
2569 
2570   const CXXBasePath *Path = nullptr;
2571   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2572     Path = &Paths.front();
2573 
2574   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2575   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2576   // user to access such bases.
2577   if (!Path && getLangOpts().MSVCCompat) {
2578     for (const CXXBasePath &PossiblePath : Paths) {
2579       if (PossiblePath.size() == 1) {
2580         Path = &PossiblePath;
2581         if (AmbigiousBaseConvID)
2582           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2583               << Base << Derived << Range;
2584         break;
2585       }
2586     }
2587   }
2588 
2589   if (Path) {
2590     if (!IgnoreAccess) {
2591       // Check that the base class can be accessed.
2592       switch (
2593           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2594       case AR_inaccessible:
2595         return true;
2596       case AR_accessible:
2597       case AR_dependent:
2598       case AR_delayed:
2599         break;
2600       }
2601     }
2602 
2603     // Build a base path if necessary.
2604     if (BasePath)
2605       ::BuildBasePathArray(*Path, *BasePath);
2606     return false;
2607   }
2608 
2609   if (AmbigiousBaseConvID) {
2610     // We know that the derived-to-base conversion is ambiguous, and
2611     // we're going to produce a diagnostic. Perform the derived-to-base
2612     // search just one more time to compute all of the possible paths so
2613     // that we can print them out. This is more expensive than any of
2614     // the previous derived-to-base checks we've done, but at this point
2615     // performance isn't as much of an issue.
2616     Paths.clear();
2617     Paths.setRecordingPaths(true);
2618     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2619     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2620     (void)StillOkay;
2621 
2622     // Build up a textual representation of the ambiguous paths, e.g.,
2623     // D -> B -> A, that will be used to illustrate the ambiguous
2624     // conversions in the diagnostic. We only print one of the paths
2625     // to each base class subobject.
2626     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2627 
2628     Diag(Loc, AmbigiousBaseConvID)
2629     << Derived << Base << PathDisplayStr << Range << Name;
2630   }
2631   return true;
2632 }
2633 
2634 bool
2635 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2636                                    SourceLocation Loc, SourceRange Range,
2637                                    CXXCastPath *BasePath,
2638                                    bool IgnoreAccess) {
2639   return CheckDerivedToBaseConversion(
2640       Derived, Base, diag::err_upcast_to_inaccessible_base,
2641       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2642       BasePath, IgnoreAccess);
2643 }
2644 
2645 
2646 /// Builds a string representing ambiguous paths from a
2647 /// specific derived class to different subobjects of the same base
2648 /// class.
2649 ///
2650 /// This function builds a string that can be used in error messages
2651 /// to show the different paths that one can take through the
2652 /// inheritance hierarchy to go from the derived class to different
2653 /// subobjects of a base class. The result looks something like this:
2654 /// @code
2655 /// struct D -> struct B -> struct A
2656 /// struct D -> struct C -> struct A
2657 /// @endcode
2658 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2659   std::string PathDisplayStr;
2660   std::set<unsigned> DisplayedPaths;
2661   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2662        Path != Paths.end(); ++Path) {
2663     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2664       // We haven't displayed a path to this particular base
2665       // class subobject yet.
2666       PathDisplayStr += "\n    ";
2667       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2668       for (CXXBasePath::const_iterator Element = Path->begin();
2669            Element != Path->end(); ++Element)
2670         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2671     }
2672   }
2673 
2674   return PathDisplayStr;
2675 }
2676 
2677 //===----------------------------------------------------------------------===//
2678 // C++ class member Handling
2679 //===----------------------------------------------------------------------===//
2680 
2681 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2682 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2683                                 SourceLocation ASLoc,
2684                                 SourceLocation ColonLoc,
2685                                 AttributeList *Attrs) {
2686   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2687   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2688                                                   ASLoc, ColonLoc);
2689   CurContext->addHiddenDecl(ASDecl);
2690   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2691 }
2692 
2693 /// CheckOverrideControl - Check C++11 override control semantics.
2694 void Sema::CheckOverrideControl(NamedDecl *D) {
2695   if (D->isInvalidDecl())
2696     return;
2697 
2698   // We only care about "override" and "final" declarations.
2699   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2700     return;
2701 
2702   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2703 
2704   // We can't check dependent instance methods.
2705   if (MD && MD->isInstance() &&
2706       (MD->getParent()->hasAnyDependentBases() ||
2707        MD->getType()->isDependentType()))
2708     return;
2709 
2710   if (MD && !MD->isVirtual()) {
2711     // If we have a non-virtual method, check if if hides a virtual method.
2712     // (In that case, it's most likely the method has the wrong type.)
2713     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2714     FindHiddenVirtualMethods(MD, OverloadedMethods);
2715 
2716     if (!OverloadedMethods.empty()) {
2717       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2718         Diag(OA->getLocation(),
2719              diag::override_keyword_hides_virtual_member_function)
2720           << "override" << (OverloadedMethods.size() > 1);
2721       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2722         Diag(FA->getLocation(),
2723              diag::override_keyword_hides_virtual_member_function)
2724           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2725           << (OverloadedMethods.size() > 1);
2726       }
2727       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2728       MD->setInvalidDecl();
2729       return;
2730     }
2731     // Fall through into the general case diagnostic.
2732     // FIXME: We might want to attempt typo correction here.
2733   }
2734 
2735   if (!MD || !MD->isVirtual()) {
2736     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2737       Diag(OA->getLocation(),
2738            diag::override_keyword_only_allowed_on_virtual_member_functions)
2739         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2740       D->dropAttr<OverrideAttr>();
2741     }
2742     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2743       Diag(FA->getLocation(),
2744            diag::override_keyword_only_allowed_on_virtual_member_functions)
2745         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2746         << FixItHint::CreateRemoval(FA->getLocation());
2747       D->dropAttr<FinalAttr>();
2748     }
2749     return;
2750   }
2751 
2752   // C++11 [class.virtual]p5:
2753   //   If a function is marked with the virt-specifier override and
2754   //   does not override a member function of a base class, the program is
2755   //   ill-formed.
2756   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2757   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2758     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2759       << MD->getDeclName();
2760 }
2761 
2762 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2763   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2764     return;
2765   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2766   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2767     return;
2768 
2769   SourceLocation Loc = MD->getLocation();
2770   SourceLocation SpellingLoc = Loc;
2771   if (getSourceManager().isMacroArgExpansion(Loc))
2772     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2773   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2774   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2775       return;
2776 
2777   if (MD->size_overridden_methods() > 0) {
2778     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2779                           ? diag::warn_destructor_marked_not_override_overriding
2780                           : diag::warn_function_marked_not_override_overriding;
2781     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2782     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2783     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2784   }
2785 }
2786 
2787 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2788 /// function overrides a virtual member function marked 'final', according to
2789 /// C++11 [class.virtual]p4.
2790 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2791                                                   const CXXMethodDecl *Old) {
2792   FinalAttr *FA = Old->getAttr<FinalAttr>();
2793   if (!FA)
2794     return false;
2795 
2796   Diag(New->getLocation(), diag::err_final_function_overridden)
2797     << New->getDeclName()
2798     << FA->isSpelledAsSealed();
2799   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2800   return true;
2801 }
2802 
2803 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2804   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2805   // FIXME: Destruction of ObjC lifetime types has side-effects.
2806   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2807     return !RD->isCompleteDefinition() ||
2808            !RD->hasTrivialDefaultConstructor() ||
2809            !RD->hasTrivialDestructor();
2810   return false;
2811 }
2812 
2813 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2814   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2815     if (it->isDeclspecPropertyAttribute())
2816       return it;
2817   return nullptr;
2818 }
2819 
2820 // Check if there is a field shadowing.
2821 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2822                                       DeclarationName FieldName,
2823                                       const CXXRecordDecl *RD) {
2824   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2825     return;
2826 
2827   // To record a shadowed field in a base
2828   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2829   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2830                            CXXBasePath &Path) {
2831     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2832     // Record an ambiguous path directly
2833     if (Bases.find(Base) != Bases.end())
2834       return true;
2835     for (const auto Field : Base->lookup(FieldName)) {
2836       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2837           Field->getAccess() != AS_private) {
2838         assert(Field->getAccess() != AS_none);
2839         assert(Bases.find(Base) == Bases.end());
2840         Bases[Base] = Field;
2841         return true;
2842       }
2843     }
2844     return false;
2845   };
2846 
2847   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2848                      /*DetectVirtual=*/true);
2849   if (!RD->lookupInBases(FieldShadowed, Paths))
2850     return;
2851 
2852   for (const auto &P : Paths) {
2853     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2854     auto It = Bases.find(Base);
2855     // Skip duplicated bases
2856     if (It == Bases.end())
2857       continue;
2858     auto BaseField = It->second;
2859     assert(BaseField->getAccess() != AS_private);
2860     if (AS_none !=
2861         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2862       Diag(Loc, diag::warn_shadow_field)
2863         << FieldName << RD << Base;
2864       Diag(BaseField->getLocation(), diag::note_shadow_field);
2865       Bases.erase(It);
2866     }
2867   }
2868 }
2869 
2870 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2871 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2872 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2873 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2874 /// present (but parsing it has been deferred).
2875 NamedDecl *
2876 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2877                                MultiTemplateParamsArg TemplateParameterLists,
2878                                Expr *BW, const VirtSpecifiers &VS,
2879                                InClassInitStyle InitStyle) {
2880   const DeclSpec &DS = D.getDeclSpec();
2881   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2882   DeclarationName Name = NameInfo.getName();
2883   SourceLocation Loc = NameInfo.getLoc();
2884 
2885   // For anonymous bitfields, the location should point to the type.
2886   if (Loc.isInvalid())
2887     Loc = D.getLocStart();
2888 
2889   Expr *BitWidth = static_cast<Expr*>(BW);
2890 
2891   assert(isa<CXXRecordDecl>(CurContext));
2892   assert(!DS.isFriendSpecified());
2893 
2894   bool isFunc = D.isDeclarationOfFunction();
2895   AttributeList *MSPropertyAttr =
2896       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2897 
2898   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2899     // The Microsoft extension __interface only permits public member functions
2900     // and prohibits constructors, destructors, operators, non-public member
2901     // functions, static methods and data members.
2902     unsigned InvalidDecl;
2903     bool ShowDeclName = true;
2904     if (!isFunc &&
2905         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2906       InvalidDecl = 0;
2907     else if (!isFunc)
2908       InvalidDecl = 1;
2909     else if (AS != AS_public)
2910       InvalidDecl = 2;
2911     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2912       InvalidDecl = 3;
2913     else switch (Name.getNameKind()) {
2914       case DeclarationName::CXXConstructorName:
2915         InvalidDecl = 4;
2916         ShowDeclName = false;
2917         break;
2918 
2919       case DeclarationName::CXXDestructorName:
2920         InvalidDecl = 5;
2921         ShowDeclName = false;
2922         break;
2923 
2924       case DeclarationName::CXXOperatorName:
2925       case DeclarationName::CXXConversionFunctionName:
2926         InvalidDecl = 6;
2927         break;
2928 
2929       default:
2930         InvalidDecl = 0;
2931         break;
2932     }
2933 
2934     if (InvalidDecl) {
2935       if (ShowDeclName)
2936         Diag(Loc, diag::err_invalid_member_in_interface)
2937           << (InvalidDecl-1) << Name;
2938       else
2939         Diag(Loc, diag::err_invalid_member_in_interface)
2940           << (InvalidDecl-1) << "";
2941       return nullptr;
2942     }
2943   }
2944 
2945   // C++ 9.2p6: A member shall not be declared to have automatic storage
2946   // duration (auto, register) or with the extern storage-class-specifier.
2947   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2948   // data members and cannot be applied to names declared const or static,
2949   // and cannot be applied to reference members.
2950   switch (DS.getStorageClassSpec()) {
2951   case DeclSpec::SCS_unspecified:
2952   case DeclSpec::SCS_typedef:
2953   case DeclSpec::SCS_static:
2954     break;
2955   case DeclSpec::SCS_mutable:
2956     if (isFunc) {
2957       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2958 
2959       // FIXME: It would be nicer if the keyword was ignored only for this
2960       // declarator. Otherwise we could get follow-up errors.
2961       D.getMutableDeclSpec().ClearStorageClassSpecs();
2962     }
2963     break;
2964   default:
2965     Diag(DS.getStorageClassSpecLoc(),
2966          diag::err_storageclass_invalid_for_member);
2967     D.getMutableDeclSpec().ClearStorageClassSpecs();
2968     break;
2969   }
2970 
2971   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2972                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2973                       !isFunc);
2974 
2975   if (DS.isConstexprSpecified() && isInstField) {
2976     SemaDiagnosticBuilder B =
2977         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2978     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2979     if (InitStyle == ICIS_NoInit) {
2980       B << 0 << 0;
2981       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2982         B << FixItHint::CreateRemoval(ConstexprLoc);
2983       else {
2984         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2985         D.getMutableDeclSpec().ClearConstexprSpec();
2986         const char *PrevSpec;
2987         unsigned DiagID;
2988         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2989             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2990         (void)Failed;
2991         assert(!Failed && "Making a constexpr member const shouldn't fail");
2992       }
2993     } else {
2994       B << 1;
2995       const char *PrevSpec;
2996       unsigned DiagID;
2997       if (D.getMutableDeclSpec().SetStorageClassSpec(
2998           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2999           Context.getPrintingPolicy())) {
3000         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3001                "This is the only DeclSpec that should fail to be applied");
3002         B << 1;
3003       } else {
3004         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3005         isInstField = false;
3006       }
3007     }
3008   }
3009 
3010   NamedDecl *Member;
3011   if (isInstField) {
3012     CXXScopeSpec &SS = D.getCXXScopeSpec();
3013 
3014     // Data members must have identifiers for names.
3015     if (!Name.isIdentifier()) {
3016       Diag(Loc, diag::err_bad_variable_name)
3017         << Name;
3018       return nullptr;
3019     }
3020 
3021     IdentifierInfo *II = Name.getAsIdentifierInfo();
3022 
3023     // Member field could not be with "template" keyword.
3024     // So TemplateParameterLists should be empty in this case.
3025     if (TemplateParameterLists.size()) {
3026       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3027       if (TemplateParams->size()) {
3028         // There is no such thing as a member field template.
3029         Diag(D.getIdentifierLoc(), diag::err_template_member)
3030             << II
3031             << SourceRange(TemplateParams->getTemplateLoc(),
3032                 TemplateParams->getRAngleLoc());
3033       } else {
3034         // There is an extraneous 'template<>' for this member.
3035         Diag(TemplateParams->getTemplateLoc(),
3036             diag::err_template_member_noparams)
3037             << II
3038             << SourceRange(TemplateParams->getTemplateLoc(),
3039                 TemplateParams->getRAngleLoc());
3040       }
3041       return nullptr;
3042     }
3043 
3044     if (SS.isSet() && !SS.isInvalid()) {
3045       // The user provided a superfluous scope specifier inside a class
3046       // definition:
3047       //
3048       // class X {
3049       //   int X::member;
3050       // };
3051       if (DeclContext *DC = computeDeclContext(SS, false))
3052         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3053                                      D.getName().getKind() ==
3054                                          UnqualifiedIdKind::IK_TemplateId);
3055       else
3056         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3057           << Name << SS.getRange();
3058 
3059       SS.clear();
3060     }
3061 
3062     if (MSPropertyAttr) {
3063       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3064                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3065       if (!Member)
3066         return nullptr;
3067       isInstField = false;
3068     } else {
3069       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3070                                 BitWidth, InitStyle, AS);
3071       if (!Member)
3072         return nullptr;
3073     }
3074 
3075     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3076   } else {
3077     Member = HandleDeclarator(S, D, TemplateParameterLists);
3078     if (!Member)
3079       return nullptr;
3080 
3081     // Non-instance-fields can't have a bitfield.
3082     if (BitWidth) {
3083       if (Member->isInvalidDecl()) {
3084         // don't emit another diagnostic.
3085       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3086         // C++ 9.6p3: A bit-field shall not be a static member.
3087         // "static member 'A' cannot be a bit-field"
3088         Diag(Loc, diag::err_static_not_bitfield)
3089           << Name << BitWidth->getSourceRange();
3090       } else if (isa<TypedefDecl>(Member)) {
3091         // "typedef member 'x' cannot be a bit-field"
3092         Diag(Loc, diag::err_typedef_not_bitfield)
3093           << Name << BitWidth->getSourceRange();
3094       } else {
3095         // A function typedef ("typedef int f(); f a;").
3096         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3097         Diag(Loc, diag::err_not_integral_type_bitfield)
3098           << Name << cast<ValueDecl>(Member)->getType()
3099           << BitWidth->getSourceRange();
3100       }
3101 
3102       BitWidth = nullptr;
3103       Member->setInvalidDecl();
3104     }
3105 
3106     Member->setAccess(AS);
3107 
3108     // If we have declared a member function template or static data member
3109     // template, set the access of the templated declaration as well.
3110     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3111       FunTmpl->getTemplatedDecl()->setAccess(AS);
3112     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3113       VarTmpl->getTemplatedDecl()->setAccess(AS);
3114   }
3115 
3116   if (VS.isOverrideSpecified())
3117     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3118   if (VS.isFinalSpecified())
3119     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3120                                             VS.isFinalSpelledSealed()));
3121 
3122   if (VS.getLastLocation().isValid()) {
3123     // Update the end location of a method that has a virt-specifiers.
3124     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3125       MD->setRangeEnd(VS.getLastLocation());
3126   }
3127 
3128   CheckOverrideControl(Member);
3129 
3130   assert((Name || isInstField) && "No identifier for non-field ?");
3131 
3132   if (isInstField) {
3133     FieldDecl *FD = cast<FieldDecl>(Member);
3134     FieldCollector->Add(FD);
3135 
3136     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3137       // Remember all explicit private FieldDecls that have a name, no side
3138       // effects and are not part of a dependent type declaration.
3139       if (!FD->isImplicit() && FD->getDeclName() &&
3140           FD->getAccess() == AS_private &&
3141           !FD->hasAttr<UnusedAttr>() &&
3142           !FD->getParent()->isDependentContext() &&
3143           !InitializationHasSideEffects(*FD))
3144         UnusedPrivateFields.insert(FD);
3145     }
3146   }
3147 
3148   return Member;
3149 }
3150 
3151 namespace {
3152   class UninitializedFieldVisitor
3153       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3154     Sema &S;
3155     // List of Decls to generate a warning on.  Also remove Decls that become
3156     // initialized.
3157     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3158     // List of base classes of the record.  Classes are removed after their
3159     // initializers.
3160     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3161     // Vector of decls to be removed from the Decl set prior to visiting the
3162     // nodes.  These Decls may have been initialized in the prior initializer.
3163     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3164     // If non-null, add a note to the warning pointing back to the constructor.
3165     const CXXConstructorDecl *Constructor;
3166     // Variables to hold state when processing an initializer list.  When
3167     // InitList is true, special case initialization of FieldDecls matching
3168     // InitListFieldDecl.
3169     bool InitList;
3170     FieldDecl *InitListFieldDecl;
3171     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3172 
3173   public:
3174     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3175     UninitializedFieldVisitor(Sema &S,
3176                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3177                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3178       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3179         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3180 
3181     // Returns true if the use of ME is not an uninitialized use.
3182     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3183                                          bool CheckReferenceOnly) {
3184       llvm::SmallVector<FieldDecl*, 4> Fields;
3185       bool ReferenceField = false;
3186       while (ME) {
3187         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3188         if (!FD)
3189           return false;
3190         Fields.push_back(FD);
3191         if (FD->getType()->isReferenceType())
3192           ReferenceField = true;
3193         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3194       }
3195 
3196       // Binding a reference to an unintialized field is not an
3197       // uninitialized use.
3198       if (CheckReferenceOnly && !ReferenceField)
3199         return true;
3200 
3201       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3202       // Discard the first field since it is the field decl that is being
3203       // initialized.
3204       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3205         UsedFieldIndex.push_back((*I)->getFieldIndex());
3206       }
3207 
3208       for (auto UsedIter = UsedFieldIndex.begin(),
3209                 UsedEnd = UsedFieldIndex.end(),
3210                 OrigIter = InitFieldIndex.begin(),
3211                 OrigEnd = InitFieldIndex.end();
3212            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3213         if (*UsedIter < *OrigIter)
3214           return true;
3215         if (*UsedIter > *OrigIter)
3216           break;
3217       }
3218 
3219       return false;
3220     }
3221 
3222     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3223                           bool AddressOf) {
3224       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3225         return;
3226 
3227       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3228       // or union.
3229       MemberExpr *FieldME = ME;
3230 
3231       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3232 
3233       Expr *Base = ME;
3234       while (MemberExpr *SubME =
3235                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3236 
3237         if (isa<VarDecl>(SubME->getMemberDecl()))
3238           return;
3239 
3240         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3241           if (!FD->isAnonymousStructOrUnion())
3242             FieldME = SubME;
3243 
3244         if (!FieldME->getType().isPODType(S.Context))
3245           AllPODFields = false;
3246 
3247         Base = SubME->getBase();
3248       }
3249 
3250       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3251         return;
3252 
3253       if (AddressOf && AllPODFields)
3254         return;
3255 
3256       ValueDecl* FoundVD = FieldME->getMemberDecl();
3257 
3258       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3259         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3260           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3261         }
3262 
3263         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3264           QualType T = BaseCast->getType();
3265           if (T->isPointerType() &&
3266               BaseClasses.count(T->getPointeeType())) {
3267             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3268                 << T->getPointeeType() << FoundVD;
3269           }
3270         }
3271       }
3272 
3273       if (!Decls.count(FoundVD))
3274         return;
3275 
3276       const bool IsReference = FoundVD->getType()->isReferenceType();
3277 
3278       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3279         // Special checking for initializer lists.
3280         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3281           return;
3282         }
3283       } else {
3284         // Prevent double warnings on use of unbounded references.
3285         if (CheckReferenceOnly && !IsReference)
3286           return;
3287       }
3288 
3289       unsigned diag = IsReference
3290           ? diag::warn_reference_field_is_uninit
3291           : diag::warn_field_is_uninit;
3292       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3293       if (Constructor)
3294         S.Diag(Constructor->getLocation(),
3295                diag::note_uninit_in_this_constructor)
3296           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3297 
3298     }
3299 
3300     void HandleValue(Expr *E, bool AddressOf) {
3301       E = E->IgnoreParens();
3302 
3303       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3304         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3305                          AddressOf /*AddressOf*/);
3306         return;
3307       }
3308 
3309       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3310         Visit(CO->getCond());
3311         HandleValue(CO->getTrueExpr(), AddressOf);
3312         HandleValue(CO->getFalseExpr(), AddressOf);
3313         return;
3314       }
3315 
3316       if (BinaryConditionalOperator *BCO =
3317               dyn_cast<BinaryConditionalOperator>(E)) {
3318         Visit(BCO->getCond());
3319         HandleValue(BCO->getFalseExpr(), AddressOf);
3320         return;
3321       }
3322 
3323       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3324         HandleValue(OVE->getSourceExpr(), AddressOf);
3325         return;
3326       }
3327 
3328       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3329         switch (BO->getOpcode()) {
3330         default:
3331           break;
3332         case(BO_PtrMemD):
3333         case(BO_PtrMemI):
3334           HandleValue(BO->getLHS(), AddressOf);
3335           Visit(BO->getRHS());
3336           return;
3337         case(BO_Comma):
3338           Visit(BO->getLHS());
3339           HandleValue(BO->getRHS(), AddressOf);
3340           return;
3341         }
3342       }
3343 
3344       Visit(E);
3345     }
3346 
3347     void CheckInitListExpr(InitListExpr *ILE) {
3348       InitFieldIndex.push_back(0);
3349       for (auto Child : ILE->children()) {
3350         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3351           CheckInitListExpr(SubList);
3352         } else {
3353           Visit(Child);
3354         }
3355         ++InitFieldIndex.back();
3356       }
3357       InitFieldIndex.pop_back();
3358     }
3359 
3360     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3361                           FieldDecl *Field, const Type *BaseClass) {
3362       // Remove Decls that may have been initialized in the previous
3363       // initializer.
3364       for (ValueDecl* VD : DeclsToRemove)
3365         Decls.erase(VD);
3366       DeclsToRemove.clear();
3367 
3368       Constructor = FieldConstructor;
3369       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3370 
3371       if (ILE && Field) {
3372         InitList = true;
3373         InitListFieldDecl = Field;
3374         InitFieldIndex.clear();
3375         CheckInitListExpr(ILE);
3376       } else {
3377         InitList = false;
3378         Visit(E);
3379       }
3380 
3381       if (Field)
3382         Decls.erase(Field);
3383       if (BaseClass)
3384         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3385     }
3386 
3387     void VisitMemberExpr(MemberExpr *ME) {
3388       // All uses of unbounded reference fields will warn.
3389       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3390     }
3391 
3392     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3393       if (E->getCastKind() == CK_LValueToRValue) {
3394         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3395         return;
3396       }
3397 
3398       Inherited::VisitImplicitCastExpr(E);
3399     }
3400 
3401     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3402       if (E->getConstructor()->isCopyConstructor()) {
3403         Expr *ArgExpr = E->getArg(0);
3404         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3405           if (ILE->getNumInits() == 1)
3406             ArgExpr = ILE->getInit(0);
3407         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3408           if (ICE->getCastKind() == CK_NoOp)
3409             ArgExpr = ICE->getSubExpr();
3410         HandleValue(ArgExpr, false /*AddressOf*/);
3411         return;
3412       }
3413       Inherited::VisitCXXConstructExpr(E);
3414     }
3415 
3416     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3417       Expr *Callee = E->getCallee();
3418       if (isa<MemberExpr>(Callee)) {
3419         HandleValue(Callee, false /*AddressOf*/);
3420         for (auto Arg : E->arguments())
3421           Visit(Arg);
3422         return;
3423       }
3424 
3425       Inherited::VisitCXXMemberCallExpr(E);
3426     }
3427 
3428     void VisitCallExpr(CallExpr *E) {
3429       // Treat std::move as a use.
3430       if (E->isCallToStdMove()) {
3431         HandleValue(E->getArg(0), /*AddressOf=*/false);
3432         return;
3433       }
3434 
3435       Inherited::VisitCallExpr(E);
3436     }
3437 
3438     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3439       Expr *Callee = E->getCallee();
3440 
3441       if (isa<UnresolvedLookupExpr>(Callee))
3442         return Inherited::VisitCXXOperatorCallExpr(E);
3443 
3444       Visit(Callee);
3445       for (auto Arg : E->arguments())
3446         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3447     }
3448 
3449     void VisitBinaryOperator(BinaryOperator *E) {
3450       // If a field assignment is detected, remove the field from the
3451       // uninitiailized field set.
3452       if (E->getOpcode() == BO_Assign)
3453         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3454           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3455             if (!FD->getType()->isReferenceType())
3456               DeclsToRemove.push_back(FD);
3457 
3458       if (E->isCompoundAssignmentOp()) {
3459         HandleValue(E->getLHS(), false /*AddressOf*/);
3460         Visit(E->getRHS());
3461         return;
3462       }
3463 
3464       Inherited::VisitBinaryOperator(E);
3465     }
3466 
3467     void VisitUnaryOperator(UnaryOperator *E) {
3468       if (E->isIncrementDecrementOp()) {
3469         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3470         return;
3471       }
3472       if (E->getOpcode() == UO_AddrOf) {
3473         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3474           HandleValue(ME->getBase(), true /*AddressOf*/);
3475           return;
3476         }
3477       }
3478 
3479       Inherited::VisitUnaryOperator(E);
3480     }
3481   };
3482 
3483   // Diagnose value-uses of fields to initialize themselves, e.g.
3484   //   foo(foo)
3485   // where foo is not also a parameter to the constructor.
3486   // Also diagnose across field uninitialized use such as
3487   //   x(y), y(x)
3488   // TODO: implement -Wuninitialized and fold this into that framework.
3489   static void DiagnoseUninitializedFields(
3490       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3491 
3492     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3493                                            Constructor->getLocation())) {
3494       return;
3495     }
3496 
3497     if (Constructor->isInvalidDecl())
3498       return;
3499 
3500     const CXXRecordDecl *RD = Constructor->getParent();
3501 
3502     if (RD->getDescribedClassTemplate())
3503       return;
3504 
3505     // Holds fields that are uninitialized.
3506     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3507 
3508     // At the beginning, all fields are uninitialized.
3509     for (auto *I : RD->decls()) {
3510       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3511         UninitializedFields.insert(FD);
3512       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3513         UninitializedFields.insert(IFD->getAnonField());
3514       }
3515     }
3516 
3517     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3518     for (auto I : RD->bases())
3519       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3520 
3521     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3522       return;
3523 
3524     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3525                                                    UninitializedFields,
3526                                                    UninitializedBaseClasses);
3527 
3528     for (const auto *FieldInit : Constructor->inits()) {
3529       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3530         break;
3531 
3532       Expr *InitExpr = FieldInit->getInit();
3533       if (!InitExpr)
3534         continue;
3535 
3536       if (CXXDefaultInitExpr *Default =
3537               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3538         InitExpr = Default->getExpr();
3539         if (!InitExpr)
3540           continue;
3541         // In class initializers will point to the constructor.
3542         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3543                                               FieldInit->getAnyMember(),
3544                                               FieldInit->getBaseClass());
3545       } else {
3546         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3547                                               FieldInit->getAnyMember(),
3548                                               FieldInit->getBaseClass());
3549       }
3550     }
3551   }
3552 } // namespace
3553 
3554 /// Enter a new C++ default initializer scope. After calling this, the
3555 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3556 /// parsing or instantiating the initializer failed.
3557 void Sema::ActOnStartCXXInClassMemberInitializer() {
3558   // Create a synthetic function scope to represent the call to the constructor
3559   // that notionally surrounds a use of this initializer.
3560   PushFunctionScope();
3561 }
3562 
3563 /// This is invoked after parsing an in-class initializer for a
3564 /// non-static C++ class member, and after instantiating an in-class initializer
3565 /// in a class template. Such actions are deferred until the class is complete.
3566 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3567                                                   SourceLocation InitLoc,
3568                                                   Expr *InitExpr) {
3569   // Pop the notional constructor scope we created earlier.
3570   PopFunctionScopeInfo(nullptr, D);
3571 
3572   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3573   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3574          "must set init style when field is created");
3575 
3576   if (!InitExpr) {
3577     D->setInvalidDecl();
3578     if (FD)
3579       FD->removeInClassInitializer();
3580     return;
3581   }
3582 
3583   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3584     FD->setInvalidDecl();
3585     FD->removeInClassInitializer();
3586     return;
3587   }
3588 
3589   ExprResult Init = InitExpr;
3590   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3591     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3592     InitializationKind Kind =
3593         FD->getInClassInitStyle() == ICIS_ListInit
3594             ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3595                                                    InitExpr->getLocStart(),
3596                                                    InitExpr->getLocEnd())
3597             : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3598     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3599     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3600     if (Init.isInvalid()) {
3601       FD->setInvalidDecl();
3602       return;
3603     }
3604   }
3605 
3606   // C++11 [class.base.init]p7:
3607   //   The initialization of each base and member constitutes a
3608   //   full-expression.
3609   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3610   if (Init.isInvalid()) {
3611     FD->setInvalidDecl();
3612     return;
3613   }
3614 
3615   InitExpr = Init.get();
3616 
3617   FD->setInClassInitializer(InitExpr);
3618 }
3619 
3620 /// Find the direct and/or virtual base specifiers that
3621 /// correspond to the given base type, for use in base initialization
3622 /// within a constructor.
3623 static bool FindBaseInitializer(Sema &SemaRef,
3624                                 CXXRecordDecl *ClassDecl,
3625                                 QualType BaseType,
3626                                 const CXXBaseSpecifier *&DirectBaseSpec,
3627                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3628   // First, check for a direct base class.
3629   DirectBaseSpec = nullptr;
3630   for (const auto &Base : ClassDecl->bases()) {
3631     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3632       // We found a direct base of this type. That's what we're
3633       // initializing.
3634       DirectBaseSpec = &Base;
3635       break;
3636     }
3637   }
3638 
3639   // Check for a virtual base class.
3640   // FIXME: We might be able to short-circuit this if we know in advance that
3641   // there are no virtual bases.
3642   VirtualBaseSpec = nullptr;
3643   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3644     // We haven't found a base yet; search the class hierarchy for a
3645     // virtual base class.
3646     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3647                        /*DetectVirtual=*/false);
3648     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3649                               SemaRef.Context.getTypeDeclType(ClassDecl),
3650                               BaseType, Paths)) {
3651       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3652            Path != Paths.end(); ++Path) {
3653         if (Path->back().Base->isVirtual()) {
3654           VirtualBaseSpec = Path->back().Base;
3655           break;
3656         }
3657       }
3658     }
3659   }
3660 
3661   return DirectBaseSpec || VirtualBaseSpec;
3662 }
3663 
3664 /// Handle a C++ member initializer using braced-init-list syntax.
3665 MemInitResult
3666 Sema::ActOnMemInitializer(Decl *ConstructorD,
3667                           Scope *S,
3668                           CXXScopeSpec &SS,
3669                           IdentifierInfo *MemberOrBase,
3670                           ParsedType TemplateTypeTy,
3671                           const DeclSpec &DS,
3672                           SourceLocation IdLoc,
3673                           Expr *InitList,
3674                           SourceLocation EllipsisLoc) {
3675   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3676                              DS, IdLoc, InitList,
3677                              EllipsisLoc);
3678 }
3679 
3680 /// Handle a C++ member initializer using parentheses syntax.
3681 MemInitResult
3682 Sema::ActOnMemInitializer(Decl *ConstructorD,
3683                           Scope *S,
3684                           CXXScopeSpec &SS,
3685                           IdentifierInfo *MemberOrBase,
3686                           ParsedType TemplateTypeTy,
3687                           const DeclSpec &DS,
3688                           SourceLocation IdLoc,
3689                           SourceLocation LParenLoc,
3690                           ArrayRef<Expr *> Args,
3691                           SourceLocation RParenLoc,
3692                           SourceLocation EllipsisLoc) {
3693   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3694                                            Args, RParenLoc);
3695   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3696                              DS, IdLoc, List, EllipsisLoc);
3697 }
3698 
3699 namespace {
3700 
3701 // Callback to only accept typo corrections that can be a valid C++ member
3702 // intializer: either a non-static field member or a base class.
3703 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3704 public:
3705   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3706       : ClassDecl(ClassDecl) {}
3707 
3708   bool ValidateCandidate(const TypoCorrection &candidate) override {
3709     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3710       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3711         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3712       return isa<TypeDecl>(ND);
3713     }
3714     return false;
3715   }
3716 
3717 private:
3718   CXXRecordDecl *ClassDecl;
3719 };
3720 
3721 }
3722 
3723 /// Handle a C++ member initializer.
3724 MemInitResult
3725 Sema::BuildMemInitializer(Decl *ConstructorD,
3726                           Scope *S,
3727                           CXXScopeSpec &SS,
3728                           IdentifierInfo *MemberOrBase,
3729                           ParsedType TemplateTypeTy,
3730                           const DeclSpec &DS,
3731                           SourceLocation IdLoc,
3732                           Expr *Init,
3733                           SourceLocation EllipsisLoc) {
3734   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3735   if (!Res.isUsable())
3736     return true;
3737   Init = Res.get();
3738 
3739   if (!ConstructorD)
3740     return true;
3741 
3742   AdjustDeclIfTemplate(ConstructorD);
3743 
3744   CXXConstructorDecl *Constructor
3745     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3746   if (!Constructor) {
3747     // The user wrote a constructor initializer on a function that is
3748     // not a C++ constructor. Ignore the error for now, because we may
3749     // have more member initializers coming; we'll diagnose it just
3750     // once in ActOnMemInitializers.
3751     return true;
3752   }
3753 
3754   CXXRecordDecl *ClassDecl = Constructor->getParent();
3755 
3756   // C++ [class.base.init]p2:
3757   //   Names in a mem-initializer-id are looked up in the scope of the
3758   //   constructor's class and, if not found in that scope, are looked
3759   //   up in the scope containing the constructor's definition.
3760   //   [Note: if the constructor's class contains a member with the
3761   //   same name as a direct or virtual base class of the class, a
3762   //   mem-initializer-id naming the member or base class and composed
3763   //   of a single identifier refers to the class member. A
3764   //   mem-initializer-id for the hidden base class may be specified
3765   //   using a qualified name. ]
3766   if (!SS.getScopeRep() && !TemplateTypeTy) {
3767     // Look for a member, first.
3768     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3769     if (!Result.empty()) {
3770       ValueDecl *Member;
3771       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3772           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3773         if (EllipsisLoc.isValid())
3774           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3775             << MemberOrBase
3776             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3777 
3778         return BuildMemberInitializer(Member, Init, IdLoc);
3779       }
3780     }
3781   }
3782   // It didn't name a member, so see if it names a class.
3783   QualType BaseType;
3784   TypeSourceInfo *TInfo = nullptr;
3785 
3786   if (TemplateTypeTy) {
3787     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3788   } else if (DS.getTypeSpecType() == TST_decltype) {
3789     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3790   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3791     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3792     return true;
3793   } else {
3794     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3795     LookupParsedName(R, S, &SS);
3796 
3797     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3798     if (!TyD) {
3799       if (R.isAmbiguous()) return true;
3800 
3801       // We don't want access-control diagnostics here.
3802       R.suppressDiagnostics();
3803 
3804       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3805         bool NotUnknownSpecialization = false;
3806         DeclContext *DC = computeDeclContext(SS, false);
3807         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3808           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3809 
3810         if (!NotUnknownSpecialization) {
3811           // When the scope specifier can refer to a member of an unknown
3812           // specialization, we take it as a type name.
3813           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3814                                        SS.getWithLocInContext(Context),
3815                                        *MemberOrBase, IdLoc);
3816           if (BaseType.isNull())
3817             return true;
3818 
3819           TInfo = Context.CreateTypeSourceInfo(BaseType);
3820           DependentNameTypeLoc TL =
3821               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3822           if (!TL.isNull()) {
3823             TL.setNameLoc(IdLoc);
3824             TL.setElaboratedKeywordLoc(SourceLocation());
3825             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3826           }
3827 
3828           R.clear();
3829           R.setLookupName(MemberOrBase);
3830         }
3831       }
3832 
3833       // If no results were found, try to correct typos.
3834       TypoCorrection Corr;
3835       if (R.empty() && BaseType.isNull() &&
3836           (Corr = CorrectTypo(
3837                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3838                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3839                CTK_ErrorRecovery, ClassDecl))) {
3840         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3841           // We have found a non-static data member with a similar
3842           // name to what was typed; complain and initialize that
3843           // member.
3844           diagnoseTypo(Corr,
3845                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3846                          << MemberOrBase << true);
3847           return BuildMemberInitializer(Member, Init, IdLoc);
3848         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3849           const CXXBaseSpecifier *DirectBaseSpec;
3850           const CXXBaseSpecifier *VirtualBaseSpec;
3851           if (FindBaseInitializer(*this, ClassDecl,
3852                                   Context.getTypeDeclType(Type),
3853                                   DirectBaseSpec, VirtualBaseSpec)) {
3854             // We have found a direct or virtual base class with a
3855             // similar name to what was typed; complain and initialize
3856             // that base class.
3857             diagnoseTypo(Corr,
3858                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3859                            << MemberOrBase << false,
3860                          PDiag() /*Suppress note, we provide our own.*/);
3861 
3862             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3863                                                               : VirtualBaseSpec;
3864             Diag(BaseSpec->getLocStart(),
3865                  diag::note_base_class_specified_here)
3866               << BaseSpec->getType()
3867               << BaseSpec->getSourceRange();
3868 
3869             TyD = Type;
3870           }
3871         }
3872       }
3873 
3874       if (!TyD && BaseType.isNull()) {
3875         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3876           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3877         return true;
3878       }
3879     }
3880 
3881     if (BaseType.isNull()) {
3882       BaseType = Context.getTypeDeclType(TyD);
3883       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3884       if (SS.isSet()) {
3885         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3886                                              BaseType);
3887         TInfo = Context.CreateTypeSourceInfo(BaseType);
3888         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3889         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3890         TL.setElaboratedKeywordLoc(SourceLocation());
3891         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3892       }
3893     }
3894   }
3895 
3896   if (!TInfo)
3897     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3898 
3899   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3900 }
3901 
3902 /// Checks a member initializer expression for cases where reference (or
3903 /// pointer) members are bound to by-value parameters (or their addresses).
3904 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3905                                                Expr *Init,
3906                                                SourceLocation IdLoc) {
3907   QualType MemberTy = Member->getType();
3908 
3909   // We only handle pointers and references currently.
3910   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3911   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3912     return;
3913 
3914   const bool IsPointer = MemberTy->isPointerType();
3915   if (IsPointer) {
3916     if (const UnaryOperator *Op
3917           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3918       // The only case we're worried about with pointers requires taking the
3919       // address.
3920       if (Op->getOpcode() != UO_AddrOf)
3921         return;
3922 
3923       Init = Op->getSubExpr();
3924     } else {
3925       // We only handle address-of expression initializers for pointers.
3926       return;
3927     }
3928   }
3929 
3930   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3931     // We only warn when referring to a non-reference parameter declaration.
3932     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3933     if (!Parameter || Parameter->getType()->isReferenceType())
3934       return;
3935 
3936     S.Diag(Init->getExprLoc(),
3937            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3938                      : diag::warn_bind_ref_member_to_parameter)
3939       << Member << Parameter << Init->getSourceRange();
3940   } else {
3941     // Other initializers are fine.
3942     return;
3943   }
3944 
3945   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3946     << (unsigned)IsPointer;
3947 }
3948 
3949 MemInitResult
3950 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3951                              SourceLocation IdLoc) {
3952   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3953   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3954   assert((DirectMember || IndirectMember) &&
3955          "Member must be a FieldDecl or IndirectFieldDecl");
3956 
3957   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3958     return true;
3959 
3960   if (Member->isInvalidDecl())
3961     return true;
3962 
3963   MultiExprArg Args;
3964   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3965     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3966   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3967     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3968   } else {
3969     // Template instantiation doesn't reconstruct ParenListExprs for us.
3970     Args = Init;
3971   }
3972 
3973   SourceRange InitRange = Init->getSourceRange();
3974 
3975   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3976     // Can't check initialization for a member of dependent type or when
3977     // any of the arguments are type-dependent expressions.
3978     DiscardCleanupsInEvaluationContext();
3979   } else {
3980     bool InitList = false;
3981     if (isa<InitListExpr>(Init)) {
3982       InitList = true;
3983       Args = Init;
3984     }
3985 
3986     // Initialize the member.
3987     InitializedEntity MemberEntity =
3988       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3989                    : InitializedEntity::InitializeMember(IndirectMember,
3990                                                          nullptr);
3991     InitializationKind Kind =
3992         InitList ? InitializationKind::CreateDirectList(
3993                        IdLoc, Init->getLocStart(), Init->getLocEnd())
3994                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3995                                                     InitRange.getEnd());
3996 
3997     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3998     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3999                                             nullptr);
4000     if (MemberInit.isInvalid())
4001       return true;
4002 
4003     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
4004 
4005     // C++11 [class.base.init]p7:
4006     //   The initialization of each base and member constitutes a
4007     //   full-expression.
4008     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4009     if (MemberInit.isInvalid())
4010       return true;
4011 
4012     Init = MemberInit.get();
4013   }
4014 
4015   if (DirectMember) {
4016     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4017                                             InitRange.getBegin(), Init,
4018                                             InitRange.getEnd());
4019   } else {
4020     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4021                                             InitRange.getBegin(), Init,
4022                                             InitRange.getEnd());
4023   }
4024 }
4025 
4026 MemInitResult
4027 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4028                                  CXXRecordDecl *ClassDecl) {
4029   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4030   if (!LangOpts.CPlusPlus11)
4031     return Diag(NameLoc, diag::err_delegating_ctor)
4032       << TInfo->getTypeLoc().getLocalSourceRange();
4033   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4034 
4035   bool InitList = true;
4036   MultiExprArg Args = Init;
4037   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4038     InitList = false;
4039     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4040   }
4041 
4042   SourceRange InitRange = Init->getSourceRange();
4043   // Initialize the object.
4044   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4045                                      QualType(ClassDecl->getTypeForDecl(), 0));
4046   InitializationKind Kind =
4047       InitList ? InitializationKind::CreateDirectList(
4048                      NameLoc, Init->getLocStart(), Init->getLocEnd())
4049                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4050                                                   InitRange.getEnd());
4051   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4052   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4053                                               Args, nullptr);
4054   if (DelegationInit.isInvalid())
4055     return true;
4056 
4057   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4058          "Delegating constructor with no target?");
4059 
4060   // C++11 [class.base.init]p7:
4061   //   The initialization of each base and member constitutes a
4062   //   full-expression.
4063   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4064                                        InitRange.getBegin());
4065   if (DelegationInit.isInvalid())
4066     return true;
4067 
4068   // If we are in a dependent context, template instantiation will
4069   // perform this type-checking again. Just save the arguments that we
4070   // received in a ParenListExpr.
4071   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4072   // of the information that we have about the base
4073   // initializer. However, deconstructing the ASTs is a dicey process,
4074   // and this approach is far more likely to get the corner cases right.
4075   if (CurContext->isDependentContext())
4076     DelegationInit = Init;
4077 
4078   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4079                                           DelegationInit.getAs<Expr>(),
4080                                           InitRange.getEnd());
4081 }
4082 
4083 MemInitResult
4084 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4085                            Expr *Init, CXXRecordDecl *ClassDecl,
4086                            SourceLocation EllipsisLoc) {
4087   SourceLocation BaseLoc
4088     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4089 
4090   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4091     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4092              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4093 
4094   // C++ [class.base.init]p2:
4095   //   [...] Unless the mem-initializer-id names a nonstatic data
4096   //   member of the constructor's class or a direct or virtual base
4097   //   of that class, the mem-initializer is ill-formed. A
4098   //   mem-initializer-list can initialize a base class using any
4099   //   name that denotes that base class type.
4100   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4101 
4102   SourceRange InitRange = Init->getSourceRange();
4103   if (EllipsisLoc.isValid()) {
4104     // This is a pack expansion.
4105     if (!BaseType->containsUnexpandedParameterPack())  {
4106       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4107         << SourceRange(BaseLoc, InitRange.getEnd());
4108 
4109       EllipsisLoc = SourceLocation();
4110     }
4111   } else {
4112     // Check for any unexpanded parameter packs.
4113     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4114       return true;
4115 
4116     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4117       return true;
4118   }
4119 
4120   // Check for direct and virtual base classes.
4121   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4122   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4123   if (!Dependent) {
4124     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4125                                        BaseType))
4126       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4127 
4128     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4129                         VirtualBaseSpec);
4130 
4131     // C++ [base.class.init]p2:
4132     // Unless the mem-initializer-id names a nonstatic data member of the
4133     // constructor's class or a direct or virtual base of that class, the
4134     // mem-initializer is ill-formed.
4135     if (!DirectBaseSpec && !VirtualBaseSpec) {
4136       // If the class has any dependent bases, then it's possible that
4137       // one of those types will resolve to the same type as
4138       // BaseType. Therefore, just treat this as a dependent base
4139       // class initialization.  FIXME: Should we try to check the
4140       // initialization anyway? It seems odd.
4141       if (ClassDecl->hasAnyDependentBases())
4142         Dependent = true;
4143       else
4144         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4145           << BaseType << Context.getTypeDeclType(ClassDecl)
4146           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4147     }
4148   }
4149 
4150   if (Dependent) {
4151     DiscardCleanupsInEvaluationContext();
4152 
4153     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4154                                             /*IsVirtual=*/false,
4155                                             InitRange.getBegin(), Init,
4156                                             InitRange.getEnd(), EllipsisLoc);
4157   }
4158 
4159   // C++ [base.class.init]p2:
4160   //   If a mem-initializer-id is ambiguous because it designates both
4161   //   a direct non-virtual base class and an inherited virtual base
4162   //   class, the mem-initializer is ill-formed.
4163   if (DirectBaseSpec && VirtualBaseSpec)
4164     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4165       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4166 
4167   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4168   if (!BaseSpec)
4169     BaseSpec = VirtualBaseSpec;
4170 
4171   // Initialize the base.
4172   bool InitList = true;
4173   MultiExprArg Args = Init;
4174   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4175     InitList = false;
4176     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4177   }
4178 
4179   InitializedEntity BaseEntity =
4180     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4181   InitializationKind Kind =
4182       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4183                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4184                                                   InitRange.getEnd());
4185   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4186   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4187   if (BaseInit.isInvalid())
4188     return true;
4189 
4190   // C++11 [class.base.init]p7:
4191   //   The initialization of each base and member constitutes a
4192   //   full-expression.
4193   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4194   if (BaseInit.isInvalid())
4195     return true;
4196 
4197   // If we are in a dependent context, template instantiation will
4198   // perform this type-checking again. Just save the arguments that we
4199   // received in a ParenListExpr.
4200   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4201   // of the information that we have about the base
4202   // initializer. However, deconstructing the ASTs is a dicey process,
4203   // and this approach is far more likely to get the corner cases right.
4204   if (CurContext->isDependentContext())
4205     BaseInit = Init;
4206 
4207   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4208                                           BaseSpec->isVirtual(),
4209                                           InitRange.getBegin(),
4210                                           BaseInit.getAs<Expr>(),
4211                                           InitRange.getEnd(), EllipsisLoc);
4212 }
4213 
4214 // Create a static_cast\<T&&>(expr).
4215 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4216   if (T.isNull()) T = E->getType();
4217   QualType TargetType = SemaRef.BuildReferenceType(
4218       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4219   SourceLocation ExprLoc = E->getLocStart();
4220   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4221       TargetType, ExprLoc);
4222 
4223   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4224                                    SourceRange(ExprLoc, ExprLoc),
4225                                    E->getSourceRange()).get();
4226 }
4227 
4228 /// ImplicitInitializerKind - How an implicit base or member initializer should
4229 /// initialize its base or member.
4230 enum ImplicitInitializerKind {
4231   IIK_Default,
4232   IIK_Copy,
4233   IIK_Move,
4234   IIK_Inherit
4235 };
4236 
4237 static bool
4238 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4239                              ImplicitInitializerKind ImplicitInitKind,
4240                              CXXBaseSpecifier *BaseSpec,
4241                              bool IsInheritedVirtualBase,
4242                              CXXCtorInitializer *&CXXBaseInit) {
4243   InitializedEntity InitEntity
4244     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4245                                         IsInheritedVirtualBase);
4246 
4247   ExprResult BaseInit;
4248 
4249   switch (ImplicitInitKind) {
4250   case IIK_Inherit:
4251   case IIK_Default: {
4252     InitializationKind InitKind
4253       = InitializationKind::CreateDefault(Constructor->getLocation());
4254     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4255     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4256     break;
4257   }
4258 
4259   case IIK_Move:
4260   case IIK_Copy: {
4261     bool Moving = ImplicitInitKind == IIK_Move;
4262     ParmVarDecl *Param = Constructor->getParamDecl(0);
4263     QualType ParamType = Param->getType().getNonReferenceType();
4264 
4265     Expr *CopyCtorArg =
4266       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4267                           SourceLocation(), Param, false,
4268                           Constructor->getLocation(), ParamType,
4269                           VK_LValue, nullptr);
4270 
4271     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4272 
4273     // Cast to the base class to avoid ambiguities.
4274     QualType ArgTy =
4275       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4276                                        ParamType.getQualifiers());
4277 
4278     if (Moving) {
4279       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4280     }
4281 
4282     CXXCastPath BasePath;
4283     BasePath.push_back(BaseSpec);
4284     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4285                                             CK_UncheckedDerivedToBase,
4286                                             Moving ? VK_XValue : VK_LValue,
4287                                             &BasePath).get();
4288 
4289     InitializationKind InitKind
4290       = InitializationKind::CreateDirect(Constructor->getLocation(),
4291                                          SourceLocation(), SourceLocation());
4292     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4293     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4294     break;
4295   }
4296   }
4297 
4298   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4299   if (BaseInit.isInvalid())
4300     return true;
4301 
4302   CXXBaseInit =
4303     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4304                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4305                                                         SourceLocation()),
4306                                              BaseSpec->isVirtual(),
4307                                              SourceLocation(),
4308                                              BaseInit.getAs<Expr>(),
4309                                              SourceLocation(),
4310                                              SourceLocation());
4311 
4312   return false;
4313 }
4314 
4315 static bool RefersToRValueRef(Expr *MemRef) {
4316   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4317   return Referenced->getType()->isRValueReferenceType();
4318 }
4319 
4320 static bool
4321 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4322                                ImplicitInitializerKind ImplicitInitKind,
4323                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4324                                CXXCtorInitializer *&CXXMemberInit) {
4325   if (Field->isInvalidDecl())
4326     return true;
4327 
4328   SourceLocation Loc = Constructor->getLocation();
4329 
4330   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4331     bool Moving = ImplicitInitKind == IIK_Move;
4332     ParmVarDecl *Param = Constructor->getParamDecl(0);
4333     QualType ParamType = Param->getType().getNonReferenceType();
4334 
4335     // Suppress copying zero-width bitfields.
4336     if (Field->isZeroLengthBitField(SemaRef.Context))
4337       return false;
4338 
4339     Expr *MemberExprBase =
4340       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4341                           SourceLocation(), Param, false,
4342                           Loc, ParamType, VK_LValue, nullptr);
4343 
4344     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4345 
4346     if (Moving) {
4347       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4348     }
4349 
4350     // Build a reference to this field within the parameter.
4351     CXXScopeSpec SS;
4352     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4353                               Sema::LookupMemberName);
4354     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4355                                   : cast<ValueDecl>(Field), AS_public);
4356     MemberLookup.resolveKind();
4357     ExprResult CtorArg
4358       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4359                                          ParamType, Loc,
4360                                          /*IsArrow=*/false,
4361                                          SS,
4362                                          /*TemplateKWLoc=*/SourceLocation(),
4363                                          /*FirstQualifierInScope=*/nullptr,
4364                                          MemberLookup,
4365                                          /*TemplateArgs=*/nullptr,
4366                                          /*S*/nullptr);
4367     if (CtorArg.isInvalid())
4368       return true;
4369 
4370     // C++11 [class.copy]p15:
4371     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4372     //     with static_cast<T&&>(x.m);
4373     if (RefersToRValueRef(CtorArg.get())) {
4374       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4375     }
4376 
4377     InitializedEntity Entity =
4378         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4379                                                        /*Implicit*/ true)
4380                  : InitializedEntity::InitializeMember(Field, nullptr,
4381                                                        /*Implicit*/ true);
4382 
4383     // Direct-initialize to use the copy constructor.
4384     InitializationKind InitKind =
4385       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4386 
4387     Expr *CtorArgE = CtorArg.getAs<Expr>();
4388     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4389     ExprResult MemberInit =
4390         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4391     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4392     if (MemberInit.isInvalid())
4393       return true;
4394 
4395     if (Indirect)
4396       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4397           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4398     else
4399       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4400           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4401     return false;
4402   }
4403 
4404   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4405          "Unhandled implicit init kind!");
4406 
4407   QualType FieldBaseElementType =
4408     SemaRef.Context.getBaseElementType(Field->getType());
4409 
4410   if (FieldBaseElementType->isRecordType()) {
4411     InitializedEntity InitEntity =
4412         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4413                                                        /*Implicit*/ true)
4414                  : InitializedEntity::InitializeMember(Field, nullptr,
4415                                                        /*Implicit*/ true);
4416     InitializationKind InitKind =
4417       InitializationKind::CreateDefault(Loc);
4418 
4419     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4420     ExprResult MemberInit =
4421       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4422 
4423     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4424     if (MemberInit.isInvalid())
4425       return true;
4426 
4427     if (Indirect)
4428       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4429                                                                Indirect, Loc,
4430                                                                Loc,
4431                                                                MemberInit.get(),
4432                                                                Loc);
4433     else
4434       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4435                                                                Field, Loc, Loc,
4436                                                                MemberInit.get(),
4437                                                                Loc);
4438     return false;
4439   }
4440 
4441   if (!Field->getParent()->isUnion()) {
4442     if (FieldBaseElementType->isReferenceType()) {
4443       SemaRef.Diag(Constructor->getLocation(),
4444                    diag::err_uninitialized_member_in_ctor)
4445       << (int)Constructor->isImplicit()
4446       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4447       << 0 << Field->getDeclName();
4448       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4449       return true;
4450     }
4451 
4452     if (FieldBaseElementType.isConstQualified()) {
4453       SemaRef.Diag(Constructor->getLocation(),
4454                    diag::err_uninitialized_member_in_ctor)
4455       << (int)Constructor->isImplicit()
4456       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4457       << 1 << Field->getDeclName();
4458       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4459       return true;
4460     }
4461   }
4462 
4463   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4464     // ARC and Weak:
4465     //   Default-initialize Objective-C pointers to NULL.
4466     CXXMemberInit
4467       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4468                                                  Loc, Loc,
4469                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4470                                                  Loc);
4471     return false;
4472   }
4473 
4474   // Nothing to initialize.
4475   CXXMemberInit = nullptr;
4476   return false;
4477 }
4478 
4479 namespace {
4480 struct BaseAndFieldInfo {
4481   Sema &S;
4482   CXXConstructorDecl *Ctor;
4483   bool AnyErrorsInInits;
4484   ImplicitInitializerKind IIK;
4485   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4486   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4487   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4488 
4489   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4490     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4491     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4492     if (Ctor->getInheritedConstructor())
4493       IIK = IIK_Inherit;
4494     else if (Generated && Ctor->isCopyConstructor())
4495       IIK = IIK_Copy;
4496     else if (Generated && Ctor->isMoveConstructor())
4497       IIK = IIK_Move;
4498     else
4499       IIK = IIK_Default;
4500   }
4501 
4502   bool isImplicitCopyOrMove() const {
4503     switch (IIK) {
4504     case IIK_Copy:
4505     case IIK_Move:
4506       return true;
4507 
4508     case IIK_Default:
4509     case IIK_Inherit:
4510       return false;
4511     }
4512 
4513     llvm_unreachable("Invalid ImplicitInitializerKind!");
4514   }
4515 
4516   bool addFieldInitializer(CXXCtorInitializer *Init) {
4517     AllToInit.push_back(Init);
4518 
4519     // Check whether this initializer makes the field "used".
4520     if (Init->getInit()->HasSideEffects(S.Context))
4521       S.UnusedPrivateFields.remove(Init->getAnyMember());
4522 
4523     return false;
4524   }
4525 
4526   bool isInactiveUnionMember(FieldDecl *Field) {
4527     RecordDecl *Record = Field->getParent();
4528     if (!Record->isUnion())
4529       return false;
4530 
4531     if (FieldDecl *Active =
4532             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4533       return Active != Field->getCanonicalDecl();
4534 
4535     // In an implicit copy or move constructor, ignore any in-class initializer.
4536     if (isImplicitCopyOrMove())
4537       return true;
4538 
4539     // If there's no explicit initialization, the field is active only if it
4540     // has an in-class initializer...
4541     if (Field->hasInClassInitializer())
4542       return false;
4543     // ... or it's an anonymous struct or union whose class has an in-class
4544     // initializer.
4545     if (!Field->isAnonymousStructOrUnion())
4546       return true;
4547     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4548     return !FieldRD->hasInClassInitializer();
4549   }
4550 
4551   /// Determine whether the given field is, or is within, a union member
4552   /// that is inactive (because there was an initializer given for a different
4553   /// member of the union, or because the union was not initialized at all).
4554   bool isWithinInactiveUnionMember(FieldDecl *Field,
4555                                    IndirectFieldDecl *Indirect) {
4556     if (!Indirect)
4557       return isInactiveUnionMember(Field);
4558 
4559     for (auto *C : Indirect->chain()) {
4560       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4561       if (Field && isInactiveUnionMember(Field))
4562         return true;
4563     }
4564     return false;
4565   }
4566 };
4567 }
4568 
4569 /// Determine whether the given type is an incomplete or zero-lenfgth
4570 /// array type.
4571 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4572   if (T->isIncompleteArrayType())
4573     return true;
4574 
4575   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4576     if (!ArrayT->getSize())
4577       return true;
4578 
4579     T = ArrayT->getElementType();
4580   }
4581 
4582   return false;
4583 }
4584 
4585 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4586                                     FieldDecl *Field,
4587                                     IndirectFieldDecl *Indirect = nullptr) {
4588   if (Field->isInvalidDecl())
4589     return false;
4590 
4591   // Overwhelmingly common case: we have a direct initializer for this field.
4592   if (CXXCtorInitializer *Init =
4593           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4594     return Info.addFieldInitializer(Init);
4595 
4596   // C++11 [class.base.init]p8:
4597   //   if the entity is a non-static data member that has a
4598   //   brace-or-equal-initializer and either
4599   //   -- the constructor's class is a union and no other variant member of that
4600   //      union is designated by a mem-initializer-id or
4601   //   -- the constructor's class is not a union, and, if the entity is a member
4602   //      of an anonymous union, no other member of that union is designated by
4603   //      a mem-initializer-id,
4604   //   the entity is initialized as specified in [dcl.init].
4605   //
4606   // We also apply the same rules to handle anonymous structs within anonymous
4607   // unions.
4608   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4609     return false;
4610 
4611   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4612     ExprResult DIE =
4613         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4614     if (DIE.isInvalid())
4615       return true;
4616     CXXCtorInitializer *Init;
4617     if (Indirect)
4618       Init = new (SemaRef.Context)
4619           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4620                              SourceLocation(), DIE.get(), SourceLocation());
4621     else
4622       Init = new (SemaRef.Context)
4623           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4624                              SourceLocation(), DIE.get(), SourceLocation());
4625     return Info.addFieldInitializer(Init);
4626   }
4627 
4628   // Don't initialize incomplete or zero-length arrays.
4629   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4630     return false;
4631 
4632   // Don't try to build an implicit initializer if there were semantic
4633   // errors in any of the initializers (and therefore we might be
4634   // missing some that the user actually wrote).
4635   if (Info.AnyErrorsInInits)
4636     return false;
4637 
4638   CXXCtorInitializer *Init = nullptr;
4639   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4640                                      Indirect, Init))
4641     return true;
4642 
4643   if (!Init)
4644     return false;
4645 
4646   return Info.addFieldInitializer(Init);
4647 }
4648 
4649 bool
4650 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4651                                CXXCtorInitializer *Initializer) {
4652   assert(Initializer->isDelegatingInitializer());
4653   Constructor->setNumCtorInitializers(1);
4654   CXXCtorInitializer **initializer =
4655     new (Context) CXXCtorInitializer*[1];
4656   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4657   Constructor->setCtorInitializers(initializer);
4658 
4659   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4660     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4661     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4662   }
4663 
4664   DelegatingCtorDecls.push_back(Constructor);
4665 
4666   DiagnoseUninitializedFields(*this, Constructor);
4667 
4668   return false;
4669 }
4670 
4671 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4672                                ArrayRef<CXXCtorInitializer *> Initializers) {
4673   if (Constructor->isDependentContext()) {
4674     // Just store the initializers as written, they will be checked during
4675     // instantiation.
4676     if (!Initializers.empty()) {
4677       Constructor->setNumCtorInitializers(Initializers.size());
4678       CXXCtorInitializer **baseOrMemberInitializers =
4679         new (Context) CXXCtorInitializer*[Initializers.size()];
4680       memcpy(baseOrMemberInitializers, Initializers.data(),
4681              Initializers.size() * sizeof(CXXCtorInitializer*));
4682       Constructor->setCtorInitializers(baseOrMemberInitializers);
4683     }
4684 
4685     // Let template instantiation know whether we had errors.
4686     if (AnyErrors)
4687       Constructor->setInvalidDecl();
4688 
4689     return false;
4690   }
4691 
4692   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4693 
4694   // We need to build the initializer AST according to order of construction
4695   // and not what user specified in the Initializers list.
4696   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4697   if (!ClassDecl)
4698     return true;
4699 
4700   bool HadError = false;
4701 
4702   for (unsigned i = 0; i < Initializers.size(); i++) {
4703     CXXCtorInitializer *Member = Initializers[i];
4704 
4705     if (Member->isBaseInitializer())
4706       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4707     else {
4708       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4709 
4710       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4711         for (auto *C : F->chain()) {
4712           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4713           if (FD && FD->getParent()->isUnion())
4714             Info.ActiveUnionMember.insert(std::make_pair(
4715                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4716         }
4717       } else if (FieldDecl *FD = Member->getMember()) {
4718         if (FD->getParent()->isUnion())
4719           Info.ActiveUnionMember.insert(std::make_pair(
4720               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4721       }
4722     }
4723   }
4724 
4725   // Keep track of the direct virtual bases.
4726   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4727   for (auto &I : ClassDecl->bases()) {
4728     if (I.isVirtual())
4729       DirectVBases.insert(&I);
4730   }
4731 
4732   // Push virtual bases before others.
4733   for (auto &VBase : ClassDecl->vbases()) {
4734     if (CXXCtorInitializer *Value
4735         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4736       // [class.base.init]p7, per DR257:
4737       //   A mem-initializer where the mem-initializer-id names a virtual base
4738       //   class is ignored during execution of a constructor of any class that
4739       //   is not the most derived class.
4740       if (ClassDecl->isAbstract()) {
4741         // FIXME: Provide a fixit to remove the base specifier. This requires
4742         // tracking the location of the associated comma for a base specifier.
4743         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4744           << VBase.getType() << ClassDecl;
4745         DiagnoseAbstractType(ClassDecl);
4746       }
4747 
4748       Info.AllToInit.push_back(Value);
4749     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4750       // [class.base.init]p8, per DR257:
4751       //   If a given [...] base class is not named by a mem-initializer-id
4752       //   [...] and the entity is not a virtual base class of an abstract
4753       //   class, then [...] the entity is default-initialized.
4754       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4755       CXXCtorInitializer *CXXBaseInit;
4756       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4757                                        &VBase, IsInheritedVirtualBase,
4758                                        CXXBaseInit)) {
4759         HadError = true;
4760         continue;
4761       }
4762 
4763       Info.AllToInit.push_back(CXXBaseInit);
4764     }
4765   }
4766 
4767   // Non-virtual bases.
4768   for (auto &Base : ClassDecl->bases()) {
4769     // Virtuals are in the virtual base list and already constructed.
4770     if (Base.isVirtual())
4771       continue;
4772 
4773     if (CXXCtorInitializer *Value
4774           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4775       Info.AllToInit.push_back(Value);
4776     } else if (!AnyErrors) {
4777       CXXCtorInitializer *CXXBaseInit;
4778       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4779                                        &Base, /*IsInheritedVirtualBase=*/false,
4780                                        CXXBaseInit)) {
4781         HadError = true;
4782         continue;
4783       }
4784 
4785       Info.AllToInit.push_back(CXXBaseInit);
4786     }
4787   }
4788 
4789   // Fields.
4790   for (auto *Mem : ClassDecl->decls()) {
4791     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4792       // C++ [class.bit]p2:
4793       //   A declaration for a bit-field that omits the identifier declares an
4794       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4795       //   initialized.
4796       if (F->isUnnamedBitfield())
4797         continue;
4798 
4799       // If we're not generating the implicit copy/move constructor, then we'll
4800       // handle anonymous struct/union fields based on their individual
4801       // indirect fields.
4802       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4803         continue;
4804 
4805       if (CollectFieldInitializer(*this, Info, F))
4806         HadError = true;
4807       continue;
4808     }
4809 
4810     // Beyond this point, we only consider default initialization.
4811     if (Info.isImplicitCopyOrMove())
4812       continue;
4813 
4814     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4815       if (F->getType()->isIncompleteArrayType()) {
4816         assert(ClassDecl->hasFlexibleArrayMember() &&
4817                "Incomplete array type is not valid");
4818         continue;
4819       }
4820 
4821       // Initialize each field of an anonymous struct individually.
4822       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4823         HadError = true;
4824 
4825       continue;
4826     }
4827   }
4828 
4829   unsigned NumInitializers = Info.AllToInit.size();
4830   if (NumInitializers > 0) {
4831     Constructor->setNumCtorInitializers(NumInitializers);
4832     CXXCtorInitializer **baseOrMemberInitializers =
4833       new (Context) CXXCtorInitializer*[NumInitializers];
4834     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4835            NumInitializers * sizeof(CXXCtorInitializer*));
4836     Constructor->setCtorInitializers(baseOrMemberInitializers);
4837 
4838     // Constructors implicitly reference the base and member
4839     // destructors.
4840     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4841                                            Constructor->getParent());
4842   }
4843 
4844   return HadError;
4845 }
4846 
4847 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4848   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4849     const RecordDecl *RD = RT->getDecl();
4850     if (RD->isAnonymousStructOrUnion()) {
4851       for (auto *Field : RD->fields())
4852         PopulateKeysForFields(Field, IdealInits);
4853       return;
4854     }
4855   }
4856   IdealInits.push_back(Field->getCanonicalDecl());
4857 }
4858 
4859 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4860   return Context.getCanonicalType(BaseType).getTypePtr();
4861 }
4862 
4863 static const void *GetKeyForMember(ASTContext &Context,
4864                                    CXXCtorInitializer *Member) {
4865   if (!Member->isAnyMemberInitializer())
4866     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4867 
4868   return Member->getAnyMember()->getCanonicalDecl();
4869 }
4870 
4871 static void DiagnoseBaseOrMemInitializerOrder(
4872     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4873     ArrayRef<CXXCtorInitializer *> Inits) {
4874   if (Constructor->getDeclContext()->isDependentContext())
4875     return;
4876 
4877   // Don't check initializers order unless the warning is enabled at the
4878   // location of at least one initializer.
4879   bool ShouldCheckOrder = false;
4880   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4881     CXXCtorInitializer *Init = Inits[InitIndex];
4882     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4883                                  Init->getSourceLocation())) {
4884       ShouldCheckOrder = true;
4885       break;
4886     }
4887   }
4888   if (!ShouldCheckOrder)
4889     return;
4890 
4891   // Build the list of bases and members in the order that they'll
4892   // actually be initialized.  The explicit initializers should be in
4893   // this same order but may be missing things.
4894   SmallVector<const void*, 32> IdealInitKeys;
4895 
4896   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4897 
4898   // 1. Virtual bases.
4899   for (const auto &VBase : ClassDecl->vbases())
4900     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4901 
4902   // 2. Non-virtual bases.
4903   for (const auto &Base : ClassDecl->bases()) {
4904     if (Base.isVirtual())
4905       continue;
4906     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4907   }
4908 
4909   // 3. Direct fields.
4910   for (auto *Field : ClassDecl->fields()) {
4911     if (Field->isUnnamedBitfield())
4912       continue;
4913 
4914     PopulateKeysForFields(Field, IdealInitKeys);
4915   }
4916 
4917   unsigned NumIdealInits = IdealInitKeys.size();
4918   unsigned IdealIndex = 0;
4919 
4920   CXXCtorInitializer *PrevInit = nullptr;
4921   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4922     CXXCtorInitializer *Init = Inits[InitIndex];
4923     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4924 
4925     // Scan forward to try to find this initializer in the idealized
4926     // initializers list.
4927     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4928       if (InitKey == IdealInitKeys[IdealIndex])
4929         break;
4930 
4931     // If we didn't find this initializer, it must be because we
4932     // scanned past it on a previous iteration.  That can only
4933     // happen if we're out of order;  emit a warning.
4934     if (IdealIndex == NumIdealInits && PrevInit) {
4935       Sema::SemaDiagnosticBuilder D =
4936         SemaRef.Diag(PrevInit->getSourceLocation(),
4937                      diag::warn_initializer_out_of_order);
4938 
4939       if (PrevInit->isAnyMemberInitializer())
4940         D << 0 << PrevInit->getAnyMember()->getDeclName();
4941       else
4942         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4943 
4944       if (Init->isAnyMemberInitializer())
4945         D << 0 << Init->getAnyMember()->getDeclName();
4946       else
4947         D << 1 << Init->getTypeSourceInfo()->getType();
4948 
4949       // Move back to the initializer's location in the ideal list.
4950       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4951         if (InitKey == IdealInitKeys[IdealIndex])
4952           break;
4953 
4954       assert(IdealIndex < NumIdealInits &&
4955              "initializer not found in initializer list");
4956     }
4957 
4958     PrevInit = Init;
4959   }
4960 }
4961 
4962 namespace {
4963 bool CheckRedundantInit(Sema &S,
4964                         CXXCtorInitializer *Init,
4965                         CXXCtorInitializer *&PrevInit) {
4966   if (!PrevInit) {
4967     PrevInit = Init;
4968     return false;
4969   }
4970 
4971   if (FieldDecl *Field = Init->getAnyMember())
4972     S.Diag(Init->getSourceLocation(),
4973            diag::err_multiple_mem_initialization)
4974       << Field->getDeclName()
4975       << Init->getSourceRange();
4976   else {
4977     const Type *BaseClass = Init->getBaseClass();
4978     assert(BaseClass && "neither field nor base");
4979     S.Diag(Init->getSourceLocation(),
4980            diag::err_multiple_base_initialization)
4981       << QualType(BaseClass, 0)
4982       << Init->getSourceRange();
4983   }
4984   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4985     << 0 << PrevInit->getSourceRange();
4986 
4987   return true;
4988 }
4989 
4990 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4991 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4992 
4993 bool CheckRedundantUnionInit(Sema &S,
4994                              CXXCtorInitializer *Init,
4995                              RedundantUnionMap &Unions) {
4996   FieldDecl *Field = Init->getAnyMember();
4997   RecordDecl *Parent = Field->getParent();
4998   NamedDecl *Child = Field;
4999 
5000   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5001     if (Parent->isUnion()) {
5002       UnionEntry &En = Unions[Parent];
5003       if (En.first && En.first != Child) {
5004         S.Diag(Init->getSourceLocation(),
5005                diag::err_multiple_mem_union_initialization)
5006           << Field->getDeclName()
5007           << Init->getSourceRange();
5008         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5009           << 0 << En.second->getSourceRange();
5010         return true;
5011       }
5012       if (!En.first) {
5013         En.first = Child;
5014         En.second = Init;
5015       }
5016       if (!Parent->isAnonymousStructOrUnion())
5017         return false;
5018     }
5019 
5020     Child = Parent;
5021     Parent = cast<RecordDecl>(Parent->getDeclContext());
5022   }
5023 
5024   return false;
5025 }
5026 }
5027 
5028 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5029 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5030                                 SourceLocation ColonLoc,
5031                                 ArrayRef<CXXCtorInitializer*> MemInits,
5032                                 bool AnyErrors) {
5033   if (!ConstructorDecl)
5034     return;
5035 
5036   AdjustDeclIfTemplate(ConstructorDecl);
5037 
5038   CXXConstructorDecl *Constructor
5039     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5040 
5041   if (!Constructor) {
5042     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5043     return;
5044   }
5045 
5046   // Mapping for the duplicate initializers check.
5047   // For member initializers, this is keyed with a FieldDecl*.
5048   // For base initializers, this is keyed with a Type*.
5049   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5050 
5051   // Mapping for the inconsistent anonymous-union initializers check.
5052   RedundantUnionMap MemberUnions;
5053 
5054   bool HadError = false;
5055   for (unsigned i = 0; i < MemInits.size(); i++) {
5056     CXXCtorInitializer *Init = MemInits[i];
5057 
5058     // Set the source order index.
5059     Init->setSourceOrder(i);
5060 
5061     if (Init->isAnyMemberInitializer()) {
5062       const void *Key = GetKeyForMember(Context, Init);
5063       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5064           CheckRedundantUnionInit(*this, Init, MemberUnions))
5065         HadError = true;
5066     } else if (Init->isBaseInitializer()) {
5067       const void *Key = GetKeyForMember(Context, Init);
5068       if (CheckRedundantInit(*this, Init, Members[Key]))
5069         HadError = true;
5070     } else {
5071       assert(Init->isDelegatingInitializer());
5072       // This must be the only initializer
5073       if (MemInits.size() != 1) {
5074         Diag(Init->getSourceLocation(),
5075              diag::err_delegating_initializer_alone)
5076           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5077         // We will treat this as being the only initializer.
5078       }
5079       SetDelegatingInitializer(Constructor, MemInits[i]);
5080       // Return immediately as the initializer is set.
5081       return;
5082     }
5083   }
5084 
5085   if (HadError)
5086     return;
5087 
5088   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5089 
5090   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5091 
5092   DiagnoseUninitializedFields(*this, Constructor);
5093 }
5094 
5095 void
5096 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5097                                              CXXRecordDecl *ClassDecl) {
5098   // Ignore dependent contexts. Also ignore unions, since their members never
5099   // have destructors implicitly called.
5100   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5101     return;
5102 
5103   // FIXME: all the access-control diagnostics are positioned on the
5104   // field/base declaration.  That's probably good; that said, the
5105   // user might reasonably want to know why the destructor is being
5106   // emitted, and we currently don't say.
5107 
5108   // Non-static data members.
5109   for (auto *Field : ClassDecl->fields()) {
5110     if (Field->isInvalidDecl())
5111       continue;
5112 
5113     // Don't destroy incomplete or zero-length arrays.
5114     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5115       continue;
5116 
5117     QualType FieldType = Context.getBaseElementType(Field->getType());
5118 
5119     const RecordType* RT = FieldType->getAs<RecordType>();
5120     if (!RT)
5121       continue;
5122 
5123     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5124     if (FieldClassDecl->isInvalidDecl())
5125       continue;
5126     if (FieldClassDecl->hasIrrelevantDestructor())
5127       continue;
5128     // The destructor for an implicit anonymous union member is never invoked.
5129     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5130       continue;
5131 
5132     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5133     assert(Dtor && "No dtor found for FieldClassDecl!");
5134     CheckDestructorAccess(Field->getLocation(), Dtor,
5135                           PDiag(diag::err_access_dtor_field)
5136                             << Field->getDeclName()
5137                             << FieldType);
5138 
5139     MarkFunctionReferenced(Location, Dtor);
5140     DiagnoseUseOfDecl(Dtor, Location);
5141   }
5142 
5143   // We only potentially invoke the destructors of potentially constructed
5144   // subobjects.
5145   bool VisitVirtualBases = !ClassDecl->isAbstract();
5146 
5147   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5148 
5149   // Bases.
5150   for (const auto &Base : ClassDecl->bases()) {
5151     // Bases are always records in a well-formed non-dependent class.
5152     const RecordType *RT = Base.getType()->getAs<RecordType>();
5153 
5154     // Remember direct virtual bases.
5155     if (Base.isVirtual()) {
5156       if (!VisitVirtualBases)
5157         continue;
5158       DirectVirtualBases.insert(RT);
5159     }
5160 
5161     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5162     // If our base class is invalid, we probably can't get its dtor anyway.
5163     if (BaseClassDecl->isInvalidDecl())
5164       continue;
5165     if (BaseClassDecl->hasIrrelevantDestructor())
5166       continue;
5167 
5168     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5169     assert(Dtor && "No dtor found for BaseClassDecl!");
5170 
5171     // FIXME: caret should be on the start of the class name
5172     CheckDestructorAccess(Base.getLocStart(), Dtor,
5173                           PDiag(diag::err_access_dtor_base)
5174                             << Base.getType()
5175                             << Base.getSourceRange(),
5176                           Context.getTypeDeclType(ClassDecl));
5177 
5178     MarkFunctionReferenced(Location, Dtor);
5179     DiagnoseUseOfDecl(Dtor, Location);
5180   }
5181 
5182   if (!VisitVirtualBases)
5183     return;
5184 
5185   // Virtual bases.
5186   for (const auto &VBase : ClassDecl->vbases()) {
5187     // Bases are always records in a well-formed non-dependent class.
5188     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5189 
5190     // Ignore direct virtual bases.
5191     if (DirectVirtualBases.count(RT))
5192       continue;
5193 
5194     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5195     // If our base class is invalid, we probably can't get its dtor anyway.
5196     if (BaseClassDecl->isInvalidDecl())
5197       continue;
5198     if (BaseClassDecl->hasIrrelevantDestructor())
5199       continue;
5200 
5201     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5202     assert(Dtor && "No dtor found for BaseClassDecl!");
5203     if (CheckDestructorAccess(
5204             ClassDecl->getLocation(), Dtor,
5205             PDiag(diag::err_access_dtor_vbase)
5206                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5207             Context.getTypeDeclType(ClassDecl)) ==
5208         AR_accessible) {
5209       CheckDerivedToBaseConversion(
5210           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5211           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5212           SourceRange(), DeclarationName(), nullptr);
5213     }
5214 
5215     MarkFunctionReferenced(Location, Dtor);
5216     DiagnoseUseOfDecl(Dtor, Location);
5217   }
5218 }
5219 
5220 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5221   if (!CDtorDecl)
5222     return;
5223 
5224   if (CXXConstructorDecl *Constructor
5225       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5226     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5227     DiagnoseUninitializedFields(*this, Constructor);
5228   }
5229 }
5230 
5231 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5232   if (!getLangOpts().CPlusPlus)
5233     return false;
5234 
5235   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5236   if (!RD)
5237     return false;
5238 
5239   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5240   // class template specialization here, but doing so breaks a lot of code.
5241 
5242   // We can't answer whether something is abstract until it has a
5243   // definition. If it's currently being defined, we'll walk back
5244   // over all the declarations when we have a full definition.
5245   const CXXRecordDecl *Def = RD->getDefinition();
5246   if (!Def || Def->isBeingDefined())
5247     return false;
5248 
5249   return RD->isAbstract();
5250 }
5251 
5252 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5253                                   TypeDiagnoser &Diagnoser) {
5254   if (!isAbstractType(Loc, T))
5255     return false;
5256 
5257   T = Context.getBaseElementType(T);
5258   Diagnoser.diagnose(*this, Loc, T);
5259   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5260   return true;
5261 }
5262 
5263 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5264   // Check if we've already emitted the list of pure virtual functions
5265   // for this class.
5266   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5267     return;
5268 
5269   // If the diagnostic is suppressed, don't emit the notes. We're only
5270   // going to emit them once, so try to attach them to a diagnostic we're
5271   // actually going to show.
5272   if (Diags.isLastDiagnosticIgnored())
5273     return;
5274 
5275   CXXFinalOverriderMap FinalOverriders;
5276   RD->getFinalOverriders(FinalOverriders);
5277 
5278   // Keep a set of seen pure methods so we won't diagnose the same method
5279   // more than once.
5280   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5281 
5282   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5283                                    MEnd = FinalOverriders.end();
5284        M != MEnd;
5285        ++M) {
5286     for (OverridingMethods::iterator SO = M->second.begin(),
5287                                   SOEnd = M->second.end();
5288          SO != SOEnd; ++SO) {
5289       // C++ [class.abstract]p4:
5290       //   A class is abstract if it contains or inherits at least one
5291       //   pure virtual function for which the final overrider is pure
5292       //   virtual.
5293 
5294       //
5295       if (SO->second.size() != 1)
5296         continue;
5297 
5298       if (!SO->second.front().Method->isPure())
5299         continue;
5300 
5301       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5302         continue;
5303 
5304       Diag(SO->second.front().Method->getLocation(),
5305            diag::note_pure_virtual_function)
5306         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5307     }
5308   }
5309 
5310   if (!PureVirtualClassDiagSet)
5311     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5312   PureVirtualClassDiagSet->insert(RD);
5313 }
5314 
5315 namespace {
5316 struct AbstractUsageInfo {
5317   Sema &S;
5318   CXXRecordDecl *Record;
5319   CanQualType AbstractType;
5320   bool Invalid;
5321 
5322   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5323     : S(S), Record(Record),
5324       AbstractType(S.Context.getCanonicalType(
5325                    S.Context.getTypeDeclType(Record))),
5326       Invalid(false) {}
5327 
5328   void DiagnoseAbstractType() {
5329     if (Invalid) return;
5330     S.DiagnoseAbstractType(Record);
5331     Invalid = true;
5332   }
5333 
5334   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5335 };
5336 
5337 struct CheckAbstractUsage {
5338   AbstractUsageInfo &Info;
5339   const NamedDecl *Ctx;
5340 
5341   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5342     : Info(Info), Ctx(Ctx) {}
5343 
5344   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5345     switch (TL.getTypeLocClass()) {
5346 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5347 #define TYPELOC(CLASS, PARENT) \
5348     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5349 #include "clang/AST/TypeLocNodes.def"
5350     }
5351   }
5352 
5353   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5354     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5355     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5356       if (!TL.getParam(I))
5357         continue;
5358 
5359       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5360       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5361     }
5362   }
5363 
5364   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5365     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5366   }
5367 
5368   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5369     // Visit the type parameters from a permissive context.
5370     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5371       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5372       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5373         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5374           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5375       // TODO: other template argument types?
5376     }
5377   }
5378 
5379   // Visit pointee types from a permissive context.
5380 #define CheckPolymorphic(Type) \
5381   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5382     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5383   }
5384   CheckPolymorphic(PointerTypeLoc)
5385   CheckPolymorphic(ReferenceTypeLoc)
5386   CheckPolymorphic(MemberPointerTypeLoc)
5387   CheckPolymorphic(BlockPointerTypeLoc)
5388   CheckPolymorphic(AtomicTypeLoc)
5389 
5390   /// Handle all the types we haven't given a more specific
5391   /// implementation for above.
5392   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5393     // Every other kind of type that we haven't called out already
5394     // that has an inner type is either (1) sugar or (2) contains that
5395     // inner type in some way as a subobject.
5396     if (TypeLoc Next = TL.getNextTypeLoc())
5397       return Visit(Next, Sel);
5398 
5399     // If there's no inner type and we're in a permissive context,
5400     // don't diagnose.
5401     if (Sel == Sema::AbstractNone) return;
5402 
5403     // Check whether the type matches the abstract type.
5404     QualType T = TL.getType();
5405     if (T->isArrayType()) {
5406       Sel = Sema::AbstractArrayType;
5407       T = Info.S.Context.getBaseElementType(T);
5408     }
5409     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5410     if (CT != Info.AbstractType) return;
5411 
5412     // It matched; do some magic.
5413     if (Sel == Sema::AbstractArrayType) {
5414       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5415         << T << TL.getSourceRange();
5416     } else {
5417       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5418         << Sel << T << TL.getSourceRange();
5419     }
5420     Info.DiagnoseAbstractType();
5421   }
5422 };
5423 
5424 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5425                                   Sema::AbstractDiagSelID Sel) {
5426   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5427 }
5428 
5429 }
5430 
5431 /// Check for invalid uses of an abstract type in a method declaration.
5432 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5433                                     CXXMethodDecl *MD) {
5434   // No need to do the check on definitions, which require that
5435   // the return/param types be complete.
5436   if (MD->doesThisDeclarationHaveABody())
5437     return;
5438 
5439   // For safety's sake, just ignore it if we don't have type source
5440   // information.  This should never happen for non-implicit methods,
5441   // but...
5442   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5443     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5444 }
5445 
5446 /// Check for invalid uses of an abstract type within a class definition.
5447 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5448                                     CXXRecordDecl *RD) {
5449   for (auto *D : RD->decls()) {
5450     if (D->isImplicit()) continue;
5451 
5452     // Methods and method templates.
5453     if (isa<CXXMethodDecl>(D)) {
5454       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5455     } else if (isa<FunctionTemplateDecl>(D)) {
5456       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5457       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5458 
5459     // Fields and static variables.
5460     } else if (isa<FieldDecl>(D)) {
5461       FieldDecl *FD = cast<FieldDecl>(D);
5462       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5463         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5464     } else if (isa<VarDecl>(D)) {
5465       VarDecl *VD = cast<VarDecl>(D);
5466       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5467         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5468 
5469     // Nested classes and class templates.
5470     } else if (isa<CXXRecordDecl>(D)) {
5471       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5472     } else if (isa<ClassTemplateDecl>(D)) {
5473       CheckAbstractClassUsage(Info,
5474                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5475     }
5476   }
5477 }
5478 
5479 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5480   Attr *ClassAttr = getDLLAttr(Class);
5481   if (!ClassAttr)
5482     return;
5483 
5484   assert(ClassAttr->getKind() == attr::DLLExport);
5485 
5486   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5487 
5488   if (TSK == TSK_ExplicitInstantiationDeclaration)
5489     // Don't go any further if this is just an explicit instantiation
5490     // declaration.
5491     return;
5492 
5493   for (Decl *Member : Class->decls()) {
5494     // Defined static variables that are members of an exported base
5495     // class must be marked export too.
5496     auto *VD = dyn_cast<VarDecl>(Member);
5497     if (VD && Member->getAttr<DLLExportAttr>() &&
5498         VD->getStorageClass() == SC_Static &&
5499         TSK == TSK_ImplicitInstantiation)
5500       S.MarkVariableReferenced(VD->getLocation(), VD);
5501 
5502     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5503     if (!MD)
5504       continue;
5505 
5506     if (Member->getAttr<DLLExportAttr>()) {
5507       if (MD->isUserProvided()) {
5508         // Instantiate non-default class member functions ...
5509 
5510         // .. except for certain kinds of template specializations.
5511         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5512           continue;
5513 
5514         S.MarkFunctionReferenced(Class->getLocation(), MD);
5515 
5516         // The function will be passed to the consumer when its definition is
5517         // encountered.
5518       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5519                  MD->isCopyAssignmentOperator() ||
5520                  MD->isMoveAssignmentOperator()) {
5521         // Synthesize and instantiate non-trivial implicit methods, explicitly
5522         // defaulted methods, and the copy and move assignment operators. The
5523         // latter are exported even if they are trivial, because the address of
5524         // an operator can be taken and should compare equal across libraries.
5525         DiagnosticErrorTrap Trap(S.Diags);
5526         S.MarkFunctionReferenced(Class->getLocation(), MD);
5527         if (Trap.hasErrorOccurred()) {
5528           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5529               << Class << !S.getLangOpts().CPlusPlus11;
5530           break;
5531         }
5532 
5533         // There is no later point when we will see the definition of this
5534         // function, so pass it to the consumer now.
5535         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5536       }
5537     }
5538   }
5539 }
5540 
5541 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5542                                                         CXXRecordDecl *Class) {
5543   // Only the MS ABI has default constructor closures, so we don't need to do
5544   // this semantic checking anywhere else.
5545   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5546     return;
5547 
5548   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5549   for (Decl *Member : Class->decls()) {
5550     // Look for exported default constructors.
5551     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5552     if (!CD || !CD->isDefaultConstructor())
5553       continue;
5554     auto *Attr = CD->getAttr<DLLExportAttr>();
5555     if (!Attr)
5556       continue;
5557 
5558     // If the class is non-dependent, mark the default arguments as ODR-used so
5559     // that we can properly codegen the constructor closure.
5560     if (!Class->isDependentContext()) {
5561       for (ParmVarDecl *PD : CD->parameters()) {
5562         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5563         S.DiscardCleanupsInEvaluationContext();
5564       }
5565     }
5566 
5567     if (LastExportedDefaultCtor) {
5568       S.Diag(LastExportedDefaultCtor->getLocation(),
5569              diag::err_attribute_dll_ambiguous_default_ctor)
5570           << Class;
5571       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5572           << CD->getDeclName();
5573       return;
5574     }
5575     LastExportedDefaultCtor = CD;
5576   }
5577 }
5578 
5579 /// Check class-level dllimport/dllexport attribute.
5580 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5581   Attr *ClassAttr = getDLLAttr(Class);
5582 
5583   // MSVC inherits DLL attributes to partial class template specializations.
5584   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5585     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5586       if (Attr *TemplateAttr =
5587               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5588         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5589         A->setInherited(true);
5590         ClassAttr = A;
5591       }
5592     }
5593   }
5594 
5595   if (!ClassAttr)
5596     return;
5597 
5598   if (!Class->isExternallyVisible()) {
5599     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5600         << Class << ClassAttr;
5601     return;
5602   }
5603 
5604   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5605       !ClassAttr->isInherited()) {
5606     // Diagnose dll attributes on members of class with dll attribute.
5607     for (Decl *Member : Class->decls()) {
5608       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5609         continue;
5610       InheritableAttr *MemberAttr = getDLLAttr(Member);
5611       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5612         continue;
5613 
5614       Diag(MemberAttr->getLocation(),
5615              diag::err_attribute_dll_member_of_dll_class)
5616           << MemberAttr << ClassAttr;
5617       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5618       Member->setInvalidDecl();
5619     }
5620   }
5621 
5622   if (Class->getDescribedClassTemplate())
5623     // Don't inherit dll attribute until the template is instantiated.
5624     return;
5625 
5626   // The class is either imported or exported.
5627   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5628 
5629   // Check if this was a dllimport attribute propagated from a derived class to
5630   // a base class template specialization. We don't apply these attributes to
5631   // static data members.
5632   const bool PropagatedImport =
5633       !ClassExported &&
5634       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5635 
5636   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5637 
5638   // Ignore explicit dllexport on explicit class template instantiation declarations.
5639   if (ClassExported && !ClassAttr->isInherited() &&
5640       TSK == TSK_ExplicitInstantiationDeclaration) {
5641     Class->dropAttr<DLLExportAttr>();
5642     return;
5643   }
5644 
5645   // Force declaration of implicit members so they can inherit the attribute.
5646   ForceDeclarationOfImplicitMembers(Class);
5647 
5648   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5649   // seem to be true in practice?
5650 
5651   for (Decl *Member : Class->decls()) {
5652     VarDecl *VD = dyn_cast<VarDecl>(Member);
5653     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5654 
5655     // Only methods and static fields inherit the attributes.
5656     if (!VD && !MD)
5657       continue;
5658 
5659     if (MD) {
5660       // Don't process deleted methods.
5661       if (MD->isDeleted())
5662         continue;
5663 
5664       if (MD->isInlined()) {
5665         // MinGW does not import or export inline methods.
5666         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5667             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5668           continue;
5669 
5670         // MSVC versions before 2015 don't export the move assignment operators
5671         // and move constructor, so don't attempt to import/export them if
5672         // we have a definition.
5673         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5674         if ((MD->isMoveAssignmentOperator() ||
5675              (Ctor && Ctor->isMoveConstructor())) &&
5676             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5677           continue;
5678 
5679         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5680         // operator is exported anyway.
5681         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5682             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5683           continue;
5684       }
5685     }
5686 
5687     // Don't apply dllimport attributes to static data members of class template
5688     // instantiations when the attribute is propagated from a derived class.
5689     if (VD && PropagatedImport)
5690       continue;
5691 
5692     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5693       continue;
5694 
5695     if (!getDLLAttr(Member)) {
5696       auto *NewAttr =
5697           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5698       NewAttr->setInherited(true);
5699       Member->addAttr(NewAttr);
5700 
5701       if (MD) {
5702         // Propagate DLLAttr to friend re-declarations of MD that have already
5703         // been constructed.
5704         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5705              FD = FD->getPreviousDecl()) {
5706           if (FD->getFriendObjectKind() == Decl::FOK_None)
5707             continue;
5708           assert(!getDLLAttr(FD) &&
5709                  "friend re-decl should not already have a DLLAttr");
5710           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5711           NewAttr->setInherited(true);
5712           FD->addAttr(NewAttr);
5713         }
5714       }
5715     }
5716   }
5717 
5718   if (ClassExported)
5719     DelayedDllExportClasses.push_back(Class);
5720 }
5721 
5722 /// Perform propagation of DLL attributes from a derived class to a
5723 /// templated base class for MS compatibility.
5724 void Sema::propagateDLLAttrToBaseClassTemplate(
5725     CXXRecordDecl *Class, Attr *ClassAttr,
5726     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5727   if (getDLLAttr(
5728           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5729     // If the base class template has a DLL attribute, don't try to change it.
5730     return;
5731   }
5732 
5733   auto TSK = BaseTemplateSpec->getSpecializationKind();
5734   if (!getDLLAttr(BaseTemplateSpec) &&
5735       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5736        TSK == TSK_ImplicitInstantiation)) {
5737     // The template hasn't been instantiated yet (or it has, but only as an
5738     // explicit instantiation declaration or implicit instantiation, which means
5739     // we haven't codegenned any members yet), so propagate the attribute.
5740     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5741     NewAttr->setInherited(true);
5742     BaseTemplateSpec->addAttr(NewAttr);
5743 
5744     // If this was an import, mark that we propagated it from a derived class to
5745     // a base class template specialization.
5746     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5747       ImportAttr->setPropagatedToBaseTemplate();
5748 
5749     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5750     // needs to be run again to work see the new attribute. Otherwise this will
5751     // get run whenever the template is instantiated.
5752     if (TSK != TSK_Undeclared)
5753       checkClassLevelDLLAttribute(BaseTemplateSpec);
5754 
5755     return;
5756   }
5757 
5758   if (getDLLAttr(BaseTemplateSpec)) {
5759     // The template has already been specialized or instantiated with an
5760     // attribute, explicitly or through propagation. We should not try to change
5761     // it.
5762     return;
5763   }
5764 
5765   // The template was previously instantiated or explicitly specialized without
5766   // a dll attribute, It's too late for us to add an attribute, so warn that
5767   // this is unsupported.
5768   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5769       << BaseTemplateSpec->isExplicitSpecialization();
5770   Diag(ClassAttr->getLocation(), diag::note_attribute);
5771   if (BaseTemplateSpec->isExplicitSpecialization()) {
5772     Diag(BaseTemplateSpec->getLocation(),
5773            diag::note_template_class_explicit_specialization_was_here)
5774         << BaseTemplateSpec;
5775   } else {
5776     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5777            diag::note_template_class_instantiation_was_here)
5778         << BaseTemplateSpec;
5779   }
5780 }
5781 
5782 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5783                                         SourceLocation DefaultLoc) {
5784   switch (S.getSpecialMember(MD)) {
5785   case Sema::CXXDefaultConstructor:
5786     S.DefineImplicitDefaultConstructor(DefaultLoc,
5787                                        cast<CXXConstructorDecl>(MD));
5788     break;
5789   case Sema::CXXCopyConstructor:
5790     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5791     break;
5792   case Sema::CXXCopyAssignment:
5793     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5794     break;
5795   case Sema::CXXDestructor:
5796     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5797     break;
5798   case Sema::CXXMoveConstructor:
5799     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5800     break;
5801   case Sema::CXXMoveAssignment:
5802     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5803     break;
5804   case Sema::CXXInvalid:
5805     llvm_unreachable("Invalid special member.");
5806   }
5807 }
5808 
5809 /// Determine whether a type is permitted to be passed or returned in
5810 /// registers, per C++ [class.temporary]p3.
5811 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5812                                TargetInfo::CallingConvKind CCK) {
5813   if (D->isDependentType() || D->isInvalidDecl())
5814     return false;
5815 
5816   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5817   // The PS4 platform ABI follows the behavior of Clang 3.2.
5818   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5819     return !D->hasNonTrivialDestructorForCall() &&
5820            !D->hasNonTrivialCopyConstructorForCall();
5821 
5822   if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
5823     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5824     bool DtorIsTrivialForCall = false;
5825 
5826     // If a class has at least one non-deleted, trivial copy constructor, it
5827     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5828     //
5829     // Note: This permits classes with non-trivial copy or move ctors to be
5830     // passed in registers, so long as they *also* have a trivial copy ctor,
5831     // which is non-conforming.
5832     if (D->needsImplicitCopyConstructor()) {
5833       if (!D->defaultedCopyConstructorIsDeleted()) {
5834         if (D->hasTrivialCopyConstructor())
5835           CopyCtorIsTrivial = true;
5836         if (D->hasTrivialCopyConstructorForCall())
5837           CopyCtorIsTrivialForCall = true;
5838       }
5839     } else {
5840       for (const CXXConstructorDecl *CD : D->ctors()) {
5841         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5842           if (CD->isTrivial())
5843             CopyCtorIsTrivial = true;
5844           if (CD->isTrivialForCall())
5845             CopyCtorIsTrivialForCall = true;
5846         }
5847       }
5848     }
5849 
5850     if (D->needsImplicitDestructor()) {
5851       if (!D->defaultedDestructorIsDeleted() &&
5852           D->hasTrivialDestructorForCall())
5853         DtorIsTrivialForCall = true;
5854     } else if (const auto *DD = D->getDestructor()) {
5855       if (!DD->isDeleted() && DD->isTrivialForCall())
5856         DtorIsTrivialForCall = true;
5857     }
5858 
5859     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5860     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5861       return true;
5862 
5863     // If a class has a destructor, we'd really like to pass it indirectly
5864     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5865     // impossible for small types, which it will pass in a single register or
5866     // stack slot. Most objects with dtors are large-ish, so handle that early.
5867     // We can't call out all large objects as being indirect because there are
5868     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5869     // how we pass large POD types.
5870 
5871     // Note: This permits small classes with nontrivial destructors to be
5872     // passed in registers, which is non-conforming.
5873     if (CopyCtorIsTrivial &&
5874         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5875       return true;
5876     return false;
5877   }
5878 
5879   // Per C++ [class.temporary]p3, the relevant condition is:
5880   //   each copy constructor, move constructor, and destructor of X is
5881   //   either trivial or deleted, and X has at least one non-deleted copy
5882   //   or move constructor
5883   bool HasNonDeletedCopyOrMove = false;
5884 
5885   if (D->needsImplicitCopyConstructor() &&
5886       !D->defaultedCopyConstructorIsDeleted()) {
5887     if (!D->hasTrivialCopyConstructorForCall())
5888       return false;
5889     HasNonDeletedCopyOrMove = true;
5890   }
5891 
5892   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5893       !D->defaultedMoveConstructorIsDeleted()) {
5894     if (!D->hasTrivialMoveConstructorForCall())
5895       return false;
5896     HasNonDeletedCopyOrMove = true;
5897   }
5898 
5899   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5900       !D->hasTrivialDestructorForCall())
5901     return false;
5902 
5903   for (const CXXMethodDecl *MD : D->methods()) {
5904     if (MD->isDeleted())
5905       continue;
5906 
5907     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5908     if (CD && CD->isCopyOrMoveConstructor())
5909       HasNonDeletedCopyOrMove = true;
5910     else if (!isa<CXXDestructorDecl>(MD))
5911       continue;
5912 
5913     if (!MD->isTrivialForCall())
5914       return false;
5915   }
5916 
5917   return HasNonDeletedCopyOrMove;
5918 }
5919 
5920 /// Perform semantic checks on a class definition that has been
5921 /// completing, introducing implicitly-declared members, checking for
5922 /// abstract types, etc.
5923 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5924   if (!Record)
5925     return;
5926 
5927   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5928     AbstractUsageInfo Info(*this, Record);
5929     CheckAbstractClassUsage(Info, Record);
5930   }
5931 
5932   // If this is not an aggregate type and has no user-declared constructor,
5933   // complain about any non-static data members of reference or const scalar
5934   // type, since they will never get initializers.
5935   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5936       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5937       !Record->isLambda()) {
5938     bool Complained = false;
5939     for (const auto *F : Record->fields()) {
5940       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5941         continue;
5942 
5943       if (F->getType()->isReferenceType() ||
5944           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5945         if (!Complained) {
5946           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5947             << Record->getTagKind() << Record;
5948           Complained = true;
5949         }
5950 
5951         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5952           << F->getType()->isReferenceType()
5953           << F->getDeclName();
5954       }
5955     }
5956   }
5957 
5958   if (Record->getIdentifier()) {
5959     // C++ [class.mem]p13:
5960     //   If T is the name of a class, then each of the following shall have a
5961     //   name different from T:
5962     //     - every member of every anonymous union that is a member of class T.
5963     //
5964     // C++ [class.mem]p14:
5965     //   In addition, if class T has a user-declared constructor (12.1), every
5966     //   non-static data member of class T shall have a name different from T.
5967     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5968     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5969          ++I) {
5970       NamedDecl *D = *I;
5971       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5972           isa<IndirectFieldDecl>(D)) {
5973         Diag(D->getLocation(), diag::err_member_name_of_class)
5974           << D->getDeclName();
5975         break;
5976       }
5977     }
5978   }
5979 
5980   // Warn if the class has virtual methods but non-virtual public destructor.
5981   if (Record->isPolymorphic() && !Record->isDependentType()) {
5982     CXXDestructorDecl *dtor = Record->getDestructor();
5983     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5984         !Record->hasAttr<FinalAttr>())
5985       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5986            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5987   }
5988 
5989   if (Record->isAbstract()) {
5990     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5991       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5992         << FA->isSpelledAsSealed();
5993       DiagnoseAbstractType(Record);
5994     }
5995   }
5996 
5997   // Set HasTrivialSpecialMemberForCall if the record has attribute
5998   // "trivial_abi".
5999   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6000 
6001   if (HasTrivialABI)
6002     Record->setHasTrivialSpecialMemberForCall();
6003 
6004   bool HasMethodWithOverrideControl = false,
6005        HasOverridingMethodWithoutOverrideControl = false;
6006   if (!Record->isDependentType()) {
6007     for (auto *M : Record->methods()) {
6008       // See if a method overloads virtual methods in a base
6009       // class without overriding any.
6010       if (!M->isStatic())
6011         DiagnoseHiddenVirtualMethods(M);
6012       if (M->hasAttr<OverrideAttr>())
6013         HasMethodWithOverrideControl = true;
6014       else if (M->size_overridden_methods() > 0)
6015         HasOverridingMethodWithoutOverrideControl = true;
6016       // Check whether the explicitly-defaulted special members are valid.
6017       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6018         CheckExplicitlyDefaultedSpecialMember(M);
6019 
6020       // For an explicitly defaulted or deleted special member, we defer
6021       // determining triviality until the class is complete. That time is now!
6022       CXXSpecialMember CSM = getSpecialMember(M);
6023       if (!M->isImplicit() && !M->isUserProvided()) {
6024         if (CSM != CXXInvalid) {
6025           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6026           // Inform the class that we've finished declaring this member.
6027           Record->finishedDefaultedOrDeletedMember(M);
6028           M->setTrivialForCall(
6029               HasTrivialABI ||
6030               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6031           Record->setTrivialForCallFlags(M);
6032         }
6033       }
6034 
6035       // Set triviality for the purpose of calls if this is a user-provided
6036       // copy/move constructor or destructor.
6037       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6038            CSM == CXXDestructor) && M->isUserProvided()) {
6039         M->setTrivialForCall(HasTrivialABI);
6040         Record->setTrivialForCallFlags(M);
6041       }
6042 
6043       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6044           M->hasAttr<DLLExportAttr>()) {
6045         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6046             M->isTrivial() &&
6047             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6048              CSM == CXXDestructor))
6049           M->dropAttr<DLLExportAttr>();
6050 
6051         if (M->hasAttr<DLLExportAttr>()) {
6052           DefineImplicitSpecialMember(*this, M, M->getLocation());
6053           ActOnFinishInlineFunctionDef(M);
6054         }
6055       }
6056     }
6057   }
6058 
6059   if (HasMethodWithOverrideControl &&
6060       HasOverridingMethodWithoutOverrideControl) {
6061     // At least one method has the 'override' control declared.
6062     // Diagnose all other overridden methods which do not have 'override' specified on them.
6063     for (auto *M : Record->methods())
6064       DiagnoseAbsenceOfOverrideControl(M);
6065   }
6066 
6067   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6068   // whether this class uses any C++ features that are implemented
6069   // completely differently in MSVC, and if so, emit a diagnostic.
6070   // That diagnostic defaults to an error, but we allow projects to
6071   // map it down to a warning (or ignore it).  It's a fairly common
6072   // practice among users of the ms_struct pragma to mass-annotate
6073   // headers, sweeping up a bunch of types that the project doesn't
6074   // really rely on MSVC-compatible layout for.  We must therefore
6075   // support "ms_struct except for C++ stuff" as a secondary ABI.
6076   if (Record->isMsStruct(Context) &&
6077       (Record->isPolymorphic() || Record->getNumBases())) {
6078     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6079   }
6080 
6081   checkClassLevelDLLAttribute(Record);
6082 
6083   bool ClangABICompat4 =
6084       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6085   TargetInfo::CallingConvKind CCK =
6086       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6087   bool CanPass = canPassInRegisters(*this, Record, CCK);
6088 
6089   // Do not change ArgPassingRestrictions if it has already been set to
6090   // APK_CanNeverPassInRegs.
6091   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6092     Record->setArgPassingRestrictions(CanPass
6093                                           ? RecordDecl::APK_CanPassInRegs
6094                                           : RecordDecl::APK_CannotPassInRegs);
6095 
6096   // If canPassInRegisters returns true despite the record having a non-trivial
6097   // destructor, the record is destructed in the callee. This happens only when
6098   // the record or one of its subobjects has a field annotated with trivial_abi
6099   // or a field qualified with ObjC __strong/__weak.
6100   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6101     Record->setParamDestroyedInCallee(true);
6102   else if (Record->hasNonTrivialDestructor())
6103     Record->setParamDestroyedInCallee(CanPass);
6104 }
6105 
6106 /// Look up the special member function that would be called by a special
6107 /// member function for a subobject of class type.
6108 ///
6109 /// \param Class The class type of the subobject.
6110 /// \param CSM The kind of special member function.
6111 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6112 /// \param ConstRHS True if this is a copy operation with a const object
6113 ///        on its RHS, that is, if the argument to the outer special member
6114 ///        function is 'const' and this is not a field marked 'mutable'.
6115 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6116     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6117     unsigned FieldQuals, bool ConstRHS) {
6118   unsigned LHSQuals = 0;
6119   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6120     LHSQuals = FieldQuals;
6121 
6122   unsigned RHSQuals = FieldQuals;
6123   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6124     RHSQuals = 0;
6125   else if (ConstRHS)
6126     RHSQuals |= Qualifiers::Const;
6127 
6128   return S.LookupSpecialMember(Class, CSM,
6129                                RHSQuals & Qualifiers::Const,
6130                                RHSQuals & Qualifiers::Volatile,
6131                                false,
6132                                LHSQuals & Qualifiers::Const,
6133                                LHSQuals & Qualifiers::Volatile);
6134 }
6135 
6136 class Sema::InheritedConstructorInfo {
6137   Sema &S;
6138   SourceLocation UseLoc;
6139 
6140   /// A mapping from the base classes through which the constructor was
6141   /// inherited to the using shadow declaration in that base class (or a null
6142   /// pointer if the constructor was declared in that base class).
6143   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6144       InheritedFromBases;
6145 
6146 public:
6147   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6148                            ConstructorUsingShadowDecl *Shadow)
6149       : S(S), UseLoc(UseLoc) {
6150     bool DiagnosedMultipleConstructedBases = false;
6151     CXXRecordDecl *ConstructedBase = nullptr;
6152     UsingDecl *ConstructedBaseUsing = nullptr;
6153 
6154     // Find the set of such base class subobjects and check that there's a
6155     // unique constructed subobject.
6156     for (auto *D : Shadow->redecls()) {
6157       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6158       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6159       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6160 
6161       InheritedFromBases.insert(
6162           std::make_pair(DNominatedBase->getCanonicalDecl(),
6163                          DShadow->getNominatedBaseClassShadowDecl()));
6164       if (DShadow->constructsVirtualBase())
6165         InheritedFromBases.insert(
6166             std::make_pair(DConstructedBase->getCanonicalDecl(),
6167                            DShadow->getConstructedBaseClassShadowDecl()));
6168       else
6169         assert(DNominatedBase == DConstructedBase);
6170 
6171       // [class.inhctor.init]p2:
6172       //   If the constructor was inherited from multiple base class subobjects
6173       //   of type B, the program is ill-formed.
6174       if (!ConstructedBase) {
6175         ConstructedBase = DConstructedBase;
6176         ConstructedBaseUsing = D->getUsingDecl();
6177       } else if (ConstructedBase != DConstructedBase &&
6178                  !Shadow->isInvalidDecl()) {
6179         if (!DiagnosedMultipleConstructedBases) {
6180           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6181               << Shadow->getTargetDecl();
6182           S.Diag(ConstructedBaseUsing->getLocation(),
6183                diag::note_ambiguous_inherited_constructor_using)
6184               << ConstructedBase;
6185           DiagnosedMultipleConstructedBases = true;
6186         }
6187         S.Diag(D->getUsingDecl()->getLocation(),
6188                diag::note_ambiguous_inherited_constructor_using)
6189             << DConstructedBase;
6190       }
6191     }
6192 
6193     if (DiagnosedMultipleConstructedBases)
6194       Shadow->setInvalidDecl();
6195   }
6196 
6197   /// Find the constructor to use for inherited construction of a base class,
6198   /// and whether that base class constructor inherits the constructor from a
6199   /// virtual base class (in which case it won't actually invoke it).
6200   std::pair<CXXConstructorDecl *, bool>
6201   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6202     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6203     if (It == InheritedFromBases.end())
6204       return std::make_pair(nullptr, false);
6205 
6206     // This is an intermediary class.
6207     if (It->second)
6208       return std::make_pair(
6209           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6210           It->second->constructsVirtualBase());
6211 
6212     // This is the base class from which the constructor was inherited.
6213     return std::make_pair(Ctor, false);
6214   }
6215 };
6216 
6217 /// Is the special member function which would be selected to perform the
6218 /// specified operation on the specified class type a constexpr constructor?
6219 static bool
6220 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6221                          Sema::CXXSpecialMember CSM, unsigned Quals,
6222                          bool ConstRHS,
6223                          CXXConstructorDecl *InheritedCtor = nullptr,
6224                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6225   // If we're inheriting a constructor, see if we need to call it for this base
6226   // class.
6227   if (InheritedCtor) {
6228     assert(CSM == Sema::CXXDefaultConstructor);
6229     auto BaseCtor =
6230         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6231     if (BaseCtor)
6232       return BaseCtor->isConstexpr();
6233   }
6234 
6235   if (CSM == Sema::CXXDefaultConstructor)
6236     return ClassDecl->hasConstexprDefaultConstructor();
6237 
6238   Sema::SpecialMemberOverloadResult SMOR =
6239       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6240   if (!SMOR.getMethod())
6241     // A constructor we wouldn't select can't be "involved in initializing"
6242     // anything.
6243     return true;
6244   return SMOR.getMethod()->isConstexpr();
6245 }
6246 
6247 /// Determine whether the specified special member function would be constexpr
6248 /// if it were implicitly defined.
6249 static bool defaultedSpecialMemberIsConstexpr(
6250     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6251     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6252     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6253   if (!S.getLangOpts().CPlusPlus11)
6254     return false;
6255 
6256   // C++11 [dcl.constexpr]p4:
6257   // In the definition of a constexpr constructor [...]
6258   bool Ctor = true;
6259   switch (CSM) {
6260   case Sema::CXXDefaultConstructor:
6261     if (Inherited)
6262       break;
6263     // Since default constructor lookup is essentially trivial (and cannot
6264     // involve, for instance, template instantiation), we compute whether a
6265     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6266     //
6267     // This is important for performance; we need to know whether the default
6268     // constructor is constexpr to determine whether the type is a literal type.
6269     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6270 
6271   case Sema::CXXCopyConstructor:
6272   case Sema::CXXMoveConstructor:
6273     // For copy or move constructors, we need to perform overload resolution.
6274     break;
6275 
6276   case Sema::CXXCopyAssignment:
6277   case Sema::CXXMoveAssignment:
6278     if (!S.getLangOpts().CPlusPlus14)
6279       return false;
6280     // In C++1y, we need to perform overload resolution.
6281     Ctor = false;
6282     break;
6283 
6284   case Sema::CXXDestructor:
6285   case Sema::CXXInvalid:
6286     return false;
6287   }
6288 
6289   //   -- if the class is a non-empty union, or for each non-empty anonymous
6290   //      union member of a non-union class, exactly one non-static data member
6291   //      shall be initialized; [DR1359]
6292   //
6293   // If we squint, this is guaranteed, since exactly one non-static data member
6294   // will be initialized (if the constructor isn't deleted), we just don't know
6295   // which one.
6296   if (Ctor && ClassDecl->isUnion())
6297     return CSM == Sema::CXXDefaultConstructor
6298                ? ClassDecl->hasInClassInitializer() ||
6299                      !ClassDecl->hasVariantMembers()
6300                : true;
6301 
6302   //   -- the class shall not have any virtual base classes;
6303   if (Ctor && ClassDecl->getNumVBases())
6304     return false;
6305 
6306   // C++1y [class.copy]p26:
6307   //   -- [the class] is a literal type, and
6308   if (!Ctor && !ClassDecl->isLiteral())
6309     return false;
6310 
6311   //   -- every constructor involved in initializing [...] base class
6312   //      sub-objects shall be a constexpr constructor;
6313   //   -- the assignment operator selected to copy/move each direct base
6314   //      class is a constexpr function, and
6315   for (const auto &B : ClassDecl->bases()) {
6316     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6317     if (!BaseType) continue;
6318 
6319     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6320     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6321                                   InheritedCtor, Inherited))
6322       return false;
6323   }
6324 
6325   //   -- every constructor involved in initializing non-static data members
6326   //      [...] shall be a constexpr constructor;
6327   //   -- every non-static data member and base class sub-object shall be
6328   //      initialized
6329   //   -- for each non-static data member of X that is of class type (or array
6330   //      thereof), the assignment operator selected to copy/move that member is
6331   //      a constexpr function
6332   for (const auto *F : ClassDecl->fields()) {
6333     if (F->isInvalidDecl())
6334       continue;
6335     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6336       continue;
6337     QualType BaseType = S.Context.getBaseElementType(F->getType());
6338     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6339       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6340       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6341                                     BaseType.getCVRQualifiers(),
6342                                     ConstArg && !F->isMutable()))
6343         return false;
6344     } else if (CSM == Sema::CXXDefaultConstructor) {
6345       return false;
6346     }
6347   }
6348 
6349   // All OK, it's constexpr!
6350   return true;
6351 }
6352 
6353 static Sema::ImplicitExceptionSpecification
6354 ComputeDefaultedSpecialMemberExceptionSpec(
6355     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6356     Sema::InheritedConstructorInfo *ICI);
6357 
6358 static Sema::ImplicitExceptionSpecification
6359 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6360   auto CSM = S.getSpecialMember(MD);
6361   if (CSM != Sema::CXXInvalid)
6362     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6363 
6364   auto *CD = cast<CXXConstructorDecl>(MD);
6365   assert(CD->getInheritedConstructor() &&
6366          "only special members have implicit exception specs");
6367   Sema::InheritedConstructorInfo ICI(
6368       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6369   return ComputeDefaultedSpecialMemberExceptionSpec(
6370       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6371 }
6372 
6373 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6374                                                             CXXMethodDecl *MD) {
6375   FunctionProtoType::ExtProtoInfo EPI;
6376 
6377   // Build an exception specification pointing back at this member.
6378   EPI.ExceptionSpec.Type = EST_Unevaluated;
6379   EPI.ExceptionSpec.SourceDecl = MD;
6380 
6381   // Set the calling convention to the default for C++ instance methods.
6382   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6383       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6384                                             /*IsCXXMethod=*/true));
6385   return EPI;
6386 }
6387 
6388 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6389   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6390   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6391     return;
6392 
6393   // Evaluate the exception specification.
6394   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6395   auto ESI = IES.getExceptionSpec();
6396 
6397   // Update the type of the special member to use it.
6398   UpdateExceptionSpec(MD, ESI);
6399 
6400   // A user-provided destructor can be defined outside the class. When that
6401   // happens, be sure to update the exception specification on both
6402   // declarations.
6403   const FunctionProtoType *CanonicalFPT =
6404     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6405   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6406     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6407 }
6408 
6409 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6410   CXXRecordDecl *RD = MD->getParent();
6411   CXXSpecialMember CSM = getSpecialMember(MD);
6412 
6413   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6414          "not an explicitly-defaulted special member");
6415 
6416   // Whether this was the first-declared instance of the constructor.
6417   // This affects whether we implicitly add an exception spec and constexpr.
6418   bool First = MD == MD->getCanonicalDecl();
6419 
6420   bool HadError = false;
6421 
6422   // C++11 [dcl.fct.def.default]p1:
6423   //   A function that is explicitly defaulted shall
6424   //     -- be a special member function (checked elsewhere),
6425   //     -- have the same type (except for ref-qualifiers, and except that a
6426   //        copy operation can take a non-const reference) as an implicit
6427   //        declaration, and
6428   //     -- not have default arguments.
6429   unsigned ExpectedParams = 1;
6430   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6431     ExpectedParams = 0;
6432   if (MD->getNumParams() != ExpectedParams) {
6433     // This also checks for default arguments: a copy or move constructor with a
6434     // default argument is classified as a default constructor, and assignment
6435     // operations and destructors can't have default arguments.
6436     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6437       << CSM << MD->getSourceRange();
6438     HadError = true;
6439   } else if (MD->isVariadic()) {
6440     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6441       << CSM << MD->getSourceRange();
6442     HadError = true;
6443   }
6444 
6445   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6446 
6447   bool CanHaveConstParam = false;
6448   if (CSM == CXXCopyConstructor)
6449     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6450   else if (CSM == CXXCopyAssignment)
6451     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6452 
6453   QualType ReturnType = Context.VoidTy;
6454   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6455     // Check for return type matching.
6456     ReturnType = Type->getReturnType();
6457     QualType ExpectedReturnType =
6458         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6459     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6460       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6461         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6462       HadError = true;
6463     }
6464 
6465     // A defaulted special member cannot have cv-qualifiers.
6466     if (Type->getTypeQuals()) {
6467       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6468         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6469       HadError = true;
6470     }
6471   }
6472 
6473   // Check for parameter type matching.
6474   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6475   bool HasConstParam = false;
6476   if (ExpectedParams && ArgType->isReferenceType()) {
6477     // Argument must be reference to possibly-const T.
6478     QualType ReferentType = ArgType->getPointeeType();
6479     HasConstParam = ReferentType.isConstQualified();
6480 
6481     if (ReferentType.isVolatileQualified()) {
6482       Diag(MD->getLocation(),
6483            diag::err_defaulted_special_member_volatile_param) << CSM;
6484       HadError = true;
6485     }
6486 
6487     if (HasConstParam && !CanHaveConstParam) {
6488       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6489         Diag(MD->getLocation(),
6490              diag::err_defaulted_special_member_copy_const_param)
6491           << (CSM == CXXCopyAssignment);
6492         // FIXME: Explain why this special member can't be const.
6493       } else {
6494         Diag(MD->getLocation(),
6495              diag::err_defaulted_special_member_move_const_param)
6496           << (CSM == CXXMoveAssignment);
6497       }
6498       HadError = true;
6499     }
6500   } else if (ExpectedParams) {
6501     // A copy assignment operator can take its argument by value, but a
6502     // defaulted one cannot.
6503     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6504     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6505     HadError = true;
6506   }
6507 
6508   // C++11 [dcl.fct.def.default]p2:
6509   //   An explicitly-defaulted function may be declared constexpr only if it
6510   //   would have been implicitly declared as constexpr,
6511   // Do not apply this rule to members of class templates, since core issue 1358
6512   // makes such functions always instantiate to constexpr functions. For
6513   // functions which cannot be constexpr (for non-constructors in C++11 and for
6514   // destructors in C++1y), this is checked elsewhere.
6515   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6516                                                      HasConstParam);
6517   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6518                                  : isa<CXXConstructorDecl>(MD)) &&
6519       MD->isConstexpr() && !Constexpr &&
6520       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6521     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6522     // FIXME: Explain why the special member can't be constexpr.
6523     HadError = true;
6524   }
6525 
6526   //   and may have an explicit exception-specification only if it is compatible
6527   //   with the exception-specification on the implicit declaration.
6528   if (Type->hasExceptionSpec()) {
6529     // Delay the check if this is the first declaration of the special member,
6530     // since we may not have parsed some necessary in-class initializers yet.
6531     if (First) {
6532       // If the exception specification needs to be instantiated, do so now,
6533       // before we clobber it with an EST_Unevaluated specification below.
6534       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6535         InstantiateExceptionSpec(MD->getLocStart(), MD);
6536         Type = MD->getType()->getAs<FunctionProtoType>();
6537       }
6538       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6539     } else
6540       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6541   }
6542 
6543   //   If a function is explicitly defaulted on its first declaration,
6544   if (First) {
6545     //  -- it is implicitly considered to be constexpr if the implicit
6546     //     definition would be,
6547     MD->setConstexpr(Constexpr);
6548 
6549     //  -- it is implicitly considered to have the same exception-specification
6550     //     as if it had been implicitly declared,
6551     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6552     EPI.ExceptionSpec.Type = EST_Unevaluated;
6553     EPI.ExceptionSpec.SourceDecl = MD;
6554     MD->setType(Context.getFunctionType(ReturnType,
6555                                         llvm::makeArrayRef(&ArgType,
6556                                                            ExpectedParams),
6557                                         EPI));
6558   }
6559 
6560   if (ShouldDeleteSpecialMember(MD, CSM)) {
6561     if (First) {
6562       SetDeclDeleted(MD, MD->getLocation());
6563     } else {
6564       // C++11 [dcl.fct.def.default]p4:
6565       //   [For a] user-provided explicitly-defaulted function [...] if such a
6566       //   function is implicitly defined as deleted, the program is ill-formed.
6567       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6568       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6569       HadError = true;
6570     }
6571   }
6572 
6573   if (HadError)
6574     MD->setInvalidDecl();
6575 }
6576 
6577 /// Check whether the exception specification provided for an
6578 /// explicitly-defaulted special member matches the exception specification
6579 /// that would have been generated for an implicit special member, per
6580 /// C++11 [dcl.fct.def.default]p2.
6581 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6582     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6583   // If the exception specification was explicitly specified but hadn't been
6584   // parsed when the method was defaulted, grab it now.
6585   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6586     SpecifiedType =
6587         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6588 
6589   // Compute the implicit exception specification.
6590   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6591                                                        /*IsCXXMethod=*/true);
6592   FunctionProtoType::ExtProtoInfo EPI(CC);
6593   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6594   EPI.ExceptionSpec = IES.getExceptionSpec();
6595   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6596     Context.getFunctionType(Context.VoidTy, None, EPI));
6597 
6598   // Ensure that it matches.
6599   CheckEquivalentExceptionSpec(
6600     PDiag(diag::err_incorrect_defaulted_exception_spec)
6601       << getSpecialMember(MD), PDiag(),
6602     ImplicitType, SourceLocation(),
6603     SpecifiedType, MD->getLocation());
6604 }
6605 
6606 void Sema::CheckDelayedMemberExceptionSpecs() {
6607   decltype(DelayedExceptionSpecChecks) Checks;
6608   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6609 
6610   std::swap(Checks, DelayedExceptionSpecChecks);
6611   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6612 
6613   // Perform any deferred checking of exception specifications for virtual
6614   // destructors.
6615   for (auto &Check : Checks)
6616     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6617 
6618   // Check that any explicitly-defaulted methods have exception specifications
6619   // compatible with their implicit exception specifications.
6620   for (auto &Spec : Specs)
6621     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6622 }
6623 
6624 namespace {
6625 /// CRTP base class for visiting operations performed by a special member
6626 /// function (or inherited constructor).
6627 template<typename Derived>
6628 struct SpecialMemberVisitor {
6629   Sema &S;
6630   CXXMethodDecl *MD;
6631   Sema::CXXSpecialMember CSM;
6632   Sema::InheritedConstructorInfo *ICI;
6633 
6634   // Properties of the special member, computed for convenience.
6635   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6636 
6637   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6638                        Sema::InheritedConstructorInfo *ICI)
6639       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6640     switch (CSM) {
6641     case Sema::CXXDefaultConstructor:
6642     case Sema::CXXCopyConstructor:
6643     case Sema::CXXMoveConstructor:
6644       IsConstructor = true;
6645       break;
6646     case Sema::CXXCopyAssignment:
6647     case Sema::CXXMoveAssignment:
6648       IsAssignment = true;
6649       break;
6650     case Sema::CXXDestructor:
6651       break;
6652     case Sema::CXXInvalid:
6653       llvm_unreachable("invalid special member kind");
6654     }
6655 
6656     if (MD->getNumParams()) {
6657       if (const ReferenceType *RT =
6658               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6659         ConstArg = RT->getPointeeType().isConstQualified();
6660     }
6661   }
6662 
6663   Derived &getDerived() { return static_cast<Derived&>(*this); }
6664 
6665   /// Is this a "move" special member?
6666   bool isMove() const {
6667     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6668   }
6669 
6670   /// Look up the corresponding special member in the given class.
6671   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6672                                              unsigned Quals, bool IsMutable) {
6673     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6674                                        ConstArg && !IsMutable);
6675   }
6676 
6677   /// Look up the constructor for the specified base class to see if it's
6678   /// overridden due to this being an inherited constructor.
6679   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6680     if (!ICI)
6681       return {};
6682     assert(CSM == Sema::CXXDefaultConstructor);
6683     auto *BaseCtor =
6684       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6685     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6686       return MD;
6687     return {};
6688   }
6689 
6690   /// A base or member subobject.
6691   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6692 
6693   /// Get the location to use for a subobject in diagnostics.
6694   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6695     // FIXME: For an indirect virtual base, the direct base leading to
6696     // the indirect virtual base would be a more useful choice.
6697     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6698       return B->getBaseTypeLoc();
6699     else
6700       return Subobj.get<FieldDecl*>()->getLocation();
6701   }
6702 
6703   enum BasesToVisit {
6704     /// Visit all non-virtual (direct) bases.
6705     VisitNonVirtualBases,
6706     /// Visit all direct bases, virtual or not.
6707     VisitDirectBases,
6708     /// Visit all non-virtual bases, and all virtual bases if the class
6709     /// is not abstract.
6710     VisitPotentiallyConstructedBases,
6711     /// Visit all direct or virtual bases.
6712     VisitAllBases
6713   };
6714 
6715   // Visit the bases and members of the class.
6716   bool visit(BasesToVisit Bases) {
6717     CXXRecordDecl *RD = MD->getParent();
6718 
6719     if (Bases == VisitPotentiallyConstructedBases)
6720       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6721 
6722     for (auto &B : RD->bases())
6723       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6724           getDerived().visitBase(&B))
6725         return true;
6726 
6727     if (Bases == VisitAllBases)
6728       for (auto &B : RD->vbases())
6729         if (getDerived().visitBase(&B))
6730           return true;
6731 
6732     for (auto *F : RD->fields())
6733       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6734           getDerived().visitField(F))
6735         return true;
6736 
6737     return false;
6738   }
6739 };
6740 }
6741 
6742 namespace {
6743 struct SpecialMemberDeletionInfo
6744     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6745   bool Diagnose;
6746 
6747   SourceLocation Loc;
6748 
6749   bool AllFieldsAreConst;
6750 
6751   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6752                             Sema::CXXSpecialMember CSM,
6753                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6754       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6755         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6756 
6757   bool inUnion() const { return MD->getParent()->isUnion(); }
6758 
6759   Sema::CXXSpecialMember getEffectiveCSM() {
6760     return ICI ? Sema::CXXInvalid : CSM;
6761   }
6762 
6763   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6764   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6765 
6766   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6767   bool shouldDeleteForField(FieldDecl *FD);
6768   bool shouldDeleteForAllConstMembers();
6769 
6770   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6771                                      unsigned Quals);
6772   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6773                                     Sema::SpecialMemberOverloadResult SMOR,
6774                                     bool IsDtorCallInCtor);
6775 
6776   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6777 };
6778 }
6779 
6780 /// Is the given special member inaccessible when used on the given
6781 /// sub-object.
6782 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6783                                              CXXMethodDecl *target) {
6784   /// If we're operating on a base class, the object type is the
6785   /// type of this special member.
6786   QualType objectTy;
6787   AccessSpecifier access = target->getAccess();
6788   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6789     objectTy = S.Context.getTypeDeclType(MD->getParent());
6790     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6791 
6792   // If we're operating on a field, the object type is the type of the field.
6793   } else {
6794     objectTy = S.Context.getTypeDeclType(target->getParent());
6795   }
6796 
6797   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6798 }
6799 
6800 /// Check whether we should delete a special member due to the implicit
6801 /// definition containing a call to a special member of a subobject.
6802 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6803     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6804     bool IsDtorCallInCtor) {
6805   CXXMethodDecl *Decl = SMOR.getMethod();
6806   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6807 
6808   int DiagKind = -1;
6809 
6810   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6811     DiagKind = !Decl ? 0 : 1;
6812   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6813     DiagKind = 2;
6814   else if (!isAccessible(Subobj, Decl))
6815     DiagKind = 3;
6816   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6817            !Decl->isTrivial()) {
6818     // A member of a union must have a trivial corresponding special member.
6819     // As a weird special case, a destructor call from a union's constructor
6820     // must be accessible and non-deleted, but need not be trivial. Such a
6821     // destructor is never actually called, but is semantically checked as
6822     // if it were.
6823     DiagKind = 4;
6824   }
6825 
6826   if (DiagKind == -1)
6827     return false;
6828 
6829   if (Diagnose) {
6830     if (Field) {
6831       S.Diag(Field->getLocation(),
6832              diag::note_deleted_special_member_class_subobject)
6833         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6834         << Field << DiagKind << IsDtorCallInCtor;
6835     } else {
6836       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6837       S.Diag(Base->getLocStart(),
6838              diag::note_deleted_special_member_class_subobject)
6839         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6840         << Base->getType() << DiagKind << IsDtorCallInCtor;
6841     }
6842 
6843     if (DiagKind == 1)
6844       S.NoteDeletedFunction(Decl);
6845     // FIXME: Explain inaccessibility if DiagKind == 3.
6846   }
6847 
6848   return true;
6849 }
6850 
6851 /// Check whether we should delete a special member function due to having a
6852 /// direct or virtual base class or non-static data member of class type M.
6853 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6854     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6855   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6856   bool IsMutable = Field && Field->isMutable();
6857 
6858   // C++11 [class.ctor]p5:
6859   // -- any direct or virtual base class, or non-static data member with no
6860   //    brace-or-equal-initializer, has class type M (or array thereof) and
6861   //    either M has no default constructor or overload resolution as applied
6862   //    to M's default constructor results in an ambiguity or in a function
6863   //    that is deleted or inaccessible
6864   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6865   // -- a direct or virtual base class B that cannot be copied/moved because
6866   //    overload resolution, as applied to B's corresponding special member,
6867   //    results in an ambiguity or a function that is deleted or inaccessible
6868   //    from the defaulted special member
6869   // C++11 [class.dtor]p5:
6870   // -- any direct or virtual base class [...] has a type with a destructor
6871   //    that is deleted or inaccessible
6872   if (!(CSM == Sema::CXXDefaultConstructor &&
6873         Field && Field->hasInClassInitializer()) &&
6874       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6875                                    false))
6876     return true;
6877 
6878   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6879   // -- any direct or virtual base class or non-static data member has a
6880   //    type with a destructor that is deleted or inaccessible
6881   if (IsConstructor) {
6882     Sema::SpecialMemberOverloadResult SMOR =
6883         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6884                               false, false, false, false, false);
6885     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6886       return true;
6887   }
6888 
6889   return false;
6890 }
6891 
6892 /// Check whether we should delete a special member function due to the class
6893 /// having a particular direct or virtual base class.
6894 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6895   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6896   // If program is correct, BaseClass cannot be null, but if it is, the error
6897   // must be reported elsewhere.
6898   if (!BaseClass)
6899     return false;
6900   // If we have an inheriting constructor, check whether we're calling an
6901   // inherited constructor instead of a default constructor.
6902   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6903   if (auto *BaseCtor = SMOR.getMethod()) {
6904     // Note that we do not check access along this path; other than that,
6905     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6906     // FIXME: Check that the base has a usable destructor! Sink this into
6907     // shouldDeleteForClassSubobject.
6908     if (BaseCtor->isDeleted() && Diagnose) {
6909       S.Diag(Base->getLocStart(),
6910              diag::note_deleted_special_member_class_subobject)
6911         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6912         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6913       S.NoteDeletedFunction(BaseCtor);
6914     }
6915     return BaseCtor->isDeleted();
6916   }
6917   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6918 }
6919 
6920 /// Check whether we should delete a special member function due to the class
6921 /// having a particular non-static data member.
6922 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6923   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6924   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6925 
6926   if (CSM == Sema::CXXDefaultConstructor) {
6927     // For a default constructor, all references must be initialized in-class
6928     // and, if a union, it must have a non-const member.
6929     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6930       if (Diagnose)
6931         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6932           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6933       return true;
6934     }
6935     // C++11 [class.ctor]p5: any non-variant non-static data member of
6936     // const-qualified type (or array thereof) with no
6937     // brace-or-equal-initializer does not have a user-provided default
6938     // constructor.
6939     if (!inUnion() && FieldType.isConstQualified() &&
6940         !FD->hasInClassInitializer() &&
6941         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6942       if (Diagnose)
6943         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6944           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6945       return true;
6946     }
6947 
6948     if (inUnion() && !FieldType.isConstQualified())
6949       AllFieldsAreConst = false;
6950   } else if (CSM == Sema::CXXCopyConstructor) {
6951     // For a copy constructor, data members must not be of rvalue reference
6952     // type.
6953     if (FieldType->isRValueReferenceType()) {
6954       if (Diagnose)
6955         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6956           << MD->getParent() << FD << FieldType;
6957       return true;
6958     }
6959   } else if (IsAssignment) {
6960     // For an assignment operator, data members must not be of reference type.
6961     if (FieldType->isReferenceType()) {
6962       if (Diagnose)
6963         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6964           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6965       return true;
6966     }
6967     if (!FieldRecord && FieldType.isConstQualified()) {
6968       // C++11 [class.copy]p23:
6969       // -- a non-static data member of const non-class type (or array thereof)
6970       if (Diagnose)
6971         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6972           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6973       return true;
6974     }
6975   }
6976 
6977   if (FieldRecord) {
6978     // Some additional restrictions exist on the variant members.
6979     if (!inUnion() && FieldRecord->isUnion() &&
6980         FieldRecord->isAnonymousStructOrUnion()) {
6981       bool AllVariantFieldsAreConst = true;
6982 
6983       // FIXME: Handle anonymous unions declared within anonymous unions.
6984       for (auto *UI : FieldRecord->fields()) {
6985         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6986 
6987         if (!UnionFieldType.isConstQualified())
6988           AllVariantFieldsAreConst = false;
6989 
6990         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6991         if (UnionFieldRecord &&
6992             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6993                                           UnionFieldType.getCVRQualifiers()))
6994           return true;
6995       }
6996 
6997       // At least one member in each anonymous union must be non-const
6998       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6999           !FieldRecord->field_empty()) {
7000         if (Diagnose)
7001           S.Diag(FieldRecord->getLocation(),
7002                  diag::note_deleted_default_ctor_all_const)
7003             << !!ICI << MD->getParent() << /*anonymous union*/1;
7004         return true;
7005       }
7006 
7007       // Don't check the implicit member of the anonymous union type.
7008       // This is technically non-conformant, but sanity demands it.
7009       return false;
7010     }
7011 
7012     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7013                                       FieldType.getCVRQualifiers()))
7014       return true;
7015   }
7016 
7017   return false;
7018 }
7019 
7020 /// C++11 [class.ctor] p5:
7021 ///   A defaulted default constructor for a class X is defined as deleted if
7022 /// X is a union and all of its variant members are of const-qualified type.
7023 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7024   // This is a silly definition, because it gives an empty union a deleted
7025   // default constructor. Don't do that.
7026   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7027     bool AnyFields = false;
7028     for (auto *F : MD->getParent()->fields())
7029       if ((AnyFields = !F->isUnnamedBitfield()))
7030         break;
7031     if (!AnyFields)
7032       return false;
7033     if (Diagnose)
7034       S.Diag(MD->getParent()->getLocation(),
7035              diag::note_deleted_default_ctor_all_const)
7036         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7037     return true;
7038   }
7039   return false;
7040 }
7041 
7042 /// Determine whether a defaulted special member function should be defined as
7043 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7044 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7045 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7046                                      InheritedConstructorInfo *ICI,
7047                                      bool Diagnose) {
7048   if (MD->isInvalidDecl())
7049     return false;
7050   CXXRecordDecl *RD = MD->getParent();
7051   assert(!RD->isDependentType() && "do deletion after instantiation");
7052   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7053     return false;
7054 
7055   // C++11 [expr.lambda.prim]p19:
7056   //   The closure type associated with a lambda-expression has a
7057   //   deleted (8.4.3) default constructor and a deleted copy
7058   //   assignment operator.
7059   if (RD->isLambda() &&
7060       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7061     if (Diagnose)
7062       Diag(RD->getLocation(), diag::note_lambda_decl);
7063     return true;
7064   }
7065 
7066   // For an anonymous struct or union, the copy and assignment special members
7067   // will never be used, so skip the check. For an anonymous union declared at
7068   // namespace scope, the constructor and destructor are used.
7069   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7070       RD->isAnonymousStructOrUnion())
7071     return false;
7072 
7073   // C++11 [class.copy]p7, p18:
7074   //   If the class definition declares a move constructor or move assignment
7075   //   operator, an implicitly declared copy constructor or copy assignment
7076   //   operator is defined as deleted.
7077   if (MD->isImplicit() &&
7078       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7079     CXXMethodDecl *UserDeclaredMove = nullptr;
7080 
7081     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7082     // deletion of the corresponding copy operation, not both copy operations.
7083     // MSVC 2015 has adopted the standards conforming behavior.
7084     bool DeletesOnlyMatchingCopy =
7085         getLangOpts().MSVCCompat &&
7086         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7087 
7088     if (RD->hasUserDeclaredMoveConstructor() &&
7089         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7090       if (!Diagnose) return true;
7091 
7092       // Find any user-declared move constructor.
7093       for (auto *I : RD->ctors()) {
7094         if (I->isMoveConstructor()) {
7095           UserDeclaredMove = I;
7096           break;
7097         }
7098       }
7099       assert(UserDeclaredMove);
7100     } else if (RD->hasUserDeclaredMoveAssignment() &&
7101                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7102       if (!Diagnose) return true;
7103 
7104       // Find any user-declared move assignment operator.
7105       for (auto *I : RD->methods()) {
7106         if (I->isMoveAssignmentOperator()) {
7107           UserDeclaredMove = I;
7108           break;
7109         }
7110       }
7111       assert(UserDeclaredMove);
7112     }
7113 
7114     if (UserDeclaredMove) {
7115       Diag(UserDeclaredMove->getLocation(),
7116            diag::note_deleted_copy_user_declared_move)
7117         << (CSM == CXXCopyAssignment) << RD
7118         << UserDeclaredMove->isMoveAssignmentOperator();
7119       return true;
7120     }
7121   }
7122 
7123   // Do access control from the special member function
7124   ContextRAII MethodContext(*this, MD);
7125 
7126   // C++11 [class.dtor]p5:
7127   // -- for a virtual destructor, lookup of the non-array deallocation function
7128   //    results in an ambiguity or in a function that is deleted or inaccessible
7129   if (CSM == CXXDestructor && MD->isVirtual()) {
7130     FunctionDecl *OperatorDelete = nullptr;
7131     DeclarationName Name =
7132       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7133     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7134                                  OperatorDelete, /*Diagnose*/false)) {
7135       if (Diagnose)
7136         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7137       return true;
7138     }
7139   }
7140 
7141   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7142 
7143   // Per DR1611, do not consider virtual bases of constructors of abstract
7144   // classes, since we are not going to construct them.
7145   // Per DR1658, do not consider virtual bases of destructors of abstract
7146   // classes either.
7147   // Per DR2180, for assignment operators we only assign (and thus only
7148   // consider) direct bases.
7149   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7150                                  : SMI.VisitPotentiallyConstructedBases))
7151     return true;
7152 
7153   if (SMI.shouldDeleteForAllConstMembers())
7154     return true;
7155 
7156   if (getLangOpts().CUDA) {
7157     // We should delete the special member in CUDA mode if target inference
7158     // failed.
7159     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7160                                                    Diagnose);
7161   }
7162 
7163   return false;
7164 }
7165 
7166 /// Perform lookup for a special member of the specified kind, and determine
7167 /// whether it is trivial. If the triviality can be determined without the
7168 /// lookup, skip it. This is intended for use when determining whether a
7169 /// special member of a containing object is trivial, and thus does not ever
7170 /// perform overload resolution for default constructors.
7171 ///
7172 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7173 /// member that was most likely to be intended to be trivial, if any.
7174 ///
7175 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7176 /// determine whether the special member is trivial.
7177 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7178                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7179                                      bool ConstRHS,
7180                                      Sema::TrivialABIHandling TAH,
7181                                      CXXMethodDecl **Selected) {
7182   if (Selected)
7183     *Selected = nullptr;
7184 
7185   switch (CSM) {
7186   case Sema::CXXInvalid:
7187     llvm_unreachable("not a special member");
7188 
7189   case Sema::CXXDefaultConstructor:
7190     // C++11 [class.ctor]p5:
7191     //   A default constructor is trivial if:
7192     //    - all the [direct subobjects] have trivial default constructors
7193     //
7194     // Note, no overload resolution is performed in this case.
7195     if (RD->hasTrivialDefaultConstructor())
7196       return true;
7197 
7198     if (Selected) {
7199       // If there's a default constructor which could have been trivial, dig it
7200       // out. Otherwise, if there's any user-provided default constructor, point
7201       // to that as an example of why there's not a trivial one.
7202       CXXConstructorDecl *DefCtor = nullptr;
7203       if (RD->needsImplicitDefaultConstructor())
7204         S.DeclareImplicitDefaultConstructor(RD);
7205       for (auto *CI : RD->ctors()) {
7206         if (!CI->isDefaultConstructor())
7207           continue;
7208         DefCtor = CI;
7209         if (!DefCtor->isUserProvided())
7210           break;
7211       }
7212 
7213       *Selected = DefCtor;
7214     }
7215 
7216     return false;
7217 
7218   case Sema::CXXDestructor:
7219     // C++11 [class.dtor]p5:
7220     //   A destructor is trivial if:
7221     //    - all the direct [subobjects] have trivial destructors
7222     if (RD->hasTrivialDestructor() ||
7223         (TAH == Sema::TAH_ConsiderTrivialABI &&
7224          RD->hasTrivialDestructorForCall()))
7225       return true;
7226 
7227     if (Selected) {
7228       if (RD->needsImplicitDestructor())
7229         S.DeclareImplicitDestructor(RD);
7230       *Selected = RD->getDestructor();
7231     }
7232 
7233     return false;
7234 
7235   case Sema::CXXCopyConstructor:
7236     // C++11 [class.copy]p12:
7237     //   A copy constructor is trivial if:
7238     //    - the constructor selected to copy each direct [subobject] is trivial
7239     if (RD->hasTrivialCopyConstructor() ||
7240         (TAH == Sema::TAH_ConsiderTrivialABI &&
7241          RD->hasTrivialCopyConstructorForCall())) {
7242       if (Quals == Qualifiers::Const)
7243         // We must either select the trivial copy constructor or reach an
7244         // ambiguity; no need to actually perform overload resolution.
7245         return true;
7246     } else if (!Selected) {
7247       return false;
7248     }
7249     // In C++98, we are not supposed to perform overload resolution here, but we
7250     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7251     // cases like B as having a non-trivial copy constructor:
7252     //   struct A { template<typename T> A(T&); };
7253     //   struct B { mutable A a; };
7254     goto NeedOverloadResolution;
7255 
7256   case Sema::CXXCopyAssignment:
7257     // C++11 [class.copy]p25:
7258     //   A copy assignment operator is trivial if:
7259     //    - the assignment operator selected to copy each direct [subobject] is
7260     //      trivial
7261     if (RD->hasTrivialCopyAssignment()) {
7262       if (Quals == Qualifiers::Const)
7263         return true;
7264     } else if (!Selected) {
7265       return false;
7266     }
7267     // In C++98, we are not supposed to perform overload resolution here, but we
7268     // treat that as a language defect.
7269     goto NeedOverloadResolution;
7270 
7271   case Sema::CXXMoveConstructor:
7272   case Sema::CXXMoveAssignment:
7273   NeedOverloadResolution:
7274     Sema::SpecialMemberOverloadResult SMOR =
7275         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7276 
7277     // The standard doesn't describe how to behave if the lookup is ambiguous.
7278     // We treat it as not making the member non-trivial, just like the standard
7279     // mandates for the default constructor. This should rarely matter, because
7280     // the member will also be deleted.
7281     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7282       return true;
7283 
7284     if (!SMOR.getMethod()) {
7285       assert(SMOR.getKind() ==
7286              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7287       return false;
7288     }
7289 
7290     // We deliberately don't check if we found a deleted special member. We're
7291     // not supposed to!
7292     if (Selected)
7293       *Selected = SMOR.getMethod();
7294 
7295     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7296         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7297       return SMOR.getMethod()->isTrivialForCall();
7298     return SMOR.getMethod()->isTrivial();
7299   }
7300 
7301   llvm_unreachable("unknown special method kind");
7302 }
7303 
7304 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7305   for (auto *CI : RD->ctors())
7306     if (!CI->isImplicit())
7307       return CI;
7308 
7309   // Look for constructor templates.
7310   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7311   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7312     if (CXXConstructorDecl *CD =
7313           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7314       return CD;
7315   }
7316 
7317   return nullptr;
7318 }
7319 
7320 /// The kind of subobject we are checking for triviality. The values of this
7321 /// enumeration are used in diagnostics.
7322 enum TrivialSubobjectKind {
7323   /// The subobject is a base class.
7324   TSK_BaseClass,
7325   /// The subobject is a non-static data member.
7326   TSK_Field,
7327   /// The object is actually the complete object.
7328   TSK_CompleteObject
7329 };
7330 
7331 /// Check whether the special member selected for a given type would be trivial.
7332 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7333                                       QualType SubType, bool ConstRHS,
7334                                       Sema::CXXSpecialMember CSM,
7335                                       TrivialSubobjectKind Kind,
7336                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7337   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7338   if (!SubRD)
7339     return true;
7340 
7341   CXXMethodDecl *Selected;
7342   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7343                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7344     return true;
7345 
7346   if (Diagnose) {
7347     if (ConstRHS)
7348       SubType.addConst();
7349 
7350     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7351       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7352         << Kind << SubType.getUnqualifiedType();
7353       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7354         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7355     } else if (!Selected)
7356       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7357         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7358     else if (Selected->isUserProvided()) {
7359       if (Kind == TSK_CompleteObject)
7360         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7361           << Kind << SubType.getUnqualifiedType() << CSM;
7362       else {
7363         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7364           << Kind << SubType.getUnqualifiedType() << CSM;
7365         S.Diag(Selected->getLocation(), diag::note_declared_at);
7366       }
7367     } else {
7368       if (Kind != TSK_CompleteObject)
7369         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7370           << Kind << SubType.getUnqualifiedType() << CSM;
7371 
7372       // Explain why the defaulted or deleted special member isn't trivial.
7373       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7374                                Diagnose);
7375     }
7376   }
7377 
7378   return false;
7379 }
7380 
7381 /// Check whether the members of a class type allow a special member to be
7382 /// trivial.
7383 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7384                                      Sema::CXXSpecialMember CSM,
7385                                      bool ConstArg,
7386                                      Sema::TrivialABIHandling TAH,
7387                                      bool Diagnose) {
7388   for (const auto *FI : RD->fields()) {
7389     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7390       continue;
7391 
7392     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7393 
7394     // Pretend anonymous struct or union members are members of this class.
7395     if (FI->isAnonymousStructOrUnion()) {
7396       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7397                                     CSM, ConstArg, TAH, Diagnose))
7398         return false;
7399       continue;
7400     }
7401 
7402     // C++11 [class.ctor]p5:
7403     //   A default constructor is trivial if [...]
7404     //    -- no non-static data member of its class has a
7405     //       brace-or-equal-initializer
7406     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7407       if (Diagnose)
7408         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7409       return false;
7410     }
7411 
7412     // Objective C ARC 4.3.5:
7413     //   [...] nontrivally ownership-qualified types are [...] not trivially
7414     //   default constructible, copy constructible, move constructible, copy
7415     //   assignable, move assignable, or destructible [...]
7416     if (FieldType.hasNonTrivialObjCLifetime()) {
7417       if (Diagnose)
7418         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7419           << RD << FieldType.getObjCLifetime();
7420       return false;
7421     }
7422 
7423     bool ConstRHS = ConstArg && !FI->isMutable();
7424     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7425                                    CSM, TSK_Field, TAH, Diagnose))
7426       return false;
7427   }
7428 
7429   return true;
7430 }
7431 
7432 /// Diagnose why the specified class does not have a trivial special member of
7433 /// the given kind.
7434 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7435   QualType Ty = Context.getRecordType(RD);
7436 
7437   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7438   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7439                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7440                             /*Diagnose*/true);
7441 }
7442 
7443 /// Determine whether a defaulted or deleted special member function is trivial,
7444 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7445 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7446 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7447                                   TrivialABIHandling TAH, bool Diagnose) {
7448   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7449 
7450   CXXRecordDecl *RD = MD->getParent();
7451 
7452   bool ConstArg = false;
7453 
7454   // C++11 [class.copy]p12, p25: [DR1593]
7455   //   A [special member] is trivial if [...] its parameter-type-list is
7456   //   equivalent to the parameter-type-list of an implicit declaration [...]
7457   switch (CSM) {
7458   case CXXDefaultConstructor:
7459   case CXXDestructor:
7460     // Trivial default constructors and destructors cannot have parameters.
7461     break;
7462 
7463   case CXXCopyConstructor:
7464   case CXXCopyAssignment: {
7465     // Trivial copy operations always have const, non-volatile parameter types.
7466     ConstArg = true;
7467     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7468     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7469     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7470       if (Diagnose)
7471         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7472           << Param0->getSourceRange() << Param0->getType()
7473           << Context.getLValueReferenceType(
7474                Context.getRecordType(RD).withConst());
7475       return false;
7476     }
7477     break;
7478   }
7479 
7480   case CXXMoveConstructor:
7481   case CXXMoveAssignment: {
7482     // Trivial move operations always have non-cv-qualified parameters.
7483     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7484     const RValueReferenceType *RT =
7485       Param0->getType()->getAs<RValueReferenceType>();
7486     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7487       if (Diagnose)
7488         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7489           << Param0->getSourceRange() << Param0->getType()
7490           << Context.getRValueReferenceType(Context.getRecordType(RD));
7491       return false;
7492     }
7493     break;
7494   }
7495 
7496   case CXXInvalid:
7497     llvm_unreachable("not a special member");
7498   }
7499 
7500   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7501     if (Diagnose)
7502       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7503            diag::note_nontrivial_default_arg)
7504         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7505     return false;
7506   }
7507   if (MD->isVariadic()) {
7508     if (Diagnose)
7509       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7510     return false;
7511   }
7512 
7513   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7514   //   A copy/move [constructor or assignment operator] is trivial if
7515   //    -- the [member] selected to copy/move each direct base class subobject
7516   //       is trivial
7517   //
7518   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7519   //   A [default constructor or destructor] is trivial if
7520   //    -- all the direct base classes have trivial [default constructors or
7521   //       destructors]
7522   for (const auto &BI : RD->bases())
7523     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7524                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7525       return false;
7526 
7527   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7528   //   A copy/move [constructor or assignment operator] for a class X is
7529   //   trivial if
7530   //    -- for each non-static data member of X that is of class type (or array
7531   //       thereof), the constructor selected to copy/move that member is
7532   //       trivial
7533   //
7534   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7535   //   A [default constructor or destructor] is trivial if
7536   //    -- for all of the non-static data members of its class that are of class
7537   //       type (or array thereof), each such class has a trivial [default
7538   //       constructor or destructor]
7539   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7540     return false;
7541 
7542   // C++11 [class.dtor]p5:
7543   //   A destructor is trivial if [...]
7544   //    -- the destructor is not virtual
7545   if (CSM == CXXDestructor && MD->isVirtual()) {
7546     if (Diagnose)
7547       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7548     return false;
7549   }
7550 
7551   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7552   //   A [special member] for class X is trivial if [...]
7553   //    -- class X has no virtual functions and no virtual base classes
7554   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7555     if (!Diagnose)
7556       return false;
7557 
7558     if (RD->getNumVBases()) {
7559       // Check for virtual bases. We already know that the corresponding
7560       // member in all bases is trivial, so vbases must all be direct.
7561       CXXBaseSpecifier &BS = *RD->vbases_begin();
7562       assert(BS.isVirtual());
7563       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7564       return false;
7565     }
7566 
7567     // Must have a virtual method.
7568     for (const auto *MI : RD->methods()) {
7569       if (MI->isVirtual()) {
7570         SourceLocation MLoc = MI->getLocStart();
7571         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7572         return false;
7573       }
7574     }
7575 
7576     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7577   }
7578 
7579   // Looks like it's trivial!
7580   return true;
7581 }
7582 
7583 namespace {
7584 struct FindHiddenVirtualMethod {
7585   Sema *S;
7586   CXXMethodDecl *Method;
7587   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7588   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7589 
7590 private:
7591   /// Check whether any most overriden method from MD in Methods
7592   static bool CheckMostOverridenMethods(
7593       const CXXMethodDecl *MD,
7594       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7595     if (MD->size_overridden_methods() == 0)
7596       return Methods.count(MD->getCanonicalDecl());
7597     for (const CXXMethodDecl *O : MD->overridden_methods())
7598       if (CheckMostOverridenMethods(O, Methods))
7599         return true;
7600     return false;
7601   }
7602 
7603 public:
7604   /// Member lookup function that determines whether a given C++
7605   /// method overloads virtual methods in a base class without overriding any,
7606   /// to be used with CXXRecordDecl::lookupInBases().
7607   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7608     RecordDecl *BaseRecord =
7609         Specifier->getType()->getAs<RecordType>()->getDecl();
7610 
7611     DeclarationName Name = Method->getDeclName();
7612     assert(Name.getNameKind() == DeclarationName::Identifier);
7613 
7614     bool foundSameNameMethod = false;
7615     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7616     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7617          Path.Decls = Path.Decls.slice(1)) {
7618       NamedDecl *D = Path.Decls.front();
7619       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7620         MD = MD->getCanonicalDecl();
7621         foundSameNameMethod = true;
7622         // Interested only in hidden virtual methods.
7623         if (!MD->isVirtual())
7624           continue;
7625         // If the method we are checking overrides a method from its base
7626         // don't warn about the other overloaded methods. Clang deviates from
7627         // GCC by only diagnosing overloads of inherited virtual functions that
7628         // do not override any other virtual functions in the base. GCC's
7629         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7630         // function from a base class. These cases may be better served by a
7631         // warning (not specific to virtual functions) on call sites when the
7632         // call would select a different function from the base class, were it
7633         // visible.
7634         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7635         if (!S->IsOverload(Method, MD, false))
7636           return true;
7637         // Collect the overload only if its hidden.
7638         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7639           overloadedMethods.push_back(MD);
7640       }
7641     }
7642 
7643     if (foundSameNameMethod)
7644       OverloadedMethods.append(overloadedMethods.begin(),
7645                                overloadedMethods.end());
7646     return foundSameNameMethod;
7647   }
7648 };
7649 } // end anonymous namespace
7650 
7651 /// Add the most overriden methods from MD to Methods
7652 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7653                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7654   if (MD->size_overridden_methods() == 0)
7655     Methods.insert(MD->getCanonicalDecl());
7656   else
7657     for (const CXXMethodDecl *O : MD->overridden_methods())
7658       AddMostOverridenMethods(O, Methods);
7659 }
7660 
7661 /// Check if a method overloads virtual methods in a base class without
7662 /// overriding any.
7663 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7664                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7665   if (!MD->getDeclName().isIdentifier())
7666     return;
7667 
7668   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7669                      /*bool RecordPaths=*/false,
7670                      /*bool DetectVirtual=*/false);
7671   FindHiddenVirtualMethod FHVM;
7672   FHVM.Method = MD;
7673   FHVM.S = this;
7674 
7675   // Keep the base methods that were overriden or introduced in the subclass
7676   // by 'using' in a set. A base method not in this set is hidden.
7677   CXXRecordDecl *DC = MD->getParent();
7678   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7679   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7680     NamedDecl *ND = *I;
7681     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7682       ND = shad->getTargetDecl();
7683     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7684       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7685   }
7686 
7687   if (DC->lookupInBases(FHVM, Paths))
7688     OverloadedMethods = FHVM.OverloadedMethods;
7689 }
7690 
7691 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7692                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7693   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7694     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7695     PartialDiagnostic PD = PDiag(
7696          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7697     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7698     Diag(overloadedMD->getLocation(), PD);
7699   }
7700 }
7701 
7702 /// Diagnose methods which overload virtual methods in a base class
7703 /// without overriding any.
7704 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7705   if (MD->isInvalidDecl())
7706     return;
7707 
7708   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7709     return;
7710 
7711   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7712   FindHiddenVirtualMethods(MD, OverloadedMethods);
7713   if (!OverloadedMethods.empty()) {
7714     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7715       << MD << (OverloadedMethods.size() > 1);
7716 
7717     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7718   }
7719 }
7720 
7721 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7722   auto PrintDiagAndRemoveAttr = [&]() {
7723     // No diagnostics if this is a template instantiation.
7724     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7725       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7726            diag::ext_cannot_use_trivial_abi) << &RD;
7727     RD.dropAttr<TrivialABIAttr>();
7728   };
7729 
7730   // Ill-formed if the struct has virtual functions.
7731   if (RD.isPolymorphic()) {
7732     PrintDiagAndRemoveAttr();
7733     return;
7734   }
7735 
7736   for (const auto &B : RD.bases()) {
7737     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7738     // virtual base.
7739     if ((!B.getType()->isDependentType() &&
7740          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7741         B.isVirtual()) {
7742       PrintDiagAndRemoveAttr();
7743       return;
7744     }
7745   }
7746 
7747   for (const auto *FD : RD.fields()) {
7748     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7749     // non-trivial for the purpose of calls.
7750     QualType FT = FD->getType();
7751     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7752       PrintDiagAndRemoveAttr();
7753       return;
7754     }
7755 
7756     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7757       if (!RT->isDependentType() &&
7758           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7759         PrintDiagAndRemoveAttr();
7760         return;
7761       }
7762   }
7763 }
7764 
7765 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7766                                              Decl *TagDecl,
7767                                              SourceLocation LBrac,
7768                                              SourceLocation RBrac,
7769                                              AttributeList *AttrList) {
7770   if (!TagDecl)
7771     return;
7772 
7773   AdjustDeclIfTemplate(TagDecl);
7774 
7775   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7776     if (l->getKind() != AttributeList::AT_Visibility)
7777       continue;
7778     l->setInvalid();
7779     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7780       l->getName();
7781   }
7782 
7783   // See if trivial_abi has to be dropped.
7784   auto *RD = dyn_cast<CXXRecordDecl>(TagDecl);
7785   if (RD && RD->hasAttr<TrivialABIAttr>())
7786     checkIllFormedTrivialABIStruct(*RD);
7787 
7788   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7789               // strict aliasing violation!
7790               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7791               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7792 
7793   CheckCompletedCXXClass(RD);
7794 }
7795 
7796 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7797 /// special functions, such as the default constructor, copy
7798 /// constructor, or destructor, to the given C++ class (C++
7799 /// [special]p1).  This routine can only be executed just before the
7800 /// definition of the class is complete.
7801 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7802   if (ClassDecl->needsImplicitDefaultConstructor()) {
7803     ++ASTContext::NumImplicitDefaultConstructors;
7804 
7805     if (ClassDecl->hasInheritedConstructor())
7806       DeclareImplicitDefaultConstructor(ClassDecl);
7807   }
7808 
7809   if (ClassDecl->needsImplicitCopyConstructor()) {
7810     ++ASTContext::NumImplicitCopyConstructors;
7811 
7812     // If the properties or semantics of the copy constructor couldn't be
7813     // determined while the class was being declared, force a declaration
7814     // of it now.
7815     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7816         ClassDecl->hasInheritedConstructor())
7817       DeclareImplicitCopyConstructor(ClassDecl);
7818     // For the MS ABI we need to know whether the copy ctor is deleted. A
7819     // prerequisite for deleting the implicit copy ctor is that the class has a
7820     // move ctor or move assignment that is either user-declared or whose
7821     // semantics are inherited from a subobject. FIXME: We should provide a more
7822     // direct way for CodeGen to ask whether the constructor was deleted.
7823     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7824              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7825               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7826               ClassDecl->hasUserDeclaredMoveAssignment() ||
7827               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7828       DeclareImplicitCopyConstructor(ClassDecl);
7829   }
7830 
7831   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7832     ++ASTContext::NumImplicitMoveConstructors;
7833 
7834     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7835         ClassDecl->hasInheritedConstructor())
7836       DeclareImplicitMoveConstructor(ClassDecl);
7837   }
7838 
7839   if (ClassDecl->needsImplicitCopyAssignment()) {
7840     ++ASTContext::NumImplicitCopyAssignmentOperators;
7841 
7842     // If we have a dynamic class, then the copy assignment operator may be
7843     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7844     // it shows up in the right place in the vtable and that we diagnose
7845     // problems with the implicit exception specification.
7846     if (ClassDecl->isDynamicClass() ||
7847         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7848         ClassDecl->hasInheritedAssignment())
7849       DeclareImplicitCopyAssignment(ClassDecl);
7850   }
7851 
7852   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7853     ++ASTContext::NumImplicitMoveAssignmentOperators;
7854 
7855     // Likewise for the move assignment operator.
7856     if (ClassDecl->isDynamicClass() ||
7857         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7858         ClassDecl->hasInheritedAssignment())
7859       DeclareImplicitMoveAssignment(ClassDecl);
7860   }
7861 
7862   if (ClassDecl->needsImplicitDestructor()) {
7863     ++ASTContext::NumImplicitDestructors;
7864 
7865     // If we have a dynamic class, then the destructor may be virtual, so we
7866     // have to declare the destructor immediately. This ensures that, e.g., it
7867     // shows up in the right place in the vtable and that we diagnose problems
7868     // with the implicit exception specification.
7869     if (ClassDecl->isDynamicClass() ||
7870         ClassDecl->needsOverloadResolutionForDestructor())
7871       DeclareImplicitDestructor(ClassDecl);
7872   }
7873 }
7874 
7875 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7876   if (!D)
7877     return 0;
7878 
7879   // The order of template parameters is not important here. All names
7880   // get added to the same scope.
7881   SmallVector<TemplateParameterList *, 4> ParameterLists;
7882 
7883   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7884     D = TD->getTemplatedDecl();
7885 
7886   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7887     ParameterLists.push_back(PSD->getTemplateParameters());
7888 
7889   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7890     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7891       ParameterLists.push_back(DD->getTemplateParameterList(i));
7892 
7893     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7894       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7895         ParameterLists.push_back(FTD->getTemplateParameters());
7896     }
7897   }
7898 
7899   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7900     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7901       ParameterLists.push_back(TD->getTemplateParameterList(i));
7902 
7903     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7904       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7905         ParameterLists.push_back(CTD->getTemplateParameters());
7906     }
7907   }
7908 
7909   unsigned Count = 0;
7910   for (TemplateParameterList *Params : ParameterLists) {
7911     if (Params->size() > 0)
7912       // Ignore explicit specializations; they don't contribute to the template
7913       // depth.
7914       ++Count;
7915     for (NamedDecl *Param : *Params) {
7916       if (Param->getDeclName()) {
7917         S->AddDecl(Param);
7918         IdResolver.AddDecl(Param);
7919       }
7920     }
7921   }
7922 
7923   return Count;
7924 }
7925 
7926 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7927   if (!RecordD) return;
7928   AdjustDeclIfTemplate(RecordD);
7929   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7930   PushDeclContext(S, Record);
7931 }
7932 
7933 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7934   if (!RecordD) return;
7935   PopDeclContext();
7936 }
7937 
7938 /// This is used to implement the constant expression evaluation part of the
7939 /// attribute enable_if extension. There is nothing in standard C++ which would
7940 /// require reentering parameters.
7941 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7942   if (!Param)
7943     return;
7944 
7945   S->AddDecl(Param);
7946   if (Param->getDeclName())
7947     IdResolver.AddDecl(Param);
7948 }
7949 
7950 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7951 /// parsing a top-level (non-nested) C++ class, and we are now
7952 /// parsing those parts of the given Method declaration that could
7953 /// not be parsed earlier (C++ [class.mem]p2), such as default
7954 /// arguments. This action should enter the scope of the given
7955 /// Method declaration as if we had just parsed the qualified method
7956 /// name. However, it should not bring the parameters into scope;
7957 /// that will be performed by ActOnDelayedCXXMethodParameter.
7958 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7959 }
7960 
7961 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7962 /// C++ method declaration. We're (re-)introducing the given
7963 /// function parameter into scope for use in parsing later parts of
7964 /// the method declaration. For example, we could see an
7965 /// ActOnParamDefaultArgument event for this parameter.
7966 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7967   if (!ParamD)
7968     return;
7969 
7970   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7971 
7972   // If this parameter has an unparsed default argument, clear it out
7973   // to make way for the parsed default argument.
7974   if (Param->hasUnparsedDefaultArg())
7975     Param->setDefaultArg(nullptr);
7976 
7977   S->AddDecl(Param);
7978   if (Param->getDeclName())
7979     IdResolver.AddDecl(Param);
7980 }
7981 
7982 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7983 /// processing the delayed method declaration for Method. The method
7984 /// declaration is now considered finished. There may be a separate
7985 /// ActOnStartOfFunctionDef action later (not necessarily
7986 /// immediately!) for this method, if it was also defined inside the
7987 /// class body.
7988 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7989   if (!MethodD)
7990     return;
7991 
7992   AdjustDeclIfTemplate(MethodD);
7993 
7994   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7995 
7996   // Now that we have our default arguments, check the constructor
7997   // again. It could produce additional diagnostics or affect whether
7998   // the class has implicitly-declared destructors, among other
7999   // things.
8000   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8001     CheckConstructor(Constructor);
8002 
8003   // Check the default arguments, which we may have added.
8004   if (!Method->isInvalidDecl())
8005     CheckCXXDefaultArguments(Method);
8006 }
8007 
8008 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8009 /// the well-formedness of the constructor declarator @p D with type @p
8010 /// R. If there are any errors in the declarator, this routine will
8011 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8012 /// will be updated to reflect a well-formed type for the constructor and
8013 /// returned.
8014 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8015                                           StorageClass &SC) {
8016   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8017 
8018   // C++ [class.ctor]p3:
8019   //   A constructor shall not be virtual (10.3) or static (9.4). A
8020   //   constructor can be invoked for a const, volatile or const
8021   //   volatile object. A constructor shall not be declared const,
8022   //   volatile, or const volatile (9.3.2).
8023   if (isVirtual) {
8024     if (!D.isInvalidType())
8025       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8026         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8027         << SourceRange(D.getIdentifierLoc());
8028     D.setInvalidType();
8029   }
8030   if (SC == SC_Static) {
8031     if (!D.isInvalidType())
8032       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8033         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8034         << SourceRange(D.getIdentifierLoc());
8035     D.setInvalidType();
8036     SC = SC_None;
8037   }
8038 
8039   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8040     diagnoseIgnoredQualifiers(
8041         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8042         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8043         D.getDeclSpec().getRestrictSpecLoc(),
8044         D.getDeclSpec().getAtomicSpecLoc());
8045     D.setInvalidType();
8046   }
8047 
8048   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8049   if (FTI.TypeQuals != 0) {
8050     if (FTI.TypeQuals & Qualifiers::Const)
8051       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8052         << "const" << SourceRange(D.getIdentifierLoc());
8053     if (FTI.TypeQuals & Qualifiers::Volatile)
8054       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8055         << "volatile" << SourceRange(D.getIdentifierLoc());
8056     if (FTI.TypeQuals & Qualifiers::Restrict)
8057       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8058         << "restrict" << SourceRange(D.getIdentifierLoc());
8059     D.setInvalidType();
8060   }
8061 
8062   // C++0x [class.ctor]p4:
8063   //   A constructor shall not be declared with a ref-qualifier.
8064   if (FTI.hasRefQualifier()) {
8065     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8066       << FTI.RefQualifierIsLValueRef
8067       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8068     D.setInvalidType();
8069   }
8070 
8071   // Rebuild the function type "R" without any type qualifiers (in
8072   // case any of the errors above fired) and with "void" as the
8073   // return type, since constructors don't have return types.
8074   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8075   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8076     return R;
8077 
8078   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8079   EPI.TypeQuals = 0;
8080   EPI.RefQualifier = RQ_None;
8081 
8082   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8083 }
8084 
8085 /// CheckConstructor - Checks a fully-formed constructor for
8086 /// well-formedness, issuing any diagnostics required. Returns true if
8087 /// the constructor declarator is invalid.
8088 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8089   CXXRecordDecl *ClassDecl
8090     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8091   if (!ClassDecl)
8092     return Constructor->setInvalidDecl();
8093 
8094   // C++ [class.copy]p3:
8095   //   A declaration of a constructor for a class X is ill-formed if
8096   //   its first parameter is of type (optionally cv-qualified) X and
8097   //   either there are no other parameters or else all other
8098   //   parameters have default arguments.
8099   if (!Constructor->isInvalidDecl() &&
8100       ((Constructor->getNumParams() == 1) ||
8101        (Constructor->getNumParams() > 1 &&
8102         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8103       Constructor->getTemplateSpecializationKind()
8104                                               != TSK_ImplicitInstantiation) {
8105     QualType ParamType = Constructor->getParamDecl(0)->getType();
8106     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8107     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8108       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8109       const char *ConstRef
8110         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8111                                                         : " const &";
8112       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8113         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8114 
8115       // FIXME: Rather that making the constructor invalid, we should endeavor
8116       // to fix the type.
8117       Constructor->setInvalidDecl();
8118     }
8119   }
8120 }
8121 
8122 /// CheckDestructor - Checks a fully-formed destructor definition for
8123 /// well-formedness, issuing any diagnostics required.  Returns true
8124 /// on error.
8125 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8126   CXXRecordDecl *RD = Destructor->getParent();
8127 
8128   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8129     SourceLocation Loc;
8130 
8131     if (!Destructor->isImplicit())
8132       Loc = Destructor->getLocation();
8133     else
8134       Loc = RD->getLocation();
8135 
8136     // If we have a virtual destructor, look up the deallocation function
8137     if (FunctionDecl *OperatorDelete =
8138             FindDeallocationFunctionForDestructor(Loc, RD)) {
8139       Expr *ThisArg = nullptr;
8140 
8141       // If the notional 'delete this' expression requires a non-trivial
8142       // conversion from 'this' to the type of a destroying operator delete's
8143       // first parameter, perform that conversion now.
8144       if (OperatorDelete->isDestroyingOperatorDelete()) {
8145         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8146         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8147           // C++ [class.dtor]p13:
8148           //   ... as if for the expression 'delete this' appearing in a
8149           //   non-virtual destructor of the destructor's class.
8150           ContextRAII SwitchContext(*this, Destructor);
8151           ExprResult This =
8152               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8153           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8154           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8155           if (This.isInvalid()) {
8156             // FIXME: Register this as a context note so that it comes out
8157             // in the right order.
8158             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8159             return true;
8160           }
8161           ThisArg = This.get();
8162         }
8163       }
8164 
8165       MarkFunctionReferenced(Loc, OperatorDelete);
8166       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8167     }
8168   }
8169 
8170   return false;
8171 }
8172 
8173 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8174 /// the well-formednes of the destructor declarator @p D with type @p
8175 /// R. If there are any errors in the declarator, this routine will
8176 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8177 /// will be updated to reflect a well-formed type for the destructor and
8178 /// returned.
8179 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8180                                          StorageClass& SC) {
8181   // C++ [class.dtor]p1:
8182   //   [...] A typedef-name that names a class is a class-name
8183   //   (7.1.3); however, a typedef-name that names a class shall not
8184   //   be used as the identifier in the declarator for a destructor
8185   //   declaration.
8186   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8187   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8188     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8189       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8190   else if (const TemplateSpecializationType *TST =
8191              DeclaratorType->getAs<TemplateSpecializationType>())
8192     if (TST->isTypeAlias())
8193       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8194         << DeclaratorType << 1;
8195 
8196   // C++ [class.dtor]p2:
8197   //   A destructor is used to destroy objects of its class type. A
8198   //   destructor takes no parameters, and no return type can be
8199   //   specified for it (not even void). The address of a destructor
8200   //   shall not be taken. A destructor shall not be static. A
8201   //   destructor can be invoked for a const, volatile or const
8202   //   volatile object. A destructor shall not be declared const,
8203   //   volatile or const volatile (9.3.2).
8204   if (SC == SC_Static) {
8205     if (!D.isInvalidType())
8206       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8207         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8208         << SourceRange(D.getIdentifierLoc())
8209         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8210 
8211     SC = SC_None;
8212   }
8213   if (!D.isInvalidType()) {
8214     // Destructors don't have return types, but the parser will
8215     // happily parse something like:
8216     //
8217     //   class X {
8218     //     float ~X();
8219     //   };
8220     //
8221     // The return type will be eliminated later.
8222     if (D.getDeclSpec().hasTypeSpecifier())
8223       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8224         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8225         << SourceRange(D.getIdentifierLoc());
8226     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8227       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8228                                 SourceLocation(),
8229                                 D.getDeclSpec().getConstSpecLoc(),
8230                                 D.getDeclSpec().getVolatileSpecLoc(),
8231                                 D.getDeclSpec().getRestrictSpecLoc(),
8232                                 D.getDeclSpec().getAtomicSpecLoc());
8233       D.setInvalidType();
8234     }
8235   }
8236 
8237   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8238   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8239     if (FTI.TypeQuals & Qualifiers::Const)
8240       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8241         << "const" << SourceRange(D.getIdentifierLoc());
8242     if (FTI.TypeQuals & Qualifiers::Volatile)
8243       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8244         << "volatile" << SourceRange(D.getIdentifierLoc());
8245     if (FTI.TypeQuals & Qualifiers::Restrict)
8246       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8247         << "restrict" << SourceRange(D.getIdentifierLoc());
8248     D.setInvalidType();
8249   }
8250 
8251   // C++0x [class.dtor]p2:
8252   //   A destructor shall not be declared with a ref-qualifier.
8253   if (FTI.hasRefQualifier()) {
8254     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8255       << FTI.RefQualifierIsLValueRef
8256       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8257     D.setInvalidType();
8258   }
8259 
8260   // Make sure we don't have any parameters.
8261   if (FTIHasNonVoidParameters(FTI)) {
8262     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8263 
8264     // Delete the parameters.
8265     FTI.freeParams();
8266     D.setInvalidType();
8267   }
8268 
8269   // Make sure the destructor isn't variadic.
8270   if (FTI.isVariadic) {
8271     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8272     D.setInvalidType();
8273   }
8274 
8275   // Rebuild the function type "R" without any type qualifiers or
8276   // parameters (in case any of the errors above fired) and with
8277   // "void" as the return type, since destructors don't have return
8278   // types.
8279   if (!D.isInvalidType())
8280     return R;
8281 
8282   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8283   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8284   EPI.Variadic = false;
8285   EPI.TypeQuals = 0;
8286   EPI.RefQualifier = RQ_None;
8287   return Context.getFunctionType(Context.VoidTy, None, EPI);
8288 }
8289 
8290 static void extendLeft(SourceRange &R, SourceRange Before) {
8291   if (Before.isInvalid())
8292     return;
8293   R.setBegin(Before.getBegin());
8294   if (R.getEnd().isInvalid())
8295     R.setEnd(Before.getEnd());
8296 }
8297 
8298 static void extendRight(SourceRange &R, SourceRange After) {
8299   if (After.isInvalid())
8300     return;
8301   if (R.getBegin().isInvalid())
8302     R.setBegin(After.getBegin());
8303   R.setEnd(After.getEnd());
8304 }
8305 
8306 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8307 /// well-formednes of the conversion function declarator @p D with
8308 /// type @p R. If there are any errors in the declarator, this routine
8309 /// will emit diagnostics and return true. Otherwise, it will return
8310 /// false. Either way, the type @p R will be updated to reflect a
8311 /// well-formed type for the conversion operator.
8312 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8313                                      StorageClass& SC) {
8314   // C++ [class.conv.fct]p1:
8315   //   Neither parameter types nor return type can be specified. The
8316   //   type of a conversion function (8.3.5) is "function taking no
8317   //   parameter returning conversion-type-id."
8318   if (SC == SC_Static) {
8319     if (!D.isInvalidType())
8320       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8321         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8322         << D.getName().getSourceRange();
8323     D.setInvalidType();
8324     SC = SC_None;
8325   }
8326 
8327   TypeSourceInfo *ConvTSI = nullptr;
8328   QualType ConvType =
8329       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8330 
8331   const DeclSpec &DS = D.getDeclSpec();
8332   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8333     // Conversion functions don't have return types, but the parser will
8334     // happily parse something like:
8335     //
8336     //   class X {
8337     //     float operator bool();
8338     //   };
8339     //
8340     // The return type will be changed later anyway.
8341     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8342       << SourceRange(DS.getTypeSpecTypeLoc())
8343       << SourceRange(D.getIdentifierLoc());
8344     D.setInvalidType();
8345   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8346     // It's also plausible that the user writes type qualifiers in the wrong
8347     // place, such as:
8348     //   struct S { const operator int(); };
8349     // FIXME: we could provide a fixit to move the qualifiers onto the
8350     // conversion type.
8351     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8352         << SourceRange(D.getIdentifierLoc()) << 0;
8353     D.setInvalidType();
8354   }
8355 
8356   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8357 
8358   // Make sure we don't have any parameters.
8359   if (Proto->getNumParams() > 0) {
8360     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8361 
8362     // Delete the parameters.
8363     D.getFunctionTypeInfo().freeParams();
8364     D.setInvalidType();
8365   } else if (Proto->isVariadic()) {
8366     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8367     D.setInvalidType();
8368   }
8369 
8370   // Diagnose "&operator bool()" and other such nonsense.  This
8371   // is actually a gcc extension which we don't support.
8372   if (Proto->getReturnType() != ConvType) {
8373     bool NeedsTypedef = false;
8374     SourceRange Before, After;
8375 
8376     // Walk the chunks and extract information on them for our diagnostic.
8377     bool PastFunctionChunk = false;
8378     for (auto &Chunk : D.type_objects()) {
8379       switch (Chunk.Kind) {
8380       case DeclaratorChunk::Function:
8381         if (!PastFunctionChunk) {
8382           if (Chunk.Fun.HasTrailingReturnType) {
8383             TypeSourceInfo *TRT = nullptr;
8384             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8385             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8386           }
8387           PastFunctionChunk = true;
8388           break;
8389         }
8390         LLVM_FALLTHROUGH;
8391       case DeclaratorChunk::Array:
8392         NeedsTypedef = true;
8393         extendRight(After, Chunk.getSourceRange());
8394         break;
8395 
8396       case DeclaratorChunk::Pointer:
8397       case DeclaratorChunk::BlockPointer:
8398       case DeclaratorChunk::Reference:
8399       case DeclaratorChunk::MemberPointer:
8400       case DeclaratorChunk::Pipe:
8401         extendLeft(Before, Chunk.getSourceRange());
8402         break;
8403 
8404       case DeclaratorChunk::Paren:
8405         extendLeft(Before, Chunk.Loc);
8406         extendRight(After, Chunk.EndLoc);
8407         break;
8408       }
8409     }
8410 
8411     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8412                          After.isValid()  ? After.getBegin() :
8413                                             D.getIdentifierLoc();
8414     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8415     DB << Before << After;
8416 
8417     if (!NeedsTypedef) {
8418       DB << /*don't need a typedef*/0;
8419 
8420       // If we can provide a correct fix-it hint, do so.
8421       if (After.isInvalid() && ConvTSI) {
8422         SourceLocation InsertLoc =
8423             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8424         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8425            << FixItHint::CreateInsertionFromRange(
8426                   InsertLoc, CharSourceRange::getTokenRange(Before))
8427            << FixItHint::CreateRemoval(Before);
8428       }
8429     } else if (!Proto->getReturnType()->isDependentType()) {
8430       DB << /*typedef*/1 << Proto->getReturnType();
8431     } else if (getLangOpts().CPlusPlus11) {
8432       DB << /*alias template*/2 << Proto->getReturnType();
8433     } else {
8434       DB << /*might not be fixable*/3;
8435     }
8436 
8437     // Recover by incorporating the other type chunks into the result type.
8438     // Note, this does *not* change the name of the function. This is compatible
8439     // with the GCC extension:
8440     //   struct S { &operator int(); } s;
8441     //   int &r = s.operator int(); // ok in GCC
8442     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8443     ConvType = Proto->getReturnType();
8444   }
8445 
8446   // C++ [class.conv.fct]p4:
8447   //   The conversion-type-id shall not represent a function type nor
8448   //   an array type.
8449   if (ConvType->isArrayType()) {
8450     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8451     ConvType = Context.getPointerType(ConvType);
8452     D.setInvalidType();
8453   } else if (ConvType->isFunctionType()) {
8454     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8455     ConvType = Context.getPointerType(ConvType);
8456     D.setInvalidType();
8457   }
8458 
8459   // Rebuild the function type "R" without any parameters (in case any
8460   // of the errors above fired) and with the conversion type as the
8461   // return type.
8462   if (D.isInvalidType())
8463     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8464 
8465   // C++0x explicit conversion operators.
8466   if (DS.isExplicitSpecified())
8467     Diag(DS.getExplicitSpecLoc(),
8468          getLangOpts().CPlusPlus11
8469              ? diag::warn_cxx98_compat_explicit_conversion_functions
8470              : diag::ext_explicit_conversion_functions)
8471         << SourceRange(DS.getExplicitSpecLoc());
8472 }
8473 
8474 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8475 /// the declaration of the given C++ conversion function. This routine
8476 /// is responsible for recording the conversion function in the C++
8477 /// class, if possible.
8478 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8479   assert(Conversion && "Expected to receive a conversion function declaration");
8480 
8481   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8482 
8483   // Make sure we aren't redeclaring the conversion function.
8484   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8485 
8486   // C++ [class.conv.fct]p1:
8487   //   [...] A conversion function is never used to convert a
8488   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8489   //   same object type (or a reference to it), to a (possibly
8490   //   cv-qualified) base class of that type (or a reference to it),
8491   //   or to (possibly cv-qualified) void.
8492   // FIXME: Suppress this warning if the conversion function ends up being a
8493   // virtual function that overrides a virtual function in a base class.
8494   QualType ClassType
8495     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8496   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8497     ConvType = ConvTypeRef->getPointeeType();
8498   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8499       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8500     /* Suppress diagnostics for instantiations. */;
8501   else if (ConvType->isRecordType()) {
8502     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8503     if (ConvType == ClassType)
8504       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8505         << ClassType;
8506     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8507       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8508         <<  ClassType << ConvType;
8509   } else if (ConvType->isVoidType()) {
8510     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8511       << ClassType << ConvType;
8512   }
8513 
8514   if (FunctionTemplateDecl *ConversionTemplate
8515                                 = Conversion->getDescribedFunctionTemplate())
8516     return ConversionTemplate;
8517 
8518   return Conversion;
8519 }
8520 
8521 namespace {
8522 /// Utility class to accumulate and print a diagnostic listing the invalid
8523 /// specifier(s) on a declaration.
8524 struct BadSpecifierDiagnoser {
8525   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8526       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8527   ~BadSpecifierDiagnoser() {
8528     Diagnostic << Specifiers;
8529   }
8530 
8531   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8532     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8533   }
8534   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8535     return check(SpecLoc,
8536                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8537   }
8538   void check(SourceLocation SpecLoc, const char *Spec) {
8539     if (SpecLoc.isInvalid()) return;
8540     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8541     if (!Specifiers.empty()) Specifiers += " ";
8542     Specifiers += Spec;
8543   }
8544 
8545   Sema &S;
8546   Sema::SemaDiagnosticBuilder Diagnostic;
8547   std::string Specifiers;
8548 };
8549 }
8550 
8551 /// Check the validity of a declarator that we parsed for a deduction-guide.
8552 /// These aren't actually declarators in the grammar, so we need to check that
8553 /// the user didn't specify any pieces that are not part of the deduction-guide
8554 /// grammar.
8555 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8556                                          StorageClass &SC) {
8557   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8558   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8559   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8560 
8561   // C++ [temp.deduct.guide]p3:
8562   //   A deduction-gide shall be declared in the same scope as the
8563   //   corresponding class template.
8564   if (!CurContext->getRedeclContext()->Equals(
8565           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8566     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8567       << GuidedTemplateDecl;
8568     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8569   }
8570 
8571   auto &DS = D.getMutableDeclSpec();
8572   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8573   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8574       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8575       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8576     BadSpecifierDiagnoser Diagnoser(
8577         *this, D.getIdentifierLoc(),
8578         diag::err_deduction_guide_invalid_specifier);
8579 
8580     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8581     DS.ClearStorageClassSpecs();
8582     SC = SC_None;
8583 
8584     // 'explicit' is permitted.
8585     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8586     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8587     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8588     DS.ClearConstexprSpec();
8589 
8590     Diagnoser.check(DS.getConstSpecLoc(), "const");
8591     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8592     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8593     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8594     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8595     DS.ClearTypeQualifiers();
8596 
8597     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8598     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8599     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8600     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8601     DS.ClearTypeSpecType();
8602   }
8603 
8604   if (D.isInvalidType())
8605     return;
8606 
8607   // Check the declarator is simple enough.
8608   bool FoundFunction = false;
8609   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8610     if (Chunk.Kind == DeclaratorChunk::Paren)
8611       continue;
8612     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8613       Diag(D.getDeclSpec().getLocStart(),
8614           diag::err_deduction_guide_with_complex_decl)
8615         << D.getSourceRange();
8616       break;
8617     }
8618     if (!Chunk.Fun.hasTrailingReturnType()) {
8619       Diag(D.getName().getLocStart(),
8620            diag::err_deduction_guide_no_trailing_return_type);
8621       break;
8622     }
8623 
8624     // Check that the return type is written as a specialization of
8625     // the template specified as the deduction-guide's name.
8626     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8627     TypeSourceInfo *TSI = nullptr;
8628     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8629     assert(TSI && "deduction guide has valid type but invalid return type?");
8630     bool AcceptableReturnType = false;
8631     bool MightInstantiateToSpecialization = false;
8632     if (auto RetTST =
8633             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8634       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8635       bool TemplateMatches =
8636           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8637       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8638         AcceptableReturnType = true;
8639       else {
8640         // This could still instantiate to the right type, unless we know it
8641         // names the wrong class template.
8642         auto *TD = SpecifiedName.getAsTemplateDecl();
8643         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8644                                              !TemplateMatches);
8645       }
8646     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8647       MightInstantiateToSpecialization = true;
8648     }
8649 
8650     if (!AcceptableReturnType) {
8651       Diag(TSI->getTypeLoc().getLocStart(),
8652            diag::err_deduction_guide_bad_trailing_return_type)
8653         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8654         << TSI->getTypeLoc().getSourceRange();
8655     }
8656 
8657     // Keep going to check that we don't have any inner declarator pieces (we
8658     // could still have a function returning a pointer to a function).
8659     FoundFunction = true;
8660   }
8661 
8662   if (D.isFunctionDefinition())
8663     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8664 }
8665 
8666 //===----------------------------------------------------------------------===//
8667 // Namespace Handling
8668 //===----------------------------------------------------------------------===//
8669 
8670 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8671 /// reopened.
8672 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8673                                             SourceLocation Loc,
8674                                             IdentifierInfo *II, bool *IsInline,
8675                                             NamespaceDecl *PrevNS) {
8676   assert(*IsInline != PrevNS->isInline());
8677 
8678   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8679   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8680   // inline namespaces, with the intention of bringing names into namespace std.
8681   //
8682   // We support this just well enough to get that case working; this is not
8683   // sufficient to support reopening namespaces as inline in general.
8684   if (*IsInline && II && II->getName().startswith("__atomic") &&
8685       S.getSourceManager().isInSystemHeader(Loc)) {
8686     // Mark all prior declarations of the namespace as inline.
8687     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8688          NS = NS->getPreviousDecl())
8689       NS->setInline(*IsInline);
8690     // Patch up the lookup table for the containing namespace. This isn't really
8691     // correct, but it's good enough for this particular case.
8692     for (auto *I : PrevNS->decls())
8693       if (auto *ND = dyn_cast<NamedDecl>(I))
8694         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8695     return;
8696   }
8697 
8698   if (PrevNS->isInline())
8699     // The user probably just forgot the 'inline', so suggest that it
8700     // be added back.
8701     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8702       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8703   else
8704     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8705 
8706   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8707   *IsInline = PrevNS->isInline();
8708 }
8709 
8710 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8711 /// definition.
8712 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8713                                    SourceLocation InlineLoc,
8714                                    SourceLocation NamespaceLoc,
8715                                    SourceLocation IdentLoc,
8716                                    IdentifierInfo *II,
8717                                    SourceLocation LBrace,
8718                                    AttributeList *AttrList,
8719                                    UsingDirectiveDecl *&UD) {
8720   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8721   // For anonymous namespace, take the location of the left brace.
8722   SourceLocation Loc = II ? IdentLoc : LBrace;
8723   bool IsInline = InlineLoc.isValid();
8724   bool IsInvalid = false;
8725   bool IsStd = false;
8726   bool AddToKnown = false;
8727   Scope *DeclRegionScope = NamespcScope->getParent();
8728 
8729   NamespaceDecl *PrevNS = nullptr;
8730   if (II) {
8731     // C++ [namespace.def]p2:
8732     //   The identifier in an original-namespace-definition shall not
8733     //   have been previously defined in the declarative region in
8734     //   which the original-namespace-definition appears. The
8735     //   identifier in an original-namespace-definition is the name of
8736     //   the namespace. Subsequently in that declarative region, it is
8737     //   treated as an original-namespace-name.
8738     //
8739     // Since namespace names are unique in their scope, and we don't
8740     // look through using directives, just look for any ordinary names
8741     // as if by qualified name lookup.
8742     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8743                    ForExternalRedeclaration);
8744     LookupQualifiedName(R, CurContext->getRedeclContext());
8745     NamedDecl *PrevDecl =
8746         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8747     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8748 
8749     if (PrevNS) {
8750       // This is an extended namespace definition.
8751       if (IsInline != PrevNS->isInline())
8752         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8753                                         &IsInline, PrevNS);
8754     } else if (PrevDecl) {
8755       // This is an invalid name redefinition.
8756       Diag(Loc, diag::err_redefinition_different_kind)
8757         << II;
8758       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8759       IsInvalid = true;
8760       // Continue on to push Namespc as current DeclContext and return it.
8761     } else if (II->isStr("std") &&
8762                CurContext->getRedeclContext()->isTranslationUnit()) {
8763       // This is the first "real" definition of the namespace "std", so update
8764       // our cache of the "std" namespace to point at this definition.
8765       PrevNS = getStdNamespace();
8766       IsStd = true;
8767       AddToKnown = !IsInline;
8768     } else {
8769       // We've seen this namespace for the first time.
8770       AddToKnown = !IsInline;
8771     }
8772   } else {
8773     // Anonymous namespaces.
8774 
8775     // Determine whether the parent already has an anonymous namespace.
8776     DeclContext *Parent = CurContext->getRedeclContext();
8777     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8778       PrevNS = TU->getAnonymousNamespace();
8779     } else {
8780       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8781       PrevNS = ND->getAnonymousNamespace();
8782     }
8783 
8784     if (PrevNS && IsInline != PrevNS->isInline())
8785       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8786                                       &IsInline, PrevNS);
8787   }
8788 
8789   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8790                                                  StartLoc, Loc, II, PrevNS);
8791   if (IsInvalid)
8792     Namespc->setInvalidDecl();
8793 
8794   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8795   AddPragmaAttributes(DeclRegionScope, Namespc);
8796 
8797   // FIXME: Should we be merging attributes?
8798   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8799     PushNamespaceVisibilityAttr(Attr, Loc);
8800 
8801   if (IsStd)
8802     StdNamespace = Namespc;
8803   if (AddToKnown)
8804     KnownNamespaces[Namespc] = false;
8805 
8806   if (II) {
8807     PushOnScopeChains(Namespc, DeclRegionScope);
8808   } else {
8809     // Link the anonymous namespace into its parent.
8810     DeclContext *Parent = CurContext->getRedeclContext();
8811     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8812       TU->setAnonymousNamespace(Namespc);
8813     } else {
8814       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8815     }
8816 
8817     CurContext->addDecl(Namespc);
8818 
8819     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8820     //   behaves as if it were replaced by
8821     //     namespace unique { /* empty body */ }
8822     //     using namespace unique;
8823     //     namespace unique { namespace-body }
8824     //   where all occurrences of 'unique' in a translation unit are
8825     //   replaced by the same identifier and this identifier differs
8826     //   from all other identifiers in the entire program.
8827 
8828     // We just create the namespace with an empty name and then add an
8829     // implicit using declaration, just like the standard suggests.
8830     //
8831     // CodeGen enforces the "universally unique" aspect by giving all
8832     // declarations semantically contained within an anonymous
8833     // namespace internal linkage.
8834 
8835     if (!PrevNS) {
8836       UD = UsingDirectiveDecl::Create(Context, Parent,
8837                                       /* 'using' */ LBrace,
8838                                       /* 'namespace' */ SourceLocation(),
8839                                       /* qualifier */ NestedNameSpecifierLoc(),
8840                                       /* identifier */ SourceLocation(),
8841                                       Namespc,
8842                                       /* Ancestor */ Parent);
8843       UD->setImplicit();
8844       Parent->addDecl(UD);
8845     }
8846   }
8847 
8848   ActOnDocumentableDecl(Namespc);
8849 
8850   // Although we could have an invalid decl (i.e. the namespace name is a
8851   // redefinition), push it as current DeclContext and try to continue parsing.
8852   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8853   // for the namespace has the declarations that showed up in that particular
8854   // namespace definition.
8855   PushDeclContext(NamespcScope, Namespc);
8856   return Namespc;
8857 }
8858 
8859 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8860 /// is a namespace alias, returns the namespace it points to.
8861 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8862   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8863     return AD->getNamespace();
8864   return dyn_cast_or_null<NamespaceDecl>(D);
8865 }
8866 
8867 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8868 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8869 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8870   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8871   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8872   Namespc->setRBraceLoc(RBrace);
8873   PopDeclContext();
8874   if (Namespc->hasAttr<VisibilityAttr>())
8875     PopPragmaVisibility(true, RBrace);
8876 }
8877 
8878 CXXRecordDecl *Sema::getStdBadAlloc() const {
8879   return cast_or_null<CXXRecordDecl>(
8880                                   StdBadAlloc.get(Context.getExternalSource()));
8881 }
8882 
8883 EnumDecl *Sema::getStdAlignValT() const {
8884   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8885 }
8886 
8887 NamespaceDecl *Sema::getStdNamespace() const {
8888   return cast_or_null<NamespaceDecl>(
8889                                  StdNamespace.get(Context.getExternalSource()));
8890 }
8891 
8892 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8893   if (!StdExperimentalNamespaceCache) {
8894     if (auto Std = getStdNamespace()) {
8895       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8896                           SourceLocation(), LookupNamespaceName);
8897       if (!LookupQualifiedName(Result, Std) ||
8898           !(StdExperimentalNamespaceCache =
8899                 Result.getAsSingle<NamespaceDecl>()))
8900         Result.suppressDiagnostics();
8901     }
8902   }
8903   return StdExperimentalNamespaceCache;
8904 }
8905 
8906 namespace {
8907 
8908 enum UnsupportedSTLSelect {
8909   USS_InvalidMember,
8910   USS_MissingMember,
8911   USS_NonTrivial,
8912   USS_Other
8913 };
8914 
8915 struct InvalidSTLDiagnoser {
8916   Sema &S;
8917   SourceLocation Loc;
8918   QualType TyForDiags;
8919 
8920   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8921                       const VarDecl *VD = nullptr) {
8922     {
8923       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8924                << TyForDiags << ((int)Sel);
8925       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8926         assert(!Name.empty());
8927         D << Name;
8928       }
8929     }
8930     if (Sel == USS_InvalidMember) {
8931       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8932           << VD << VD->getSourceRange();
8933     }
8934     return QualType();
8935   }
8936 };
8937 } // namespace
8938 
8939 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
8940                                            SourceLocation Loc) {
8941   assert(getLangOpts().CPlusPlus &&
8942          "Looking for comparison category type outside of C++.");
8943 
8944   // Check if we've already successfully checked the comparison category type
8945   // before. If so, skip checking it again.
8946   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
8947   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
8948     return Info->getType();
8949 
8950   // If lookup failed
8951   if (!Info) {
8952     std::string NameForDiags = "std::";
8953     NameForDiags += ComparisonCategories::getCategoryString(Kind);
8954     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
8955         << NameForDiags;
8956     return QualType();
8957   }
8958 
8959   assert(Info->Kind == Kind);
8960   assert(Info->Record);
8961 
8962   // Update the Record decl in case we encountered a forward declaration on our
8963   // first pass. FIXME: This is a bit of a hack.
8964   if (Info->Record->hasDefinition())
8965     Info->Record = Info->Record->getDefinition();
8966 
8967   // Use an elaborated type for diagnostics which has a name containing the
8968   // prepended 'std' namespace but not any inline namespace names.
8969   QualType TyForDiags = [&]() {
8970     auto *NNS =
8971         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
8972     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
8973   }();
8974 
8975   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
8976     return QualType();
8977 
8978   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
8979 
8980   if (!Info->Record->isTriviallyCopyable())
8981     return UnsupportedSTLError(USS_NonTrivial);
8982 
8983   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
8984     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
8985     // Tolerate empty base classes.
8986     if (Base->isEmpty())
8987       continue;
8988     // Reject STL implementations which have at least one non-empty base.
8989     return UnsupportedSTLError();
8990   }
8991 
8992   // Check that the STL has implemented the types using a single integer field.
8993   // This expectation allows better codegen for builtin operators. We require:
8994   //   (1) The class has exactly one field.
8995   //   (2) The field is an integral or enumeration type.
8996   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
8997   if (std::distance(FIt, FEnd) != 1 ||
8998       !FIt->getType()->isIntegralOrEnumerationType()) {
8999     return UnsupportedSTLError();
9000   }
9001 
9002   // Build each of the require values and store them in Info.
9003   for (ComparisonCategoryResult CCR :
9004        ComparisonCategories::getPossibleResultsForType(Kind)) {
9005     StringRef MemName = ComparisonCategories::getResultString(CCR);
9006     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9007 
9008     if (!ValInfo)
9009       return UnsupportedSTLError(USS_MissingMember, MemName);
9010 
9011     VarDecl *VD = ValInfo->VD;
9012     assert(VD && "should not be null!");
9013 
9014     // Attempt to diagnose reasons why the STL definition of this type
9015     // might be foobar, including it failing to be a constant expression.
9016     // TODO Handle more ways the lookup or result can be invalid.
9017     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9018         !VD->checkInitIsICE())
9019       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9020 
9021     // Attempt to evaluate the var decl as a constant expression and extract
9022     // the value of its first field as a ICE. If this fails, the STL
9023     // implementation is not supported.
9024     if (!ValInfo->hasValidIntValue())
9025       return UnsupportedSTLError();
9026 
9027     MarkVariableReferenced(Loc, VD);
9028   }
9029 
9030   // We've successfully built the required types and expressions. Update
9031   // the cache and return the newly cached value.
9032   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9033   return Info->getType();
9034 }
9035 
9036 /// Retrieve the special "std" namespace, which may require us to
9037 /// implicitly define the namespace.
9038 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9039   if (!StdNamespace) {
9040     // The "std" namespace has not yet been defined, so build one implicitly.
9041     StdNamespace = NamespaceDecl::Create(Context,
9042                                          Context.getTranslationUnitDecl(),
9043                                          /*Inline=*/false,
9044                                          SourceLocation(), SourceLocation(),
9045                                          &PP.getIdentifierTable().get("std"),
9046                                          /*PrevDecl=*/nullptr);
9047     getStdNamespace()->setImplicit(true);
9048   }
9049 
9050   return getStdNamespace();
9051 }
9052 
9053 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9054   assert(getLangOpts().CPlusPlus &&
9055          "Looking for std::initializer_list outside of C++.");
9056 
9057   // We're looking for implicit instantiations of
9058   // template <typename E> class std::initializer_list.
9059 
9060   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9061     return false;
9062 
9063   ClassTemplateDecl *Template = nullptr;
9064   const TemplateArgument *Arguments = nullptr;
9065 
9066   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9067 
9068     ClassTemplateSpecializationDecl *Specialization =
9069         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9070     if (!Specialization)
9071       return false;
9072 
9073     Template = Specialization->getSpecializedTemplate();
9074     Arguments = Specialization->getTemplateArgs().data();
9075   } else if (const TemplateSpecializationType *TST =
9076                  Ty->getAs<TemplateSpecializationType>()) {
9077     Template = dyn_cast_or_null<ClassTemplateDecl>(
9078         TST->getTemplateName().getAsTemplateDecl());
9079     Arguments = TST->getArgs();
9080   }
9081   if (!Template)
9082     return false;
9083 
9084   if (!StdInitializerList) {
9085     // Haven't recognized std::initializer_list yet, maybe this is it.
9086     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9087     if (TemplateClass->getIdentifier() !=
9088             &PP.getIdentifierTable().get("initializer_list") ||
9089         !getStdNamespace()->InEnclosingNamespaceSetOf(
9090             TemplateClass->getDeclContext()))
9091       return false;
9092     // This is a template called std::initializer_list, but is it the right
9093     // template?
9094     TemplateParameterList *Params = Template->getTemplateParameters();
9095     if (Params->getMinRequiredArguments() != 1)
9096       return false;
9097     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9098       return false;
9099 
9100     // It's the right template.
9101     StdInitializerList = Template;
9102   }
9103 
9104   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9105     return false;
9106 
9107   // This is an instance of std::initializer_list. Find the argument type.
9108   if (Element)
9109     *Element = Arguments[0].getAsType();
9110   return true;
9111 }
9112 
9113 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9114   NamespaceDecl *Std = S.getStdNamespace();
9115   if (!Std) {
9116     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9117     return nullptr;
9118   }
9119 
9120   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9121                       Loc, Sema::LookupOrdinaryName);
9122   if (!S.LookupQualifiedName(Result, Std)) {
9123     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9124     return nullptr;
9125   }
9126   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9127   if (!Template) {
9128     Result.suppressDiagnostics();
9129     // We found something weird. Complain about the first thing we found.
9130     NamedDecl *Found = *Result.begin();
9131     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9132     return nullptr;
9133   }
9134 
9135   // We found some template called std::initializer_list. Now verify that it's
9136   // correct.
9137   TemplateParameterList *Params = Template->getTemplateParameters();
9138   if (Params->getMinRequiredArguments() != 1 ||
9139       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9140     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9141     return nullptr;
9142   }
9143 
9144   return Template;
9145 }
9146 
9147 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9148   if (!StdInitializerList) {
9149     StdInitializerList = LookupStdInitializerList(*this, Loc);
9150     if (!StdInitializerList)
9151       return QualType();
9152   }
9153 
9154   TemplateArgumentListInfo Args(Loc, Loc);
9155   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9156                                        Context.getTrivialTypeSourceInfo(Element,
9157                                                                         Loc)));
9158   return Context.getCanonicalType(
9159       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9160 }
9161 
9162 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9163   // C++ [dcl.init.list]p2:
9164   //   A constructor is an initializer-list constructor if its first parameter
9165   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9166   //   std::initializer_list<E> for some type E, and either there are no other
9167   //   parameters or else all other parameters have default arguments.
9168   if (Ctor->getNumParams() < 1 ||
9169       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9170     return false;
9171 
9172   QualType ArgType = Ctor->getParamDecl(0)->getType();
9173   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9174     ArgType = RT->getPointeeType().getUnqualifiedType();
9175 
9176   return isStdInitializerList(ArgType, nullptr);
9177 }
9178 
9179 /// Determine whether a using statement is in a context where it will be
9180 /// apply in all contexts.
9181 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9182   switch (CurContext->getDeclKind()) {
9183     case Decl::TranslationUnit:
9184       return true;
9185     case Decl::LinkageSpec:
9186       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9187     default:
9188       return false;
9189   }
9190 }
9191 
9192 namespace {
9193 
9194 // Callback to only accept typo corrections that are namespaces.
9195 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9196 public:
9197   bool ValidateCandidate(const TypoCorrection &candidate) override {
9198     if (NamedDecl *ND = candidate.getCorrectionDecl())
9199       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9200     return false;
9201   }
9202 };
9203 
9204 }
9205 
9206 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9207                                        CXXScopeSpec &SS,
9208                                        SourceLocation IdentLoc,
9209                                        IdentifierInfo *Ident) {
9210   R.clear();
9211   if (TypoCorrection Corrected =
9212           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9213                         llvm::make_unique<NamespaceValidatorCCC>(),
9214                         Sema::CTK_ErrorRecovery)) {
9215     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9216       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9217       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9218                               Ident->getName().equals(CorrectedStr);
9219       S.diagnoseTypo(Corrected,
9220                      S.PDiag(diag::err_using_directive_member_suggest)
9221                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9222                      S.PDiag(diag::note_namespace_defined_here));
9223     } else {
9224       S.diagnoseTypo(Corrected,
9225                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9226                      S.PDiag(diag::note_namespace_defined_here));
9227     }
9228     R.addDecl(Corrected.getFoundDecl());
9229     return true;
9230   }
9231   return false;
9232 }
9233 
9234 Decl *Sema::ActOnUsingDirective(Scope *S,
9235                                           SourceLocation UsingLoc,
9236                                           SourceLocation NamespcLoc,
9237                                           CXXScopeSpec &SS,
9238                                           SourceLocation IdentLoc,
9239                                           IdentifierInfo *NamespcName,
9240                                           AttributeList *AttrList) {
9241   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9242   assert(NamespcName && "Invalid NamespcName.");
9243   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9244 
9245   // This can only happen along a recovery path.
9246   while (S->isTemplateParamScope())
9247     S = S->getParent();
9248   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9249 
9250   UsingDirectiveDecl *UDir = nullptr;
9251   NestedNameSpecifier *Qualifier = nullptr;
9252   if (SS.isSet())
9253     Qualifier = SS.getScopeRep();
9254 
9255   // Lookup namespace name.
9256   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9257   LookupParsedName(R, S, &SS);
9258   if (R.isAmbiguous())
9259     return nullptr;
9260 
9261   if (R.empty()) {
9262     R.clear();
9263     // Allow "using namespace std;" or "using namespace ::std;" even if
9264     // "std" hasn't been defined yet, for GCC compatibility.
9265     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9266         NamespcName->isStr("std")) {
9267       Diag(IdentLoc, diag::ext_using_undefined_std);
9268       R.addDecl(getOrCreateStdNamespace());
9269       R.resolveKind();
9270     }
9271     // Otherwise, attempt typo correction.
9272     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9273   }
9274 
9275   if (!R.empty()) {
9276     NamedDecl *Named = R.getRepresentativeDecl();
9277     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9278     assert(NS && "expected namespace decl");
9279 
9280     // The use of a nested name specifier may trigger deprecation warnings.
9281     DiagnoseUseOfDecl(Named, IdentLoc);
9282 
9283     // C++ [namespace.udir]p1:
9284     //   A using-directive specifies that the names in the nominated
9285     //   namespace can be used in the scope in which the
9286     //   using-directive appears after the using-directive. During
9287     //   unqualified name lookup (3.4.1), the names appear as if they
9288     //   were declared in the nearest enclosing namespace which
9289     //   contains both the using-directive and the nominated
9290     //   namespace. [Note: in this context, "contains" means "contains
9291     //   directly or indirectly". ]
9292 
9293     // Find enclosing context containing both using-directive and
9294     // nominated namespace.
9295     DeclContext *CommonAncestor = NS;
9296     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9297       CommonAncestor = CommonAncestor->getParent();
9298 
9299     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9300                                       SS.getWithLocInContext(Context),
9301                                       IdentLoc, Named, CommonAncestor);
9302 
9303     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9304         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9305       Diag(IdentLoc, diag::warn_using_directive_in_header);
9306     }
9307 
9308     PushUsingDirective(S, UDir);
9309   } else {
9310     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9311   }
9312 
9313   if (UDir)
9314     ProcessDeclAttributeList(S, UDir, AttrList);
9315 
9316   return UDir;
9317 }
9318 
9319 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9320   // If the scope has an associated entity and the using directive is at
9321   // namespace or translation unit scope, add the UsingDirectiveDecl into
9322   // its lookup structure so qualified name lookup can find it.
9323   DeclContext *Ctx = S->getEntity();
9324   if (Ctx && !Ctx->isFunctionOrMethod())
9325     Ctx->addDecl(UDir);
9326   else
9327     // Otherwise, it is at block scope. The using-directives will affect lookup
9328     // only to the end of the scope.
9329     S->PushUsingDirective(UDir);
9330 }
9331 
9332 
9333 Decl *Sema::ActOnUsingDeclaration(Scope *S,
9334                                   AccessSpecifier AS,
9335                                   SourceLocation UsingLoc,
9336                                   SourceLocation TypenameLoc,
9337                                   CXXScopeSpec &SS,
9338                                   UnqualifiedId &Name,
9339                                   SourceLocation EllipsisLoc,
9340                                   AttributeList *AttrList) {
9341   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9342 
9343   if (SS.isEmpty()) {
9344     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9345     return nullptr;
9346   }
9347 
9348   switch (Name.getKind()) {
9349   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9350   case UnqualifiedIdKind::IK_Identifier:
9351   case UnqualifiedIdKind::IK_OperatorFunctionId:
9352   case UnqualifiedIdKind::IK_LiteralOperatorId:
9353   case UnqualifiedIdKind::IK_ConversionFunctionId:
9354     break;
9355 
9356   case UnqualifiedIdKind::IK_ConstructorName:
9357   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9358     // C++11 inheriting constructors.
9359     Diag(Name.getLocStart(),
9360          getLangOpts().CPlusPlus11 ?
9361            diag::warn_cxx98_compat_using_decl_constructor :
9362            diag::err_using_decl_constructor)
9363       << SS.getRange();
9364 
9365     if (getLangOpts().CPlusPlus11) break;
9366 
9367     return nullptr;
9368 
9369   case UnqualifiedIdKind::IK_DestructorName:
9370     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9371       << SS.getRange();
9372     return nullptr;
9373 
9374   case UnqualifiedIdKind::IK_TemplateId:
9375     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9376       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9377     return nullptr;
9378 
9379   case UnqualifiedIdKind::IK_DeductionGuideName:
9380     llvm_unreachable("cannot parse qualified deduction guide name");
9381   }
9382 
9383   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9384   DeclarationName TargetName = TargetNameInfo.getName();
9385   if (!TargetName)
9386     return nullptr;
9387 
9388   // Warn about access declarations.
9389   if (UsingLoc.isInvalid()) {
9390     Diag(Name.getLocStart(),
9391          getLangOpts().CPlusPlus11 ? diag::err_access_decl
9392                                    : diag::warn_access_decl_deprecated)
9393       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9394   }
9395 
9396   if (EllipsisLoc.isInvalid()) {
9397     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9398         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9399       return nullptr;
9400   } else {
9401     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9402         !TargetNameInfo.containsUnexpandedParameterPack()) {
9403       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9404         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9405       EllipsisLoc = SourceLocation();
9406     }
9407   }
9408 
9409   NamedDecl *UD =
9410       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9411                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9412                             /*IsInstantiation*/false);
9413   if (UD)
9414     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9415 
9416   return UD;
9417 }
9418 
9419 /// Determine whether a using declaration considers the given
9420 /// declarations as "equivalent", e.g., if they are redeclarations of
9421 /// the same entity or are both typedefs of the same type.
9422 static bool
9423 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9424   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9425     return true;
9426 
9427   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9428     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9429       return Context.hasSameType(TD1->getUnderlyingType(),
9430                                  TD2->getUnderlyingType());
9431 
9432   return false;
9433 }
9434 
9435 
9436 /// Determines whether to create a using shadow decl for a particular
9437 /// decl, given the set of decls existing prior to this using lookup.
9438 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9439                                 const LookupResult &Previous,
9440                                 UsingShadowDecl *&PrevShadow) {
9441   // Diagnose finding a decl which is not from a base class of the
9442   // current class.  We do this now because there are cases where this
9443   // function will silently decide not to build a shadow decl, which
9444   // will pre-empt further diagnostics.
9445   //
9446   // We don't need to do this in C++11 because we do the check once on
9447   // the qualifier.
9448   //
9449   // FIXME: diagnose the following if we care enough:
9450   //   struct A { int foo; };
9451   //   struct B : A { using A::foo; };
9452   //   template <class T> struct C : A {};
9453   //   template <class T> struct D : C<T> { using B::foo; } // <---
9454   // This is invalid (during instantiation) in C++03 because B::foo
9455   // resolves to the using decl in B, which is not a base class of D<T>.
9456   // We can't diagnose it immediately because C<T> is an unknown
9457   // specialization.  The UsingShadowDecl in D<T> then points directly
9458   // to A::foo, which will look well-formed when we instantiate.
9459   // The right solution is to not collapse the shadow-decl chain.
9460   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9461     DeclContext *OrigDC = Orig->getDeclContext();
9462 
9463     // Handle enums and anonymous structs.
9464     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9465     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9466     while (OrigRec->isAnonymousStructOrUnion())
9467       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9468 
9469     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9470       if (OrigDC == CurContext) {
9471         Diag(Using->getLocation(),
9472              diag::err_using_decl_nested_name_specifier_is_current_class)
9473           << Using->getQualifierLoc().getSourceRange();
9474         Diag(Orig->getLocation(), diag::note_using_decl_target);
9475         Using->setInvalidDecl();
9476         return true;
9477       }
9478 
9479       Diag(Using->getQualifierLoc().getBeginLoc(),
9480            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9481         << Using->getQualifier()
9482         << cast<CXXRecordDecl>(CurContext)
9483         << Using->getQualifierLoc().getSourceRange();
9484       Diag(Orig->getLocation(), diag::note_using_decl_target);
9485       Using->setInvalidDecl();
9486       return true;
9487     }
9488   }
9489 
9490   if (Previous.empty()) return false;
9491 
9492   NamedDecl *Target = Orig;
9493   if (isa<UsingShadowDecl>(Target))
9494     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9495 
9496   // If the target happens to be one of the previous declarations, we
9497   // don't have a conflict.
9498   //
9499   // FIXME: but we might be increasing its access, in which case we
9500   // should redeclare it.
9501   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9502   bool FoundEquivalentDecl = false;
9503   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9504          I != E; ++I) {
9505     NamedDecl *D = (*I)->getUnderlyingDecl();
9506     // We can have UsingDecls in our Previous results because we use the same
9507     // LookupResult for checking whether the UsingDecl itself is a valid
9508     // redeclaration.
9509     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9510       continue;
9511 
9512     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9513       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9514         PrevShadow = Shadow;
9515       FoundEquivalentDecl = true;
9516     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9517       // We don't conflict with an existing using shadow decl of an equivalent
9518       // declaration, but we're not a redeclaration of it.
9519       FoundEquivalentDecl = true;
9520     }
9521 
9522     if (isVisible(D))
9523       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9524   }
9525 
9526   if (FoundEquivalentDecl)
9527     return false;
9528 
9529   if (FunctionDecl *FD = Target->getAsFunction()) {
9530     NamedDecl *OldDecl = nullptr;
9531     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9532                           /*IsForUsingDecl*/ true)) {
9533     case Ovl_Overload:
9534       return false;
9535 
9536     case Ovl_NonFunction:
9537       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9538       break;
9539 
9540     // We found a decl with the exact signature.
9541     case Ovl_Match:
9542       // If we're in a record, we want to hide the target, so we
9543       // return true (without a diagnostic) to tell the caller not to
9544       // build a shadow decl.
9545       if (CurContext->isRecord())
9546         return true;
9547 
9548       // If we're not in a record, this is an error.
9549       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9550       break;
9551     }
9552 
9553     Diag(Target->getLocation(), diag::note_using_decl_target);
9554     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9555     Using->setInvalidDecl();
9556     return true;
9557   }
9558 
9559   // Target is not a function.
9560 
9561   if (isa<TagDecl>(Target)) {
9562     // No conflict between a tag and a non-tag.
9563     if (!Tag) return false;
9564 
9565     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9566     Diag(Target->getLocation(), diag::note_using_decl_target);
9567     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9568     Using->setInvalidDecl();
9569     return true;
9570   }
9571 
9572   // No conflict between a tag and a non-tag.
9573   if (!NonTag) return false;
9574 
9575   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9576   Diag(Target->getLocation(), diag::note_using_decl_target);
9577   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9578   Using->setInvalidDecl();
9579   return true;
9580 }
9581 
9582 /// Determine whether a direct base class is a virtual base class.
9583 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9584   if (!Derived->getNumVBases())
9585     return false;
9586   for (auto &B : Derived->bases())
9587     if (B.getType()->getAsCXXRecordDecl() == Base)
9588       return B.isVirtual();
9589   llvm_unreachable("not a direct base class");
9590 }
9591 
9592 /// Builds a shadow declaration corresponding to a 'using' declaration.
9593 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9594                                             UsingDecl *UD,
9595                                             NamedDecl *Orig,
9596                                             UsingShadowDecl *PrevDecl) {
9597   // If we resolved to another shadow declaration, just coalesce them.
9598   NamedDecl *Target = Orig;
9599   if (isa<UsingShadowDecl>(Target)) {
9600     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9601     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9602   }
9603 
9604   NamedDecl *NonTemplateTarget = Target;
9605   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9606     NonTemplateTarget = TargetTD->getTemplatedDecl();
9607 
9608   UsingShadowDecl *Shadow;
9609   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9610     bool IsVirtualBase =
9611         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9612                             UD->getQualifier()->getAsRecordDecl());
9613     Shadow = ConstructorUsingShadowDecl::Create(
9614         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9615   } else {
9616     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9617                                      Target);
9618   }
9619   UD->addShadowDecl(Shadow);
9620 
9621   Shadow->setAccess(UD->getAccess());
9622   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9623     Shadow->setInvalidDecl();
9624 
9625   Shadow->setPreviousDecl(PrevDecl);
9626 
9627   if (S)
9628     PushOnScopeChains(Shadow, S);
9629   else
9630     CurContext->addDecl(Shadow);
9631 
9632 
9633   return Shadow;
9634 }
9635 
9636 /// Hides a using shadow declaration.  This is required by the current
9637 /// using-decl implementation when a resolvable using declaration in a
9638 /// class is followed by a declaration which would hide or override
9639 /// one or more of the using decl's targets; for example:
9640 ///
9641 ///   struct Base { void foo(int); };
9642 ///   struct Derived : Base {
9643 ///     using Base::foo;
9644 ///     void foo(int);
9645 ///   };
9646 ///
9647 /// The governing language is C++03 [namespace.udecl]p12:
9648 ///
9649 ///   When a using-declaration brings names from a base class into a
9650 ///   derived class scope, member functions in the derived class
9651 ///   override and/or hide member functions with the same name and
9652 ///   parameter types in a base class (rather than conflicting).
9653 ///
9654 /// There are two ways to implement this:
9655 ///   (1) optimistically create shadow decls when they're not hidden
9656 ///       by existing declarations, or
9657 ///   (2) don't create any shadow decls (or at least don't make them
9658 ///       visible) until we've fully parsed/instantiated the class.
9659 /// The problem with (1) is that we might have to retroactively remove
9660 /// a shadow decl, which requires several O(n) operations because the
9661 /// decl structures are (very reasonably) not designed for removal.
9662 /// (2) avoids this but is very fiddly and phase-dependent.
9663 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9664   if (Shadow->getDeclName().getNameKind() ==
9665         DeclarationName::CXXConversionFunctionName)
9666     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9667 
9668   // Remove it from the DeclContext...
9669   Shadow->getDeclContext()->removeDecl(Shadow);
9670 
9671   // ...and the scope, if applicable...
9672   if (S) {
9673     S->RemoveDecl(Shadow);
9674     IdResolver.RemoveDecl(Shadow);
9675   }
9676 
9677   // ...and the using decl.
9678   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9679 
9680   // TODO: complain somehow if Shadow was used.  It shouldn't
9681   // be possible for this to happen, because...?
9682 }
9683 
9684 /// Find the base specifier for a base class with the given type.
9685 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9686                                                 QualType DesiredBase,
9687                                                 bool &AnyDependentBases) {
9688   // Check whether the named type is a direct base class.
9689   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9690   for (auto &Base : Derived->bases()) {
9691     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9692     if (CanonicalDesiredBase == BaseType)
9693       return &Base;
9694     if (BaseType->isDependentType())
9695       AnyDependentBases = true;
9696   }
9697   return nullptr;
9698 }
9699 
9700 namespace {
9701 class UsingValidatorCCC : public CorrectionCandidateCallback {
9702 public:
9703   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9704                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9705       : HasTypenameKeyword(HasTypenameKeyword),
9706         IsInstantiation(IsInstantiation), OldNNS(NNS),
9707         RequireMemberOf(RequireMemberOf) {}
9708 
9709   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9710     NamedDecl *ND = Candidate.getCorrectionDecl();
9711 
9712     // Keywords are not valid here.
9713     if (!ND || isa<NamespaceDecl>(ND))
9714       return false;
9715 
9716     // Completely unqualified names are invalid for a 'using' declaration.
9717     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9718       return false;
9719 
9720     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9721     // reject.
9722 
9723     if (RequireMemberOf) {
9724       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9725       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9726         // No-one ever wants a using-declaration to name an injected-class-name
9727         // of a base class, unless they're declaring an inheriting constructor.
9728         ASTContext &Ctx = ND->getASTContext();
9729         if (!Ctx.getLangOpts().CPlusPlus11)
9730           return false;
9731         QualType FoundType = Ctx.getRecordType(FoundRecord);
9732 
9733         // Check that the injected-class-name is named as a member of its own
9734         // type; we don't want to suggest 'using Derived::Base;', since that
9735         // means something else.
9736         NestedNameSpecifier *Specifier =
9737             Candidate.WillReplaceSpecifier()
9738                 ? Candidate.getCorrectionSpecifier()
9739                 : OldNNS;
9740         if (!Specifier->getAsType() ||
9741             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9742           return false;
9743 
9744         // Check that this inheriting constructor declaration actually names a
9745         // direct base class of the current class.
9746         bool AnyDependentBases = false;
9747         if (!findDirectBaseWithType(RequireMemberOf,
9748                                     Ctx.getRecordType(FoundRecord),
9749                                     AnyDependentBases) &&
9750             !AnyDependentBases)
9751           return false;
9752       } else {
9753         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9754         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9755           return false;
9756 
9757         // FIXME: Check that the base class member is accessible?
9758       }
9759     } else {
9760       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9761       if (FoundRecord && FoundRecord->isInjectedClassName())
9762         return false;
9763     }
9764 
9765     if (isa<TypeDecl>(ND))
9766       return HasTypenameKeyword || !IsInstantiation;
9767 
9768     return !HasTypenameKeyword;
9769   }
9770 
9771 private:
9772   bool HasTypenameKeyword;
9773   bool IsInstantiation;
9774   NestedNameSpecifier *OldNNS;
9775   CXXRecordDecl *RequireMemberOf;
9776 };
9777 } // end anonymous namespace
9778 
9779 /// Builds a using declaration.
9780 ///
9781 /// \param IsInstantiation - Whether this call arises from an
9782 ///   instantiation of an unresolved using declaration.  We treat
9783 ///   the lookup differently for these declarations.
9784 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9785                                        SourceLocation UsingLoc,
9786                                        bool HasTypenameKeyword,
9787                                        SourceLocation TypenameLoc,
9788                                        CXXScopeSpec &SS,
9789                                        DeclarationNameInfo NameInfo,
9790                                        SourceLocation EllipsisLoc,
9791                                        AttributeList *AttrList,
9792                                        bool IsInstantiation) {
9793   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9794   SourceLocation IdentLoc = NameInfo.getLoc();
9795   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9796 
9797   // FIXME: We ignore attributes for now.
9798 
9799   // For an inheriting constructor declaration, the name of the using
9800   // declaration is the name of a constructor in this class, not in the
9801   // base class.
9802   DeclarationNameInfo UsingName = NameInfo;
9803   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9804     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9805       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9806           Context.getCanonicalType(Context.getRecordType(RD))));
9807 
9808   // Do the redeclaration lookup in the current scope.
9809   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9810                         ForVisibleRedeclaration);
9811   Previous.setHideTags(false);
9812   if (S) {
9813     LookupName(Previous, S);
9814 
9815     // It is really dumb that we have to do this.
9816     LookupResult::Filter F = Previous.makeFilter();
9817     while (F.hasNext()) {
9818       NamedDecl *D = F.next();
9819       if (!isDeclInScope(D, CurContext, S))
9820         F.erase();
9821       // If we found a local extern declaration that's not ordinarily visible,
9822       // and this declaration is being added to a non-block scope, ignore it.
9823       // We're only checking for scope conflicts here, not also for violations
9824       // of the linkage rules.
9825       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9826                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9827         F.erase();
9828     }
9829     F.done();
9830   } else {
9831     assert(IsInstantiation && "no scope in non-instantiation");
9832     if (CurContext->isRecord())
9833       LookupQualifiedName(Previous, CurContext);
9834     else {
9835       // No redeclaration check is needed here; in non-member contexts we
9836       // diagnosed all possible conflicts with other using-declarations when
9837       // building the template:
9838       //
9839       // For a dependent non-type using declaration, the only valid case is
9840       // if we instantiate to a single enumerator. We check for conflicts
9841       // between shadow declarations we introduce, and we check in the template
9842       // definition for conflicts between a non-type using declaration and any
9843       // other declaration, which together covers all cases.
9844       //
9845       // A dependent typename using declaration will never successfully
9846       // instantiate, since it will always name a class member, so we reject
9847       // that in the template definition.
9848     }
9849   }
9850 
9851   // Check for invalid redeclarations.
9852   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9853                                   SS, IdentLoc, Previous))
9854     return nullptr;
9855 
9856   // Check for bad qualifiers.
9857   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9858                               IdentLoc))
9859     return nullptr;
9860 
9861   DeclContext *LookupContext = computeDeclContext(SS);
9862   NamedDecl *D;
9863   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9864   if (!LookupContext || EllipsisLoc.isValid()) {
9865     if (HasTypenameKeyword) {
9866       // FIXME: not all declaration name kinds are legal here
9867       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9868                                               UsingLoc, TypenameLoc,
9869                                               QualifierLoc,
9870                                               IdentLoc, NameInfo.getName(),
9871                                               EllipsisLoc);
9872     } else {
9873       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9874                                            QualifierLoc, NameInfo, EllipsisLoc);
9875     }
9876     D->setAccess(AS);
9877     CurContext->addDecl(D);
9878     return D;
9879   }
9880 
9881   auto Build = [&](bool Invalid) {
9882     UsingDecl *UD =
9883         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9884                           UsingName, HasTypenameKeyword);
9885     UD->setAccess(AS);
9886     CurContext->addDecl(UD);
9887     UD->setInvalidDecl(Invalid);
9888     return UD;
9889   };
9890   auto BuildInvalid = [&]{ return Build(true); };
9891   auto BuildValid = [&]{ return Build(false); };
9892 
9893   if (RequireCompleteDeclContext(SS, LookupContext))
9894     return BuildInvalid();
9895 
9896   // Look up the target name.
9897   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9898 
9899   // Unlike most lookups, we don't always want to hide tag
9900   // declarations: tag names are visible through the using declaration
9901   // even if hidden by ordinary names, *except* in a dependent context
9902   // where it's important for the sanity of two-phase lookup.
9903   if (!IsInstantiation)
9904     R.setHideTags(false);
9905 
9906   // For the purposes of this lookup, we have a base object type
9907   // equal to that of the current context.
9908   if (CurContext->isRecord()) {
9909     R.setBaseObjectType(
9910                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9911   }
9912 
9913   LookupQualifiedName(R, LookupContext);
9914 
9915   // Try to correct typos if possible. If constructor name lookup finds no
9916   // results, that means the named class has no explicit constructors, and we
9917   // suppressed declaring implicit ones (probably because it's dependent or
9918   // invalid).
9919   if (R.empty() &&
9920       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9921     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9922     // it will believe that glibc provides a ::gets in cases where it does not,
9923     // and will try to pull it into namespace std with a using-declaration.
9924     // Just ignore the using-declaration in that case.
9925     auto *II = NameInfo.getName().getAsIdentifierInfo();
9926     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9927         CurContext->isStdNamespace() &&
9928         isa<TranslationUnitDecl>(LookupContext) &&
9929         getSourceManager().isInSystemHeader(UsingLoc))
9930       return nullptr;
9931     if (TypoCorrection Corrected = CorrectTypo(
9932             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9933             llvm::make_unique<UsingValidatorCCC>(
9934                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9935                 dyn_cast<CXXRecordDecl>(CurContext)),
9936             CTK_ErrorRecovery)) {
9937       // We reject candidates where DroppedSpecifier == true, hence the
9938       // literal '0' below.
9939       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9940                                 << NameInfo.getName() << LookupContext << 0
9941                                 << SS.getRange());
9942 
9943       // If we picked a correction with no attached Decl we can't do anything
9944       // useful with it, bail out.
9945       NamedDecl *ND = Corrected.getCorrectionDecl();
9946       if (!ND)
9947         return BuildInvalid();
9948 
9949       // If we corrected to an inheriting constructor, handle it as one.
9950       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9951       if (RD && RD->isInjectedClassName()) {
9952         // The parent of the injected class name is the class itself.
9953         RD = cast<CXXRecordDecl>(RD->getParent());
9954 
9955         // Fix up the information we'll use to build the using declaration.
9956         if (Corrected.WillReplaceSpecifier()) {
9957           NestedNameSpecifierLocBuilder Builder;
9958           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9959                               QualifierLoc.getSourceRange());
9960           QualifierLoc = Builder.getWithLocInContext(Context);
9961         }
9962 
9963         // In this case, the name we introduce is the name of a derived class
9964         // constructor.
9965         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9966         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9967             Context.getCanonicalType(Context.getRecordType(CurClass))));
9968         UsingName.setNamedTypeInfo(nullptr);
9969         for (auto *Ctor : LookupConstructors(RD))
9970           R.addDecl(Ctor);
9971         R.resolveKind();
9972       } else {
9973         // FIXME: Pick up all the declarations if we found an overloaded
9974         // function.
9975         UsingName.setName(ND->getDeclName());
9976         R.addDecl(ND);
9977       }
9978     } else {
9979       Diag(IdentLoc, diag::err_no_member)
9980         << NameInfo.getName() << LookupContext << SS.getRange();
9981       return BuildInvalid();
9982     }
9983   }
9984 
9985   if (R.isAmbiguous())
9986     return BuildInvalid();
9987 
9988   if (HasTypenameKeyword) {
9989     // If we asked for a typename and got a non-type decl, error out.
9990     if (!R.getAsSingle<TypeDecl>()) {
9991       Diag(IdentLoc, diag::err_using_typename_non_type);
9992       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9993         Diag((*I)->getUnderlyingDecl()->getLocation(),
9994              diag::note_using_decl_target);
9995       return BuildInvalid();
9996     }
9997   } else {
9998     // If we asked for a non-typename and we got a type, error out,
9999     // but only if this is an instantiation of an unresolved using
10000     // decl.  Otherwise just silently find the type name.
10001     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10002       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10003       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10004       return BuildInvalid();
10005     }
10006   }
10007 
10008   // C++14 [namespace.udecl]p6:
10009   // A using-declaration shall not name a namespace.
10010   if (R.getAsSingle<NamespaceDecl>()) {
10011     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10012       << SS.getRange();
10013     return BuildInvalid();
10014   }
10015 
10016   // C++14 [namespace.udecl]p7:
10017   // A using-declaration shall not name a scoped enumerator.
10018   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10019     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10020       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10021         << SS.getRange();
10022       return BuildInvalid();
10023     }
10024   }
10025 
10026   UsingDecl *UD = BuildValid();
10027 
10028   // Some additional rules apply to inheriting constructors.
10029   if (UsingName.getName().getNameKind() ==
10030         DeclarationName::CXXConstructorName) {
10031     // Suppress access diagnostics; the access check is instead performed at the
10032     // point of use for an inheriting constructor.
10033     R.suppressDiagnostics();
10034     if (CheckInheritingConstructorUsingDecl(UD))
10035       return UD;
10036   }
10037 
10038   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10039     UsingShadowDecl *PrevDecl = nullptr;
10040     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10041       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10042   }
10043 
10044   return UD;
10045 }
10046 
10047 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10048                                     ArrayRef<NamedDecl *> Expansions) {
10049   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10050          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10051          isa<UsingPackDecl>(InstantiatedFrom));
10052 
10053   auto *UPD =
10054       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10055   UPD->setAccess(InstantiatedFrom->getAccess());
10056   CurContext->addDecl(UPD);
10057   return UPD;
10058 }
10059 
10060 /// Additional checks for a using declaration referring to a constructor name.
10061 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10062   assert(!UD->hasTypename() && "expecting a constructor name");
10063 
10064   const Type *SourceType = UD->getQualifier()->getAsType();
10065   assert(SourceType &&
10066          "Using decl naming constructor doesn't have type in scope spec.");
10067   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10068 
10069   // Check whether the named type is a direct base class.
10070   bool AnyDependentBases = false;
10071   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10072                                       AnyDependentBases);
10073   if (!Base && !AnyDependentBases) {
10074     Diag(UD->getUsingLoc(),
10075          diag::err_using_decl_constructor_not_in_direct_base)
10076       << UD->getNameInfo().getSourceRange()
10077       << QualType(SourceType, 0) << TargetClass;
10078     UD->setInvalidDecl();
10079     return true;
10080   }
10081 
10082   if (Base)
10083     Base->setInheritConstructors();
10084 
10085   return false;
10086 }
10087 
10088 /// Checks that the given using declaration is not an invalid
10089 /// redeclaration.  Note that this is checking only for the using decl
10090 /// itself, not for any ill-formedness among the UsingShadowDecls.
10091 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10092                                        bool HasTypenameKeyword,
10093                                        const CXXScopeSpec &SS,
10094                                        SourceLocation NameLoc,
10095                                        const LookupResult &Prev) {
10096   NestedNameSpecifier *Qual = SS.getScopeRep();
10097 
10098   // C++03 [namespace.udecl]p8:
10099   // C++0x [namespace.udecl]p10:
10100   //   A using-declaration is a declaration and can therefore be used
10101   //   repeatedly where (and only where) multiple declarations are
10102   //   allowed.
10103   //
10104   // That's in non-member contexts.
10105   if (!CurContext->getRedeclContext()->isRecord()) {
10106     // A dependent qualifier outside a class can only ever resolve to an
10107     // enumeration type. Therefore it conflicts with any other non-type
10108     // declaration in the same scope.
10109     // FIXME: How should we check for dependent type-type conflicts at block
10110     // scope?
10111     if (Qual->isDependent() && !HasTypenameKeyword) {
10112       for (auto *D : Prev) {
10113         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10114           bool OldCouldBeEnumerator =
10115               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10116           Diag(NameLoc,
10117                OldCouldBeEnumerator ? diag::err_redefinition
10118                                     : diag::err_redefinition_different_kind)
10119               << Prev.getLookupName();
10120           Diag(D->getLocation(), diag::note_previous_definition);
10121           return true;
10122         }
10123       }
10124     }
10125     return false;
10126   }
10127 
10128   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10129     NamedDecl *D = *I;
10130 
10131     bool DTypename;
10132     NestedNameSpecifier *DQual;
10133     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10134       DTypename = UD->hasTypename();
10135       DQual = UD->getQualifier();
10136     } else if (UnresolvedUsingValueDecl *UD
10137                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10138       DTypename = false;
10139       DQual = UD->getQualifier();
10140     } else if (UnresolvedUsingTypenameDecl *UD
10141                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10142       DTypename = true;
10143       DQual = UD->getQualifier();
10144     } else continue;
10145 
10146     // using decls differ if one says 'typename' and the other doesn't.
10147     // FIXME: non-dependent using decls?
10148     if (HasTypenameKeyword != DTypename) continue;
10149 
10150     // using decls differ if they name different scopes (but note that
10151     // template instantiation can cause this check to trigger when it
10152     // didn't before instantiation).
10153     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10154         Context.getCanonicalNestedNameSpecifier(DQual))
10155       continue;
10156 
10157     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10158     Diag(D->getLocation(), diag::note_using_decl) << 1;
10159     return true;
10160   }
10161 
10162   return false;
10163 }
10164 
10165 
10166 /// Checks that the given nested-name qualifier used in a using decl
10167 /// in the current context is appropriately related to the current
10168 /// scope.  If an error is found, diagnoses it and returns true.
10169 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10170                                    bool HasTypename,
10171                                    const CXXScopeSpec &SS,
10172                                    const DeclarationNameInfo &NameInfo,
10173                                    SourceLocation NameLoc) {
10174   DeclContext *NamedContext = computeDeclContext(SS);
10175 
10176   if (!CurContext->isRecord()) {
10177     // C++03 [namespace.udecl]p3:
10178     // C++0x [namespace.udecl]p8:
10179     //   A using-declaration for a class member shall be a member-declaration.
10180 
10181     // If we weren't able to compute a valid scope, it might validly be a
10182     // dependent class scope or a dependent enumeration unscoped scope. If
10183     // we have a 'typename' keyword, the scope must resolve to a class type.
10184     if ((HasTypename && !NamedContext) ||
10185         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10186       auto *RD = NamedContext
10187                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10188                      : nullptr;
10189       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10190         RD = nullptr;
10191 
10192       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10193         << SS.getRange();
10194 
10195       // If we have a complete, non-dependent source type, try to suggest a
10196       // way to get the same effect.
10197       if (!RD)
10198         return true;
10199 
10200       // Find what this using-declaration was referring to.
10201       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10202       R.setHideTags(false);
10203       R.suppressDiagnostics();
10204       LookupQualifiedName(R, RD);
10205 
10206       if (R.getAsSingle<TypeDecl>()) {
10207         if (getLangOpts().CPlusPlus11) {
10208           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10209           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10210             << 0 // alias declaration
10211             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10212                                           NameInfo.getName().getAsString() +
10213                                               " = ");
10214         } else {
10215           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10216           SourceLocation InsertLoc =
10217               getLocForEndOfToken(NameInfo.getLocEnd());
10218           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10219             << 1 // typedef declaration
10220             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10221             << FixItHint::CreateInsertion(
10222                    InsertLoc, " " + NameInfo.getName().getAsString());
10223         }
10224       } else if (R.getAsSingle<VarDecl>()) {
10225         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10226         // repeating the type of the static data member here.
10227         FixItHint FixIt;
10228         if (getLangOpts().CPlusPlus11) {
10229           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10230           FixIt = FixItHint::CreateReplacement(
10231               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10232         }
10233 
10234         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10235           << 2 // reference declaration
10236           << FixIt;
10237       } else if (R.getAsSingle<EnumConstantDecl>()) {
10238         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10239         // repeating the type of the enumeration here, and we can't do so if
10240         // the type is anonymous.
10241         FixItHint FixIt;
10242         if (getLangOpts().CPlusPlus11) {
10243           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10244           FixIt = FixItHint::CreateReplacement(
10245               UsingLoc,
10246               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10247         }
10248 
10249         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10250           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10251           << FixIt;
10252       }
10253       return true;
10254     }
10255 
10256     // Otherwise, this might be valid.
10257     return false;
10258   }
10259 
10260   // The current scope is a record.
10261 
10262   // If the named context is dependent, we can't decide much.
10263   if (!NamedContext) {
10264     // FIXME: in C++0x, we can diagnose if we can prove that the
10265     // nested-name-specifier does not refer to a base class, which is
10266     // still possible in some cases.
10267 
10268     // Otherwise we have to conservatively report that things might be
10269     // okay.
10270     return false;
10271   }
10272 
10273   if (!NamedContext->isRecord()) {
10274     // Ideally this would point at the last name in the specifier,
10275     // but we don't have that level of source info.
10276     Diag(SS.getRange().getBegin(),
10277          diag::err_using_decl_nested_name_specifier_is_not_class)
10278       << SS.getScopeRep() << SS.getRange();
10279     return true;
10280   }
10281 
10282   if (!NamedContext->isDependentContext() &&
10283       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10284     return true;
10285 
10286   if (getLangOpts().CPlusPlus11) {
10287     // C++11 [namespace.udecl]p3:
10288     //   In a using-declaration used as a member-declaration, the
10289     //   nested-name-specifier shall name a base class of the class
10290     //   being defined.
10291 
10292     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10293                                  cast<CXXRecordDecl>(NamedContext))) {
10294       if (CurContext == NamedContext) {
10295         Diag(NameLoc,
10296              diag::err_using_decl_nested_name_specifier_is_current_class)
10297           << SS.getRange();
10298         return true;
10299       }
10300 
10301       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10302         Diag(SS.getRange().getBegin(),
10303              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10304           << SS.getScopeRep()
10305           << cast<CXXRecordDecl>(CurContext)
10306           << SS.getRange();
10307       }
10308       return true;
10309     }
10310 
10311     return false;
10312   }
10313 
10314   // C++03 [namespace.udecl]p4:
10315   //   A using-declaration used as a member-declaration shall refer
10316   //   to a member of a base class of the class being defined [etc.].
10317 
10318   // Salient point: SS doesn't have to name a base class as long as
10319   // lookup only finds members from base classes.  Therefore we can
10320   // diagnose here only if we can prove that that can't happen,
10321   // i.e. if the class hierarchies provably don't intersect.
10322 
10323   // TODO: it would be nice if "definitely valid" results were cached
10324   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10325   // need to be repeated.
10326 
10327   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10328   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10329     Bases.insert(Base);
10330     return true;
10331   };
10332 
10333   // Collect all bases. Return false if we find a dependent base.
10334   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10335     return false;
10336 
10337   // Returns true if the base is dependent or is one of the accumulated base
10338   // classes.
10339   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10340     return !Bases.count(Base);
10341   };
10342 
10343   // Return false if the class has a dependent base or if it or one
10344   // of its bases is present in the base set of the current context.
10345   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10346       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10347     return false;
10348 
10349   Diag(SS.getRange().getBegin(),
10350        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10351     << SS.getScopeRep()
10352     << cast<CXXRecordDecl>(CurContext)
10353     << SS.getRange();
10354 
10355   return true;
10356 }
10357 
10358 Decl *Sema::ActOnAliasDeclaration(Scope *S,
10359                                   AccessSpecifier AS,
10360                                   MultiTemplateParamsArg TemplateParamLists,
10361                                   SourceLocation UsingLoc,
10362                                   UnqualifiedId &Name,
10363                                   AttributeList *AttrList,
10364                                   TypeResult Type,
10365                                   Decl *DeclFromDeclSpec) {
10366   // Skip up to the relevant declaration scope.
10367   while (S->isTemplateParamScope())
10368     S = S->getParent();
10369   assert((S->getFlags() & Scope::DeclScope) &&
10370          "got alias-declaration outside of declaration scope");
10371 
10372   if (Type.isInvalid())
10373     return nullptr;
10374 
10375   bool Invalid = false;
10376   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10377   TypeSourceInfo *TInfo = nullptr;
10378   GetTypeFromParser(Type.get(), &TInfo);
10379 
10380   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10381     return nullptr;
10382 
10383   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10384                                       UPPC_DeclarationType)) {
10385     Invalid = true;
10386     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10387                                              TInfo->getTypeLoc().getBeginLoc());
10388   }
10389 
10390   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10391                         TemplateParamLists.size()
10392                             ? forRedeclarationInCurContext()
10393                             : ForVisibleRedeclaration);
10394   LookupName(Previous, S);
10395 
10396   // Warn about shadowing the name of a template parameter.
10397   if (Previous.isSingleResult() &&
10398       Previous.getFoundDecl()->isTemplateParameter()) {
10399     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10400     Previous.clear();
10401   }
10402 
10403   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10404          "name in alias declaration must be an identifier");
10405   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10406                                                Name.StartLocation,
10407                                                Name.Identifier, TInfo);
10408 
10409   NewTD->setAccess(AS);
10410 
10411   if (Invalid)
10412     NewTD->setInvalidDecl();
10413 
10414   ProcessDeclAttributeList(S, NewTD, AttrList);
10415   AddPragmaAttributes(S, NewTD);
10416 
10417   CheckTypedefForVariablyModifiedType(S, NewTD);
10418   Invalid |= NewTD->isInvalidDecl();
10419 
10420   bool Redeclaration = false;
10421 
10422   NamedDecl *NewND;
10423   if (TemplateParamLists.size()) {
10424     TypeAliasTemplateDecl *OldDecl = nullptr;
10425     TemplateParameterList *OldTemplateParams = nullptr;
10426 
10427     if (TemplateParamLists.size() != 1) {
10428       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10429         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10430          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10431     }
10432     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10433 
10434     // Check that we can declare a template here.
10435     if (CheckTemplateDeclScope(S, TemplateParams))
10436       return nullptr;
10437 
10438     // Only consider previous declarations in the same scope.
10439     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10440                          /*ExplicitInstantiationOrSpecialization*/false);
10441     if (!Previous.empty()) {
10442       Redeclaration = true;
10443 
10444       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10445       if (!OldDecl && !Invalid) {
10446         Diag(UsingLoc, diag::err_redefinition_different_kind)
10447           << Name.Identifier;
10448 
10449         NamedDecl *OldD = Previous.getRepresentativeDecl();
10450         if (OldD->getLocation().isValid())
10451           Diag(OldD->getLocation(), diag::note_previous_definition);
10452 
10453         Invalid = true;
10454       }
10455 
10456       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10457         if (TemplateParameterListsAreEqual(TemplateParams,
10458                                            OldDecl->getTemplateParameters(),
10459                                            /*Complain=*/true,
10460                                            TPL_TemplateMatch))
10461           OldTemplateParams = OldDecl->getTemplateParameters();
10462         else
10463           Invalid = true;
10464 
10465         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10466         if (!Invalid &&
10467             !Context.hasSameType(OldTD->getUnderlyingType(),
10468                                  NewTD->getUnderlyingType())) {
10469           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10470           // but we can't reasonably accept it.
10471           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10472             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10473           if (OldTD->getLocation().isValid())
10474             Diag(OldTD->getLocation(), diag::note_previous_definition);
10475           Invalid = true;
10476         }
10477       }
10478     }
10479 
10480     // Merge any previous default template arguments into our parameters,
10481     // and check the parameter list.
10482     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10483                                    TPC_TypeAliasTemplate))
10484       return nullptr;
10485 
10486     TypeAliasTemplateDecl *NewDecl =
10487       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10488                                     Name.Identifier, TemplateParams,
10489                                     NewTD);
10490     NewTD->setDescribedAliasTemplate(NewDecl);
10491 
10492     NewDecl->setAccess(AS);
10493 
10494     if (Invalid)
10495       NewDecl->setInvalidDecl();
10496     else if (OldDecl) {
10497       NewDecl->setPreviousDecl(OldDecl);
10498       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10499     }
10500 
10501     NewND = NewDecl;
10502   } else {
10503     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10504       setTagNameForLinkagePurposes(TD, NewTD);
10505       handleTagNumbering(TD, S);
10506     }
10507     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10508     NewND = NewTD;
10509   }
10510 
10511   PushOnScopeChains(NewND, S);
10512   ActOnDocumentableDecl(NewND);
10513   return NewND;
10514 }
10515 
10516 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10517                                    SourceLocation AliasLoc,
10518                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10519                                    SourceLocation IdentLoc,
10520                                    IdentifierInfo *Ident) {
10521 
10522   // Lookup the namespace name.
10523   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10524   LookupParsedName(R, S, &SS);
10525 
10526   if (R.isAmbiguous())
10527     return nullptr;
10528 
10529   if (R.empty()) {
10530     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10531       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10532       return nullptr;
10533     }
10534   }
10535   assert(!R.isAmbiguous() && !R.empty());
10536   NamedDecl *ND = R.getRepresentativeDecl();
10537 
10538   // Check if we have a previous declaration with the same name.
10539   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10540                      ForVisibleRedeclaration);
10541   LookupName(PrevR, S);
10542 
10543   // Check we're not shadowing a template parameter.
10544   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10545     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10546     PrevR.clear();
10547   }
10548 
10549   // Filter out any other lookup result from an enclosing scope.
10550   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10551                        /*AllowInlineNamespace*/false);
10552 
10553   // Find the previous declaration and check that we can redeclare it.
10554   NamespaceAliasDecl *Prev = nullptr;
10555   if (PrevR.isSingleResult()) {
10556     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10557     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10558       // We already have an alias with the same name that points to the same
10559       // namespace; check that it matches.
10560       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10561         Prev = AD;
10562       } else if (isVisible(PrevDecl)) {
10563         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10564           << Alias;
10565         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10566           << AD->getNamespace();
10567         return nullptr;
10568       }
10569     } else if (isVisible(PrevDecl)) {
10570       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10571                             ? diag::err_redefinition
10572                             : diag::err_redefinition_different_kind;
10573       Diag(AliasLoc, DiagID) << Alias;
10574       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10575       return nullptr;
10576     }
10577   }
10578 
10579   // The use of a nested name specifier may trigger deprecation warnings.
10580   DiagnoseUseOfDecl(ND, IdentLoc);
10581 
10582   NamespaceAliasDecl *AliasDecl =
10583     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10584                                Alias, SS.getWithLocInContext(Context),
10585                                IdentLoc, ND);
10586   if (Prev)
10587     AliasDecl->setPreviousDecl(Prev);
10588 
10589   PushOnScopeChains(AliasDecl, S);
10590   return AliasDecl;
10591 }
10592 
10593 namespace {
10594 struct SpecialMemberExceptionSpecInfo
10595     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10596   SourceLocation Loc;
10597   Sema::ImplicitExceptionSpecification ExceptSpec;
10598 
10599   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10600                                  Sema::CXXSpecialMember CSM,
10601                                  Sema::InheritedConstructorInfo *ICI,
10602                                  SourceLocation Loc)
10603       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10604 
10605   bool visitBase(CXXBaseSpecifier *Base);
10606   bool visitField(FieldDecl *FD);
10607 
10608   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10609                            unsigned Quals);
10610 
10611   void visitSubobjectCall(Subobject Subobj,
10612                           Sema::SpecialMemberOverloadResult SMOR);
10613 };
10614 }
10615 
10616 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10617   auto *RT = Base->getType()->getAs<RecordType>();
10618   if (!RT)
10619     return false;
10620 
10621   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10622   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10623   if (auto *BaseCtor = SMOR.getMethod()) {
10624     visitSubobjectCall(Base, BaseCtor);
10625     return false;
10626   }
10627 
10628   visitClassSubobject(BaseClass, Base, 0);
10629   return false;
10630 }
10631 
10632 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10633   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10634     Expr *E = FD->getInClassInitializer();
10635     if (!E)
10636       // FIXME: It's a little wasteful to build and throw away a
10637       // CXXDefaultInitExpr here.
10638       // FIXME: We should have a single context note pointing at Loc, and
10639       // this location should be MD->getLocation() instead, since that's
10640       // the location where we actually use the default init expression.
10641       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10642     if (E)
10643       ExceptSpec.CalledExpr(E);
10644   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10645                             ->getAs<RecordType>()) {
10646     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10647                         FD->getType().getCVRQualifiers());
10648   }
10649   return false;
10650 }
10651 
10652 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10653                                                          Subobject Subobj,
10654                                                          unsigned Quals) {
10655   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10656   bool IsMutable = Field && Field->isMutable();
10657   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10658 }
10659 
10660 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10661     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10662   // Note, if lookup fails, it doesn't matter what exception specification we
10663   // choose because the special member will be deleted.
10664   if (CXXMethodDecl *MD = SMOR.getMethod())
10665     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10666 }
10667 
10668 static Sema::ImplicitExceptionSpecification
10669 ComputeDefaultedSpecialMemberExceptionSpec(
10670     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10671     Sema::InheritedConstructorInfo *ICI) {
10672   CXXRecordDecl *ClassDecl = MD->getParent();
10673 
10674   // C++ [except.spec]p14:
10675   //   An implicitly declared special member function (Clause 12) shall have an
10676   //   exception-specification. [...]
10677   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10678   if (ClassDecl->isInvalidDecl())
10679     return Info.ExceptSpec;
10680 
10681   // C++1z [except.spec]p7:
10682   //   [Look for exceptions thrown by] a constructor selected [...] to
10683   //   initialize a potentially constructed subobject,
10684   // C++1z [except.spec]p8:
10685   //   The exception specification for an implicitly-declared destructor, or a
10686   //   destructor without a noexcept-specifier, is potentially-throwing if and
10687   //   only if any of the destructors for any of its potentially constructed
10688   //   subojects is potentially throwing.
10689   // FIXME: We respect the first rule but ignore the "potentially constructed"
10690   // in the second rule to resolve a core issue (no number yet) that would have
10691   // us reject:
10692   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10693   //   struct B : A {};
10694   //   struct C : B { void f(); };
10695   // ... due to giving B::~B() a non-throwing exception specification.
10696   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10697                                 : Info.VisitAllBases);
10698 
10699   return Info.ExceptSpec;
10700 }
10701 
10702 namespace {
10703 /// RAII object to register a special member as being currently declared.
10704 struct DeclaringSpecialMember {
10705   Sema &S;
10706   Sema::SpecialMemberDecl D;
10707   Sema::ContextRAII SavedContext;
10708   bool WasAlreadyBeingDeclared;
10709 
10710   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10711       : S(S), D(RD, CSM), SavedContext(S, RD) {
10712     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10713     if (WasAlreadyBeingDeclared)
10714       // This almost never happens, but if it does, ensure that our cache
10715       // doesn't contain a stale result.
10716       S.SpecialMemberCache.clear();
10717     else {
10718       // Register a note to be produced if we encounter an error while
10719       // declaring the special member.
10720       Sema::CodeSynthesisContext Ctx;
10721       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10722       // FIXME: We don't have a location to use here. Using the class's
10723       // location maintains the fiction that we declare all special members
10724       // with the class, but (1) it's not clear that lying about that helps our
10725       // users understand what's going on, and (2) there may be outer contexts
10726       // on the stack (some of which are relevant) and printing them exposes
10727       // our lies.
10728       Ctx.PointOfInstantiation = RD->getLocation();
10729       Ctx.Entity = RD;
10730       Ctx.SpecialMember = CSM;
10731       S.pushCodeSynthesisContext(Ctx);
10732     }
10733   }
10734   ~DeclaringSpecialMember() {
10735     if (!WasAlreadyBeingDeclared) {
10736       S.SpecialMembersBeingDeclared.erase(D);
10737       S.popCodeSynthesisContext();
10738     }
10739   }
10740 
10741   /// Are we already trying to declare this special member?
10742   bool isAlreadyBeingDeclared() const {
10743     return WasAlreadyBeingDeclared;
10744   }
10745 };
10746 }
10747 
10748 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10749   // Look up any existing declarations, but don't trigger declaration of all
10750   // implicit special members with this name.
10751   DeclarationName Name = FD->getDeclName();
10752   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10753                  ForExternalRedeclaration);
10754   for (auto *D : FD->getParent()->lookup(Name))
10755     if (auto *Acceptable = R.getAcceptableDecl(D))
10756       R.addDecl(Acceptable);
10757   R.resolveKind();
10758   R.suppressDiagnostics();
10759 
10760   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10761 }
10762 
10763 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10764                                                      CXXRecordDecl *ClassDecl) {
10765   // C++ [class.ctor]p5:
10766   //   A default constructor for a class X is a constructor of class X
10767   //   that can be called without an argument. If there is no
10768   //   user-declared constructor for class X, a default constructor is
10769   //   implicitly declared. An implicitly-declared default constructor
10770   //   is an inline public member of its class.
10771   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10772          "Should not build implicit default constructor!");
10773 
10774   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10775   if (DSM.isAlreadyBeingDeclared())
10776     return nullptr;
10777 
10778   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10779                                                      CXXDefaultConstructor,
10780                                                      false);
10781 
10782   // Create the actual constructor declaration.
10783   CanQualType ClassType
10784     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10785   SourceLocation ClassLoc = ClassDecl->getLocation();
10786   DeclarationName Name
10787     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10788   DeclarationNameInfo NameInfo(Name, ClassLoc);
10789   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10790       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10791       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10792       /*isImplicitlyDeclared=*/true, Constexpr);
10793   DefaultCon->setAccess(AS_public);
10794   DefaultCon->setDefaulted();
10795 
10796   if (getLangOpts().CUDA) {
10797     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10798                                             DefaultCon,
10799                                             /* ConstRHS */ false,
10800                                             /* Diagnose */ false);
10801   }
10802 
10803   // Build an exception specification pointing back at this constructor.
10804   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10805   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10806 
10807   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10808   // constructors is easy to compute.
10809   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10810 
10811   // Note that we have declared this constructor.
10812   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10813 
10814   Scope *S = getScopeForContext(ClassDecl);
10815   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10816 
10817   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10818     SetDeclDeleted(DefaultCon, ClassLoc);
10819 
10820   if (S)
10821     PushOnScopeChains(DefaultCon, S, false);
10822   ClassDecl->addDecl(DefaultCon);
10823 
10824   return DefaultCon;
10825 }
10826 
10827 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10828                                             CXXConstructorDecl *Constructor) {
10829   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10830           !Constructor->doesThisDeclarationHaveABody() &&
10831           !Constructor->isDeleted()) &&
10832     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10833   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10834     return;
10835 
10836   CXXRecordDecl *ClassDecl = Constructor->getParent();
10837   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10838 
10839   SynthesizedFunctionScope Scope(*this, Constructor);
10840 
10841   // The exception specification is needed because we are defining the
10842   // function.
10843   ResolveExceptionSpec(CurrentLocation,
10844                        Constructor->getType()->castAs<FunctionProtoType>());
10845   MarkVTableUsed(CurrentLocation, ClassDecl);
10846 
10847   // Add a context note for diagnostics produced after this point.
10848   Scope.addContextNote(CurrentLocation);
10849 
10850   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10851     Constructor->setInvalidDecl();
10852     return;
10853   }
10854 
10855   SourceLocation Loc = Constructor->getLocEnd().isValid()
10856                            ? Constructor->getLocEnd()
10857                            : Constructor->getLocation();
10858   Constructor->setBody(new (Context) CompoundStmt(Loc));
10859   Constructor->markUsed(Context);
10860 
10861   if (ASTMutationListener *L = getASTMutationListener()) {
10862     L->CompletedImplicitDefinition(Constructor);
10863   }
10864 
10865   DiagnoseUninitializedFields(*this, Constructor);
10866 }
10867 
10868 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10869   // Perform any delayed checks on exception specifications.
10870   CheckDelayedMemberExceptionSpecs();
10871 }
10872 
10873 /// Find or create the fake constructor we synthesize to model constructing an
10874 /// object of a derived class via a constructor of a base class.
10875 CXXConstructorDecl *
10876 Sema::findInheritingConstructor(SourceLocation Loc,
10877                                 CXXConstructorDecl *BaseCtor,
10878                                 ConstructorUsingShadowDecl *Shadow) {
10879   CXXRecordDecl *Derived = Shadow->getParent();
10880   SourceLocation UsingLoc = Shadow->getLocation();
10881 
10882   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10883   // For now we use the name of the base class constructor as a member of the
10884   // derived class to indicate a (fake) inherited constructor name.
10885   DeclarationName Name = BaseCtor->getDeclName();
10886 
10887   // Check to see if we already have a fake constructor for this inherited
10888   // constructor call.
10889   for (NamedDecl *Ctor : Derived->lookup(Name))
10890     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10891                                ->getInheritedConstructor()
10892                                .getConstructor(),
10893                            BaseCtor))
10894       return cast<CXXConstructorDecl>(Ctor);
10895 
10896   DeclarationNameInfo NameInfo(Name, UsingLoc);
10897   TypeSourceInfo *TInfo =
10898       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10899   FunctionProtoTypeLoc ProtoLoc =
10900       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10901 
10902   // Check the inherited constructor is valid and find the list of base classes
10903   // from which it was inherited.
10904   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10905 
10906   bool Constexpr =
10907       BaseCtor->isConstexpr() &&
10908       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10909                                         false, BaseCtor, &ICI);
10910 
10911   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10912       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10913       BaseCtor->isExplicit(), /*Inline=*/true,
10914       /*ImplicitlyDeclared=*/true, Constexpr,
10915       InheritedConstructor(Shadow, BaseCtor));
10916   if (Shadow->isInvalidDecl())
10917     DerivedCtor->setInvalidDecl();
10918 
10919   // Build an unevaluated exception specification for this fake constructor.
10920   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10921   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10922   EPI.ExceptionSpec.Type = EST_Unevaluated;
10923   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10924   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10925                                                FPT->getParamTypes(), EPI));
10926 
10927   // Build the parameter declarations.
10928   SmallVector<ParmVarDecl *, 16> ParamDecls;
10929   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10930     TypeSourceInfo *TInfo =
10931         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10932     ParmVarDecl *PD = ParmVarDecl::Create(
10933         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10934         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10935     PD->setScopeInfo(0, I);
10936     PD->setImplicit();
10937     // Ensure attributes are propagated onto parameters (this matters for
10938     // format, pass_object_size, ...).
10939     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10940     ParamDecls.push_back(PD);
10941     ProtoLoc.setParam(I, PD);
10942   }
10943 
10944   // Set up the new constructor.
10945   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10946   DerivedCtor->setAccess(BaseCtor->getAccess());
10947   DerivedCtor->setParams(ParamDecls);
10948   Derived->addDecl(DerivedCtor);
10949 
10950   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10951     SetDeclDeleted(DerivedCtor, UsingLoc);
10952 
10953   return DerivedCtor;
10954 }
10955 
10956 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10957   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10958                                Ctor->getInheritedConstructor().getShadowDecl());
10959   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10960                             /*Diagnose*/true);
10961 }
10962 
10963 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10964                                        CXXConstructorDecl *Constructor) {
10965   CXXRecordDecl *ClassDecl = Constructor->getParent();
10966   assert(Constructor->getInheritedConstructor() &&
10967          !Constructor->doesThisDeclarationHaveABody() &&
10968          !Constructor->isDeleted());
10969   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10970     return;
10971 
10972   // Initializations are performed "as if by a defaulted default constructor",
10973   // so enter the appropriate scope.
10974   SynthesizedFunctionScope Scope(*this, Constructor);
10975 
10976   // The exception specification is needed because we are defining the
10977   // function.
10978   ResolveExceptionSpec(CurrentLocation,
10979                        Constructor->getType()->castAs<FunctionProtoType>());
10980   MarkVTableUsed(CurrentLocation, ClassDecl);
10981 
10982   // Add a context note for diagnostics produced after this point.
10983   Scope.addContextNote(CurrentLocation);
10984 
10985   ConstructorUsingShadowDecl *Shadow =
10986       Constructor->getInheritedConstructor().getShadowDecl();
10987   CXXConstructorDecl *InheritedCtor =
10988       Constructor->getInheritedConstructor().getConstructor();
10989 
10990   // [class.inhctor.init]p1:
10991   //   initialization proceeds as if a defaulted default constructor is used to
10992   //   initialize the D object and each base class subobject from which the
10993   //   constructor was inherited
10994 
10995   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10996   CXXRecordDecl *RD = Shadow->getParent();
10997   SourceLocation InitLoc = Shadow->getLocation();
10998 
10999   // Build explicit initializers for all base classes from which the
11000   // constructor was inherited.
11001   SmallVector<CXXCtorInitializer*, 8> Inits;
11002   for (bool VBase : {false, true}) {
11003     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11004       if (B.isVirtual() != VBase)
11005         continue;
11006 
11007       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11008       if (!BaseRD)
11009         continue;
11010 
11011       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11012       if (!BaseCtor.first)
11013         continue;
11014 
11015       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11016       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11017           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11018 
11019       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11020       Inits.push_back(new (Context) CXXCtorInitializer(
11021           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11022           SourceLocation()));
11023     }
11024   }
11025 
11026   // We now proceed as if for a defaulted default constructor, with the relevant
11027   // initializers replaced.
11028 
11029   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11030     Constructor->setInvalidDecl();
11031     return;
11032   }
11033 
11034   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11035   Constructor->markUsed(Context);
11036 
11037   if (ASTMutationListener *L = getASTMutationListener()) {
11038     L->CompletedImplicitDefinition(Constructor);
11039   }
11040 
11041   DiagnoseUninitializedFields(*this, Constructor);
11042 }
11043 
11044 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11045   // C++ [class.dtor]p2:
11046   //   If a class has no user-declared destructor, a destructor is
11047   //   declared implicitly. An implicitly-declared destructor is an
11048   //   inline public member of its class.
11049   assert(ClassDecl->needsImplicitDestructor());
11050 
11051   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11052   if (DSM.isAlreadyBeingDeclared())
11053     return nullptr;
11054 
11055   // Create the actual destructor declaration.
11056   CanQualType ClassType
11057     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11058   SourceLocation ClassLoc = ClassDecl->getLocation();
11059   DeclarationName Name
11060     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11061   DeclarationNameInfo NameInfo(Name, ClassLoc);
11062   CXXDestructorDecl *Destructor
11063       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11064                                   QualType(), nullptr, /*isInline=*/true,
11065                                   /*isImplicitlyDeclared=*/true);
11066   Destructor->setAccess(AS_public);
11067   Destructor->setDefaulted();
11068 
11069   if (getLangOpts().CUDA) {
11070     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11071                                             Destructor,
11072                                             /* ConstRHS */ false,
11073                                             /* Diagnose */ false);
11074   }
11075 
11076   // Build an exception specification pointing back at this destructor.
11077   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11078   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11079 
11080   // We don't need to use SpecialMemberIsTrivial here; triviality for
11081   // destructors is easy to compute.
11082   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11083   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11084                                 ClassDecl->hasTrivialDestructorForCall());
11085 
11086   // Note that we have declared this destructor.
11087   ++ASTContext::NumImplicitDestructorsDeclared;
11088 
11089   Scope *S = getScopeForContext(ClassDecl);
11090   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11091 
11092   // We can't check whether an implicit destructor is deleted before we complete
11093   // the definition of the class, because its validity depends on the alignment
11094   // of the class. We'll check this from ActOnFields once the class is complete.
11095   if (ClassDecl->isCompleteDefinition() &&
11096       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11097     SetDeclDeleted(Destructor, ClassLoc);
11098 
11099   // Introduce this destructor into its scope.
11100   if (S)
11101     PushOnScopeChains(Destructor, S, false);
11102   ClassDecl->addDecl(Destructor);
11103 
11104   return Destructor;
11105 }
11106 
11107 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11108                                     CXXDestructorDecl *Destructor) {
11109   assert((Destructor->isDefaulted() &&
11110           !Destructor->doesThisDeclarationHaveABody() &&
11111           !Destructor->isDeleted()) &&
11112          "DefineImplicitDestructor - call it for implicit default dtor");
11113   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11114     return;
11115 
11116   CXXRecordDecl *ClassDecl = Destructor->getParent();
11117   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11118 
11119   SynthesizedFunctionScope Scope(*this, Destructor);
11120 
11121   // The exception specification is needed because we are defining the
11122   // function.
11123   ResolveExceptionSpec(CurrentLocation,
11124                        Destructor->getType()->castAs<FunctionProtoType>());
11125   MarkVTableUsed(CurrentLocation, ClassDecl);
11126 
11127   // Add a context note for diagnostics produced after this point.
11128   Scope.addContextNote(CurrentLocation);
11129 
11130   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11131                                          Destructor->getParent());
11132 
11133   if (CheckDestructor(Destructor)) {
11134     Destructor->setInvalidDecl();
11135     return;
11136   }
11137 
11138   SourceLocation Loc = Destructor->getLocEnd().isValid()
11139                            ? Destructor->getLocEnd()
11140                            : Destructor->getLocation();
11141   Destructor->setBody(new (Context) CompoundStmt(Loc));
11142   Destructor->markUsed(Context);
11143 
11144   if (ASTMutationListener *L = getASTMutationListener()) {
11145     L->CompletedImplicitDefinition(Destructor);
11146   }
11147 }
11148 
11149 /// Perform any semantic analysis which needs to be delayed until all
11150 /// pending class member declarations have been parsed.
11151 void Sema::ActOnFinishCXXMemberDecls() {
11152   // If the context is an invalid C++ class, just suppress these checks.
11153   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11154     if (Record->isInvalidDecl()) {
11155       DelayedDefaultedMemberExceptionSpecs.clear();
11156       DelayedExceptionSpecChecks.clear();
11157       return;
11158     }
11159     checkForMultipleExportedDefaultConstructors(*this, Record);
11160   }
11161 }
11162 
11163 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11164   referenceDLLExportedClassMethods();
11165 }
11166 
11167 void Sema::referenceDLLExportedClassMethods() {
11168   if (!DelayedDllExportClasses.empty()) {
11169     // Calling ReferenceDllExportedMembers might cause the current function to
11170     // be called again, so use a local copy of DelayedDllExportClasses.
11171     SmallVector<CXXRecordDecl *, 4> WorkList;
11172     std::swap(DelayedDllExportClasses, WorkList);
11173     for (CXXRecordDecl *Class : WorkList)
11174       ReferenceDllExportedMembers(*this, Class);
11175   }
11176 }
11177 
11178 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11179                                          CXXDestructorDecl *Destructor) {
11180   assert(getLangOpts().CPlusPlus11 &&
11181          "adjusting dtor exception specs was introduced in c++11");
11182 
11183   // C++11 [class.dtor]p3:
11184   //   A declaration of a destructor that does not have an exception-
11185   //   specification is implicitly considered to have the same exception-
11186   //   specification as an implicit declaration.
11187   const FunctionProtoType *DtorType = Destructor->getType()->
11188                                         getAs<FunctionProtoType>();
11189   if (DtorType->hasExceptionSpec())
11190     return;
11191 
11192   // Replace the destructor's type, building off the existing one. Fortunately,
11193   // the only thing of interest in the destructor type is its extended info.
11194   // The return and arguments are fixed.
11195   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11196   EPI.ExceptionSpec.Type = EST_Unevaluated;
11197   EPI.ExceptionSpec.SourceDecl = Destructor;
11198   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11199 
11200   // FIXME: If the destructor has a body that could throw, and the newly created
11201   // spec doesn't allow exceptions, we should emit a warning, because this
11202   // change in behavior can break conforming C++03 programs at runtime.
11203   // However, we don't have a body or an exception specification yet, so it
11204   // needs to be done somewhere else.
11205 }
11206 
11207 namespace {
11208 /// An abstract base class for all helper classes used in building the
11209 //  copy/move operators. These classes serve as factory functions and help us
11210 //  avoid using the same Expr* in the AST twice.
11211 class ExprBuilder {
11212   ExprBuilder(const ExprBuilder&) = delete;
11213   ExprBuilder &operator=(const ExprBuilder&) = delete;
11214 
11215 protected:
11216   static Expr *assertNotNull(Expr *E) {
11217     assert(E && "Expression construction must not fail.");
11218     return E;
11219   }
11220 
11221 public:
11222   ExprBuilder() {}
11223   virtual ~ExprBuilder() {}
11224 
11225   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11226 };
11227 
11228 class RefBuilder: public ExprBuilder {
11229   VarDecl *Var;
11230   QualType VarType;
11231 
11232 public:
11233   Expr *build(Sema &S, SourceLocation Loc) const override {
11234     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11235   }
11236 
11237   RefBuilder(VarDecl *Var, QualType VarType)
11238       : Var(Var), VarType(VarType) {}
11239 };
11240 
11241 class ThisBuilder: public ExprBuilder {
11242 public:
11243   Expr *build(Sema &S, SourceLocation Loc) const override {
11244     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11245   }
11246 };
11247 
11248 class CastBuilder: public ExprBuilder {
11249   const ExprBuilder &Builder;
11250   QualType Type;
11251   ExprValueKind Kind;
11252   const CXXCastPath &Path;
11253 
11254 public:
11255   Expr *build(Sema &S, SourceLocation Loc) const override {
11256     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11257                                              CK_UncheckedDerivedToBase, Kind,
11258                                              &Path).get());
11259   }
11260 
11261   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11262               const CXXCastPath &Path)
11263       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11264 };
11265 
11266 class DerefBuilder: public ExprBuilder {
11267   const ExprBuilder &Builder;
11268 
11269 public:
11270   Expr *build(Sema &S, SourceLocation Loc) const override {
11271     return assertNotNull(
11272         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11273   }
11274 
11275   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11276 };
11277 
11278 class MemberBuilder: public ExprBuilder {
11279   const ExprBuilder &Builder;
11280   QualType Type;
11281   CXXScopeSpec SS;
11282   bool IsArrow;
11283   LookupResult &MemberLookup;
11284 
11285 public:
11286   Expr *build(Sema &S, SourceLocation Loc) const override {
11287     return assertNotNull(S.BuildMemberReferenceExpr(
11288         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11289         nullptr, MemberLookup, nullptr, nullptr).get());
11290   }
11291 
11292   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11293                 LookupResult &MemberLookup)
11294       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11295         MemberLookup(MemberLookup) {}
11296 };
11297 
11298 class MoveCastBuilder: public ExprBuilder {
11299   const ExprBuilder &Builder;
11300 
11301 public:
11302   Expr *build(Sema &S, SourceLocation Loc) const override {
11303     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11304   }
11305 
11306   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11307 };
11308 
11309 class LvalueConvBuilder: public ExprBuilder {
11310   const ExprBuilder &Builder;
11311 
11312 public:
11313   Expr *build(Sema &S, SourceLocation Loc) const override {
11314     return assertNotNull(
11315         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11316   }
11317 
11318   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11319 };
11320 
11321 class SubscriptBuilder: public ExprBuilder {
11322   const ExprBuilder &Base;
11323   const ExprBuilder &Index;
11324 
11325 public:
11326   Expr *build(Sema &S, SourceLocation Loc) const override {
11327     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11328         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11329   }
11330 
11331   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11332       : Base(Base), Index(Index) {}
11333 };
11334 
11335 } // end anonymous namespace
11336 
11337 /// When generating a defaulted copy or move assignment operator, if a field
11338 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11339 /// do so. This optimization only applies for arrays of scalars, and for arrays
11340 /// of class type where the selected copy/move-assignment operator is trivial.
11341 static StmtResult
11342 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11343                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11344   // Compute the size of the memory buffer to be copied.
11345   QualType SizeType = S.Context.getSizeType();
11346   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11347                    S.Context.getTypeSizeInChars(T).getQuantity());
11348 
11349   // Take the address of the field references for "from" and "to". We
11350   // directly construct UnaryOperators here because semantic analysis
11351   // does not permit us to take the address of an xvalue.
11352   Expr *From = FromB.build(S, Loc);
11353   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11354                          S.Context.getPointerType(From->getType()),
11355                          VK_RValue, OK_Ordinary, Loc, false);
11356   Expr *To = ToB.build(S, Loc);
11357   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11358                        S.Context.getPointerType(To->getType()),
11359                        VK_RValue, OK_Ordinary, Loc, false);
11360 
11361   const Type *E = T->getBaseElementTypeUnsafe();
11362   bool NeedsCollectableMemCpy =
11363     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11364 
11365   // Create a reference to the __builtin_objc_memmove_collectable function
11366   StringRef MemCpyName = NeedsCollectableMemCpy ?
11367     "__builtin_objc_memmove_collectable" :
11368     "__builtin_memcpy";
11369   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11370                  Sema::LookupOrdinaryName);
11371   S.LookupName(R, S.TUScope, true);
11372 
11373   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11374   if (!MemCpy)
11375     // Something went horribly wrong earlier, and we will have complained
11376     // about it.
11377     return StmtError();
11378 
11379   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11380                                             VK_RValue, Loc, nullptr);
11381   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11382 
11383   Expr *CallArgs[] = {
11384     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11385   };
11386   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11387                                     Loc, CallArgs, Loc);
11388 
11389   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11390   return Call.getAs<Stmt>();
11391 }
11392 
11393 /// Builds a statement that copies/moves the given entity from \p From to
11394 /// \c To.
11395 ///
11396 /// This routine is used to copy/move the members of a class with an
11397 /// implicitly-declared copy/move assignment operator. When the entities being
11398 /// copied are arrays, this routine builds for loops to copy them.
11399 ///
11400 /// \param S The Sema object used for type-checking.
11401 ///
11402 /// \param Loc The location where the implicit copy/move is being generated.
11403 ///
11404 /// \param T The type of the expressions being copied/moved. Both expressions
11405 /// must have this type.
11406 ///
11407 /// \param To The expression we are copying/moving to.
11408 ///
11409 /// \param From The expression we are copying/moving from.
11410 ///
11411 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11412 /// Otherwise, it's a non-static member subobject.
11413 ///
11414 /// \param Copying Whether we're copying or moving.
11415 ///
11416 /// \param Depth Internal parameter recording the depth of the recursion.
11417 ///
11418 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11419 /// if a memcpy should be used instead.
11420 static StmtResult
11421 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11422                                  const ExprBuilder &To, const ExprBuilder &From,
11423                                  bool CopyingBaseSubobject, bool Copying,
11424                                  unsigned Depth = 0) {
11425   // C++11 [class.copy]p28:
11426   //   Each subobject is assigned in the manner appropriate to its type:
11427   //
11428   //     - if the subobject is of class type, as if by a call to operator= with
11429   //       the subobject as the object expression and the corresponding
11430   //       subobject of x as a single function argument (as if by explicit
11431   //       qualification; that is, ignoring any possible virtual overriding
11432   //       functions in more derived classes);
11433   //
11434   // C++03 [class.copy]p13:
11435   //     - if the subobject is of class type, the copy assignment operator for
11436   //       the class is used (as if by explicit qualification; that is,
11437   //       ignoring any possible virtual overriding functions in more derived
11438   //       classes);
11439   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11440     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11441 
11442     // Look for operator=.
11443     DeclarationName Name
11444       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11445     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11446     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11447 
11448     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11449     // operator.
11450     if (!S.getLangOpts().CPlusPlus11) {
11451       LookupResult::Filter F = OpLookup.makeFilter();
11452       while (F.hasNext()) {
11453         NamedDecl *D = F.next();
11454         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11455           if (Method->isCopyAssignmentOperator() ||
11456               (!Copying && Method->isMoveAssignmentOperator()))
11457             continue;
11458 
11459         F.erase();
11460       }
11461       F.done();
11462     }
11463 
11464     // Suppress the protected check (C++ [class.protected]) for each of the
11465     // assignment operators we found. This strange dance is required when
11466     // we're assigning via a base classes's copy-assignment operator. To
11467     // ensure that we're getting the right base class subobject (without
11468     // ambiguities), we need to cast "this" to that subobject type; to
11469     // ensure that we don't go through the virtual call mechanism, we need
11470     // to qualify the operator= name with the base class (see below). However,
11471     // this means that if the base class has a protected copy assignment
11472     // operator, the protected member access check will fail. So, we
11473     // rewrite "protected" access to "public" access in this case, since we
11474     // know by construction that we're calling from a derived class.
11475     if (CopyingBaseSubobject) {
11476       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11477            L != LEnd; ++L) {
11478         if (L.getAccess() == AS_protected)
11479           L.setAccess(AS_public);
11480       }
11481     }
11482 
11483     // Create the nested-name-specifier that will be used to qualify the
11484     // reference to operator=; this is required to suppress the virtual
11485     // call mechanism.
11486     CXXScopeSpec SS;
11487     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11488     SS.MakeTrivial(S.Context,
11489                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11490                                                CanonicalT),
11491                    Loc);
11492 
11493     // Create the reference to operator=.
11494     ExprResult OpEqualRef
11495       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11496                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11497                                    /*FirstQualifierInScope=*/nullptr,
11498                                    OpLookup,
11499                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11500                                    /*SuppressQualifierCheck=*/true);
11501     if (OpEqualRef.isInvalid())
11502       return StmtError();
11503 
11504     // Build the call to the assignment operator.
11505 
11506     Expr *FromInst = From.build(S, Loc);
11507     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11508                                                   OpEqualRef.getAs<Expr>(),
11509                                                   Loc, FromInst, Loc);
11510     if (Call.isInvalid())
11511       return StmtError();
11512 
11513     // If we built a call to a trivial 'operator=' while copying an array,
11514     // bail out. We'll replace the whole shebang with a memcpy.
11515     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11516     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11517       return StmtResult((Stmt*)nullptr);
11518 
11519     // Convert to an expression-statement, and clean up any produced
11520     // temporaries.
11521     return S.ActOnExprStmt(Call);
11522   }
11523 
11524   //     - if the subobject is of scalar type, the built-in assignment
11525   //       operator is used.
11526   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11527   if (!ArrayTy) {
11528     ExprResult Assignment = S.CreateBuiltinBinOp(
11529         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11530     if (Assignment.isInvalid())
11531       return StmtError();
11532     return S.ActOnExprStmt(Assignment);
11533   }
11534 
11535   //     - if the subobject is an array, each element is assigned, in the
11536   //       manner appropriate to the element type;
11537 
11538   // Construct a loop over the array bounds, e.g.,
11539   //
11540   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11541   //
11542   // that will copy each of the array elements.
11543   QualType SizeType = S.Context.getSizeType();
11544 
11545   // Create the iteration variable.
11546   IdentifierInfo *IterationVarName = nullptr;
11547   {
11548     SmallString<8> Str;
11549     llvm::raw_svector_ostream OS(Str);
11550     OS << "__i" << Depth;
11551     IterationVarName = &S.Context.Idents.get(OS.str());
11552   }
11553   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11554                                           IterationVarName, SizeType,
11555                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11556                                           SC_None);
11557 
11558   // Initialize the iteration variable to zero.
11559   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11560   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11561 
11562   // Creates a reference to the iteration variable.
11563   RefBuilder IterationVarRef(IterationVar, SizeType);
11564   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11565 
11566   // Create the DeclStmt that holds the iteration variable.
11567   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11568 
11569   // Subscript the "from" and "to" expressions with the iteration variable.
11570   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11571   MoveCastBuilder FromIndexMove(FromIndexCopy);
11572   const ExprBuilder *FromIndex;
11573   if (Copying)
11574     FromIndex = &FromIndexCopy;
11575   else
11576     FromIndex = &FromIndexMove;
11577 
11578   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11579 
11580   // Build the copy/move for an individual element of the array.
11581   StmtResult Copy =
11582     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11583                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11584                                      Copying, Depth + 1);
11585   // Bail out if copying fails or if we determined that we should use memcpy.
11586   if (Copy.isInvalid() || !Copy.get())
11587     return Copy;
11588 
11589   // Create the comparison against the array bound.
11590   llvm::APInt Upper
11591     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11592   Expr *Comparison
11593     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11594                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11595                                      BO_NE, S.Context.BoolTy,
11596                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11597 
11598   // Create the pre-increment of the iteration variable. We can determine
11599   // whether the increment will overflow based on the value of the array
11600   // bound.
11601   Expr *Increment = new (S.Context)
11602       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11603                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11604 
11605   // Construct the loop that copies all elements of this array.
11606   return S.ActOnForStmt(
11607       Loc, Loc, InitStmt,
11608       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11609       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11610 }
11611 
11612 static StmtResult
11613 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11614                       const ExprBuilder &To, const ExprBuilder &From,
11615                       bool CopyingBaseSubobject, bool Copying) {
11616   // Maybe we should use a memcpy?
11617   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11618       T.isTriviallyCopyableType(S.Context))
11619     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11620 
11621   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11622                                                      CopyingBaseSubobject,
11623                                                      Copying, 0));
11624 
11625   // If we ended up picking a trivial assignment operator for an array of a
11626   // non-trivially-copyable class type, just emit a memcpy.
11627   if (!Result.isInvalid() && !Result.get())
11628     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11629 
11630   return Result;
11631 }
11632 
11633 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11634   // Note: The following rules are largely analoguous to the copy
11635   // constructor rules. Note that virtual bases are not taken into account
11636   // for determining the argument type of the operator. Note also that
11637   // operators taking an object instead of a reference are allowed.
11638   assert(ClassDecl->needsImplicitCopyAssignment());
11639 
11640   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11641   if (DSM.isAlreadyBeingDeclared())
11642     return nullptr;
11643 
11644   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11645   QualType RetType = Context.getLValueReferenceType(ArgType);
11646   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11647   if (Const)
11648     ArgType = ArgType.withConst();
11649   ArgType = Context.getLValueReferenceType(ArgType);
11650 
11651   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11652                                                      CXXCopyAssignment,
11653                                                      Const);
11654 
11655   //   An implicitly-declared copy assignment operator is an inline public
11656   //   member of its class.
11657   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11658   SourceLocation ClassLoc = ClassDecl->getLocation();
11659   DeclarationNameInfo NameInfo(Name, ClassLoc);
11660   CXXMethodDecl *CopyAssignment =
11661       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11662                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11663                             /*isInline=*/true, Constexpr, SourceLocation());
11664   CopyAssignment->setAccess(AS_public);
11665   CopyAssignment->setDefaulted();
11666   CopyAssignment->setImplicit();
11667 
11668   if (getLangOpts().CUDA) {
11669     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11670                                             CopyAssignment,
11671                                             /* ConstRHS */ Const,
11672                                             /* Diagnose */ false);
11673   }
11674 
11675   // Build an exception specification pointing back at this member.
11676   FunctionProtoType::ExtProtoInfo EPI =
11677       getImplicitMethodEPI(*this, CopyAssignment);
11678   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11679 
11680   // Add the parameter to the operator.
11681   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11682                                                ClassLoc, ClassLoc,
11683                                                /*Id=*/nullptr, ArgType,
11684                                                /*TInfo=*/nullptr, SC_None,
11685                                                nullptr);
11686   CopyAssignment->setParams(FromParam);
11687 
11688   CopyAssignment->setTrivial(
11689     ClassDecl->needsOverloadResolutionForCopyAssignment()
11690       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11691       : ClassDecl->hasTrivialCopyAssignment());
11692 
11693   // Note that we have added this copy-assignment operator.
11694   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11695 
11696   Scope *S = getScopeForContext(ClassDecl);
11697   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11698 
11699   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11700     SetDeclDeleted(CopyAssignment, ClassLoc);
11701 
11702   if (S)
11703     PushOnScopeChains(CopyAssignment, S, false);
11704   ClassDecl->addDecl(CopyAssignment);
11705 
11706   return CopyAssignment;
11707 }
11708 
11709 /// Diagnose an implicit copy operation for a class which is odr-used, but
11710 /// which is deprecated because the class has a user-declared copy constructor,
11711 /// copy assignment operator, or destructor.
11712 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11713   assert(CopyOp->isImplicit());
11714 
11715   CXXRecordDecl *RD = CopyOp->getParent();
11716   CXXMethodDecl *UserDeclaredOperation = nullptr;
11717 
11718   // In Microsoft mode, assignment operations don't affect constructors and
11719   // vice versa.
11720   if (RD->hasUserDeclaredDestructor()) {
11721     UserDeclaredOperation = RD->getDestructor();
11722   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11723              RD->hasUserDeclaredCopyConstructor() &&
11724              !S.getLangOpts().MSVCCompat) {
11725     // Find any user-declared copy constructor.
11726     for (auto *I : RD->ctors()) {
11727       if (I->isCopyConstructor()) {
11728         UserDeclaredOperation = I;
11729         break;
11730       }
11731     }
11732     assert(UserDeclaredOperation);
11733   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11734              RD->hasUserDeclaredCopyAssignment() &&
11735              !S.getLangOpts().MSVCCompat) {
11736     // Find any user-declared move assignment operator.
11737     for (auto *I : RD->methods()) {
11738       if (I->isCopyAssignmentOperator()) {
11739         UserDeclaredOperation = I;
11740         break;
11741       }
11742     }
11743     assert(UserDeclaredOperation);
11744   }
11745 
11746   if (UserDeclaredOperation) {
11747     S.Diag(UserDeclaredOperation->getLocation(),
11748          diag::warn_deprecated_copy_operation)
11749       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11750       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11751   }
11752 }
11753 
11754 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11755                                         CXXMethodDecl *CopyAssignOperator) {
11756   assert((CopyAssignOperator->isDefaulted() &&
11757           CopyAssignOperator->isOverloadedOperator() &&
11758           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11759           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11760           !CopyAssignOperator->isDeleted()) &&
11761          "DefineImplicitCopyAssignment called for wrong function");
11762   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11763     return;
11764 
11765   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11766   if (ClassDecl->isInvalidDecl()) {
11767     CopyAssignOperator->setInvalidDecl();
11768     return;
11769   }
11770 
11771   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11772 
11773   // The exception specification is needed because we are defining the
11774   // function.
11775   ResolveExceptionSpec(CurrentLocation,
11776                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11777 
11778   // Add a context note for diagnostics produced after this point.
11779   Scope.addContextNote(CurrentLocation);
11780 
11781   // C++11 [class.copy]p18:
11782   //   The [definition of an implicitly declared copy assignment operator] is
11783   //   deprecated if the class has a user-declared copy constructor or a
11784   //   user-declared destructor.
11785   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11786     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11787 
11788   // C++0x [class.copy]p30:
11789   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11790   //   for a non-union class X performs memberwise copy assignment of its
11791   //   subobjects. The direct base classes of X are assigned first, in the
11792   //   order of their declaration in the base-specifier-list, and then the
11793   //   immediate non-static data members of X are assigned, in the order in
11794   //   which they were declared in the class definition.
11795 
11796   // The statements that form the synthesized function body.
11797   SmallVector<Stmt*, 8> Statements;
11798 
11799   // The parameter for the "other" object, which we are copying from.
11800   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11801   Qualifiers OtherQuals = Other->getType().getQualifiers();
11802   QualType OtherRefType = Other->getType();
11803   if (const LValueReferenceType *OtherRef
11804                                 = OtherRefType->getAs<LValueReferenceType>()) {
11805     OtherRefType = OtherRef->getPointeeType();
11806     OtherQuals = OtherRefType.getQualifiers();
11807   }
11808 
11809   // Our location for everything implicitly-generated.
11810   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11811                            ? CopyAssignOperator->getLocEnd()
11812                            : CopyAssignOperator->getLocation();
11813 
11814   // Builds a DeclRefExpr for the "other" object.
11815   RefBuilder OtherRef(Other, OtherRefType);
11816 
11817   // Builds the "this" pointer.
11818   ThisBuilder This;
11819 
11820   // Assign base classes.
11821   bool Invalid = false;
11822   for (auto &Base : ClassDecl->bases()) {
11823     // Form the assignment:
11824     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11825     QualType BaseType = Base.getType().getUnqualifiedType();
11826     if (!BaseType->isRecordType()) {
11827       Invalid = true;
11828       continue;
11829     }
11830 
11831     CXXCastPath BasePath;
11832     BasePath.push_back(&Base);
11833 
11834     // Construct the "from" expression, which is an implicit cast to the
11835     // appropriately-qualified base type.
11836     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11837                      VK_LValue, BasePath);
11838 
11839     // Dereference "this".
11840     DerefBuilder DerefThis(This);
11841     CastBuilder To(DerefThis,
11842                    Context.getCVRQualifiedType(
11843                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11844                    VK_LValue, BasePath);
11845 
11846     // Build the copy.
11847     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11848                                             To, From,
11849                                             /*CopyingBaseSubobject=*/true,
11850                                             /*Copying=*/true);
11851     if (Copy.isInvalid()) {
11852       CopyAssignOperator->setInvalidDecl();
11853       return;
11854     }
11855 
11856     // Success! Record the copy.
11857     Statements.push_back(Copy.getAs<Expr>());
11858   }
11859 
11860   // Assign non-static members.
11861   for (auto *Field : ClassDecl->fields()) {
11862     // FIXME: We should form some kind of AST representation for the implied
11863     // memcpy in a union copy operation.
11864     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11865       continue;
11866 
11867     if (Field->isInvalidDecl()) {
11868       Invalid = true;
11869       continue;
11870     }
11871 
11872     // Check for members of reference type; we can't copy those.
11873     if (Field->getType()->isReferenceType()) {
11874       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11875         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11876       Diag(Field->getLocation(), diag::note_declared_at);
11877       Invalid = true;
11878       continue;
11879     }
11880 
11881     // Check for members of const-qualified, non-class type.
11882     QualType BaseType = Context.getBaseElementType(Field->getType());
11883     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11884       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11885         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11886       Diag(Field->getLocation(), diag::note_declared_at);
11887       Invalid = true;
11888       continue;
11889     }
11890 
11891     // Suppress assigning zero-width bitfields.
11892     if (Field->isZeroLengthBitField(Context))
11893       continue;
11894 
11895     QualType FieldType = Field->getType().getNonReferenceType();
11896     if (FieldType->isIncompleteArrayType()) {
11897       assert(ClassDecl->hasFlexibleArrayMember() &&
11898              "Incomplete array type is not valid");
11899       continue;
11900     }
11901 
11902     // Build references to the field in the object we're copying from and to.
11903     CXXScopeSpec SS; // Intentionally empty
11904     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11905                               LookupMemberName);
11906     MemberLookup.addDecl(Field);
11907     MemberLookup.resolveKind();
11908 
11909     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11910 
11911     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11912 
11913     // Build the copy of this field.
11914     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11915                                             To, From,
11916                                             /*CopyingBaseSubobject=*/false,
11917                                             /*Copying=*/true);
11918     if (Copy.isInvalid()) {
11919       CopyAssignOperator->setInvalidDecl();
11920       return;
11921     }
11922 
11923     // Success! Record the copy.
11924     Statements.push_back(Copy.getAs<Stmt>());
11925   }
11926 
11927   if (!Invalid) {
11928     // Add a "return *this;"
11929     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11930 
11931     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11932     if (Return.isInvalid())
11933       Invalid = true;
11934     else
11935       Statements.push_back(Return.getAs<Stmt>());
11936   }
11937 
11938   if (Invalid) {
11939     CopyAssignOperator->setInvalidDecl();
11940     return;
11941   }
11942 
11943   StmtResult Body;
11944   {
11945     CompoundScopeRAII CompoundScope(*this);
11946     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11947                              /*isStmtExpr=*/false);
11948     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11949   }
11950   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11951   CopyAssignOperator->markUsed(Context);
11952 
11953   if (ASTMutationListener *L = getASTMutationListener()) {
11954     L->CompletedImplicitDefinition(CopyAssignOperator);
11955   }
11956 }
11957 
11958 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11959   assert(ClassDecl->needsImplicitMoveAssignment());
11960 
11961   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11962   if (DSM.isAlreadyBeingDeclared())
11963     return nullptr;
11964 
11965   // Note: The following rules are largely analoguous to the move
11966   // constructor rules.
11967 
11968   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11969   QualType RetType = Context.getLValueReferenceType(ArgType);
11970   ArgType = Context.getRValueReferenceType(ArgType);
11971 
11972   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11973                                                      CXXMoveAssignment,
11974                                                      false);
11975 
11976   //   An implicitly-declared move assignment operator is an inline public
11977   //   member of its class.
11978   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11979   SourceLocation ClassLoc = ClassDecl->getLocation();
11980   DeclarationNameInfo NameInfo(Name, ClassLoc);
11981   CXXMethodDecl *MoveAssignment =
11982       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11983                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11984                             /*isInline=*/true, Constexpr, SourceLocation());
11985   MoveAssignment->setAccess(AS_public);
11986   MoveAssignment->setDefaulted();
11987   MoveAssignment->setImplicit();
11988 
11989   if (getLangOpts().CUDA) {
11990     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11991                                             MoveAssignment,
11992                                             /* ConstRHS */ false,
11993                                             /* Diagnose */ false);
11994   }
11995 
11996   // Build an exception specification pointing back at this member.
11997   FunctionProtoType::ExtProtoInfo EPI =
11998       getImplicitMethodEPI(*this, MoveAssignment);
11999   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12000 
12001   // Add the parameter to the operator.
12002   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12003                                                ClassLoc, ClassLoc,
12004                                                /*Id=*/nullptr, ArgType,
12005                                                /*TInfo=*/nullptr, SC_None,
12006                                                nullptr);
12007   MoveAssignment->setParams(FromParam);
12008 
12009   MoveAssignment->setTrivial(
12010     ClassDecl->needsOverloadResolutionForMoveAssignment()
12011       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12012       : ClassDecl->hasTrivialMoveAssignment());
12013 
12014   // Note that we have added this copy-assignment operator.
12015   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12016 
12017   Scope *S = getScopeForContext(ClassDecl);
12018   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12019 
12020   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12021     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12022     SetDeclDeleted(MoveAssignment, ClassLoc);
12023   }
12024 
12025   if (S)
12026     PushOnScopeChains(MoveAssignment, S, false);
12027   ClassDecl->addDecl(MoveAssignment);
12028 
12029   return MoveAssignment;
12030 }
12031 
12032 /// Check if we're implicitly defining a move assignment operator for a class
12033 /// with virtual bases. Such a move assignment might move-assign the virtual
12034 /// base multiple times.
12035 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12036                                                SourceLocation CurrentLocation) {
12037   assert(!Class->isDependentContext() && "should not define dependent move");
12038 
12039   // Only a virtual base could get implicitly move-assigned multiple times.
12040   // Only a non-trivial move assignment can observe this. We only want to
12041   // diagnose if we implicitly define an assignment operator that assigns
12042   // two base classes, both of which move-assign the same virtual base.
12043   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12044       Class->getNumBases() < 2)
12045     return;
12046 
12047   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12048   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12049   VBaseMap VBases;
12050 
12051   for (auto &BI : Class->bases()) {
12052     Worklist.push_back(&BI);
12053     while (!Worklist.empty()) {
12054       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12055       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12056 
12057       // If the base has no non-trivial move assignment operators,
12058       // we don't care about moves from it.
12059       if (!Base->hasNonTrivialMoveAssignment())
12060         continue;
12061 
12062       // If there's nothing virtual here, skip it.
12063       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12064         continue;
12065 
12066       // If we're not actually going to call a move assignment for this base,
12067       // or the selected move assignment is trivial, skip it.
12068       Sema::SpecialMemberOverloadResult SMOR =
12069         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12070                               /*ConstArg*/false, /*VolatileArg*/false,
12071                               /*RValueThis*/true, /*ConstThis*/false,
12072                               /*VolatileThis*/false);
12073       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12074           !SMOR.getMethod()->isMoveAssignmentOperator())
12075         continue;
12076 
12077       if (BaseSpec->isVirtual()) {
12078         // We're going to move-assign this virtual base, and its move
12079         // assignment operator is not trivial. If this can happen for
12080         // multiple distinct direct bases of Class, diagnose it. (If it
12081         // only happens in one base, we'll diagnose it when synthesizing
12082         // that base class's move assignment operator.)
12083         CXXBaseSpecifier *&Existing =
12084             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12085                 .first->second;
12086         if (Existing && Existing != &BI) {
12087           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12088             << Class << Base;
12089           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
12090             << (Base->getCanonicalDecl() ==
12091                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12092             << Base << Existing->getType() << Existing->getSourceRange();
12093           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
12094             << (Base->getCanonicalDecl() ==
12095                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12096             << Base << BI.getType() << BaseSpec->getSourceRange();
12097 
12098           // Only diagnose each vbase once.
12099           Existing = nullptr;
12100         }
12101       } else {
12102         // Only walk over bases that have defaulted move assignment operators.
12103         // We assume that any user-provided move assignment operator handles
12104         // the multiple-moves-of-vbase case itself somehow.
12105         if (!SMOR.getMethod()->isDefaulted())
12106           continue;
12107 
12108         // We're going to move the base classes of Base. Add them to the list.
12109         for (auto &BI : Base->bases())
12110           Worklist.push_back(&BI);
12111       }
12112     }
12113   }
12114 }
12115 
12116 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12117                                         CXXMethodDecl *MoveAssignOperator) {
12118   assert((MoveAssignOperator->isDefaulted() &&
12119           MoveAssignOperator->isOverloadedOperator() &&
12120           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12121           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12122           !MoveAssignOperator->isDeleted()) &&
12123          "DefineImplicitMoveAssignment called for wrong function");
12124   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12125     return;
12126 
12127   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12128   if (ClassDecl->isInvalidDecl()) {
12129     MoveAssignOperator->setInvalidDecl();
12130     return;
12131   }
12132 
12133   // C++0x [class.copy]p28:
12134   //   The implicitly-defined or move assignment operator for a non-union class
12135   //   X performs memberwise move assignment of its subobjects. The direct base
12136   //   classes of X are assigned first, in the order of their declaration in the
12137   //   base-specifier-list, and then the immediate non-static data members of X
12138   //   are assigned, in the order in which they were declared in the class
12139   //   definition.
12140 
12141   // Issue a warning if our implicit move assignment operator will move
12142   // from a virtual base more than once.
12143   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12144 
12145   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12146 
12147   // The exception specification is needed because we are defining the
12148   // function.
12149   ResolveExceptionSpec(CurrentLocation,
12150                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12151 
12152   // Add a context note for diagnostics produced after this point.
12153   Scope.addContextNote(CurrentLocation);
12154 
12155   // The statements that form the synthesized function body.
12156   SmallVector<Stmt*, 8> Statements;
12157 
12158   // The parameter for the "other" object, which we are move from.
12159   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12160   QualType OtherRefType = Other->getType()->
12161       getAs<RValueReferenceType>()->getPointeeType();
12162   assert(!OtherRefType.getQualifiers() &&
12163          "Bad argument type of defaulted move assignment");
12164 
12165   // Our location for everything implicitly-generated.
12166   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
12167                            ? MoveAssignOperator->getLocEnd()
12168                            : MoveAssignOperator->getLocation();
12169 
12170   // Builds a reference to the "other" object.
12171   RefBuilder OtherRef(Other, OtherRefType);
12172   // Cast to rvalue.
12173   MoveCastBuilder MoveOther(OtherRef);
12174 
12175   // Builds the "this" pointer.
12176   ThisBuilder This;
12177 
12178   // Assign base classes.
12179   bool Invalid = false;
12180   for (auto &Base : ClassDecl->bases()) {
12181     // C++11 [class.copy]p28:
12182     //   It is unspecified whether subobjects representing virtual base classes
12183     //   are assigned more than once by the implicitly-defined copy assignment
12184     //   operator.
12185     // FIXME: Do not assign to a vbase that will be assigned by some other base
12186     // class. For a move-assignment, this can result in the vbase being moved
12187     // multiple times.
12188 
12189     // Form the assignment:
12190     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12191     QualType BaseType = Base.getType().getUnqualifiedType();
12192     if (!BaseType->isRecordType()) {
12193       Invalid = true;
12194       continue;
12195     }
12196 
12197     CXXCastPath BasePath;
12198     BasePath.push_back(&Base);
12199 
12200     // Construct the "from" expression, which is an implicit cast to the
12201     // appropriately-qualified base type.
12202     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12203 
12204     // Dereference "this".
12205     DerefBuilder DerefThis(This);
12206 
12207     // Implicitly cast "this" to the appropriately-qualified base type.
12208     CastBuilder To(DerefThis,
12209                    Context.getCVRQualifiedType(
12210                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12211                    VK_LValue, BasePath);
12212 
12213     // Build the move.
12214     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12215                                             To, From,
12216                                             /*CopyingBaseSubobject=*/true,
12217                                             /*Copying=*/false);
12218     if (Move.isInvalid()) {
12219       MoveAssignOperator->setInvalidDecl();
12220       return;
12221     }
12222 
12223     // Success! Record the move.
12224     Statements.push_back(Move.getAs<Expr>());
12225   }
12226 
12227   // Assign non-static members.
12228   for (auto *Field : ClassDecl->fields()) {
12229     // FIXME: We should form some kind of AST representation for the implied
12230     // memcpy in a union copy operation.
12231     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12232       continue;
12233 
12234     if (Field->isInvalidDecl()) {
12235       Invalid = true;
12236       continue;
12237     }
12238 
12239     // Check for members of reference type; we can't move those.
12240     if (Field->getType()->isReferenceType()) {
12241       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12242         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12243       Diag(Field->getLocation(), diag::note_declared_at);
12244       Invalid = true;
12245       continue;
12246     }
12247 
12248     // Check for members of const-qualified, non-class type.
12249     QualType BaseType = Context.getBaseElementType(Field->getType());
12250     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12251       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12252         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12253       Diag(Field->getLocation(), diag::note_declared_at);
12254       Invalid = true;
12255       continue;
12256     }
12257 
12258     // Suppress assigning zero-width bitfields.
12259     if (Field->isZeroLengthBitField(Context))
12260       continue;
12261 
12262     QualType FieldType = Field->getType().getNonReferenceType();
12263     if (FieldType->isIncompleteArrayType()) {
12264       assert(ClassDecl->hasFlexibleArrayMember() &&
12265              "Incomplete array type is not valid");
12266       continue;
12267     }
12268 
12269     // Build references to the field in the object we're copying from and to.
12270     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12271                               LookupMemberName);
12272     MemberLookup.addDecl(Field);
12273     MemberLookup.resolveKind();
12274     MemberBuilder From(MoveOther, OtherRefType,
12275                        /*IsArrow=*/false, MemberLookup);
12276     MemberBuilder To(This, getCurrentThisType(),
12277                      /*IsArrow=*/true, MemberLookup);
12278 
12279     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12280         "Member reference with rvalue base must be rvalue except for reference "
12281         "members, which aren't allowed for move assignment.");
12282 
12283     // Build the move of this field.
12284     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12285                                             To, From,
12286                                             /*CopyingBaseSubobject=*/false,
12287                                             /*Copying=*/false);
12288     if (Move.isInvalid()) {
12289       MoveAssignOperator->setInvalidDecl();
12290       return;
12291     }
12292 
12293     // Success! Record the copy.
12294     Statements.push_back(Move.getAs<Stmt>());
12295   }
12296 
12297   if (!Invalid) {
12298     // Add a "return *this;"
12299     ExprResult ThisObj =
12300         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12301 
12302     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12303     if (Return.isInvalid())
12304       Invalid = true;
12305     else
12306       Statements.push_back(Return.getAs<Stmt>());
12307   }
12308 
12309   if (Invalid) {
12310     MoveAssignOperator->setInvalidDecl();
12311     return;
12312   }
12313 
12314   StmtResult Body;
12315   {
12316     CompoundScopeRAII CompoundScope(*this);
12317     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12318                              /*isStmtExpr=*/false);
12319     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12320   }
12321   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12322   MoveAssignOperator->markUsed(Context);
12323 
12324   if (ASTMutationListener *L = getASTMutationListener()) {
12325     L->CompletedImplicitDefinition(MoveAssignOperator);
12326   }
12327 }
12328 
12329 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12330                                                     CXXRecordDecl *ClassDecl) {
12331   // C++ [class.copy]p4:
12332   //   If the class definition does not explicitly declare a copy
12333   //   constructor, one is declared implicitly.
12334   assert(ClassDecl->needsImplicitCopyConstructor());
12335 
12336   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12337   if (DSM.isAlreadyBeingDeclared())
12338     return nullptr;
12339 
12340   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12341   QualType ArgType = ClassType;
12342   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12343   if (Const)
12344     ArgType = ArgType.withConst();
12345   ArgType = Context.getLValueReferenceType(ArgType);
12346 
12347   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12348                                                      CXXCopyConstructor,
12349                                                      Const);
12350 
12351   DeclarationName Name
12352     = Context.DeclarationNames.getCXXConstructorName(
12353                                            Context.getCanonicalType(ClassType));
12354   SourceLocation ClassLoc = ClassDecl->getLocation();
12355   DeclarationNameInfo NameInfo(Name, ClassLoc);
12356 
12357   //   An implicitly-declared copy constructor is an inline public
12358   //   member of its class.
12359   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12360       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12361       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12362       Constexpr);
12363   CopyConstructor->setAccess(AS_public);
12364   CopyConstructor->setDefaulted();
12365 
12366   if (getLangOpts().CUDA) {
12367     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12368                                             CopyConstructor,
12369                                             /* ConstRHS */ Const,
12370                                             /* Diagnose */ false);
12371   }
12372 
12373   // Build an exception specification pointing back at this member.
12374   FunctionProtoType::ExtProtoInfo EPI =
12375       getImplicitMethodEPI(*this, CopyConstructor);
12376   CopyConstructor->setType(
12377       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12378 
12379   // Add the parameter to the constructor.
12380   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12381                                                ClassLoc, ClassLoc,
12382                                                /*IdentifierInfo=*/nullptr,
12383                                                ArgType, /*TInfo=*/nullptr,
12384                                                SC_None, nullptr);
12385   CopyConstructor->setParams(FromParam);
12386 
12387   CopyConstructor->setTrivial(
12388       ClassDecl->needsOverloadResolutionForCopyConstructor()
12389           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12390           : ClassDecl->hasTrivialCopyConstructor());
12391 
12392   CopyConstructor->setTrivialForCall(
12393       ClassDecl->hasAttr<TrivialABIAttr>() ||
12394       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12395            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12396              TAH_ConsiderTrivialABI)
12397            : ClassDecl->hasTrivialCopyConstructorForCall()));
12398 
12399   // Note that we have declared this constructor.
12400   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12401 
12402   Scope *S = getScopeForContext(ClassDecl);
12403   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12404 
12405   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12406     ClassDecl->setImplicitCopyConstructorIsDeleted();
12407     SetDeclDeleted(CopyConstructor, ClassLoc);
12408   }
12409 
12410   if (S)
12411     PushOnScopeChains(CopyConstructor, S, false);
12412   ClassDecl->addDecl(CopyConstructor);
12413 
12414   return CopyConstructor;
12415 }
12416 
12417 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12418                                          CXXConstructorDecl *CopyConstructor) {
12419   assert((CopyConstructor->isDefaulted() &&
12420           CopyConstructor->isCopyConstructor() &&
12421           !CopyConstructor->doesThisDeclarationHaveABody() &&
12422           !CopyConstructor->isDeleted()) &&
12423          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12424   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12425     return;
12426 
12427   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12428   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12429 
12430   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12431 
12432   // The exception specification is needed because we are defining the
12433   // function.
12434   ResolveExceptionSpec(CurrentLocation,
12435                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12436   MarkVTableUsed(CurrentLocation, ClassDecl);
12437 
12438   // Add a context note for diagnostics produced after this point.
12439   Scope.addContextNote(CurrentLocation);
12440 
12441   // C++11 [class.copy]p7:
12442   //   The [definition of an implicitly declared copy constructor] is
12443   //   deprecated if the class has a user-declared copy assignment operator
12444   //   or a user-declared destructor.
12445   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12446     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12447 
12448   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12449     CopyConstructor->setInvalidDecl();
12450   }  else {
12451     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12452                              ? CopyConstructor->getLocEnd()
12453                              : CopyConstructor->getLocation();
12454     Sema::CompoundScopeRAII CompoundScope(*this);
12455     CopyConstructor->setBody(
12456         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12457     CopyConstructor->markUsed(Context);
12458   }
12459 
12460   if (ASTMutationListener *L = getASTMutationListener()) {
12461     L->CompletedImplicitDefinition(CopyConstructor);
12462   }
12463 }
12464 
12465 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12466                                                     CXXRecordDecl *ClassDecl) {
12467   assert(ClassDecl->needsImplicitMoveConstructor());
12468 
12469   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12470   if (DSM.isAlreadyBeingDeclared())
12471     return nullptr;
12472 
12473   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12474   QualType ArgType = Context.getRValueReferenceType(ClassType);
12475 
12476   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12477                                                      CXXMoveConstructor,
12478                                                      false);
12479 
12480   DeclarationName Name
12481     = Context.DeclarationNames.getCXXConstructorName(
12482                                            Context.getCanonicalType(ClassType));
12483   SourceLocation ClassLoc = ClassDecl->getLocation();
12484   DeclarationNameInfo NameInfo(Name, ClassLoc);
12485 
12486   // C++11 [class.copy]p11:
12487   //   An implicitly-declared copy/move constructor is an inline public
12488   //   member of its class.
12489   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12490       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12491       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12492       Constexpr);
12493   MoveConstructor->setAccess(AS_public);
12494   MoveConstructor->setDefaulted();
12495 
12496   if (getLangOpts().CUDA) {
12497     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12498                                             MoveConstructor,
12499                                             /* ConstRHS */ false,
12500                                             /* Diagnose */ false);
12501   }
12502 
12503   // Build an exception specification pointing back at this member.
12504   FunctionProtoType::ExtProtoInfo EPI =
12505       getImplicitMethodEPI(*this, MoveConstructor);
12506   MoveConstructor->setType(
12507       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12508 
12509   // Add the parameter to the constructor.
12510   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12511                                                ClassLoc, ClassLoc,
12512                                                /*IdentifierInfo=*/nullptr,
12513                                                ArgType, /*TInfo=*/nullptr,
12514                                                SC_None, nullptr);
12515   MoveConstructor->setParams(FromParam);
12516 
12517   MoveConstructor->setTrivial(
12518       ClassDecl->needsOverloadResolutionForMoveConstructor()
12519           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12520           : ClassDecl->hasTrivialMoveConstructor());
12521 
12522   MoveConstructor->setTrivialForCall(
12523       ClassDecl->hasAttr<TrivialABIAttr>() ||
12524       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12525            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12526                                     TAH_ConsiderTrivialABI)
12527            : ClassDecl->hasTrivialMoveConstructorForCall()));
12528 
12529   // Note that we have declared this constructor.
12530   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12531 
12532   Scope *S = getScopeForContext(ClassDecl);
12533   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12534 
12535   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12536     ClassDecl->setImplicitMoveConstructorIsDeleted();
12537     SetDeclDeleted(MoveConstructor, ClassLoc);
12538   }
12539 
12540   if (S)
12541     PushOnScopeChains(MoveConstructor, S, false);
12542   ClassDecl->addDecl(MoveConstructor);
12543 
12544   return MoveConstructor;
12545 }
12546 
12547 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12548                                          CXXConstructorDecl *MoveConstructor) {
12549   assert((MoveConstructor->isDefaulted() &&
12550           MoveConstructor->isMoveConstructor() &&
12551           !MoveConstructor->doesThisDeclarationHaveABody() &&
12552           !MoveConstructor->isDeleted()) &&
12553          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12554   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12555     return;
12556 
12557   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12558   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12559 
12560   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12561 
12562   // The exception specification is needed because we are defining the
12563   // function.
12564   ResolveExceptionSpec(CurrentLocation,
12565                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12566   MarkVTableUsed(CurrentLocation, ClassDecl);
12567 
12568   // Add a context note for diagnostics produced after this point.
12569   Scope.addContextNote(CurrentLocation);
12570 
12571   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12572     MoveConstructor->setInvalidDecl();
12573   } else {
12574     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12575                              ? MoveConstructor->getLocEnd()
12576                              : MoveConstructor->getLocation();
12577     Sema::CompoundScopeRAII CompoundScope(*this);
12578     MoveConstructor->setBody(ActOnCompoundStmt(
12579         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12580     MoveConstructor->markUsed(Context);
12581   }
12582 
12583   if (ASTMutationListener *L = getASTMutationListener()) {
12584     L->CompletedImplicitDefinition(MoveConstructor);
12585   }
12586 }
12587 
12588 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12589   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12590 }
12591 
12592 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12593                             SourceLocation CurrentLocation,
12594                             CXXConversionDecl *Conv) {
12595   SynthesizedFunctionScope Scope(*this, Conv);
12596   assert(!Conv->getReturnType()->isUndeducedType());
12597 
12598   CXXRecordDecl *Lambda = Conv->getParent();
12599   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12600   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12601 
12602   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12603     CallOp = InstantiateFunctionDeclaration(
12604         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12605     if (!CallOp)
12606       return;
12607 
12608     Invoker = InstantiateFunctionDeclaration(
12609         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12610     if (!Invoker)
12611       return;
12612   }
12613 
12614   if (CallOp->isInvalidDecl())
12615     return;
12616 
12617   // Mark the call operator referenced (and add to pending instantiations
12618   // if necessary).
12619   // For both the conversion and static-invoker template specializations
12620   // we construct their body's in this function, so no need to add them
12621   // to the PendingInstantiations.
12622   MarkFunctionReferenced(CurrentLocation, CallOp);
12623 
12624   // Fill in the __invoke function with a dummy implementation. IR generation
12625   // will fill in the actual details. Update its type in case it contained
12626   // an 'auto'.
12627   Invoker->markUsed(Context);
12628   Invoker->setReferenced();
12629   Invoker->setType(Conv->getReturnType()->getPointeeType());
12630   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12631 
12632   // Construct the body of the conversion function { return __invoke; }.
12633   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12634                                        VK_LValue, Conv->getLocation()).get();
12635   assert(FunctionRef && "Can't refer to __invoke function?");
12636   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12637   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12638                                      Conv->getLocation()));
12639   Conv->markUsed(Context);
12640   Conv->setReferenced();
12641 
12642   if (ASTMutationListener *L = getASTMutationListener()) {
12643     L->CompletedImplicitDefinition(Conv);
12644     L->CompletedImplicitDefinition(Invoker);
12645   }
12646 }
12647 
12648 
12649 
12650 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12651        SourceLocation CurrentLocation,
12652        CXXConversionDecl *Conv)
12653 {
12654   assert(!Conv->getParent()->isGenericLambda());
12655 
12656   SynthesizedFunctionScope Scope(*this, Conv);
12657 
12658   // Copy-initialize the lambda object as needed to capture it.
12659   Expr *This = ActOnCXXThis(CurrentLocation).get();
12660   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12661 
12662   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12663                                                         Conv->getLocation(),
12664                                                         Conv, DerefThis);
12665 
12666   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12667   // behavior.  Note that only the general conversion function does this
12668   // (since it's unusable otherwise); in the case where we inline the
12669   // block literal, it has block literal lifetime semantics.
12670   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12671     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12672                                           CK_CopyAndAutoreleaseBlockObject,
12673                                           BuildBlock.get(), nullptr, VK_RValue);
12674 
12675   if (BuildBlock.isInvalid()) {
12676     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12677     Conv->setInvalidDecl();
12678     return;
12679   }
12680 
12681   // Create the return statement that returns the block from the conversion
12682   // function.
12683   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12684   if (Return.isInvalid()) {
12685     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12686     Conv->setInvalidDecl();
12687     return;
12688   }
12689 
12690   // Set the body of the conversion function.
12691   Stmt *ReturnS = Return.get();
12692   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12693                                      Conv->getLocation()));
12694   Conv->markUsed(Context);
12695 
12696   // We're done; notify the mutation listener, if any.
12697   if (ASTMutationListener *L = getASTMutationListener()) {
12698     L->CompletedImplicitDefinition(Conv);
12699   }
12700 }
12701 
12702 /// Determine whether the given list arguments contains exactly one
12703 /// "real" (non-default) argument.
12704 static bool hasOneRealArgument(MultiExprArg Args) {
12705   switch (Args.size()) {
12706   case 0:
12707     return false;
12708 
12709   default:
12710     if (!Args[1]->isDefaultArgument())
12711       return false;
12712 
12713     LLVM_FALLTHROUGH;
12714   case 1:
12715     return !Args[0]->isDefaultArgument();
12716   }
12717 
12718   return false;
12719 }
12720 
12721 ExprResult
12722 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12723                             NamedDecl *FoundDecl,
12724                             CXXConstructorDecl *Constructor,
12725                             MultiExprArg ExprArgs,
12726                             bool HadMultipleCandidates,
12727                             bool IsListInitialization,
12728                             bool IsStdInitListInitialization,
12729                             bool RequiresZeroInit,
12730                             unsigned ConstructKind,
12731                             SourceRange ParenRange) {
12732   bool Elidable = false;
12733 
12734   // C++0x [class.copy]p34:
12735   //   When certain criteria are met, an implementation is allowed to
12736   //   omit the copy/move construction of a class object, even if the
12737   //   copy/move constructor and/or destructor for the object have
12738   //   side effects. [...]
12739   //     - when a temporary class object that has not been bound to a
12740   //       reference (12.2) would be copied/moved to a class object
12741   //       with the same cv-unqualified type, the copy/move operation
12742   //       can be omitted by constructing the temporary object
12743   //       directly into the target of the omitted copy/move
12744   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12745       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12746     Expr *SubExpr = ExprArgs[0];
12747     Elidable = SubExpr->isTemporaryObject(
12748         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12749   }
12750 
12751   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12752                                FoundDecl, Constructor,
12753                                Elidable, ExprArgs, HadMultipleCandidates,
12754                                IsListInitialization,
12755                                IsStdInitListInitialization, RequiresZeroInit,
12756                                ConstructKind, ParenRange);
12757 }
12758 
12759 ExprResult
12760 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12761                             NamedDecl *FoundDecl,
12762                             CXXConstructorDecl *Constructor,
12763                             bool Elidable,
12764                             MultiExprArg ExprArgs,
12765                             bool HadMultipleCandidates,
12766                             bool IsListInitialization,
12767                             bool IsStdInitListInitialization,
12768                             bool RequiresZeroInit,
12769                             unsigned ConstructKind,
12770                             SourceRange ParenRange) {
12771   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12772     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12773     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12774       return ExprError();
12775   }
12776 
12777   return BuildCXXConstructExpr(
12778       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12779       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12780       RequiresZeroInit, ConstructKind, ParenRange);
12781 }
12782 
12783 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12784 /// including handling of its default argument expressions.
12785 ExprResult
12786 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12787                             CXXConstructorDecl *Constructor,
12788                             bool Elidable,
12789                             MultiExprArg ExprArgs,
12790                             bool HadMultipleCandidates,
12791                             bool IsListInitialization,
12792                             bool IsStdInitListInitialization,
12793                             bool RequiresZeroInit,
12794                             unsigned ConstructKind,
12795                             SourceRange ParenRange) {
12796   assert(declaresSameEntity(
12797              Constructor->getParent(),
12798              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12799          "given constructor for wrong type");
12800   MarkFunctionReferenced(ConstructLoc, Constructor);
12801   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12802     return ExprError();
12803 
12804   return CXXConstructExpr::Create(
12805       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12806       ExprArgs, HadMultipleCandidates, IsListInitialization,
12807       IsStdInitListInitialization, RequiresZeroInit,
12808       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12809       ParenRange);
12810 }
12811 
12812 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12813   assert(Field->hasInClassInitializer());
12814 
12815   // If we already have the in-class initializer nothing needs to be done.
12816   if (Field->getInClassInitializer())
12817     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12818 
12819   // If we might have already tried and failed to instantiate, don't try again.
12820   if (Field->isInvalidDecl())
12821     return ExprError();
12822 
12823   // Maybe we haven't instantiated the in-class initializer. Go check the
12824   // pattern FieldDecl to see if it has one.
12825   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12826 
12827   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12828     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12829     DeclContext::lookup_result Lookup =
12830         ClassPattern->lookup(Field->getDeclName());
12831 
12832     // Lookup can return at most two results: the pattern for the field, or the
12833     // injected class name of the parent record. No other member can have the
12834     // same name as the field.
12835     // In modules mode, lookup can return multiple results (coming from
12836     // different modules).
12837     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12838            "more than two lookup results for field name");
12839     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12840     if (!Pattern) {
12841       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12842              "cannot have other non-field member with same name");
12843       for (auto L : Lookup)
12844         if (isa<FieldDecl>(L)) {
12845           Pattern = cast<FieldDecl>(L);
12846           break;
12847         }
12848       assert(Pattern && "We must have set the Pattern!");
12849     }
12850 
12851     if (!Pattern->hasInClassInitializer() ||
12852         InstantiateInClassInitializer(Loc, Field, Pattern,
12853                                       getTemplateInstantiationArgs(Field))) {
12854       // Don't diagnose this again.
12855       Field->setInvalidDecl();
12856       return ExprError();
12857     }
12858     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12859   }
12860 
12861   // DR1351:
12862   //   If the brace-or-equal-initializer of a non-static data member
12863   //   invokes a defaulted default constructor of its class or of an
12864   //   enclosing class in a potentially evaluated subexpression, the
12865   //   program is ill-formed.
12866   //
12867   // This resolution is unworkable: the exception specification of the
12868   // default constructor can be needed in an unevaluated context, in
12869   // particular, in the operand of a noexcept-expression, and we can be
12870   // unable to compute an exception specification for an enclosed class.
12871   //
12872   // Any attempt to resolve the exception specification of a defaulted default
12873   // constructor before the initializer is lexically complete will ultimately
12874   // come here at which point we can diagnose it.
12875   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12876   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12877       << OutermostClass << Field;
12878   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12879   // Recover by marking the field invalid, unless we're in a SFINAE context.
12880   if (!isSFINAEContext())
12881     Field->setInvalidDecl();
12882   return ExprError();
12883 }
12884 
12885 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12886   if (VD->isInvalidDecl()) return;
12887 
12888   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12889   if (ClassDecl->isInvalidDecl()) return;
12890   if (ClassDecl->hasIrrelevantDestructor()) return;
12891   if (ClassDecl->isDependentContext()) return;
12892 
12893   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12894   MarkFunctionReferenced(VD->getLocation(), Destructor);
12895   CheckDestructorAccess(VD->getLocation(), Destructor,
12896                         PDiag(diag::err_access_dtor_var)
12897                         << VD->getDeclName()
12898                         << VD->getType());
12899   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12900 
12901   if (Destructor->isTrivial()) return;
12902   if (!VD->hasGlobalStorage()) return;
12903 
12904   // Emit warning for non-trivial dtor in global scope (a real global,
12905   // class-static, function-static).
12906   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12907 
12908   // TODO: this should be re-enabled for static locals by !CXAAtExit
12909   if (!VD->isStaticLocal())
12910     Diag(VD->getLocation(), diag::warn_global_destructor);
12911 }
12912 
12913 /// Given a constructor and the set of arguments provided for the
12914 /// constructor, convert the arguments and add any required default arguments
12915 /// to form a proper call to this constructor.
12916 ///
12917 /// \returns true if an error occurred, false otherwise.
12918 bool
12919 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12920                               MultiExprArg ArgsPtr,
12921                               SourceLocation Loc,
12922                               SmallVectorImpl<Expr*> &ConvertedArgs,
12923                               bool AllowExplicit,
12924                               bool IsListInitialization) {
12925   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12926   unsigned NumArgs = ArgsPtr.size();
12927   Expr **Args = ArgsPtr.data();
12928 
12929   const FunctionProtoType *Proto
12930     = Constructor->getType()->getAs<FunctionProtoType>();
12931   assert(Proto && "Constructor without a prototype?");
12932   unsigned NumParams = Proto->getNumParams();
12933 
12934   // If too few arguments are available, we'll fill in the rest with defaults.
12935   if (NumArgs < NumParams)
12936     ConvertedArgs.reserve(NumParams);
12937   else
12938     ConvertedArgs.reserve(NumArgs);
12939 
12940   VariadicCallType CallType =
12941     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12942   SmallVector<Expr *, 8> AllArgs;
12943   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12944                                         Proto, 0,
12945                                         llvm::makeArrayRef(Args, NumArgs),
12946                                         AllArgs,
12947                                         CallType, AllowExplicit,
12948                                         IsListInitialization);
12949   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12950 
12951   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12952 
12953   CheckConstructorCall(Constructor,
12954                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12955                        Proto, Loc);
12956 
12957   return Invalid;
12958 }
12959 
12960 static inline bool
12961 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12962                                        const FunctionDecl *FnDecl) {
12963   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12964   if (isa<NamespaceDecl>(DC)) {
12965     return SemaRef.Diag(FnDecl->getLocation(),
12966                         diag::err_operator_new_delete_declared_in_namespace)
12967       << FnDecl->getDeclName();
12968   }
12969 
12970   if (isa<TranslationUnitDecl>(DC) &&
12971       FnDecl->getStorageClass() == SC_Static) {
12972     return SemaRef.Diag(FnDecl->getLocation(),
12973                         diag::err_operator_new_delete_declared_static)
12974       << FnDecl->getDeclName();
12975   }
12976 
12977   return false;
12978 }
12979 
12980 static inline bool
12981 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12982                             CanQualType ExpectedResultType,
12983                             CanQualType ExpectedFirstParamType,
12984                             unsigned DependentParamTypeDiag,
12985                             unsigned InvalidParamTypeDiag) {
12986   QualType ResultType =
12987       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12988 
12989   // Check that the result type is not dependent.
12990   if (ResultType->isDependentType())
12991     return SemaRef.Diag(FnDecl->getLocation(),
12992                         diag::err_operator_new_delete_dependent_result_type)
12993     << FnDecl->getDeclName() << ExpectedResultType;
12994 
12995   // Check that the result type is what we expect.
12996   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12997     return SemaRef.Diag(FnDecl->getLocation(),
12998                         diag::err_operator_new_delete_invalid_result_type)
12999     << FnDecl->getDeclName() << ExpectedResultType;
13000 
13001   // A function template must have at least 2 parameters.
13002   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13003     return SemaRef.Diag(FnDecl->getLocation(),
13004                       diag::err_operator_new_delete_template_too_few_parameters)
13005         << FnDecl->getDeclName();
13006 
13007   // The function decl must have at least 1 parameter.
13008   if (FnDecl->getNumParams() == 0)
13009     return SemaRef.Diag(FnDecl->getLocation(),
13010                         diag::err_operator_new_delete_too_few_parameters)
13011       << FnDecl->getDeclName();
13012 
13013   // Check the first parameter type is not dependent.
13014   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13015   if (FirstParamType->isDependentType())
13016     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13017       << FnDecl->getDeclName() << ExpectedFirstParamType;
13018 
13019   // Check that the first parameter type is what we expect.
13020   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13021       ExpectedFirstParamType)
13022     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13023     << FnDecl->getDeclName() << ExpectedFirstParamType;
13024 
13025   return false;
13026 }
13027 
13028 static bool
13029 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13030   // C++ [basic.stc.dynamic.allocation]p1:
13031   //   A program is ill-formed if an allocation function is declared in a
13032   //   namespace scope other than global scope or declared static in global
13033   //   scope.
13034   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13035     return true;
13036 
13037   CanQualType SizeTy =
13038     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13039 
13040   // C++ [basic.stc.dynamic.allocation]p1:
13041   //  The return type shall be void*. The first parameter shall have type
13042   //  std::size_t.
13043   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13044                                   SizeTy,
13045                                   diag::err_operator_new_dependent_param_type,
13046                                   diag::err_operator_new_param_type))
13047     return true;
13048 
13049   // C++ [basic.stc.dynamic.allocation]p1:
13050   //  The first parameter shall not have an associated default argument.
13051   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13052     return SemaRef.Diag(FnDecl->getLocation(),
13053                         diag::err_operator_new_default_arg)
13054       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13055 
13056   return false;
13057 }
13058 
13059 static bool
13060 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13061   // C++ [basic.stc.dynamic.deallocation]p1:
13062   //   A program is ill-formed if deallocation functions are declared in a
13063   //   namespace scope other than global scope or declared static in global
13064   //   scope.
13065   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13066     return true;
13067 
13068   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13069 
13070   // C++ P0722:
13071   //   Within a class C, the first parameter of a destroying operator delete
13072   //   shall be of type C *. The first parameter of any other deallocation
13073   //   function shall be of type void *.
13074   CanQualType ExpectedFirstParamType =
13075       MD && MD->isDestroyingOperatorDelete()
13076           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13077                 SemaRef.Context.getRecordType(MD->getParent())))
13078           : SemaRef.Context.VoidPtrTy;
13079 
13080   // C++ [basic.stc.dynamic.deallocation]p2:
13081   //   Each deallocation function shall return void
13082   if (CheckOperatorNewDeleteTypes(
13083           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13084           diag::err_operator_delete_dependent_param_type,
13085           diag::err_operator_delete_param_type))
13086     return true;
13087 
13088   // C++ P0722:
13089   //   A destroying operator delete shall be a usual deallocation function.
13090   if (MD && !MD->getParent()->isDependentContext() &&
13091       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13092     SemaRef.Diag(MD->getLocation(),
13093                  diag::err_destroying_operator_delete_not_usual);
13094     return true;
13095   }
13096 
13097   return false;
13098 }
13099 
13100 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13101 /// of this overloaded operator is well-formed. If so, returns false;
13102 /// otherwise, emits appropriate diagnostics and returns true.
13103 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13104   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13105          "Expected an overloaded operator declaration");
13106 
13107   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13108 
13109   // C++ [over.oper]p5:
13110   //   The allocation and deallocation functions, operator new,
13111   //   operator new[], operator delete and operator delete[], are
13112   //   described completely in 3.7.3. The attributes and restrictions
13113   //   found in the rest of this subclause do not apply to them unless
13114   //   explicitly stated in 3.7.3.
13115   if (Op == OO_Delete || Op == OO_Array_Delete)
13116     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13117 
13118   if (Op == OO_New || Op == OO_Array_New)
13119     return CheckOperatorNewDeclaration(*this, FnDecl);
13120 
13121   // C++ [over.oper]p6:
13122   //   An operator function shall either be a non-static member
13123   //   function or be a non-member function and have at least one
13124   //   parameter whose type is a class, a reference to a class, an
13125   //   enumeration, or a reference to an enumeration.
13126   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13127     if (MethodDecl->isStatic())
13128       return Diag(FnDecl->getLocation(),
13129                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13130   } else {
13131     bool ClassOrEnumParam = false;
13132     for (auto Param : FnDecl->parameters()) {
13133       QualType ParamType = Param->getType().getNonReferenceType();
13134       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13135           ParamType->isEnumeralType()) {
13136         ClassOrEnumParam = true;
13137         break;
13138       }
13139     }
13140 
13141     if (!ClassOrEnumParam)
13142       return Diag(FnDecl->getLocation(),
13143                   diag::err_operator_overload_needs_class_or_enum)
13144         << FnDecl->getDeclName();
13145   }
13146 
13147   // C++ [over.oper]p8:
13148   //   An operator function cannot have default arguments (8.3.6),
13149   //   except where explicitly stated below.
13150   //
13151   // Only the function-call operator allows default arguments
13152   // (C++ [over.call]p1).
13153   if (Op != OO_Call) {
13154     for (auto Param : FnDecl->parameters()) {
13155       if (Param->hasDefaultArg())
13156         return Diag(Param->getLocation(),
13157                     diag::err_operator_overload_default_arg)
13158           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13159     }
13160   }
13161 
13162   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13163     { false, false, false }
13164 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13165     , { Unary, Binary, MemberOnly }
13166 #include "clang/Basic/OperatorKinds.def"
13167   };
13168 
13169   bool CanBeUnaryOperator = OperatorUses[Op][0];
13170   bool CanBeBinaryOperator = OperatorUses[Op][1];
13171   bool MustBeMemberOperator = OperatorUses[Op][2];
13172 
13173   // C++ [over.oper]p8:
13174   //   [...] Operator functions cannot have more or fewer parameters
13175   //   than the number required for the corresponding operator, as
13176   //   described in the rest of this subclause.
13177   unsigned NumParams = FnDecl->getNumParams()
13178                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13179   if (Op != OO_Call &&
13180       ((NumParams == 1 && !CanBeUnaryOperator) ||
13181        (NumParams == 2 && !CanBeBinaryOperator) ||
13182        (NumParams < 1) || (NumParams > 2))) {
13183     // We have the wrong number of parameters.
13184     unsigned ErrorKind;
13185     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13186       ErrorKind = 2;  // 2 -> unary or binary.
13187     } else if (CanBeUnaryOperator) {
13188       ErrorKind = 0;  // 0 -> unary
13189     } else {
13190       assert(CanBeBinaryOperator &&
13191              "All non-call overloaded operators are unary or binary!");
13192       ErrorKind = 1;  // 1 -> binary
13193     }
13194 
13195     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13196       << FnDecl->getDeclName() << NumParams << ErrorKind;
13197   }
13198 
13199   // Overloaded operators other than operator() cannot be variadic.
13200   if (Op != OO_Call &&
13201       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13202     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13203       << FnDecl->getDeclName();
13204   }
13205 
13206   // Some operators must be non-static member functions.
13207   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13208     return Diag(FnDecl->getLocation(),
13209                 diag::err_operator_overload_must_be_member)
13210       << FnDecl->getDeclName();
13211   }
13212 
13213   // C++ [over.inc]p1:
13214   //   The user-defined function called operator++ implements the
13215   //   prefix and postfix ++ operator. If this function is a member
13216   //   function with no parameters, or a non-member function with one
13217   //   parameter of class or enumeration type, it defines the prefix
13218   //   increment operator ++ for objects of that type. If the function
13219   //   is a member function with one parameter (which shall be of type
13220   //   int) or a non-member function with two parameters (the second
13221   //   of which shall be of type int), it defines the postfix
13222   //   increment operator ++ for objects of that type.
13223   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13224     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13225     QualType ParamType = LastParam->getType();
13226 
13227     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13228         !ParamType->isDependentType())
13229       return Diag(LastParam->getLocation(),
13230                   diag::err_operator_overload_post_incdec_must_be_int)
13231         << LastParam->getType() << (Op == OO_MinusMinus);
13232   }
13233 
13234   return false;
13235 }
13236 
13237 static bool
13238 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13239                                           FunctionTemplateDecl *TpDecl) {
13240   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13241 
13242   // Must have one or two template parameters.
13243   if (TemplateParams->size() == 1) {
13244     NonTypeTemplateParmDecl *PmDecl =
13245         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13246 
13247     // The template parameter must be a char parameter pack.
13248     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13249         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13250       return false;
13251 
13252   } else if (TemplateParams->size() == 2) {
13253     TemplateTypeParmDecl *PmType =
13254         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13255     NonTypeTemplateParmDecl *PmArgs =
13256         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13257 
13258     // The second template parameter must be a parameter pack with the
13259     // first template parameter as its type.
13260     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13261         PmArgs->isTemplateParameterPack()) {
13262       const TemplateTypeParmType *TArgs =
13263           PmArgs->getType()->getAs<TemplateTypeParmType>();
13264       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13265           TArgs->getIndex() == PmType->getIndex()) {
13266         if (!SemaRef.inTemplateInstantiation())
13267           SemaRef.Diag(TpDecl->getLocation(),
13268                        diag::ext_string_literal_operator_template);
13269         return false;
13270       }
13271     }
13272   }
13273 
13274   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13275                diag::err_literal_operator_template)
13276       << TpDecl->getTemplateParameters()->getSourceRange();
13277   return true;
13278 }
13279 
13280 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13281 /// of this literal operator function is well-formed. If so, returns
13282 /// false; otherwise, emits appropriate diagnostics and returns true.
13283 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13284   if (isa<CXXMethodDecl>(FnDecl)) {
13285     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13286       << FnDecl->getDeclName();
13287     return true;
13288   }
13289 
13290   if (FnDecl->isExternC()) {
13291     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13292     if (const LinkageSpecDecl *LSD =
13293             FnDecl->getDeclContext()->getExternCContext())
13294       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13295     return true;
13296   }
13297 
13298   // This might be the definition of a literal operator template.
13299   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13300 
13301   // This might be a specialization of a literal operator template.
13302   if (!TpDecl)
13303     TpDecl = FnDecl->getPrimaryTemplate();
13304 
13305   // template <char...> type operator "" name() and
13306   // template <class T, T...> type operator "" name() are the only valid
13307   // template signatures, and the only valid signatures with no parameters.
13308   if (TpDecl) {
13309     if (FnDecl->param_size() != 0) {
13310       Diag(FnDecl->getLocation(),
13311            diag::err_literal_operator_template_with_params);
13312       return true;
13313     }
13314 
13315     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13316       return true;
13317 
13318   } else if (FnDecl->param_size() == 1) {
13319     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13320 
13321     QualType ParamType = Param->getType().getUnqualifiedType();
13322 
13323     // Only unsigned long long int, long double, any character type, and const
13324     // char * are allowed as the only parameters.
13325     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13326         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13327         Context.hasSameType(ParamType, Context.CharTy) ||
13328         Context.hasSameType(ParamType, Context.WideCharTy) ||
13329         Context.hasSameType(ParamType, Context.Char8Ty) ||
13330         Context.hasSameType(ParamType, Context.Char16Ty) ||
13331         Context.hasSameType(ParamType, Context.Char32Ty)) {
13332     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13333       QualType InnerType = Ptr->getPointeeType();
13334 
13335       // Pointer parameter must be a const char *.
13336       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13337                                 Context.CharTy) &&
13338             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13339         Diag(Param->getSourceRange().getBegin(),
13340              diag::err_literal_operator_param)
13341             << ParamType << "'const char *'" << Param->getSourceRange();
13342         return true;
13343       }
13344 
13345     } else if (ParamType->isRealFloatingType()) {
13346       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13347           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13348       return true;
13349 
13350     } else if (ParamType->isIntegerType()) {
13351       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13352           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13353       return true;
13354 
13355     } else {
13356       Diag(Param->getSourceRange().getBegin(),
13357            diag::err_literal_operator_invalid_param)
13358           << ParamType << Param->getSourceRange();
13359       return true;
13360     }
13361 
13362   } else if (FnDecl->param_size() == 2) {
13363     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13364 
13365     // First, verify that the first parameter is correct.
13366 
13367     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13368 
13369     // Two parameter function must have a pointer to const as a
13370     // first parameter; let's strip those qualifiers.
13371     const PointerType *PT = FirstParamType->getAs<PointerType>();
13372 
13373     if (!PT) {
13374       Diag((*Param)->getSourceRange().getBegin(),
13375            diag::err_literal_operator_param)
13376           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13377       return true;
13378     }
13379 
13380     QualType PointeeType = PT->getPointeeType();
13381     // First parameter must be const
13382     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13383       Diag((*Param)->getSourceRange().getBegin(),
13384            diag::err_literal_operator_param)
13385           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13386       return true;
13387     }
13388 
13389     QualType InnerType = PointeeType.getUnqualifiedType();
13390     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13391     // const char32_t* are allowed as the first parameter to a two-parameter
13392     // function
13393     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13394           Context.hasSameType(InnerType, Context.WideCharTy) ||
13395           Context.hasSameType(InnerType, Context.Char8Ty) ||
13396           Context.hasSameType(InnerType, Context.Char16Ty) ||
13397           Context.hasSameType(InnerType, Context.Char32Ty))) {
13398       Diag((*Param)->getSourceRange().getBegin(),
13399            diag::err_literal_operator_param)
13400           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13401       return true;
13402     }
13403 
13404     // Move on to the second and final parameter.
13405     ++Param;
13406 
13407     // The second parameter must be a std::size_t.
13408     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13409     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13410       Diag((*Param)->getSourceRange().getBegin(),
13411            diag::err_literal_operator_param)
13412           << SecondParamType << Context.getSizeType()
13413           << (*Param)->getSourceRange();
13414       return true;
13415     }
13416   } else {
13417     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13418     return true;
13419   }
13420 
13421   // Parameters are good.
13422 
13423   // A parameter-declaration-clause containing a default argument is not
13424   // equivalent to any of the permitted forms.
13425   for (auto Param : FnDecl->parameters()) {
13426     if (Param->hasDefaultArg()) {
13427       Diag(Param->getDefaultArgRange().getBegin(),
13428            diag::err_literal_operator_default_argument)
13429         << Param->getDefaultArgRange();
13430       break;
13431     }
13432   }
13433 
13434   StringRef LiteralName
13435     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13436   if (LiteralName[0] != '_' &&
13437       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13438     // C++11 [usrlit.suffix]p1:
13439     //   Literal suffix identifiers that do not start with an underscore
13440     //   are reserved for future standardization.
13441     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13442       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13443   }
13444 
13445   return false;
13446 }
13447 
13448 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13449 /// linkage specification, including the language and (if present)
13450 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13451 /// language string literal. LBraceLoc, if valid, provides the location of
13452 /// the '{' brace. Otherwise, this linkage specification does not
13453 /// have any braces.
13454 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13455                                            Expr *LangStr,
13456                                            SourceLocation LBraceLoc) {
13457   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13458   if (!Lit->isAscii()) {
13459     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13460       << LangStr->getSourceRange();
13461     return nullptr;
13462   }
13463 
13464   StringRef Lang = Lit->getString();
13465   LinkageSpecDecl::LanguageIDs Language;
13466   if (Lang == "C")
13467     Language = LinkageSpecDecl::lang_c;
13468   else if (Lang == "C++")
13469     Language = LinkageSpecDecl::lang_cxx;
13470   else {
13471     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13472       << LangStr->getSourceRange();
13473     return nullptr;
13474   }
13475 
13476   // FIXME: Add all the various semantics of linkage specifications
13477 
13478   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13479                                                LangStr->getExprLoc(), Language,
13480                                                LBraceLoc.isValid());
13481   CurContext->addDecl(D);
13482   PushDeclContext(S, D);
13483   return D;
13484 }
13485 
13486 /// ActOnFinishLinkageSpecification - Complete the definition of
13487 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13488 /// valid, it's the position of the closing '}' brace in a linkage
13489 /// specification that uses braces.
13490 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13491                                             Decl *LinkageSpec,
13492                                             SourceLocation RBraceLoc) {
13493   if (RBraceLoc.isValid()) {
13494     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13495     LSDecl->setRBraceLoc(RBraceLoc);
13496   }
13497   PopDeclContext();
13498   return LinkageSpec;
13499 }
13500 
13501 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13502                                   AttributeList *AttrList,
13503                                   SourceLocation SemiLoc) {
13504   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13505   // Attribute declarations appertain to empty declaration so we handle
13506   // them here.
13507   if (AttrList)
13508     ProcessDeclAttributeList(S, ED, AttrList);
13509 
13510   CurContext->addDecl(ED);
13511   return ED;
13512 }
13513 
13514 /// Perform semantic analysis for the variable declaration that
13515 /// occurs within a C++ catch clause, returning the newly-created
13516 /// variable.
13517 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13518                                          TypeSourceInfo *TInfo,
13519                                          SourceLocation StartLoc,
13520                                          SourceLocation Loc,
13521                                          IdentifierInfo *Name) {
13522   bool Invalid = false;
13523   QualType ExDeclType = TInfo->getType();
13524 
13525   // Arrays and functions decay.
13526   if (ExDeclType->isArrayType())
13527     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13528   else if (ExDeclType->isFunctionType())
13529     ExDeclType = Context.getPointerType(ExDeclType);
13530 
13531   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13532   // The exception-declaration shall not denote a pointer or reference to an
13533   // incomplete type, other than [cv] void*.
13534   // N2844 forbids rvalue references.
13535   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13536     Diag(Loc, diag::err_catch_rvalue_ref);
13537     Invalid = true;
13538   }
13539 
13540   if (ExDeclType->isVariablyModifiedType()) {
13541     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13542     Invalid = true;
13543   }
13544 
13545   QualType BaseType = ExDeclType;
13546   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13547   unsigned DK = diag::err_catch_incomplete;
13548   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13549     BaseType = Ptr->getPointeeType();
13550     Mode = 1;
13551     DK = diag::err_catch_incomplete_ptr;
13552   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13553     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13554     BaseType = Ref->getPointeeType();
13555     Mode = 2;
13556     DK = diag::err_catch_incomplete_ref;
13557   }
13558   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13559       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13560     Invalid = true;
13561 
13562   if (!Invalid && !ExDeclType->isDependentType() &&
13563       RequireNonAbstractType(Loc, ExDeclType,
13564                              diag::err_abstract_type_in_decl,
13565                              AbstractVariableType))
13566     Invalid = true;
13567 
13568   // Only the non-fragile NeXT runtime currently supports C++ catches
13569   // of ObjC types, and no runtime supports catching ObjC types by value.
13570   if (!Invalid && getLangOpts().ObjC1) {
13571     QualType T = ExDeclType;
13572     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13573       T = RT->getPointeeType();
13574 
13575     if (T->isObjCObjectType()) {
13576       Diag(Loc, diag::err_objc_object_catch);
13577       Invalid = true;
13578     } else if (T->isObjCObjectPointerType()) {
13579       // FIXME: should this be a test for macosx-fragile specifically?
13580       if (getLangOpts().ObjCRuntime.isFragile())
13581         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13582     }
13583   }
13584 
13585   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13586                                     ExDeclType, TInfo, SC_None);
13587   ExDecl->setExceptionVariable(true);
13588 
13589   // In ARC, infer 'retaining' for variables of retainable type.
13590   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13591     Invalid = true;
13592 
13593   if (!Invalid && !ExDeclType->isDependentType()) {
13594     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13595       // Insulate this from anything else we might currently be parsing.
13596       EnterExpressionEvaluationContext scope(
13597           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13598 
13599       // C++ [except.handle]p16:
13600       //   The object declared in an exception-declaration or, if the
13601       //   exception-declaration does not specify a name, a temporary (12.2) is
13602       //   copy-initialized (8.5) from the exception object. [...]
13603       //   The object is destroyed when the handler exits, after the destruction
13604       //   of any automatic objects initialized within the handler.
13605       //
13606       // We just pretend to initialize the object with itself, then make sure
13607       // it can be destroyed later.
13608       QualType initType = Context.getExceptionObjectType(ExDeclType);
13609 
13610       InitializedEntity entity =
13611         InitializedEntity::InitializeVariable(ExDecl);
13612       InitializationKind initKind =
13613         InitializationKind::CreateCopy(Loc, SourceLocation());
13614 
13615       Expr *opaqueValue =
13616         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13617       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13618       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13619       if (result.isInvalid())
13620         Invalid = true;
13621       else {
13622         // If the constructor used was non-trivial, set this as the
13623         // "initializer".
13624         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13625         if (!construct->getConstructor()->isTrivial()) {
13626           Expr *init = MaybeCreateExprWithCleanups(construct);
13627           ExDecl->setInit(init);
13628         }
13629 
13630         // And make sure it's destructable.
13631         FinalizeVarWithDestructor(ExDecl, recordType);
13632       }
13633     }
13634   }
13635 
13636   if (Invalid)
13637     ExDecl->setInvalidDecl();
13638 
13639   return ExDecl;
13640 }
13641 
13642 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13643 /// handler.
13644 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13645   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13646   bool Invalid = D.isInvalidType();
13647 
13648   // Check for unexpanded parameter packs.
13649   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13650                                       UPPC_ExceptionType)) {
13651     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13652                                              D.getIdentifierLoc());
13653     Invalid = true;
13654   }
13655 
13656   IdentifierInfo *II = D.getIdentifier();
13657   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13658                                              LookupOrdinaryName,
13659                                              ForVisibleRedeclaration)) {
13660     // The scope should be freshly made just for us. There is just no way
13661     // it contains any previous declaration, except for function parameters in
13662     // a function-try-block's catch statement.
13663     assert(!S->isDeclScope(PrevDecl));
13664     if (isDeclInScope(PrevDecl, CurContext, S)) {
13665       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13666         << D.getIdentifier();
13667       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13668       Invalid = true;
13669     } else if (PrevDecl->isTemplateParameter())
13670       // Maybe we will complain about the shadowed template parameter.
13671       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13672   }
13673 
13674   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13675     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13676       << D.getCXXScopeSpec().getRange();
13677     Invalid = true;
13678   }
13679 
13680   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13681                                               D.getLocStart(),
13682                                               D.getIdentifierLoc(),
13683                                               D.getIdentifier());
13684   if (Invalid)
13685     ExDecl->setInvalidDecl();
13686 
13687   // Add the exception declaration into this scope.
13688   if (II)
13689     PushOnScopeChains(ExDecl, S);
13690   else
13691     CurContext->addDecl(ExDecl);
13692 
13693   ProcessDeclAttributes(S, ExDecl, D);
13694   return ExDecl;
13695 }
13696 
13697 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13698                                          Expr *AssertExpr,
13699                                          Expr *AssertMessageExpr,
13700                                          SourceLocation RParenLoc) {
13701   StringLiteral *AssertMessage =
13702       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13703 
13704   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13705     return nullptr;
13706 
13707   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13708                                       AssertMessage, RParenLoc, false);
13709 }
13710 
13711 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13712                                          Expr *AssertExpr,
13713                                          StringLiteral *AssertMessage,
13714                                          SourceLocation RParenLoc,
13715                                          bool Failed) {
13716   assert(AssertExpr != nullptr && "Expected non-null condition");
13717   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13718       !Failed) {
13719     // In a static_assert-declaration, the constant-expression shall be a
13720     // constant expression that can be contextually converted to bool.
13721     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13722     if (Converted.isInvalid())
13723       Failed = true;
13724 
13725     llvm::APSInt Cond;
13726     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13727           diag::err_static_assert_expression_is_not_constant,
13728           /*AllowFold=*/false).isInvalid())
13729       Failed = true;
13730 
13731     if (!Failed && !Cond) {
13732       SmallString<256> MsgBuffer;
13733       llvm::raw_svector_ostream Msg(MsgBuffer);
13734       if (AssertMessage)
13735         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13736 
13737       Expr *InnerCond = nullptr;
13738       std::string InnerCondDescription;
13739       std::tie(InnerCond, InnerCondDescription) =
13740         findFailedBooleanCondition(Converted.get(),
13741                                    /*AllowTopLevelCond=*/false);
13742       if (InnerCond) {
13743         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13744           << InnerCondDescription << !AssertMessage
13745           << Msg.str() << InnerCond->getSourceRange();
13746       } else {
13747         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13748           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13749       }
13750       Failed = true;
13751     }
13752   }
13753 
13754   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13755                                                   /*DiscardedValue*/false,
13756                                                   /*IsConstexpr*/true);
13757   if (FullAssertExpr.isInvalid())
13758     Failed = true;
13759   else
13760     AssertExpr = FullAssertExpr.get();
13761 
13762   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13763                                         AssertExpr, AssertMessage, RParenLoc,
13764                                         Failed);
13765 
13766   CurContext->addDecl(Decl);
13767   return Decl;
13768 }
13769 
13770 /// Perform semantic analysis of the given friend type declaration.
13771 ///
13772 /// \returns A friend declaration that.
13773 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13774                                       SourceLocation FriendLoc,
13775                                       TypeSourceInfo *TSInfo) {
13776   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13777 
13778   QualType T = TSInfo->getType();
13779   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13780 
13781   // C++03 [class.friend]p2:
13782   //   An elaborated-type-specifier shall be used in a friend declaration
13783   //   for a class.*
13784   //
13785   //   * The class-key of the elaborated-type-specifier is required.
13786   if (!CodeSynthesisContexts.empty()) {
13787     // Do not complain about the form of friend template types during any kind
13788     // of code synthesis. For template instantiation, we will have complained
13789     // when the template was defined.
13790   } else {
13791     if (!T->isElaboratedTypeSpecifier()) {
13792       // If we evaluated the type to a record type, suggest putting
13793       // a tag in front.
13794       if (const RecordType *RT = T->getAs<RecordType>()) {
13795         RecordDecl *RD = RT->getDecl();
13796 
13797         SmallString<16> InsertionText(" ");
13798         InsertionText += RD->getKindName();
13799 
13800         Diag(TypeRange.getBegin(),
13801              getLangOpts().CPlusPlus11 ?
13802                diag::warn_cxx98_compat_unelaborated_friend_type :
13803                diag::ext_unelaborated_friend_type)
13804           << (unsigned) RD->getTagKind()
13805           << T
13806           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13807                                         InsertionText);
13808       } else {
13809         Diag(FriendLoc,
13810              getLangOpts().CPlusPlus11 ?
13811                diag::warn_cxx98_compat_nonclass_type_friend :
13812                diag::ext_nonclass_type_friend)
13813           << T
13814           << TypeRange;
13815       }
13816     } else if (T->getAs<EnumType>()) {
13817       Diag(FriendLoc,
13818            getLangOpts().CPlusPlus11 ?
13819              diag::warn_cxx98_compat_enum_friend :
13820              diag::ext_enum_friend)
13821         << T
13822         << TypeRange;
13823     }
13824 
13825     // C++11 [class.friend]p3:
13826     //   A friend declaration that does not declare a function shall have one
13827     //   of the following forms:
13828     //     friend elaborated-type-specifier ;
13829     //     friend simple-type-specifier ;
13830     //     friend typename-specifier ;
13831     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13832       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13833   }
13834 
13835   //   If the type specifier in a friend declaration designates a (possibly
13836   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13837   //   the friend declaration is ignored.
13838   return FriendDecl::Create(Context, CurContext,
13839                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13840                             FriendLoc);
13841 }
13842 
13843 /// Handle a friend tag declaration where the scope specifier was
13844 /// templated.
13845 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13846                                     unsigned TagSpec, SourceLocation TagLoc,
13847                                     CXXScopeSpec &SS,
13848                                     IdentifierInfo *Name,
13849                                     SourceLocation NameLoc,
13850                                     AttributeList *Attr,
13851                                     MultiTemplateParamsArg TempParamLists) {
13852   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13853 
13854   bool IsMemberSpecialization = false;
13855   bool Invalid = false;
13856 
13857   if (TemplateParameterList *TemplateParams =
13858           MatchTemplateParametersToScopeSpecifier(
13859               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13860               IsMemberSpecialization, Invalid)) {
13861     if (TemplateParams->size() > 0) {
13862       // This is a declaration of a class template.
13863       if (Invalid)
13864         return nullptr;
13865 
13866       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13867                                 NameLoc, Attr, TemplateParams, AS_public,
13868                                 /*ModulePrivateLoc=*/SourceLocation(),
13869                                 FriendLoc, TempParamLists.size() - 1,
13870                                 TempParamLists.data()).get();
13871     } else {
13872       // The "template<>" header is extraneous.
13873       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13874         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13875       IsMemberSpecialization = true;
13876     }
13877   }
13878 
13879   if (Invalid) return nullptr;
13880 
13881   bool isAllExplicitSpecializations = true;
13882   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13883     if (TempParamLists[I]->size()) {
13884       isAllExplicitSpecializations = false;
13885       break;
13886     }
13887   }
13888 
13889   // FIXME: don't ignore attributes.
13890 
13891   // If it's explicit specializations all the way down, just forget
13892   // about the template header and build an appropriate non-templated
13893   // friend.  TODO: for source fidelity, remember the headers.
13894   if (isAllExplicitSpecializations) {
13895     if (SS.isEmpty()) {
13896       bool Owned = false;
13897       bool IsDependent = false;
13898       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13899                       Attr, AS_public,
13900                       /*ModulePrivateLoc=*/SourceLocation(),
13901                       MultiTemplateParamsArg(), Owned, IsDependent,
13902                       /*ScopedEnumKWLoc=*/SourceLocation(),
13903                       /*ScopedEnumUsesClassTag=*/false,
13904                       /*UnderlyingType=*/TypeResult(),
13905                       /*IsTypeSpecifier=*/false,
13906                       /*IsTemplateParamOrArg=*/false);
13907     }
13908 
13909     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13910     ElaboratedTypeKeyword Keyword
13911       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13912     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13913                                    *Name, NameLoc);
13914     if (T.isNull())
13915       return nullptr;
13916 
13917     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13918     if (isa<DependentNameType>(T)) {
13919       DependentNameTypeLoc TL =
13920           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13921       TL.setElaboratedKeywordLoc(TagLoc);
13922       TL.setQualifierLoc(QualifierLoc);
13923       TL.setNameLoc(NameLoc);
13924     } else {
13925       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13926       TL.setElaboratedKeywordLoc(TagLoc);
13927       TL.setQualifierLoc(QualifierLoc);
13928       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13929     }
13930 
13931     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13932                                             TSI, FriendLoc, TempParamLists);
13933     Friend->setAccess(AS_public);
13934     CurContext->addDecl(Friend);
13935     return Friend;
13936   }
13937 
13938   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13939 
13940 
13941 
13942   // Handle the case of a templated-scope friend class.  e.g.
13943   //   template <class T> class A<T>::B;
13944   // FIXME: we don't support these right now.
13945   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13946     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13947   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13948   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13949   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13950   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13951   TL.setElaboratedKeywordLoc(TagLoc);
13952   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13953   TL.setNameLoc(NameLoc);
13954 
13955   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13956                                           TSI, FriendLoc, TempParamLists);
13957   Friend->setAccess(AS_public);
13958   Friend->setUnsupportedFriend(true);
13959   CurContext->addDecl(Friend);
13960   return Friend;
13961 }
13962 
13963 
13964 /// Handle a friend type declaration.  This works in tandem with
13965 /// ActOnTag.
13966 ///
13967 /// Notes on friend class templates:
13968 ///
13969 /// We generally treat friend class declarations as if they were
13970 /// declaring a class.  So, for example, the elaborated type specifier
13971 /// in a friend declaration is required to obey the restrictions of a
13972 /// class-head (i.e. no typedefs in the scope chain), template
13973 /// parameters are required to match up with simple template-ids, &c.
13974 /// However, unlike when declaring a template specialization, it's
13975 /// okay to refer to a template specialization without an empty
13976 /// template parameter declaration, e.g.
13977 ///   friend class A<T>::B<unsigned>;
13978 /// We permit this as a special case; if there are any template
13979 /// parameters present at all, require proper matching, i.e.
13980 ///   template <> template \<class T> friend class A<int>::B;
13981 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13982                                 MultiTemplateParamsArg TempParams) {
13983   SourceLocation Loc = DS.getLocStart();
13984 
13985   assert(DS.isFriendSpecified());
13986   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13987 
13988   // Try to convert the decl specifier to a type.  This works for
13989   // friend templates because ActOnTag never produces a ClassTemplateDecl
13990   // for a TUK_Friend.
13991   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
13992   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13993   QualType T = TSI->getType();
13994   if (TheDeclarator.isInvalidType())
13995     return nullptr;
13996 
13997   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13998     return nullptr;
13999 
14000   // This is definitely an error in C++98.  It's probably meant to
14001   // be forbidden in C++0x, too, but the specification is just
14002   // poorly written.
14003   //
14004   // The problem is with declarations like the following:
14005   //   template <T> friend A<T>::foo;
14006   // where deciding whether a class C is a friend or not now hinges
14007   // on whether there exists an instantiation of A that causes
14008   // 'foo' to equal C.  There are restrictions on class-heads
14009   // (which we declare (by fiat) elaborated friend declarations to
14010   // be) that makes this tractable.
14011   //
14012   // FIXME: handle "template <> friend class A<T>;", which
14013   // is possibly well-formed?  Who even knows?
14014   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14015     Diag(Loc, diag::err_tagless_friend_type_template)
14016       << DS.getSourceRange();
14017     return nullptr;
14018   }
14019 
14020   // C++98 [class.friend]p1: A friend of a class is a function
14021   //   or class that is not a member of the class . . .
14022   // This is fixed in DR77, which just barely didn't make the C++03
14023   // deadline.  It's also a very silly restriction that seriously
14024   // affects inner classes and which nobody else seems to implement;
14025   // thus we never diagnose it, not even in -pedantic.
14026   //
14027   // But note that we could warn about it: it's always useless to
14028   // friend one of your own members (it's not, however, worthless to
14029   // friend a member of an arbitrary specialization of your template).
14030 
14031   Decl *D;
14032   if (!TempParams.empty())
14033     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14034                                    TempParams,
14035                                    TSI,
14036                                    DS.getFriendSpecLoc());
14037   else
14038     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14039 
14040   if (!D)
14041     return nullptr;
14042 
14043   D->setAccess(AS_public);
14044   CurContext->addDecl(D);
14045 
14046   return D;
14047 }
14048 
14049 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14050                                         MultiTemplateParamsArg TemplateParams) {
14051   const DeclSpec &DS = D.getDeclSpec();
14052 
14053   assert(DS.isFriendSpecified());
14054   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14055 
14056   SourceLocation Loc = D.getIdentifierLoc();
14057   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14058 
14059   // C++ [class.friend]p1
14060   //   A friend of a class is a function or class....
14061   // Note that this sees through typedefs, which is intended.
14062   // It *doesn't* see through dependent types, which is correct
14063   // according to [temp.arg.type]p3:
14064   //   If a declaration acquires a function type through a
14065   //   type dependent on a template-parameter and this causes
14066   //   a declaration that does not use the syntactic form of a
14067   //   function declarator to have a function type, the program
14068   //   is ill-formed.
14069   if (!TInfo->getType()->isFunctionType()) {
14070     Diag(Loc, diag::err_unexpected_friend);
14071 
14072     // It might be worthwhile to try to recover by creating an
14073     // appropriate declaration.
14074     return nullptr;
14075   }
14076 
14077   // C++ [namespace.memdef]p3
14078   //  - If a friend declaration in a non-local class first declares a
14079   //    class or function, the friend class or function is a member
14080   //    of the innermost enclosing namespace.
14081   //  - The name of the friend is not found by simple name lookup
14082   //    until a matching declaration is provided in that namespace
14083   //    scope (either before or after the class declaration granting
14084   //    friendship).
14085   //  - If a friend function is called, its name may be found by the
14086   //    name lookup that considers functions from namespaces and
14087   //    classes associated with the types of the function arguments.
14088   //  - When looking for a prior declaration of a class or a function
14089   //    declared as a friend, scopes outside the innermost enclosing
14090   //    namespace scope are not considered.
14091 
14092   CXXScopeSpec &SS = D.getCXXScopeSpec();
14093   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14094   DeclarationName Name = NameInfo.getName();
14095   assert(Name);
14096 
14097   // Check for unexpanded parameter packs.
14098   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14099       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14100       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14101     return nullptr;
14102 
14103   // The context we found the declaration in, or in which we should
14104   // create the declaration.
14105   DeclContext *DC;
14106   Scope *DCScope = S;
14107   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14108                         ForExternalRedeclaration);
14109 
14110   // There are five cases here.
14111   //   - There's no scope specifier and we're in a local class. Only look
14112   //     for functions declared in the immediately-enclosing block scope.
14113   // We recover from invalid scope qualifiers as if they just weren't there.
14114   FunctionDecl *FunctionContainingLocalClass = nullptr;
14115   if ((SS.isInvalid() || !SS.isSet()) &&
14116       (FunctionContainingLocalClass =
14117            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14118     // C++11 [class.friend]p11:
14119     //   If a friend declaration appears in a local class and the name
14120     //   specified is an unqualified name, a prior declaration is
14121     //   looked up without considering scopes that are outside the
14122     //   innermost enclosing non-class scope. For a friend function
14123     //   declaration, if there is no prior declaration, the program is
14124     //   ill-formed.
14125 
14126     // Find the innermost enclosing non-class scope. This is the block
14127     // scope containing the local class definition (or for a nested class,
14128     // the outer local class).
14129     DCScope = S->getFnParent();
14130 
14131     // Look up the function name in the scope.
14132     Previous.clear(LookupLocalFriendName);
14133     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14134 
14135     if (!Previous.empty()) {
14136       // All possible previous declarations must have the same context:
14137       // either they were declared at block scope or they are members of
14138       // one of the enclosing local classes.
14139       DC = Previous.getRepresentativeDecl()->getDeclContext();
14140     } else {
14141       // This is ill-formed, but provide the context that we would have
14142       // declared the function in, if we were permitted to, for error recovery.
14143       DC = FunctionContainingLocalClass;
14144     }
14145     adjustContextForLocalExternDecl(DC);
14146 
14147     // C++ [class.friend]p6:
14148     //   A function can be defined in a friend declaration of a class if and
14149     //   only if the class is a non-local class (9.8), the function name is
14150     //   unqualified, and the function has namespace scope.
14151     if (D.isFunctionDefinition()) {
14152       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14153     }
14154 
14155   //   - There's no scope specifier, in which case we just go to the
14156   //     appropriate scope and look for a function or function template
14157   //     there as appropriate.
14158   } else if (SS.isInvalid() || !SS.isSet()) {
14159     // C++11 [namespace.memdef]p3:
14160     //   If the name in a friend declaration is neither qualified nor
14161     //   a template-id and the declaration is a function or an
14162     //   elaborated-type-specifier, the lookup to determine whether
14163     //   the entity has been previously declared shall not consider
14164     //   any scopes outside the innermost enclosing namespace.
14165     bool isTemplateId =
14166         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14167 
14168     // Find the appropriate context according to the above.
14169     DC = CurContext;
14170 
14171     // Skip class contexts.  If someone can cite chapter and verse
14172     // for this behavior, that would be nice --- it's what GCC and
14173     // EDG do, and it seems like a reasonable intent, but the spec
14174     // really only says that checks for unqualified existing
14175     // declarations should stop at the nearest enclosing namespace,
14176     // not that they should only consider the nearest enclosing
14177     // namespace.
14178     while (DC->isRecord())
14179       DC = DC->getParent();
14180 
14181     DeclContext *LookupDC = DC;
14182     while (LookupDC->isTransparentContext())
14183       LookupDC = LookupDC->getParent();
14184 
14185     while (true) {
14186       LookupQualifiedName(Previous, LookupDC);
14187 
14188       if (!Previous.empty()) {
14189         DC = LookupDC;
14190         break;
14191       }
14192 
14193       if (isTemplateId) {
14194         if (isa<TranslationUnitDecl>(LookupDC)) break;
14195       } else {
14196         if (LookupDC->isFileContext()) break;
14197       }
14198       LookupDC = LookupDC->getParent();
14199     }
14200 
14201     DCScope = getScopeForDeclContext(S, DC);
14202 
14203   //   - There's a non-dependent scope specifier, in which case we
14204   //     compute it and do a previous lookup there for a function
14205   //     or function template.
14206   } else if (!SS.getScopeRep()->isDependent()) {
14207     DC = computeDeclContext(SS);
14208     if (!DC) return nullptr;
14209 
14210     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14211 
14212     LookupQualifiedName(Previous, DC);
14213 
14214     // Ignore things found implicitly in the wrong scope.
14215     // TODO: better diagnostics for this case.  Suggesting the right
14216     // qualified scope would be nice...
14217     LookupResult::Filter F = Previous.makeFilter();
14218     while (F.hasNext()) {
14219       NamedDecl *D = F.next();
14220       if (!DC->InEnclosingNamespaceSetOf(
14221               D->getDeclContext()->getRedeclContext()))
14222         F.erase();
14223     }
14224     F.done();
14225 
14226     if (Previous.empty()) {
14227       D.setInvalidType();
14228       Diag(Loc, diag::err_qualified_friend_not_found)
14229           << Name << TInfo->getType();
14230       return nullptr;
14231     }
14232 
14233     // C++ [class.friend]p1: A friend of a class is a function or
14234     //   class that is not a member of the class . . .
14235     if (DC->Equals(CurContext))
14236       Diag(DS.getFriendSpecLoc(),
14237            getLangOpts().CPlusPlus11 ?
14238              diag::warn_cxx98_compat_friend_is_member :
14239              diag::err_friend_is_member);
14240 
14241     if (D.isFunctionDefinition()) {
14242       // C++ [class.friend]p6:
14243       //   A function can be defined in a friend declaration of a class if and
14244       //   only if the class is a non-local class (9.8), the function name is
14245       //   unqualified, and the function has namespace scope.
14246       SemaDiagnosticBuilder DB
14247         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14248 
14249       DB << SS.getScopeRep();
14250       if (DC->isFileContext())
14251         DB << FixItHint::CreateRemoval(SS.getRange());
14252       SS.clear();
14253     }
14254 
14255   //   - There's a scope specifier that does not match any template
14256   //     parameter lists, in which case we use some arbitrary context,
14257   //     create a method or method template, and wait for instantiation.
14258   //   - There's a scope specifier that does match some template
14259   //     parameter lists, which we don't handle right now.
14260   } else {
14261     if (D.isFunctionDefinition()) {
14262       // C++ [class.friend]p6:
14263       //   A function can be defined in a friend declaration of a class if and
14264       //   only if the class is a non-local class (9.8), the function name is
14265       //   unqualified, and the function has namespace scope.
14266       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14267         << SS.getScopeRep();
14268     }
14269 
14270     DC = CurContext;
14271     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14272   }
14273 
14274   if (!DC->isRecord()) {
14275     int DiagArg = -1;
14276     switch (D.getName().getKind()) {
14277     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14278     case UnqualifiedIdKind::IK_ConstructorName:
14279       DiagArg = 0;
14280       break;
14281     case UnqualifiedIdKind::IK_DestructorName:
14282       DiagArg = 1;
14283       break;
14284     case UnqualifiedIdKind::IK_ConversionFunctionId:
14285       DiagArg = 2;
14286       break;
14287     case UnqualifiedIdKind::IK_DeductionGuideName:
14288       DiagArg = 3;
14289       break;
14290     case UnqualifiedIdKind::IK_Identifier:
14291     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14292     case UnqualifiedIdKind::IK_LiteralOperatorId:
14293     case UnqualifiedIdKind::IK_OperatorFunctionId:
14294     case UnqualifiedIdKind::IK_TemplateId:
14295       break;
14296     }
14297     // This implies that it has to be an operator or function.
14298     if (DiagArg >= 0) {
14299       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14300       return nullptr;
14301     }
14302   }
14303 
14304   // FIXME: This is an egregious hack to cope with cases where the scope stack
14305   // does not contain the declaration context, i.e., in an out-of-line
14306   // definition of a class.
14307   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14308   if (!DCScope) {
14309     FakeDCScope.setEntity(DC);
14310     DCScope = &FakeDCScope;
14311   }
14312 
14313   bool AddToScope = true;
14314   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14315                                           TemplateParams, AddToScope);
14316   if (!ND) return nullptr;
14317 
14318   assert(ND->getLexicalDeclContext() == CurContext);
14319 
14320   // If we performed typo correction, we might have added a scope specifier
14321   // and changed the decl context.
14322   DC = ND->getDeclContext();
14323 
14324   // Add the function declaration to the appropriate lookup tables,
14325   // adjusting the redeclarations list as necessary.  We don't
14326   // want to do this yet if the friending class is dependent.
14327   //
14328   // Also update the scope-based lookup if the target context's
14329   // lookup context is in lexical scope.
14330   if (!CurContext->isDependentContext()) {
14331     DC = DC->getRedeclContext();
14332     DC->makeDeclVisibleInContext(ND);
14333     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14334       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14335   }
14336 
14337   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14338                                        D.getIdentifierLoc(), ND,
14339                                        DS.getFriendSpecLoc());
14340   FrD->setAccess(AS_public);
14341   CurContext->addDecl(FrD);
14342 
14343   if (ND->isInvalidDecl()) {
14344     FrD->setInvalidDecl();
14345   } else {
14346     if (DC->isRecord()) CheckFriendAccess(ND);
14347 
14348     FunctionDecl *FD;
14349     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14350       FD = FTD->getTemplatedDecl();
14351     else
14352       FD = cast<FunctionDecl>(ND);
14353 
14354     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14355     // default argument expression, that declaration shall be a definition
14356     // and shall be the only declaration of the function or function
14357     // template in the translation unit.
14358     if (functionDeclHasDefaultArgument(FD)) {
14359       // We can't look at FD->getPreviousDecl() because it may not have been set
14360       // if we're in a dependent context. If the function is known to be a
14361       // redeclaration, we will have narrowed Previous down to the right decl.
14362       if (D.isRedeclaration()) {
14363         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14364         Diag(Previous.getRepresentativeDecl()->getLocation(),
14365              diag::note_previous_declaration);
14366       } else if (!D.isFunctionDefinition())
14367         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14368     }
14369 
14370     // Mark templated-scope function declarations as unsupported.
14371     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14372       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14373         << SS.getScopeRep() << SS.getRange()
14374         << cast<CXXRecordDecl>(CurContext);
14375       FrD->setUnsupportedFriend(true);
14376     }
14377   }
14378 
14379   return ND;
14380 }
14381 
14382 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14383   AdjustDeclIfTemplate(Dcl);
14384 
14385   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14386   if (!Fn) {
14387     Diag(DelLoc, diag::err_deleted_non_function);
14388     return;
14389   }
14390 
14391   // Deleted function does not have a body.
14392   Fn->setWillHaveBody(false);
14393 
14394   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14395     // Don't consider the implicit declaration we generate for explicit
14396     // specializations. FIXME: Do not generate these implicit declarations.
14397     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14398          Prev->getPreviousDecl()) &&
14399         !Prev->isDefined()) {
14400       Diag(DelLoc, diag::err_deleted_decl_not_first);
14401       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14402            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14403                               : diag::note_previous_declaration);
14404     }
14405     // If the declaration wasn't the first, we delete the function anyway for
14406     // recovery.
14407     Fn = Fn->getCanonicalDecl();
14408   }
14409 
14410   // dllimport/dllexport cannot be deleted.
14411   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14412     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14413     Fn->setInvalidDecl();
14414   }
14415 
14416   if (Fn->isDeleted())
14417     return;
14418 
14419   // See if we're deleting a function which is already known to override a
14420   // non-deleted virtual function.
14421   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14422     bool IssuedDiagnostic = false;
14423     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14424       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14425         if (!IssuedDiagnostic) {
14426           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14427           IssuedDiagnostic = true;
14428         }
14429         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14430       }
14431     }
14432     // If this function was implicitly deleted because it was defaulted,
14433     // explain why it was deleted.
14434     if (IssuedDiagnostic && MD->isDefaulted())
14435       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14436                                 /*Diagnose*/true);
14437   }
14438 
14439   // C++11 [basic.start.main]p3:
14440   //   A program that defines main as deleted [...] is ill-formed.
14441   if (Fn->isMain())
14442     Diag(DelLoc, diag::err_deleted_main);
14443 
14444   // C++11 [dcl.fct.def.delete]p4:
14445   //  A deleted function is implicitly inline.
14446   Fn->setImplicitlyInline();
14447   Fn->setDeletedAsWritten();
14448 }
14449 
14450 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14451   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14452 
14453   if (MD) {
14454     if (MD->getParent()->isDependentType()) {
14455       MD->setDefaulted();
14456       MD->setExplicitlyDefaulted();
14457       return;
14458     }
14459 
14460     CXXSpecialMember Member = getSpecialMember(MD);
14461     if (Member == CXXInvalid) {
14462       if (!MD->isInvalidDecl())
14463         Diag(DefaultLoc, diag::err_default_special_members);
14464       return;
14465     }
14466 
14467     MD->setDefaulted();
14468     MD->setExplicitlyDefaulted();
14469 
14470     // Unset that we will have a body for this function. We might not,
14471     // if it turns out to be trivial, and we don't need this marking now
14472     // that we've marked it as defaulted.
14473     MD->setWillHaveBody(false);
14474 
14475     // If this definition appears within the record, do the checking when
14476     // the record is complete.
14477     const FunctionDecl *Primary = MD;
14478     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14479       // Ask the template instantiation pattern that actually had the
14480       // '= default' on it.
14481       Primary = Pattern;
14482 
14483     // If the method was defaulted on its first declaration, we will have
14484     // already performed the checking in CheckCompletedCXXClass. Such a
14485     // declaration doesn't trigger an implicit definition.
14486     if (Primary->getCanonicalDecl()->isDefaulted())
14487       return;
14488 
14489     CheckExplicitlyDefaultedSpecialMember(MD);
14490 
14491     if (!MD->isInvalidDecl())
14492       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14493   } else {
14494     Diag(DefaultLoc, diag::err_default_special_members);
14495   }
14496 }
14497 
14498 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14499   for (Stmt *SubStmt : S->children()) {
14500     if (!SubStmt)
14501       continue;
14502     if (isa<ReturnStmt>(SubStmt))
14503       Self.Diag(SubStmt->getLocStart(),
14504            diag::err_return_in_constructor_handler);
14505     if (!isa<Expr>(SubStmt))
14506       SearchForReturnInStmt(Self, SubStmt);
14507   }
14508 }
14509 
14510 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14511   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14512     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14513     SearchForReturnInStmt(*this, Handler);
14514   }
14515 }
14516 
14517 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14518                                              const CXXMethodDecl *Old) {
14519   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14520   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14521 
14522   if (OldFT->hasExtParameterInfos()) {
14523     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14524       // A parameter of the overriding method should be annotated with noescape
14525       // if the corresponding parameter of the overridden method is annotated.
14526       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14527           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14528         Diag(New->getParamDecl(I)->getLocation(),
14529              diag::warn_overriding_method_missing_noescape);
14530         Diag(Old->getParamDecl(I)->getLocation(),
14531              diag::note_overridden_marked_noescape);
14532       }
14533   }
14534 
14535   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14536 
14537   // If the calling conventions match, everything is fine
14538   if (NewCC == OldCC)
14539     return false;
14540 
14541   // If the calling conventions mismatch because the new function is static,
14542   // suppress the calling convention mismatch error; the error about static
14543   // function override (err_static_overrides_virtual from
14544   // Sema::CheckFunctionDeclaration) is more clear.
14545   if (New->getStorageClass() == SC_Static)
14546     return false;
14547 
14548   Diag(New->getLocation(),
14549        diag::err_conflicting_overriding_cc_attributes)
14550     << New->getDeclName() << New->getType() << Old->getType();
14551   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14552   return true;
14553 }
14554 
14555 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14556                                              const CXXMethodDecl *Old) {
14557   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14558   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14559 
14560   if (Context.hasSameType(NewTy, OldTy) ||
14561       NewTy->isDependentType() || OldTy->isDependentType())
14562     return false;
14563 
14564   // Check if the return types are covariant
14565   QualType NewClassTy, OldClassTy;
14566 
14567   /// Both types must be pointers or references to classes.
14568   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14569     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14570       NewClassTy = NewPT->getPointeeType();
14571       OldClassTy = OldPT->getPointeeType();
14572     }
14573   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14574     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14575       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14576         NewClassTy = NewRT->getPointeeType();
14577         OldClassTy = OldRT->getPointeeType();
14578       }
14579     }
14580   }
14581 
14582   // The return types aren't either both pointers or references to a class type.
14583   if (NewClassTy.isNull()) {
14584     Diag(New->getLocation(),
14585          diag::err_different_return_type_for_overriding_virtual_function)
14586         << New->getDeclName() << NewTy << OldTy
14587         << New->getReturnTypeSourceRange();
14588     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14589         << Old->getReturnTypeSourceRange();
14590 
14591     return true;
14592   }
14593 
14594   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14595     // C++14 [class.virtual]p8:
14596     //   If the class type in the covariant return type of D::f differs from
14597     //   that of B::f, the class type in the return type of D::f shall be
14598     //   complete at the point of declaration of D::f or shall be the class
14599     //   type D.
14600     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14601       if (!RT->isBeingDefined() &&
14602           RequireCompleteType(New->getLocation(), NewClassTy,
14603                               diag::err_covariant_return_incomplete,
14604                               New->getDeclName()))
14605         return true;
14606     }
14607 
14608     // Check if the new class derives from the old class.
14609     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14610       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14611           << New->getDeclName() << NewTy << OldTy
14612           << New->getReturnTypeSourceRange();
14613       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14614           << Old->getReturnTypeSourceRange();
14615       return true;
14616     }
14617 
14618     // Check if we the conversion from derived to base is valid.
14619     if (CheckDerivedToBaseConversion(
14620             NewClassTy, OldClassTy,
14621             diag::err_covariant_return_inaccessible_base,
14622             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14623             New->getLocation(), New->getReturnTypeSourceRange(),
14624             New->getDeclName(), nullptr)) {
14625       // FIXME: this note won't trigger for delayed access control
14626       // diagnostics, and it's impossible to get an undelayed error
14627       // here from access control during the original parse because
14628       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14629       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14630           << Old->getReturnTypeSourceRange();
14631       return true;
14632     }
14633   }
14634 
14635   // The qualifiers of the return types must be the same.
14636   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14637     Diag(New->getLocation(),
14638          diag::err_covariant_return_type_different_qualifications)
14639         << New->getDeclName() << NewTy << OldTy
14640         << New->getReturnTypeSourceRange();
14641     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14642         << Old->getReturnTypeSourceRange();
14643     return true;
14644   }
14645 
14646 
14647   // The new class type must have the same or less qualifiers as the old type.
14648   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14649     Diag(New->getLocation(),
14650          diag::err_covariant_return_type_class_type_more_qualified)
14651         << New->getDeclName() << NewTy << OldTy
14652         << New->getReturnTypeSourceRange();
14653     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14654         << Old->getReturnTypeSourceRange();
14655     return true;
14656   }
14657 
14658   return false;
14659 }
14660 
14661 /// Mark the given method pure.
14662 ///
14663 /// \param Method the method to be marked pure.
14664 ///
14665 /// \param InitRange the source range that covers the "0" initializer.
14666 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14667   SourceLocation EndLoc = InitRange.getEnd();
14668   if (EndLoc.isValid())
14669     Method->setRangeEnd(EndLoc);
14670 
14671   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14672     Method->setPure();
14673     return false;
14674   }
14675 
14676   if (!Method->isInvalidDecl())
14677     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14678       << Method->getDeclName() << InitRange;
14679   return true;
14680 }
14681 
14682 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14683   if (D->getFriendObjectKind())
14684     Diag(D->getLocation(), diag::err_pure_friend);
14685   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14686     CheckPureMethod(M, ZeroLoc);
14687   else
14688     Diag(D->getLocation(), diag::err_illegal_initializer);
14689 }
14690 
14691 /// Determine whether the given declaration is a global variable or
14692 /// static data member.
14693 static bool isNonlocalVariable(const Decl *D) {
14694   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14695     return Var->hasGlobalStorage();
14696 
14697   return false;
14698 }
14699 
14700 /// Invoked when we are about to parse an initializer for the declaration
14701 /// 'Dcl'.
14702 ///
14703 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14704 /// static data member of class X, names should be looked up in the scope of
14705 /// class X. If the declaration had a scope specifier, a scope will have
14706 /// been created and passed in for this purpose. Otherwise, S will be null.
14707 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14708   // If there is no declaration, there was an error parsing it.
14709   if (!D || D->isInvalidDecl())
14710     return;
14711 
14712   // We will always have a nested name specifier here, but this declaration
14713   // might not be out of line if the specifier names the current namespace:
14714   //   extern int n;
14715   //   int ::n = 0;
14716   if (S && D->isOutOfLine())
14717     EnterDeclaratorContext(S, D->getDeclContext());
14718 
14719   // If we are parsing the initializer for a static data member, push a
14720   // new expression evaluation context that is associated with this static
14721   // data member.
14722   if (isNonlocalVariable(D))
14723     PushExpressionEvaluationContext(
14724         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14725 }
14726 
14727 /// Invoked after we are finished parsing an initializer for the declaration D.
14728 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14729   // If there is no declaration, there was an error parsing it.
14730   if (!D || D->isInvalidDecl())
14731     return;
14732 
14733   if (isNonlocalVariable(D))
14734     PopExpressionEvaluationContext();
14735 
14736   if (S && D->isOutOfLine())
14737     ExitDeclaratorContext(S);
14738 }
14739 
14740 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14741 /// C++ if/switch/while/for statement.
14742 /// e.g: "if (int x = f()) {...}"
14743 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14744   // C++ 6.4p2:
14745   // The declarator shall not specify a function or an array.
14746   // The type-specifier-seq shall not contain typedef and shall not declare a
14747   // new class or enumeration.
14748   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14749          "Parser allowed 'typedef' as storage class of condition decl.");
14750 
14751   Decl *Dcl = ActOnDeclarator(S, D);
14752   if (!Dcl)
14753     return true;
14754 
14755   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14756     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14757       << D.getSourceRange();
14758     return true;
14759   }
14760 
14761   return Dcl;
14762 }
14763 
14764 void Sema::LoadExternalVTableUses() {
14765   if (!ExternalSource)
14766     return;
14767 
14768   SmallVector<ExternalVTableUse, 4> VTables;
14769   ExternalSource->ReadUsedVTables(VTables);
14770   SmallVector<VTableUse, 4> NewUses;
14771   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14772     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14773       = VTablesUsed.find(VTables[I].Record);
14774     // Even if a definition wasn't required before, it may be required now.
14775     if (Pos != VTablesUsed.end()) {
14776       if (!Pos->second && VTables[I].DefinitionRequired)
14777         Pos->second = true;
14778       continue;
14779     }
14780 
14781     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14782     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14783   }
14784 
14785   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14786 }
14787 
14788 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14789                           bool DefinitionRequired) {
14790   // Ignore any vtable uses in unevaluated operands or for classes that do
14791   // not have a vtable.
14792   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14793       CurContext->isDependentContext() || isUnevaluatedContext())
14794     return;
14795 
14796   // Try to insert this class into the map.
14797   LoadExternalVTableUses();
14798   Class = Class->getCanonicalDecl();
14799   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14800     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14801   if (!Pos.second) {
14802     // If we already had an entry, check to see if we are promoting this vtable
14803     // to require a definition. If so, we need to reappend to the VTableUses
14804     // list, since we may have already processed the first entry.
14805     if (DefinitionRequired && !Pos.first->second) {
14806       Pos.first->second = true;
14807     } else {
14808       // Otherwise, we can early exit.
14809       return;
14810     }
14811   } else {
14812     // The Microsoft ABI requires that we perform the destructor body
14813     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14814     // the deleting destructor is emitted with the vtable, not with the
14815     // destructor definition as in the Itanium ABI.
14816     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14817       CXXDestructorDecl *DD = Class->getDestructor();
14818       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14819         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14820           // If this is an out-of-line declaration, marking it referenced will
14821           // not do anything. Manually call CheckDestructor to look up operator
14822           // delete().
14823           ContextRAII SavedContext(*this, DD);
14824           CheckDestructor(DD);
14825         } else {
14826           MarkFunctionReferenced(Loc, Class->getDestructor());
14827         }
14828       }
14829     }
14830   }
14831 
14832   // Local classes need to have their virtual members marked
14833   // immediately. For all other classes, we mark their virtual members
14834   // at the end of the translation unit.
14835   if (Class->isLocalClass())
14836     MarkVirtualMembersReferenced(Loc, Class);
14837   else
14838     VTableUses.push_back(std::make_pair(Class, Loc));
14839 }
14840 
14841 bool Sema::DefineUsedVTables() {
14842   LoadExternalVTableUses();
14843   if (VTableUses.empty())
14844     return false;
14845 
14846   // Note: The VTableUses vector could grow as a result of marking
14847   // the members of a class as "used", so we check the size each
14848   // time through the loop and prefer indices (which are stable) to
14849   // iterators (which are not).
14850   bool DefinedAnything = false;
14851   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14852     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14853     if (!Class)
14854       continue;
14855     TemplateSpecializationKind ClassTSK =
14856         Class->getTemplateSpecializationKind();
14857 
14858     SourceLocation Loc = VTableUses[I].second;
14859 
14860     bool DefineVTable = true;
14861 
14862     // If this class has a key function, but that key function is
14863     // defined in another translation unit, we don't need to emit the
14864     // vtable even though we're using it.
14865     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14866     if (KeyFunction && !KeyFunction->hasBody()) {
14867       // The key function is in another translation unit.
14868       DefineVTable = false;
14869       TemplateSpecializationKind TSK =
14870           KeyFunction->getTemplateSpecializationKind();
14871       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14872              TSK != TSK_ImplicitInstantiation &&
14873              "Instantiations don't have key functions");
14874       (void)TSK;
14875     } else if (!KeyFunction) {
14876       // If we have a class with no key function that is the subject
14877       // of an explicit instantiation declaration, suppress the
14878       // vtable; it will live with the explicit instantiation
14879       // definition.
14880       bool IsExplicitInstantiationDeclaration =
14881           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14882       for (auto R : Class->redecls()) {
14883         TemplateSpecializationKind TSK
14884           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14885         if (TSK == TSK_ExplicitInstantiationDeclaration)
14886           IsExplicitInstantiationDeclaration = true;
14887         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14888           IsExplicitInstantiationDeclaration = false;
14889           break;
14890         }
14891       }
14892 
14893       if (IsExplicitInstantiationDeclaration)
14894         DefineVTable = false;
14895     }
14896 
14897     // The exception specifications for all virtual members may be needed even
14898     // if we are not providing an authoritative form of the vtable in this TU.
14899     // We may choose to emit it available_externally anyway.
14900     if (!DefineVTable) {
14901       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14902       continue;
14903     }
14904 
14905     // Mark all of the virtual members of this class as referenced, so
14906     // that we can build a vtable. Then, tell the AST consumer that a
14907     // vtable for this class is required.
14908     DefinedAnything = true;
14909     MarkVirtualMembersReferenced(Loc, Class);
14910     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
14911     if (VTablesUsed[Canonical])
14912       Consumer.HandleVTable(Class);
14913 
14914     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14915     // no key function or the key function is inlined. Don't warn in C++ ABIs
14916     // that lack key functions, since the user won't be able to make one.
14917     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14918         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14919       const FunctionDecl *KeyFunctionDef = nullptr;
14920       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14921                            KeyFunctionDef->isInlined())) {
14922         Diag(Class->getLocation(),
14923              ClassTSK == TSK_ExplicitInstantiationDefinition
14924                  ? diag::warn_weak_template_vtable
14925                  : diag::warn_weak_vtable)
14926             << Class;
14927       }
14928     }
14929   }
14930   VTableUses.clear();
14931 
14932   return DefinedAnything;
14933 }
14934 
14935 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14936                                                  const CXXRecordDecl *RD) {
14937   for (const auto *I : RD->methods())
14938     if (I->isVirtual() && !I->isPure())
14939       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14940 }
14941 
14942 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14943                                         const CXXRecordDecl *RD) {
14944   // Mark all functions which will appear in RD's vtable as used.
14945   CXXFinalOverriderMap FinalOverriders;
14946   RD->getFinalOverriders(FinalOverriders);
14947   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14948                                             E = FinalOverriders.end();
14949        I != E; ++I) {
14950     for (OverridingMethods::const_iterator OI = I->second.begin(),
14951                                            OE = I->second.end();
14952          OI != OE; ++OI) {
14953       assert(OI->second.size() > 0 && "no final overrider");
14954       CXXMethodDecl *Overrider = OI->second.front().Method;
14955 
14956       // C++ [basic.def.odr]p2:
14957       //   [...] A virtual member function is used if it is not pure. [...]
14958       if (!Overrider->isPure())
14959         MarkFunctionReferenced(Loc, Overrider);
14960     }
14961   }
14962 
14963   // Only classes that have virtual bases need a VTT.
14964   if (RD->getNumVBases() == 0)
14965     return;
14966 
14967   for (const auto &I : RD->bases()) {
14968     const CXXRecordDecl *Base =
14969         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14970     if (Base->getNumVBases() == 0)
14971       continue;
14972     MarkVirtualMembersReferenced(Loc, Base);
14973   }
14974 }
14975 
14976 /// SetIvarInitializers - This routine builds initialization ASTs for the
14977 /// Objective-C implementation whose ivars need be initialized.
14978 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14979   if (!getLangOpts().CPlusPlus)
14980     return;
14981   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14982     SmallVector<ObjCIvarDecl*, 8> ivars;
14983     CollectIvarsToConstructOrDestruct(OID, ivars);
14984     if (ivars.empty())
14985       return;
14986     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14987     for (unsigned i = 0; i < ivars.size(); i++) {
14988       FieldDecl *Field = ivars[i];
14989       if (Field->isInvalidDecl())
14990         continue;
14991 
14992       CXXCtorInitializer *Member;
14993       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14994       InitializationKind InitKind =
14995         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14996 
14997       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14998       ExprResult MemberInit =
14999         InitSeq.Perform(*this, InitEntity, InitKind, None);
15000       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15001       // Note, MemberInit could actually come back empty if no initialization
15002       // is required (e.g., because it would call a trivial default constructor)
15003       if (!MemberInit.get() || MemberInit.isInvalid())
15004         continue;
15005 
15006       Member =
15007         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15008                                          SourceLocation(),
15009                                          MemberInit.getAs<Expr>(),
15010                                          SourceLocation());
15011       AllToInit.push_back(Member);
15012 
15013       // Be sure that the destructor is accessible and is marked as referenced.
15014       if (const RecordType *RecordTy =
15015               Context.getBaseElementType(Field->getType())
15016                   ->getAs<RecordType>()) {
15017         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15018         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15019           MarkFunctionReferenced(Field->getLocation(), Destructor);
15020           CheckDestructorAccess(Field->getLocation(), Destructor,
15021                             PDiag(diag::err_access_dtor_ivar)
15022                               << Context.getBaseElementType(Field->getType()));
15023         }
15024       }
15025     }
15026     ObjCImplementation->setIvarInitializers(Context,
15027                                             AllToInit.data(), AllToInit.size());
15028   }
15029 }
15030 
15031 static
15032 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15033                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
15034                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
15035                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
15036                            Sema &S) {
15037   if (Ctor->isInvalidDecl())
15038     return;
15039 
15040   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15041 
15042   // Target may not be determinable yet, for instance if this is a dependent
15043   // call in an uninstantiated template.
15044   if (Target) {
15045     const FunctionDecl *FNTarget = nullptr;
15046     (void)Target->hasBody(FNTarget);
15047     Target = const_cast<CXXConstructorDecl*>(
15048       cast_or_null<CXXConstructorDecl>(FNTarget));
15049   }
15050 
15051   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15052                      // Avoid dereferencing a null pointer here.
15053                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15054 
15055   if (!Current.insert(Canonical).second)
15056     return;
15057 
15058   // We know that beyond here, we aren't chaining into a cycle.
15059   if (!Target || !Target->isDelegatingConstructor() ||
15060       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15061     Valid.insert(Current.begin(), Current.end());
15062     Current.clear();
15063   // We've hit a cycle.
15064   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15065              Current.count(TCanonical)) {
15066     // If we haven't diagnosed this cycle yet, do so now.
15067     if (!Invalid.count(TCanonical)) {
15068       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15069              diag::warn_delegating_ctor_cycle)
15070         << Ctor;
15071 
15072       // Don't add a note for a function delegating directly to itself.
15073       if (TCanonical != Canonical)
15074         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15075 
15076       CXXConstructorDecl *C = Target;
15077       while (C->getCanonicalDecl() != Canonical) {
15078         const FunctionDecl *FNTarget = nullptr;
15079         (void)C->getTargetConstructor()->hasBody(FNTarget);
15080         assert(FNTarget && "Ctor cycle through bodiless function");
15081 
15082         C = const_cast<CXXConstructorDecl*>(
15083           cast<CXXConstructorDecl>(FNTarget));
15084         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15085       }
15086     }
15087 
15088     Invalid.insert(Current.begin(), Current.end());
15089     Current.clear();
15090   } else {
15091     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15092   }
15093 }
15094 
15095 
15096 void Sema::CheckDelegatingCtorCycles() {
15097   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15098 
15099   for (DelegatingCtorDeclsType::iterator
15100          I = DelegatingCtorDecls.begin(ExternalSource),
15101          E = DelegatingCtorDecls.end();
15102        I != E; ++I)
15103     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15104 
15105   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
15106                                                          CE = Invalid.end();
15107        CI != CE; ++CI)
15108     (*CI)->setInvalidDecl();
15109 }
15110 
15111 namespace {
15112   /// AST visitor that finds references to the 'this' expression.
15113   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15114     Sema &S;
15115 
15116   public:
15117     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15118 
15119     bool VisitCXXThisExpr(CXXThisExpr *E) {
15120       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15121         << E->isImplicit();
15122       return false;
15123     }
15124   };
15125 }
15126 
15127 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15128   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15129   if (!TSInfo)
15130     return false;
15131 
15132   TypeLoc TL = TSInfo->getTypeLoc();
15133   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15134   if (!ProtoTL)
15135     return false;
15136 
15137   // C++11 [expr.prim.general]p3:
15138   //   [The expression this] shall not appear before the optional
15139   //   cv-qualifier-seq and it shall not appear within the declaration of a
15140   //   static member function (although its type and value category are defined
15141   //   within a static member function as they are within a non-static member
15142   //   function). [ Note: this is because declaration matching does not occur
15143   //  until the complete declarator is known. - end note ]
15144   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15145   FindCXXThisExpr Finder(*this);
15146 
15147   // If the return type came after the cv-qualifier-seq, check it now.
15148   if (Proto->hasTrailingReturn() &&
15149       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15150     return true;
15151 
15152   // Check the exception specification.
15153   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15154     return true;
15155 
15156   return checkThisInStaticMemberFunctionAttributes(Method);
15157 }
15158 
15159 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15160   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15161   if (!TSInfo)
15162     return false;
15163 
15164   TypeLoc TL = TSInfo->getTypeLoc();
15165   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15166   if (!ProtoTL)
15167     return false;
15168 
15169   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15170   FindCXXThisExpr Finder(*this);
15171 
15172   switch (Proto->getExceptionSpecType()) {
15173   case EST_Unparsed:
15174   case EST_Uninstantiated:
15175   case EST_Unevaluated:
15176   case EST_BasicNoexcept:
15177   case EST_DynamicNone:
15178   case EST_MSAny:
15179   case EST_None:
15180     break;
15181 
15182   case EST_DependentNoexcept:
15183   case EST_NoexceptFalse:
15184   case EST_NoexceptTrue:
15185     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15186       return true;
15187     LLVM_FALLTHROUGH;
15188 
15189   case EST_Dynamic:
15190     for (const auto &E : Proto->exceptions()) {
15191       if (!Finder.TraverseType(E))
15192         return true;
15193     }
15194     break;
15195   }
15196 
15197   return false;
15198 }
15199 
15200 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15201   FindCXXThisExpr Finder(*this);
15202 
15203   // Check attributes.
15204   for (const auto *A : Method->attrs()) {
15205     // FIXME: This should be emitted by tblgen.
15206     Expr *Arg = nullptr;
15207     ArrayRef<Expr *> Args;
15208     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15209       Arg = G->getArg();
15210     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15211       Arg = G->getArg();
15212     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15213       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15214     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15215       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15216     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15217       Arg = ETLF->getSuccessValue();
15218       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15219     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15220       Arg = STLF->getSuccessValue();
15221       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15222     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15223       Arg = LR->getArg();
15224     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15225       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15226     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15227       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15228     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15229       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15230     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15231       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15232     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15233       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15234 
15235     if (Arg && !Finder.TraverseStmt(Arg))
15236       return true;
15237 
15238     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15239       if (!Finder.TraverseStmt(Args[I]))
15240         return true;
15241     }
15242   }
15243 
15244   return false;
15245 }
15246 
15247 void Sema::checkExceptionSpecification(
15248     bool IsTopLevel, ExceptionSpecificationType EST,
15249     ArrayRef<ParsedType> DynamicExceptions,
15250     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15251     SmallVectorImpl<QualType> &Exceptions,
15252     FunctionProtoType::ExceptionSpecInfo &ESI) {
15253   Exceptions.clear();
15254   ESI.Type = EST;
15255   if (EST == EST_Dynamic) {
15256     Exceptions.reserve(DynamicExceptions.size());
15257     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15258       // FIXME: Preserve type source info.
15259       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15260 
15261       if (IsTopLevel) {
15262         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15263         collectUnexpandedParameterPacks(ET, Unexpanded);
15264         if (!Unexpanded.empty()) {
15265           DiagnoseUnexpandedParameterPacks(
15266               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15267               Unexpanded);
15268           continue;
15269         }
15270       }
15271 
15272       // Check that the type is valid for an exception spec, and
15273       // drop it if not.
15274       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15275         Exceptions.push_back(ET);
15276     }
15277     ESI.Exceptions = Exceptions;
15278     return;
15279   }
15280 
15281   if (isComputedNoexcept(EST)) {
15282     assert((NoexceptExpr->isTypeDependent() ||
15283             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15284             Context.BoolTy) &&
15285            "Parser should have made sure that the expression is boolean");
15286     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15287       ESI.Type = EST_BasicNoexcept;
15288       return;
15289     }
15290 
15291     ESI.NoexceptExpr = NoexceptExpr;
15292     return;
15293   }
15294 }
15295 
15296 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15297              ExceptionSpecificationType EST,
15298              SourceRange SpecificationRange,
15299              ArrayRef<ParsedType> DynamicExceptions,
15300              ArrayRef<SourceRange> DynamicExceptionRanges,
15301              Expr *NoexceptExpr) {
15302   if (!MethodD)
15303     return;
15304 
15305   // Dig out the method we're referring to.
15306   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15307     MethodD = FunTmpl->getTemplatedDecl();
15308 
15309   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15310   if (!Method)
15311     return;
15312 
15313   // Check the exception specification.
15314   llvm::SmallVector<QualType, 4> Exceptions;
15315   FunctionProtoType::ExceptionSpecInfo ESI;
15316   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15317                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15318                               ESI);
15319 
15320   // Update the exception specification on the function type.
15321   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15322 
15323   if (Method->isStatic())
15324     checkThisInStaticMemberFunctionExceptionSpec(Method);
15325 
15326   if (Method->isVirtual()) {
15327     // Check overrides, which we previously had to delay.
15328     for (const CXXMethodDecl *O : Method->overridden_methods())
15329       CheckOverridingFunctionExceptionSpec(Method, O);
15330   }
15331 }
15332 
15333 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15334 ///
15335 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15336                                        SourceLocation DeclStart,
15337                                        Declarator &D, Expr *BitWidth,
15338                                        InClassInitStyle InitStyle,
15339                                        AccessSpecifier AS,
15340                                        AttributeList *MSPropertyAttr) {
15341   IdentifierInfo *II = D.getIdentifier();
15342   if (!II) {
15343     Diag(DeclStart, diag::err_anonymous_property);
15344     return nullptr;
15345   }
15346   SourceLocation Loc = D.getIdentifierLoc();
15347 
15348   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15349   QualType T = TInfo->getType();
15350   if (getLangOpts().CPlusPlus) {
15351     CheckExtraCXXDefaultArguments(D);
15352 
15353     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15354                                         UPPC_DataMemberType)) {
15355       D.setInvalidType();
15356       T = Context.IntTy;
15357       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15358     }
15359   }
15360 
15361   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15362 
15363   if (D.getDeclSpec().isInlineSpecified())
15364     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15365         << getLangOpts().CPlusPlus17;
15366   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15367     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15368          diag::err_invalid_thread)
15369       << DeclSpec::getSpecifierName(TSCS);
15370 
15371   // Check to see if this name was declared as a member previously
15372   NamedDecl *PrevDecl = nullptr;
15373   LookupResult Previous(*this, II, Loc, LookupMemberName,
15374                         ForVisibleRedeclaration);
15375   LookupName(Previous, S);
15376   switch (Previous.getResultKind()) {
15377   case LookupResult::Found:
15378   case LookupResult::FoundUnresolvedValue:
15379     PrevDecl = Previous.getAsSingle<NamedDecl>();
15380     break;
15381 
15382   case LookupResult::FoundOverloaded:
15383     PrevDecl = Previous.getRepresentativeDecl();
15384     break;
15385 
15386   case LookupResult::NotFound:
15387   case LookupResult::NotFoundInCurrentInstantiation:
15388   case LookupResult::Ambiguous:
15389     break;
15390   }
15391 
15392   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15393     // Maybe we will complain about the shadowed template parameter.
15394     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15395     // Just pretend that we didn't see the previous declaration.
15396     PrevDecl = nullptr;
15397   }
15398 
15399   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15400     PrevDecl = nullptr;
15401 
15402   SourceLocation TSSL = D.getLocStart();
15403   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15404   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15405       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15406   ProcessDeclAttributes(TUScope, NewPD, D);
15407   NewPD->setAccess(AS);
15408 
15409   if (NewPD->isInvalidDecl())
15410     Record->setInvalidDecl();
15411 
15412   if (D.getDeclSpec().isModulePrivateSpecified())
15413     NewPD->setModulePrivate();
15414 
15415   if (NewPD->isInvalidDecl() && PrevDecl) {
15416     // Don't introduce NewFD into scope; there's already something
15417     // with the same name in the same scope.
15418   } else if (II) {
15419     PushOnScopeChains(NewPD, S);
15420   } else
15421     Record->addDecl(NewPD);
15422 
15423   return NewPD;
15424 }
15425