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   // Microsoft docs say:
2235   // "If a base-class has a code_seg attribute, derived classes must have the
2236   // same attribute."
2237    const auto *BaseSA = CXXBaseDecl->getAttr<SectionAttr>();
2238    const auto *DerivedSA = Class->getAttr<SectionAttr>();
2239    if (BaseSA || DerivedSA) {
2240      if (!BaseSA || !DerivedSA || BaseSA->getName() != DerivedSA->getName()) {
2241        Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2242        Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2243          << CXXBaseDecl;
2244        return nullptr;
2245      }
2246    }
2247 
2248   // A class which contains a flexible array member is not suitable for use as a
2249   // base class:
2250   //   - If the layout determines that a base comes before another base,
2251   //     the flexible array member would index into the subsequent base.
2252   //   - If the layout determines that base comes before the derived class,
2253   //     the flexible array member would index into the derived class.
2254   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2255     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2256       << CXXBaseDecl->getDeclName();
2257     return nullptr;
2258   }
2259 
2260   // C++ [class]p3:
2261   //   If a class is marked final and it appears as a base-type-specifier in
2262   //   base-clause, the program is ill-formed.
2263   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2264     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2265       << CXXBaseDecl->getDeclName()
2266       << FA->isSpelledAsSealed();
2267     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2268         << CXXBaseDecl->getDeclName() << FA->getRange();
2269     return nullptr;
2270   }
2271 
2272   if (BaseDecl->isInvalidDecl())
2273     Class->setInvalidDecl();
2274 
2275   // Create the base specifier.
2276   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2277                                         Class->getTagKind() == TTK_Class,
2278                                         Access, TInfo, EllipsisLoc);
2279 }
2280 
2281 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2282 /// one entry in the base class list of a class specifier, for
2283 /// example:
2284 ///    class foo : public bar, virtual private baz {
2285 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2286 BaseResult
2287 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2288                          ParsedAttributes &Attributes,
2289                          bool Virtual, AccessSpecifier Access,
2290                          ParsedType basetype, SourceLocation BaseLoc,
2291                          SourceLocation EllipsisLoc) {
2292   if (!classdecl)
2293     return true;
2294 
2295   AdjustDeclIfTemplate(classdecl);
2296   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2297   if (!Class)
2298     return true;
2299 
2300   // We haven't yet attached the base specifiers.
2301   Class->setIsParsingBaseSpecifiers();
2302 
2303   // We do not support any C++11 attributes on base-specifiers yet.
2304   // Diagnose any attributes we see.
2305   if (!Attributes.empty()) {
2306     for (AttributeList *Attr = Attributes.getList(); Attr;
2307          Attr = Attr->getNext()) {
2308       if (Attr->isInvalid() ||
2309           Attr->getKind() == AttributeList::IgnoredAttribute)
2310         continue;
2311       Diag(Attr->getLoc(),
2312            Attr->getKind() == AttributeList::UnknownAttribute
2313              ? diag::warn_unknown_attribute_ignored
2314              : diag::err_base_specifier_attribute)
2315         << Attr->getName();
2316     }
2317   }
2318 
2319   TypeSourceInfo *TInfo = nullptr;
2320   GetTypeFromParser(basetype, &TInfo);
2321 
2322   if (EllipsisLoc.isInvalid() &&
2323       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2324                                       UPPC_BaseType))
2325     return true;
2326 
2327   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2328                                                       Virtual, Access, TInfo,
2329                                                       EllipsisLoc))
2330     return BaseSpec;
2331   else
2332     Class->setInvalidDecl();
2333 
2334   return true;
2335 }
2336 
2337 /// Use small set to collect indirect bases.  As this is only used
2338 /// locally, there's no need to abstract the small size parameter.
2339 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2340 
2341 /// Recursively add the bases of Type.  Don't add Type itself.
2342 static void
2343 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2344                   const QualType &Type)
2345 {
2346   // Even though the incoming type is a base, it might not be
2347   // a class -- it could be a template parm, for instance.
2348   if (auto Rec = Type->getAs<RecordType>()) {
2349     auto Decl = Rec->getAsCXXRecordDecl();
2350 
2351     // Iterate over its bases.
2352     for (const auto &BaseSpec : Decl->bases()) {
2353       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2354         .getUnqualifiedType();
2355       if (Set.insert(Base).second)
2356         // If we've not already seen it, recurse.
2357         NoteIndirectBases(Context, Set, Base);
2358     }
2359   }
2360 }
2361 
2362 /// Performs the actual work of attaching the given base class
2363 /// specifiers to a C++ class.
2364 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2365                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2366  if (Bases.empty())
2367     return false;
2368 
2369   // Used to keep track of which base types we have already seen, so
2370   // that we can properly diagnose redundant direct base types. Note
2371   // that the key is always the unqualified canonical type of the base
2372   // class.
2373   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2374 
2375   // Used to track indirect bases so we can see if a direct base is
2376   // ambiguous.
2377   IndirectBaseSet IndirectBaseTypes;
2378 
2379   // Copy non-redundant base specifiers into permanent storage.
2380   unsigned NumGoodBases = 0;
2381   bool Invalid = false;
2382   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2383     QualType NewBaseType
2384       = Context.getCanonicalType(Bases[idx]->getType());
2385     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2386 
2387     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2388     if (KnownBase) {
2389       // C++ [class.mi]p3:
2390       //   A class shall not be specified as a direct base class of a
2391       //   derived class more than once.
2392       Diag(Bases[idx]->getLocStart(),
2393            diag::err_duplicate_base_class)
2394         << KnownBase->getType()
2395         << Bases[idx]->getSourceRange();
2396 
2397       // Delete the duplicate base class specifier; we're going to
2398       // overwrite its pointer later.
2399       Context.Deallocate(Bases[idx]);
2400 
2401       Invalid = true;
2402     } else {
2403       // Okay, add this new base class.
2404       KnownBase = Bases[idx];
2405       Bases[NumGoodBases++] = Bases[idx];
2406 
2407       // Note this base's direct & indirect bases, if there could be ambiguity.
2408       if (Bases.size() > 1)
2409         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2410 
2411       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2412         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2413         if (Class->isInterface() &&
2414               (!RD->isInterfaceLike() ||
2415                KnownBase->getAccessSpecifier() != AS_public)) {
2416           // The Microsoft extension __interface does not permit bases that
2417           // are not themselves public interfaces.
2418           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2419             << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2420             << RD->getSourceRange();
2421           Invalid = true;
2422         }
2423         if (RD->hasAttr<WeakAttr>())
2424           Class->addAttr(WeakAttr::CreateImplicit(Context));
2425       }
2426     }
2427   }
2428 
2429   // Attach the remaining base class specifiers to the derived class.
2430   Class->setBases(Bases.data(), NumGoodBases);
2431 
2432   // Check that the only base classes that are duplicate are virtual.
2433   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2434     // Check whether this direct base is inaccessible due to ambiguity.
2435     QualType BaseType = Bases[idx]->getType();
2436 
2437     // Skip all dependent types in templates being used as base specifiers.
2438     // Checks below assume that the base specifier is a CXXRecord.
2439     if (BaseType->isDependentType())
2440       continue;
2441 
2442     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2443       .getUnqualifiedType();
2444 
2445     if (IndirectBaseTypes.count(CanonicalBase)) {
2446       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2447                          /*DetectVirtual=*/true);
2448       bool found
2449         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2450       assert(found);
2451       (void)found;
2452 
2453       if (Paths.isAmbiguous(CanonicalBase))
2454         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2455           << BaseType << getAmbiguousPathsDisplayString(Paths)
2456           << Bases[idx]->getSourceRange();
2457       else
2458         assert(Bases[idx]->isVirtual());
2459     }
2460 
2461     // Delete the base class specifier, since its data has been copied
2462     // into the CXXRecordDecl.
2463     Context.Deallocate(Bases[idx]);
2464   }
2465 
2466   return Invalid;
2467 }
2468 
2469 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2470 /// class, after checking whether there are any duplicate base
2471 /// classes.
2472 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2473                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2474   if (!ClassDecl || Bases.empty())
2475     return;
2476 
2477   AdjustDeclIfTemplate(ClassDecl);
2478   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2479 }
2480 
2481 /// Determine whether the type \p Derived is a C++ class that is
2482 /// derived from the type \p Base.
2483 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2484   if (!getLangOpts().CPlusPlus)
2485     return false;
2486 
2487   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2488   if (!DerivedRD)
2489     return false;
2490 
2491   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2492   if (!BaseRD)
2493     return false;
2494 
2495   // If either the base or the derived type is invalid, don't try to
2496   // check whether one is derived from the other.
2497   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2498     return false;
2499 
2500   // FIXME: In a modules build, do we need the entire path to be visible for us
2501   // to be able to use the inheritance relationship?
2502   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2503     return false;
2504 
2505   return DerivedRD->isDerivedFrom(BaseRD);
2506 }
2507 
2508 /// Determine whether the type \p Derived is a C++ class that is
2509 /// derived from the type \p Base.
2510 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2511                          CXXBasePaths &Paths) {
2512   if (!getLangOpts().CPlusPlus)
2513     return false;
2514 
2515   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2516   if (!DerivedRD)
2517     return false;
2518 
2519   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2520   if (!BaseRD)
2521     return false;
2522 
2523   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2524     return false;
2525 
2526   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2527 }
2528 
2529 static void BuildBasePathArray(const CXXBasePath &Path,
2530                                CXXCastPath &BasePathArray) {
2531   // We first go backward and check if we have a virtual base.
2532   // FIXME: It would be better if CXXBasePath had the base specifier for
2533   // the nearest virtual base.
2534   unsigned Start = 0;
2535   for (unsigned I = Path.size(); I != 0; --I) {
2536     if (Path[I - 1].Base->isVirtual()) {
2537       Start = I - 1;
2538       break;
2539     }
2540   }
2541 
2542   // Now add all bases.
2543   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2544     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2545 }
2546 
2547 
2548 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2549                               CXXCastPath &BasePathArray) {
2550   assert(BasePathArray.empty() && "Base path array must be empty!");
2551   assert(Paths.isRecordingPaths() && "Must record paths!");
2552   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2553 }
2554 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2555 /// conversion (where Derived and Base are class types) is
2556 /// well-formed, meaning that the conversion is unambiguous (and
2557 /// that all of the base classes are accessible). Returns true
2558 /// and emits a diagnostic if the code is ill-formed, returns false
2559 /// otherwise. Loc is the location where this routine should point to
2560 /// if there is an error, and Range is the source range to highlight
2561 /// if there is an error.
2562 ///
2563 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2564 /// diagnostic for the respective type of error will be suppressed, but the
2565 /// check for ill-formed code will still be performed.
2566 bool
2567 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2568                                    unsigned InaccessibleBaseID,
2569                                    unsigned AmbigiousBaseConvID,
2570                                    SourceLocation Loc, SourceRange Range,
2571                                    DeclarationName Name,
2572                                    CXXCastPath *BasePath,
2573                                    bool IgnoreAccess) {
2574   // First, determine whether the path from Derived to Base is
2575   // ambiguous. This is slightly more expensive than checking whether
2576   // the Derived to Base conversion exists, because here we need to
2577   // explore multiple paths to determine if there is an ambiguity.
2578   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2579                      /*DetectVirtual=*/false);
2580   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2581   if (!DerivationOkay)
2582     return true;
2583 
2584   const CXXBasePath *Path = nullptr;
2585   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2586     Path = &Paths.front();
2587 
2588   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2589   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2590   // user to access such bases.
2591   if (!Path && getLangOpts().MSVCCompat) {
2592     for (const CXXBasePath &PossiblePath : Paths) {
2593       if (PossiblePath.size() == 1) {
2594         Path = &PossiblePath;
2595         if (AmbigiousBaseConvID)
2596           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2597               << Base << Derived << Range;
2598         break;
2599       }
2600     }
2601   }
2602 
2603   if (Path) {
2604     if (!IgnoreAccess) {
2605       // Check that the base class can be accessed.
2606       switch (
2607           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2608       case AR_inaccessible:
2609         return true;
2610       case AR_accessible:
2611       case AR_dependent:
2612       case AR_delayed:
2613         break;
2614       }
2615     }
2616 
2617     // Build a base path if necessary.
2618     if (BasePath)
2619       ::BuildBasePathArray(*Path, *BasePath);
2620     return false;
2621   }
2622 
2623   if (AmbigiousBaseConvID) {
2624     // We know that the derived-to-base conversion is ambiguous, and
2625     // we're going to produce a diagnostic. Perform the derived-to-base
2626     // search just one more time to compute all of the possible paths so
2627     // that we can print them out. This is more expensive than any of
2628     // the previous derived-to-base checks we've done, but at this point
2629     // performance isn't as much of an issue.
2630     Paths.clear();
2631     Paths.setRecordingPaths(true);
2632     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2633     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2634     (void)StillOkay;
2635 
2636     // Build up a textual representation of the ambiguous paths, e.g.,
2637     // D -> B -> A, that will be used to illustrate the ambiguous
2638     // conversions in the diagnostic. We only print one of the paths
2639     // to each base class subobject.
2640     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2641 
2642     Diag(Loc, AmbigiousBaseConvID)
2643     << Derived << Base << PathDisplayStr << Range << Name;
2644   }
2645   return true;
2646 }
2647 
2648 bool
2649 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2650                                    SourceLocation Loc, SourceRange Range,
2651                                    CXXCastPath *BasePath,
2652                                    bool IgnoreAccess) {
2653   return CheckDerivedToBaseConversion(
2654       Derived, Base, diag::err_upcast_to_inaccessible_base,
2655       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2656       BasePath, IgnoreAccess);
2657 }
2658 
2659 
2660 /// Builds a string representing ambiguous paths from a
2661 /// specific derived class to different subobjects of the same base
2662 /// class.
2663 ///
2664 /// This function builds a string that can be used in error messages
2665 /// to show the different paths that one can take through the
2666 /// inheritance hierarchy to go from the derived class to different
2667 /// subobjects of a base class. The result looks something like this:
2668 /// @code
2669 /// struct D -> struct B -> struct A
2670 /// struct D -> struct C -> struct A
2671 /// @endcode
2672 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2673   std::string PathDisplayStr;
2674   std::set<unsigned> DisplayedPaths;
2675   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2676        Path != Paths.end(); ++Path) {
2677     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2678       // We haven't displayed a path to this particular base
2679       // class subobject yet.
2680       PathDisplayStr += "\n    ";
2681       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2682       for (CXXBasePath::const_iterator Element = Path->begin();
2683            Element != Path->end(); ++Element)
2684         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2685     }
2686   }
2687 
2688   return PathDisplayStr;
2689 }
2690 
2691 //===----------------------------------------------------------------------===//
2692 // C++ class member Handling
2693 //===----------------------------------------------------------------------===//
2694 
2695 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2696 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2697                                 SourceLocation ASLoc,
2698                                 SourceLocation ColonLoc,
2699                                 AttributeList *Attrs) {
2700   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2701   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2702                                                   ASLoc, ColonLoc);
2703   CurContext->addHiddenDecl(ASDecl);
2704   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2705 }
2706 
2707 /// CheckOverrideControl - Check C++11 override control semantics.
2708 void Sema::CheckOverrideControl(NamedDecl *D) {
2709   if (D->isInvalidDecl())
2710     return;
2711 
2712   // We only care about "override" and "final" declarations.
2713   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2714     return;
2715 
2716   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2717 
2718   // We can't check dependent instance methods.
2719   if (MD && MD->isInstance() &&
2720       (MD->getParent()->hasAnyDependentBases() ||
2721        MD->getType()->isDependentType()))
2722     return;
2723 
2724   if (MD && !MD->isVirtual()) {
2725     // If we have a non-virtual method, check if if hides a virtual method.
2726     // (In that case, it's most likely the method has the wrong type.)
2727     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2728     FindHiddenVirtualMethods(MD, OverloadedMethods);
2729 
2730     if (!OverloadedMethods.empty()) {
2731       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2732         Diag(OA->getLocation(),
2733              diag::override_keyword_hides_virtual_member_function)
2734           << "override" << (OverloadedMethods.size() > 1);
2735       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2736         Diag(FA->getLocation(),
2737              diag::override_keyword_hides_virtual_member_function)
2738           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2739           << (OverloadedMethods.size() > 1);
2740       }
2741       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2742       MD->setInvalidDecl();
2743       return;
2744     }
2745     // Fall through into the general case diagnostic.
2746     // FIXME: We might want to attempt typo correction here.
2747   }
2748 
2749   if (!MD || !MD->isVirtual()) {
2750     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2751       Diag(OA->getLocation(),
2752            diag::override_keyword_only_allowed_on_virtual_member_functions)
2753         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2754       D->dropAttr<OverrideAttr>();
2755     }
2756     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2757       Diag(FA->getLocation(),
2758            diag::override_keyword_only_allowed_on_virtual_member_functions)
2759         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2760         << FixItHint::CreateRemoval(FA->getLocation());
2761       D->dropAttr<FinalAttr>();
2762     }
2763     return;
2764   }
2765 
2766   // C++11 [class.virtual]p5:
2767   //   If a function is marked with the virt-specifier override and
2768   //   does not override a member function of a base class, the program is
2769   //   ill-formed.
2770   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2771   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2772     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2773       << MD->getDeclName();
2774 }
2775 
2776 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2777   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2778     return;
2779   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2780   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2781     return;
2782 
2783   SourceLocation Loc = MD->getLocation();
2784   SourceLocation SpellingLoc = Loc;
2785   if (getSourceManager().isMacroArgExpansion(Loc))
2786     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2787   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2788   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2789       return;
2790 
2791   if (MD->size_overridden_methods() > 0) {
2792     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2793                           ? diag::warn_destructor_marked_not_override_overriding
2794                           : diag::warn_function_marked_not_override_overriding;
2795     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2796     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2797     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2798   }
2799 }
2800 
2801 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2802 /// function overrides a virtual member function marked 'final', according to
2803 /// C++11 [class.virtual]p4.
2804 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2805                                                   const CXXMethodDecl *Old) {
2806   FinalAttr *FA = Old->getAttr<FinalAttr>();
2807   if (!FA)
2808     return false;
2809 
2810   Diag(New->getLocation(), diag::err_final_function_overridden)
2811     << New->getDeclName()
2812     << FA->isSpelledAsSealed();
2813   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2814   return true;
2815 }
2816 
2817 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2818   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2819   // FIXME: Destruction of ObjC lifetime types has side-effects.
2820   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2821     return !RD->isCompleteDefinition() ||
2822            !RD->hasTrivialDefaultConstructor() ||
2823            !RD->hasTrivialDestructor();
2824   return false;
2825 }
2826 
2827 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2828   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2829     if (it->isDeclspecPropertyAttribute())
2830       return it;
2831   return nullptr;
2832 }
2833 
2834 // Check if there is a field shadowing.
2835 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2836                                       DeclarationName FieldName,
2837                                       const CXXRecordDecl *RD) {
2838   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2839     return;
2840 
2841   // To record a shadowed field in a base
2842   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2843   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2844                            CXXBasePath &Path) {
2845     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2846     // Record an ambiguous path directly
2847     if (Bases.find(Base) != Bases.end())
2848       return true;
2849     for (const auto Field : Base->lookup(FieldName)) {
2850       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2851           Field->getAccess() != AS_private) {
2852         assert(Field->getAccess() != AS_none);
2853         assert(Bases.find(Base) == Bases.end());
2854         Bases[Base] = Field;
2855         return true;
2856       }
2857     }
2858     return false;
2859   };
2860 
2861   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2862                      /*DetectVirtual=*/true);
2863   if (!RD->lookupInBases(FieldShadowed, Paths))
2864     return;
2865 
2866   for (const auto &P : Paths) {
2867     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2868     auto It = Bases.find(Base);
2869     // Skip duplicated bases
2870     if (It == Bases.end())
2871       continue;
2872     auto BaseField = It->second;
2873     assert(BaseField->getAccess() != AS_private);
2874     if (AS_none !=
2875         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2876       Diag(Loc, diag::warn_shadow_field)
2877         << FieldName << RD << Base;
2878       Diag(BaseField->getLocation(), diag::note_shadow_field);
2879       Bases.erase(It);
2880     }
2881   }
2882 }
2883 
2884 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2885 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2886 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2887 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2888 /// present (but parsing it has been deferred).
2889 NamedDecl *
2890 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2891                                MultiTemplateParamsArg TemplateParameterLists,
2892                                Expr *BW, const VirtSpecifiers &VS,
2893                                InClassInitStyle InitStyle) {
2894   const DeclSpec &DS = D.getDeclSpec();
2895   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2896   DeclarationName Name = NameInfo.getName();
2897   SourceLocation Loc = NameInfo.getLoc();
2898 
2899   // For anonymous bitfields, the location should point to the type.
2900   if (Loc.isInvalid())
2901     Loc = D.getLocStart();
2902 
2903   Expr *BitWidth = static_cast<Expr*>(BW);
2904 
2905   assert(isa<CXXRecordDecl>(CurContext));
2906   assert(!DS.isFriendSpecified());
2907 
2908   bool isFunc = D.isDeclarationOfFunction();
2909   AttributeList *MSPropertyAttr =
2910       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2911 
2912   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2913     // The Microsoft extension __interface only permits public member functions
2914     // and prohibits constructors, destructors, operators, non-public member
2915     // functions, static methods and data members.
2916     unsigned InvalidDecl;
2917     bool ShowDeclName = true;
2918     if (!isFunc &&
2919         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2920       InvalidDecl = 0;
2921     else if (!isFunc)
2922       InvalidDecl = 1;
2923     else if (AS != AS_public)
2924       InvalidDecl = 2;
2925     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2926       InvalidDecl = 3;
2927     else switch (Name.getNameKind()) {
2928       case DeclarationName::CXXConstructorName:
2929         InvalidDecl = 4;
2930         ShowDeclName = false;
2931         break;
2932 
2933       case DeclarationName::CXXDestructorName:
2934         InvalidDecl = 5;
2935         ShowDeclName = false;
2936         break;
2937 
2938       case DeclarationName::CXXOperatorName:
2939       case DeclarationName::CXXConversionFunctionName:
2940         InvalidDecl = 6;
2941         break;
2942 
2943       default:
2944         InvalidDecl = 0;
2945         break;
2946     }
2947 
2948     if (InvalidDecl) {
2949       if (ShowDeclName)
2950         Diag(Loc, diag::err_invalid_member_in_interface)
2951           << (InvalidDecl-1) << Name;
2952       else
2953         Diag(Loc, diag::err_invalid_member_in_interface)
2954           << (InvalidDecl-1) << "";
2955       return nullptr;
2956     }
2957   }
2958 
2959   // C++ 9.2p6: A member shall not be declared to have automatic storage
2960   // duration (auto, register) or with the extern storage-class-specifier.
2961   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2962   // data members and cannot be applied to names declared const or static,
2963   // and cannot be applied to reference members.
2964   switch (DS.getStorageClassSpec()) {
2965   case DeclSpec::SCS_unspecified:
2966   case DeclSpec::SCS_typedef:
2967   case DeclSpec::SCS_static:
2968     break;
2969   case DeclSpec::SCS_mutable:
2970     if (isFunc) {
2971       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2972 
2973       // FIXME: It would be nicer if the keyword was ignored only for this
2974       // declarator. Otherwise we could get follow-up errors.
2975       D.getMutableDeclSpec().ClearStorageClassSpecs();
2976     }
2977     break;
2978   default:
2979     Diag(DS.getStorageClassSpecLoc(),
2980          diag::err_storageclass_invalid_for_member);
2981     D.getMutableDeclSpec().ClearStorageClassSpecs();
2982     break;
2983   }
2984 
2985   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2986                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2987                       !isFunc);
2988 
2989   if (DS.isConstexprSpecified() && isInstField) {
2990     SemaDiagnosticBuilder B =
2991         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2992     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2993     if (InitStyle == ICIS_NoInit) {
2994       B << 0 << 0;
2995       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2996         B << FixItHint::CreateRemoval(ConstexprLoc);
2997       else {
2998         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2999         D.getMutableDeclSpec().ClearConstexprSpec();
3000         const char *PrevSpec;
3001         unsigned DiagID;
3002         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3003             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3004         (void)Failed;
3005         assert(!Failed && "Making a constexpr member const shouldn't fail");
3006       }
3007     } else {
3008       B << 1;
3009       const char *PrevSpec;
3010       unsigned DiagID;
3011       if (D.getMutableDeclSpec().SetStorageClassSpec(
3012           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3013           Context.getPrintingPolicy())) {
3014         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3015                "This is the only DeclSpec that should fail to be applied");
3016         B << 1;
3017       } else {
3018         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3019         isInstField = false;
3020       }
3021     }
3022   }
3023 
3024   NamedDecl *Member;
3025   if (isInstField) {
3026     CXXScopeSpec &SS = D.getCXXScopeSpec();
3027 
3028     // Data members must have identifiers for names.
3029     if (!Name.isIdentifier()) {
3030       Diag(Loc, diag::err_bad_variable_name)
3031         << Name;
3032       return nullptr;
3033     }
3034 
3035     IdentifierInfo *II = Name.getAsIdentifierInfo();
3036 
3037     // Member field could not be with "template" keyword.
3038     // So TemplateParameterLists should be empty in this case.
3039     if (TemplateParameterLists.size()) {
3040       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3041       if (TemplateParams->size()) {
3042         // There is no such thing as a member field template.
3043         Diag(D.getIdentifierLoc(), diag::err_template_member)
3044             << II
3045             << SourceRange(TemplateParams->getTemplateLoc(),
3046                 TemplateParams->getRAngleLoc());
3047       } else {
3048         // There is an extraneous 'template<>' for this member.
3049         Diag(TemplateParams->getTemplateLoc(),
3050             diag::err_template_member_noparams)
3051             << II
3052             << SourceRange(TemplateParams->getTemplateLoc(),
3053                 TemplateParams->getRAngleLoc());
3054       }
3055       return nullptr;
3056     }
3057 
3058     if (SS.isSet() && !SS.isInvalid()) {
3059       // The user provided a superfluous scope specifier inside a class
3060       // definition:
3061       //
3062       // class X {
3063       //   int X::member;
3064       // };
3065       if (DeclContext *DC = computeDeclContext(SS, false))
3066         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3067                                      D.getName().getKind() ==
3068                                          UnqualifiedIdKind::IK_TemplateId);
3069       else
3070         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3071           << Name << SS.getRange();
3072 
3073       SS.clear();
3074     }
3075 
3076     if (MSPropertyAttr) {
3077       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3078                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3079       if (!Member)
3080         return nullptr;
3081       isInstField = false;
3082     } else {
3083       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3084                                 BitWidth, InitStyle, AS);
3085       if (!Member)
3086         return nullptr;
3087     }
3088 
3089     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3090   } else {
3091     Member = HandleDeclarator(S, D, TemplateParameterLists);
3092     if (!Member)
3093       return nullptr;
3094 
3095     // Non-instance-fields can't have a bitfield.
3096     if (BitWidth) {
3097       if (Member->isInvalidDecl()) {
3098         // don't emit another diagnostic.
3099       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3100         // C++ 9.6p3: A bit-field shall not be a static member.
3101         // "static member 'A' cannot be a bit-field"
3102         Diag(Loc, diag::err_static_not_bitfield)
3103           << Name << BitWidth->getSourceRange();
3104       } else if (isa<TypedefDecl>(Member)) {
3105         // "typedef member 'x' cannot be a bit-field"
3106         Diag(Loc, diag::err_typedef_not_bitfield)
3107           << Name << BitWidth->getSourceRange();
3108       } else {
3109         // A function typedef ("typedef int f(); f a;").
3110         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3111         Diag(Loc, diag::err_not_integral_type_bitfield)
3112           << Name << cast<ValueDecl>(Member)->getType()
3113           << BitWidth->getSourceRange();
3114       }
3115 
3116       BitWidth = nullptr;
3117       Member->setInvalidDecl();
3118     }
3119 
3120     Member->setAccess(AS);
3121 
3122     // If we have declared a member function template or static data member
3123     // template, set the access of the templated declaration as well.
3124     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3125       FunTmpl->getTemplatedDecl()->setAccess(AS);
3126     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3127       VarTmpl->getTemplatedDecl()->setAccess(AS);
3128   }
3129 
3130   if (VS.isOverrideSpecified())
3131     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3132   if (VS.isFinalSpecified())
3133     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3134                                             VS.isFinalSpelledSealed()));
3135 
3136   if (VS.getLastLocation().isValid()) {
3137     // Update the end location of a method that has a virt-specifiers.
3138     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3139       MD->setRangeEnd(VS.getLastLocation());
3140   }
3141 
3142   CheckOverrideControl(Member);
3143 
3144   assert((Name || isInstField) && "No identifier for non-field ?");
3145 
3146   if (isInstField) {
3147     FieldDecl *FD = cast<FieldDecl>(Member);
3148     FieldCollector->Add(FD);
3149 
3150     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3151       // Remember all explicit private FieldDecls that have a name, no side
3152       // effects and are not part of a dependent type declaration.
3153       if (!FD->isImplicit() && FD->getDeclName() &&
3154           FD->getAccess() == AS_private &&
3155           !FD->hasAttr<UnusedAttr>() &&
3156           !FD->getParent()->isDependentContext() &&
3157           !InitializationHasSideEffects(*FD))
3158         UnusedPrivateFields.insert(FD);
3159     }
3160   }
3161 
3162   return Member;
3163 }
3164 
3165 namespace {
3166   class UninitializedFieldVisitor
3167       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3168     Sema &S;
3169     // List of Decls to generate a warning on.  Also remove Decls that become
3170     // initialized.
3171     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3172     // List of base classes of the record.  Classes are removed after their
3173     // initializers.
3174     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3175     // Vector of decls to be removed from the Decl set prior to visiting the
3176     // nodes.  These Decls may have been initialized in the prior initializer.
3177     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3178     // If non-null, add a note to the warning pointing back to the constructor.
3179     const CXXConstructorDecl *Constructor;
3180     // Variables to hold state when processing an initializer list.  When
3181     // InitList is true, special case initialization of FieldDecls matching
3182     // InitListFieldDecl.
3183     bool InitList;
3184     FieldDecl *InitListFieldDecl;
3185     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3186 
3187   public:
3188     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3189     UninitializedFieldVisitor(Sema &S,
3190                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3191                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3192       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3193         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3194 
3195     // Returns true if the use of ME is not an uninitialized use.
3196     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3197                                          bool CheckReferenceOnly) {
3198       llvm::SmallVector<FieldDecl*, 4> Fields;
3199       bool ReferenceField = false;
3200       while (ME) {
3201         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3202         if (!FD)
3203           return false;
3204         Fields.push_back(FD);
3205         if (FD->getType()->isReferenceType())
3206           ReferenceField = true;
3207         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3208       }
3209 
3210       // Binding a reference to an unintialized field is not an
3211       // uninitialized use.
3212       if (CheckReferenceOnly && !ReferenceField)
3213         return true;
3214 
3215       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3216       // Discard the first field since it is the field decl that is being
3217       // initialized.
3218       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3219         UsedFieldIndex.push_back((*I)->getFieldIndex());
3220       }
3221 
3222       for (auto UsedIter = UsedFieldIndex.begin(),
3223                 UsedEnd = UsedFieldIndex.end(),
3224                 OrigIter = InitFieldIndex.begin(),
3225                 OrigEnd = InitFieldIndex.end();
3226            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3227         if (*UsedIter < *OrigIter)
3228           return true;
3229         if (*UsedIter > *OrigIter)
3230           break;
3231       }
3232 
3233       return false;
3234     }
3235 
3236     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3237                           bool AddressOf) {
3238       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3239         return;
3240 
3241       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3242       // or union.
3243       MemberExpr *FieldME = ME;
3244 
3245       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3246 
3247       Expr *Base = ME;
3248       while (MemberExpr *SubME =
3249                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3250 
3251         if (isa<VarDecl>(SubME->getMemberDecl()))
3252           return;
3253 
3254         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3255           if (!FD->isAnonymousStructOrUnion())
3256             FieldME = SubME;
3257 
3258         if (!FieldME->getType().isPODType(S.Context))
3259           AllPODFields = false;
3260 
3261         Base = SubME->getBase();
3262       }
3263 
3264       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3265         return;
3266 
3267       if (AddressOf && AllPODFields)
3268         return;
3269 
3270       ValueDecl* FoundVD = FieldME->getMemberDecl();
3271 
3272       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3273         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3274           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3275         }
3276 
3277         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3278           QualType T = BaseCast->getType();
3279           if (T->isPointerType() &&
3280               BaseClasses.count(T->getPointeeType())) {
3281             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3282                 << T->getPointeeType() << FoundVD;
3283           }
3284         }
3285       }
3286 
3287       if (!Decls.count(FoundVD))
3288         return;
3289 
3290       const bool IsReference = FoundVD->getType()->isReferenceType();
3291 
3292       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3293         // Special checking for initializer lists.
3294         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3295           return;
3296         }
3297       } else {
3298         // Prevent double warnings on use of unbounded references.
3299         if (CheckReferenceOnly && !IsReference)
3300           return;
3301       }
3302 
3303       unsigned diag = IsReference
3304           ? diag::warn_reference_field_is_uninit
3305           : diag::warn_field_is_uninit;
3306       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3307       if (Constructor)
3308         S.Diag(Constructor->getLocation(),
3309                diag::note_uninit_in_this_constructor)
3310           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3311 
3312     }
3313 
3314     void HandleValue(Expr *E, bool AddressOf) {
3315       E = E->IgnoreParens();
3316 
3317       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3318         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3319                          AddressOf /*AddressOf*/);
3320         return;
3321       }
3322 
3323       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3324         Visit(CO->getCond());
3325         HandleValue(CO->getTrueExpr(), AddressOf);
3326         HandleValue(CO->getFalseExpr(), AddressOf);
3327         return;
3328       }
3329 
3330       if (BinaryConditionalOperator *BCO =
3331               dyn_cast<BinaryConditionalOperator>(E)) {
3332         Visit(BCO->getCond());
3333         HandleValue(BCO->getFalseExpr(), AddressOf);
3334         return;
3335       }
3336 
3337       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3338         HandleValue(OVE->getSourceExpr(), AddressOf);
3339         return;
3340       }
3341 
3342       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3343         switch (BO->getOpcode()) {
3344         default:
3345           break;
3346         case(BO_PtrMemD):
3347         case(BO_PtrMemI):
3348           HandleValue(BO->getLHS(), AddressOf);
3349           Visit(BO->getRHS());
3350           return;
3351         case(BO_Comma):
3352           Visit(BO->getLHS());
3353           HandleValue(BO->getRHS(), AddressOf);
3354           return;
3355         }
3356       }
3357 
3358       Visit(E);
3359     }
3360 
3361     void CheckInitListExpr(InitListExpr *ILE) {
3362       InitFieldIndex.push_back(0);
3363       for (auto Child : ILE->children()) {
3364         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3365           CheckInitListExpr(SubList);
3366         } else {
3367           Visit(Child);
3368         }
3369         ++InitFieldIndex.back();
3370       }
3371       InitFieldIndex.pop_back();
3372     }
3373 
3374     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3375                           FieldDecl *Field, const Type *BaseClass) {
3376       // Remove Decls that may have been initialized in the previous
3377       // initializer.
3378       for (ValueDecl* VD : DeclsToRemove)
3379         Decls.erase(VD);
3380       DeclsToRemove.clear();
3381 
3382       Constructor = FieldConstructor;
3383       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3384 
3385       if (ILE && Field) {
3386         InitList = true;
3387         InitListFieldDecl = Field;
3388         InitFieldIndex.clear();
3389         CheckInitListExpr(ILE);
3390       } else {
3391         InitList = false;
3392         Visit(E);
3393       }
3394 
3395       if (Field)
3396         Decls.erase(Field);
3397       if (BaseClass)
3398         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3399     }
3400 
3401     void VisitMemberExpr(MemberExpr *ME) {
3402       // All uses of unbounded reference fields will warn.
3403       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3404     }
3405 
3406     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3407       if (E->getCastKind() == CK_LValueToRValue) {
3408         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3409         return;
3410       }
3411 
3412       Inherited::VisitImplicitCastExpr(E);
3413     }
3414 
3415     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3416       if (E->getConstructor()->isCopyConstructor()) {
3417         Expr *ArgExpr = E->getArg(0);
3418         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3419           if (ILE->getNumInits() == 1)
3420             ArgExpr = ILE->getInit(0);
3421         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3422           if (ICE->getCastKind() == CK_NoOp)
3423             ArgExpr = ICE->getSubExpr();
3424         HandleValue(ArgExpr, false /*AddressOf*/);
3425         return;
3426       }
3427       Inherited::VisitCXXConstructExpr(E);
3428     }
3429 
3430     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3431       Expr *Callee = E->getCallee();
3432       if (isa<MemberExpr>(Callee)) {
3433         HandleValue(Callee, false /*AddressOf*/);
3434         for (auto Arg : E->arguments())
3435           Visit(Arg);
3436         return;
3437       }
3438 
3439       Inherited::VisitCXXMemberCallExpr(E);
3440     }
3441 
3442     void VisitCallExpr(CallExpr *E) {
3443       // Treat std::move as a use.
3444       if (E->isCallToStdMove()) {
3445         HandleValue(E->getArg(0), /*AddressOf=*/false);
3446         return;
3447       }
3448 
3449       Inherited::VisitCallExpr(E);
3450     }
3451 
3452     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3453       Expr *Callee = E->getCallee();
3454 
3455       if (isa<UnresolvedLookupExpr>(Callee))
3456         return Inherited::VisitCXXOperatorCallExpr(E);
3457 
3458       Visit(Callee);
3459       for (auto Arg : E->arguments())
3460         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3461     }
3462 
3463     void VisitBinaryOperator(BinaryOperator *E) {
3464       // If a field assignment is detected, remove the field from the
3465       // uninitiailized field set.
3466       if (E->getOpcode() == BO_Assign)
3467         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3468           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3469             if (!FD->getType()->isReferenceType())
3470               DeclsToRemove.push_back(FD);
3471 
3472       if (E->isCompoundAssignmentOp()) {
3473         HandleValue(E->getLHS(), false /*AddressOf*/);
3474         Visit(E->getRHS());
3475         return;
3476       }
3477 
3478       Inherited::VisitBinaryOperator(E);
3479     }
3480 
3481     void VisitUnaryOperator(UnaryOperator *E) {
3482       if (E->isIncrementDecrementOp()) {
3483         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3484         return;
3485       }
3486       if (E->getOpcode() == UO_AddrOf) {
3487         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3488           HandleValue(ME->getBase(), true /*AddressOf*/);
3489           return;
3490         }
3491       }
3492 
3493       Inherited::VisitUnaryOperator(E);
3494     }
3495   };
3496 
3497   // Diagnose value-uses of fields to initialize themselves, e.g.
3498   //   foo(foo)
3499   // where foo is not also a parameter to the constructor.
3500   // Also diagnose across field uninitialized use such as
3501   //   x(y), y(x)
3502   // TODO: implement -Wuninitialized and fold this into that framework.
3503   static void DiagnoseUninitializedFields(
3504       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3505 
3506     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3507                                            Constructor->getLocation())) {
3508       return;
3509     }
3510 
3511     if (Constructor->isInvalidDecl())
3512       return;
3513 
3514     const CXXRecordDecl *RD = Constructor->getParent();
3515 
3516     if (RD->getDescribedClassTemplate())
3517       return;
3518 
3519     // Holds fields that are uninitialized.
3520     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3521 
3522     // At the beginning, all fields are uninitialized.
3523     for (auto *I : RD->decls()) {
3524       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3525         UninitializedFields.insert(FD);
3526       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3527         UninitializedFields.insert(IFD->getAnonField());
3528       }
3529     }
3530 
3531     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3532     for (auto I : RD->bases())
3533       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3534 
3535     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3536       return;
3537 
3538     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3539                                                    UninitializedFields,
3540                                                    UninitializedBaseClasses);
3541 
3542     for (const auto *FieldInit : Constructor->inits()) {
3543       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3544         break;
3545 
3546       Expr *InitExpr = FieldInit->getInit();
3547       if (!InitExpr)
3548         continue;
3549 
3550       if (CXXDefaultInitExpr *Default =
3551               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3552         InitExpr = Default->getExpr();
3553         if (!InitExpr)
3554           continue;
3555         // In class initializers will point to the constructor.
3556         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3557                                               FieldInit->getAnyMember(),
3558                                               FieldInit->getBaseClass());
3559       } else {
3560         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3561                                               FieldInit->getAnyMember(),
3562                                               FieldInit->getBaseClass());
3563       }
3564     }
3565   }
3566 } // namespace
3567 
3568 /// Enter a new C++ default initializer scope. After calling this, the
3569 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3570 /// parsing or instantiating the initializer failed.
3571 void Sema::ActOnStartCXXInClassMemberInitializer() {
3572   // Create a synthetic function scope to represent the call to the constructor
3573   // that notionally surrounds a use of this initializer.
3574   PushFunctionScope();
3575 }
3576 
3577 /// This is invoked after parsing an in-class initializer for a
3578 /// non-static C++ class member, and after instantiating an in-class initializer
3579 /// in a class template. Such actions are deferred until the class is complete.
3580 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3581                                                   SourceLocation InitLoc,
3582                                                   Expr *InitExpr) {
3583   // Pop the notional constructor scope we created earlier.
3584   PopFunctionScopeInfo(nullptr, D);
3585 
3586   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3587   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3588          "must set init style when field is created");
3589 
3590   if (!InitExpr) {
3591     D->setInvalidDecl();
3592     if (FD)
3593       FD->removeInClassInitializer();
3594     return;
3595   }
3596 
3597   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3598     FD->setInvalidDecl();
3599     FD->removeInClassInitializer();
3600     return;
3601   }
3602 
3603   ExprResult Init = InitExpr;
3604   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3605     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3606     InitializationKind Kind =
3607         FD->getInClassInitStyle() == ICIS_ListInit
3608             ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3609                                                    InitExpr->getLocStart(),
3610                                                    InitExpr->getLocEnd())
3611             : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3612     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3613     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3614     if (Init.isInvalid()) {
3615       FD->setInvalidDecl();
3616       return;
3617     }
3618   }
3619 
3620   // C++11 [class.base.init]p7:
3621   //   The initialization of each base and member constitutes a
3622   //   full-expression.
3623   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3624   if (Init.isInvalid()) {
3625     FD->setInvalidDecl();
3626     return;
3627   }
3628 
3629   InitExpr = Init.get();
3630 
3631   FD->setInClassInitializer(InitExpr);
3632 }
3633 
3634 /// Find the direct and/or virtual base specifiers that
3635 /// correspond to the given base type, for use in base initialization
3636 /// within a constructor.
3637 static bool FindBaseInitializer(Sema &SemaRef,
3638                                 CXXRecordDecl *ClassDecl,
3639                                 QualType BaseType,
3640                                 const CXXBaseSpecifier *&DirectBaseSpec,
3641                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3642   // First, check for a direct base class.
3643   DirectBaseSpec = nullptr;
3644   for (const auto &Base : ClassDecl->bases()) {
3645     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3646       // We found a direct base of this type. That's what we're
3647       // initializing.
3648       DirectBaseSpec = &Base;
3649       break;
3650     }
3651   }
3652 
3653   // Check for a virtual base class.
3654   // FIXME: We might be able to short-circuit this if we know in advance that
3655   // there are no virtual bases.
3656   VirtualBaseSpec = nullptr;
3657   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3658     // We haven't found a base yet; search the class hierarchy for a
3659     // virtual base class.
3660     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3661                        /*DetectVirtual=*/false);
3662     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3663                               SemaRef.Context.getTypeDeclType(ClassDecl),
3664                               BaseType, Paths)) {
3665       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3666            Path != Paths.end(); ++Path) {
3667         if (Path->back().Base->isVirtual()) {
3668           VirtualBaseSpec = Path->back().Base;
3669           break;
3670         }
3671       }
3672     }
3673   }
3674 
3675   return DirectBaseSpec || VirtualBaseSpec;
3676 }
3677 
3678 /// Handle a C++ member initializer using braced-init-list syntax.
3679 MemInitResult
3680 Sema::ActOnMemInitializer(Decl *ConstructorD,
3681                           Scope *S,
3682                           CXXScopeSpec &SS,
3683                           IdentifierInfo *MemberOrBase,
3684                           ParsedType TemplateTypeTy,
3685                           const DeclSpec &DS,
3686                           SourceLocation IdLoc,
3687                           Expr *InitList,
3688                           SourceLocation EllipsisLoc) {
3689   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3690                              DS, IdLoc, InitList,
3691                              EllipsisLoc);
3692 }
3693 
3694 /// Handle a C++ member initializer using parentheses syntax.
3695 MemInitResult
3696 Sema::ActOnMemInitializer(Decl *ConstructorD,
3697                           Scope *S,
3698                           CXXScopeSpec &SS,
3699                           IdentifierInfo *MemberOrBase,
3700                           ParsedType TemplateTypeTy,
3701                           const DeclSpec &DS,
3702                           SourceLocation IdLoc,
3703                           SourceLocation LParenLoc,
3704                           ArrayRef<Expr *> Args,
3705                           SourceLocation RParenLoc,
3706                           SourceLocation EllipsisLoc) {
3707   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3708                                            Args, RParenLoc);
3709   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3710                              DS, IdLoc, List, EllipsisLoc);
3711 }
3712 
3713 namespace {
3714 
3715 // Callback to only accept typo corrections that can be a valid C++ member
3716 // intializer: either a non-static field member or a base class.
3717 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3718 public:
3719   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3720       : ClassDecl(ClassDecl) {}
3721 
3722   bool ValidateCandidate(const TypoCorrection &candidate) override {
3723     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3724       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3725         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3726       return isa<TypeDecl>(ND);
3727     }
3728     return false;
3729   }
3730 
3731 private:
3732   CXXRecordDecl *ClassDecl;
3733 };
3734 
3735 }
3736 
3737 /// Handle a C++ member initializer.
3738 MemInitResult
3739 Sema::BuildMemInitializer(Decl *ConstructorD,
3740                           Scope *S,
3741                           CXXScopeSpec &SS,
3742                           IdentifierInfo *MemberOrBase,
3743                           ParsedType TemplateTypeTy,
3744                           const DeclSpec &DS,
3745                           SourceLocation IdLoc,
3746                           Expr *Init,
3747                           SourceLocation EllipsisLoc) {
3748   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3749   if (!Res.isUsable())
3750     return true;
3751   Init = Res.get();
3752 
3753   if (!ConstructorD)
3754     return true;
3755 
3756   AdjustDeclIfTemplate(ConstructorD);
3757 
3758   CXXConstructorDecl *Constructor
3759     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3760   if (!Constructor) {
3761     // The user wrote a constructor initializer on a function that is
3762     // not a C++ constructor. Ignore the error for now, because we may
3763     // have more member initializers coming; we'll diagnose it just
3764     // once in ActOnMemInitializers.
3765     return true;
3766   }
3767 
3768   CXXRecordDecl *ClassDecl = Constructor->getParent();
3769 
3770   // C++ [class.base.init]p2:
3771   //   Names in a mem-initializer-id are looked up in the scope of the
3772   //   constructor's class and, if not found in that scope, are looked
3773   //   up in the scope containing the constructor's definition.
3774   //   [Note: if the constructor's class contains a member with the
3775   //   same name as a direct or virtual base class of the class, a
3776   //   mem-initializer-id naming the member or base class and composed
3777   //   of a single identifier refers to the class member. A
3778   //   mem-initializer-id for the hidden base class may be specified
3779   //   using a qualified name. ]
3780   if (!SS.getScopeRep() && !TemplateTypeTy) {
3781     // Look for a member, first.
3782     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3783     if (!Result.empty()) {
3784       ValueDecl *Member;
3785       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3786           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3787         if (EllipsisLoc.isValid())
3788           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3789             << MemberOrBase
3790             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3791 
3792         return BuildMemberInitializer(Member, Init, IdLoc);
3793       }
3794     }
3795   }
3796   // It didn't name a member, so see if it names a class.
3797   QualType BaseType;
3798   TypeSourceInfo *TInfo = nullptr;
3799 
3800   if (TemplateTypeTy) {
3801     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3802   } else if (DS.getTypeSpecType() == TST_decltype) {
3803     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3804   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3805     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3806     return true;
3807   } else {
3808     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3809     LookupParsedName(R, S, &SS);
3810 
3811     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3812     if (!TyD) {
3813       if (R.isAmbiguous()) return true;
3814 
3815       // We don't want access-control diagnostics here.
3816       R.suppressDiagnostics();
3817 
3818       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3819         bool NotUnknownSpecialization = false;
3820         DeclContext *DC = computeDeclContext(SS, false);
3821         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3822           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3823 
3824         if (!NotUnknownSpecialization) {
3825           // When the scope specifier can refer to a member of an unknown
3826           // specialization, we take it as a type name.
3827           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3828                                        SS.getWithLocInContext(Context),
3829                                        *MemberOrBase, IdLoc);
3830           if (BaseType.isNull())
3831             return true;
3832 
3833           TInfo = Context.CreateTypeSourceInfo(BaseType);
3834           DependentNameTypeLoc TL =
3835               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3836           if (!TL.isNull()) {
3837             TL.setNameLoc(IdLoc);
3838             TL.setElaboratedKeywordLoc(SourceLocation());
3839             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3840           }
3841 
3842           R.clear();
3843           R.setLookupName(MemberOrBase);
3844         }
3845       }
3846 
3847       // If no results were found, try to correct typos.
3848       TypoCorrection Corr;
3849       if (R.empty() && BaseType.isNull() &&
3850           (Corr = CorrectTypo(
3851                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3852                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3853                CTK_ErrorRecovery, ClassDecl))) {
3854         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3855           // We have found a non-static data member with a similar
3856           // name to what was typed; complain and initialize that
3857           // member.
3858           diagnoseTypo(Corr,
3859                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3860                          << MemberOrBase << true);
3861           return BuildMemberInitializer(Member, Init, IdLoc);
3862         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3863           const CXXBaseSpecifier *DirectBaseSpec;
3864           const CXXBaseSpecifier *VirtualBaseSpec;
3865           if (FindBaseInitializer(*this, ClassDecl,
3866                                   Context.getTypeDeclType(Type),
3867                                   DirectBaseSpec, VirtualBaseSpec)) {
3868             // We have found a direct or virtual base class with a
3869             // similar name to what was typed; complain and initialize
3870             // that base class.
3871             diagnoseTypo(Corr,
3872                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3873                            << MemberOrBase << false,
3874                          PDiag() /*Suppress note, we provide our own.*/);
3875 
3876             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3877                                                               : VirtualBaseSpec;
3878             Diag(BaseSpec->getLocStart(),
3879                  diag::note_base_class_specified_here)
3880               << BaseSpec->getType()
3881               << BaseSpec->getSourceRange();
3882 
3883             TyD = Type;
3884           }
3885         }
3886       }
3887 
3888       if (!TyD && BaseType.isNull()) {
3889         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3890           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3891         return true;
3892       }
3893     }
3894 
3895     if (BaseType.isNull()) {
3896       BaseType = Context.getTypeDeclType(TyD);
3897       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3898       if (SS.isSet()) {
3899         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3900                                              BaseType);
3901         TInfo = Context.CreateTypeSourceInfo(BaseType);
3902         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3903         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3904         TL.setElaboratedKeywordLoc(SourceLocation());
3905         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3906       }
3907     }
3908   }
3909 
3910   if (!TInfo)
3911     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3912 
3913   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3914 }
3915 
3916 /// Checks a member initializer expression for cases where reference (or
3917 /// pointer) members are bound to by-value parameters (or their addresses).
3918 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3919                                                Expr *Init,
3920                                                SourceLocation IdLoc) {
3921   QualType MemberTy = Member->getType();
3922 
3923   // We only handle pointers and references currently.
3924   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3925   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3926     return;
3927 
3928   const bool IsPointer = MemberTy->isPointerType();
3929   if (IsPointer) {
3930     if (const UnaryOperator *Op
3931           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3932       // The only case we're worried about with pointers requires taking the
3933       // address.
3934       if (Op->getOpcode() != UO_AddrOf)
3935         return;
3936 
3937       Init = Op->getSubExpr();
3938     } else {
3939       // We only handle address-of expression initializers for pointers.
3940       return;
3941     }
3942   }
3943 
3944   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3945     // We only warn when referring to a non-reference parameter declaration.
3946     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3947     if (!Parameter || Parameter->getType()->isReferenceType())
3948       return;
3949 
3950     S.Diag(Init->getExprLoc(),
3951            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3952                      : diag::warn_bind_ref_member_to_parameter)
3953       << Member << Parameter << Init->getSourceRange();
3954   } else {
3955     // Other initializers are fine.
3956     return;
3957   }
3958 
3959   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3960     << (unsigned)IsPointer;
3961 }
3962 
3963 MemInitResult
3964 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3965                              SourceLocation IdLoc) {
3966   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3967   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3968   assert((DirectMember || IndirectMember) &&
3969          "Member must be a FieldDecl or IndirectFieldDecl");
3970 
3971   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3972     return true;
3973 
3974   if (Member->isInvalidDecl())
3975     return true;
3976 
3977   MultiExprArg Args;
3978   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3979     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3980   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3981     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3982   } else {
3983     // Template instantiation doesn't reconstruct ParenListExprs for us.
3984     Args = Init;
3985   }
3986 
3987   SourceRange InitRange = Init->getSourceRange();
3988 
3989   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3990     // Can't check initialization for a member of dependent type or when
3991     // any of the arguments are type-dependent expressions.
3992     DiscardCleanupsInEvaluationContext();
3993   } else {
3994     bool InitList = false;
3995     if (isa<InitListExpr>(Init)) {
3996       InitList = true;
3997       Args = Init;
3998     }
3999 
4000     // Initialize the member.
4001     InitializedEntity MemberEntity =
4002       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4003                    : InitializedEntity::InitializeMember(IndirectMember,
4004                                                          nullptr);
4005     InitializationKind Kind =
4006         InitList ? InitializationKind::CreateDirectList(
4007                        IdLoc, Init->getLocStart(), Init->getLocEnd())
4008                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4009                                                     InitRange.getEnd());
4010 
4011     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4012     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4013                                             nullptr);
4014     if (MemberInit.isInvalid())
4015       return true;
4016 
4017     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
4018 
4019     // C++11 [class.base.init]p7:
4020     //   The initialization of each base and member constitutes a
4021     //   full-expression.
4022     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4023     if (MemberInit.isInvalid())
4024       return true;
4025 
4026     Init = MemberInit.get();
4027   }
4028 
4029   if (DirectMember) {
4030     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4031                                             InitRange.getBegin(), Init,
4032                                             InitRange.getEnd());
4033   } else {
4034     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4035                                             InitRange.getBegin(), Init,
4036                                             InitRange.getEnd());
4037   }
4038 }
4039 
4040 MemInitResult
4041 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4042                                  CXXRecordDecl *ClassDecl) {
4043   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4044   if (!LangOpts.CPlusPlus11)
4045     return Diag(NameLoc, diag::err_delegating_ctor)
4046       << TInfo->getTypeLoc().getLocalSourceRange();
4047   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4048 
4049   bool InitList = true;
4050   MultiExprArg Args = Init;
4051   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4052     InitList = false;
4053     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4054   }
4055 
4056   SourceRange InitRange = Init->getSourceRange();
4057   // Initialize the object.
4058   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4059                                      QualType(ClassDecl->getTypeForDecl(), 0));
4060   InitializationKind Kind =
4061       InitList ? InitializationKind::CreateDirectList(
4062                      NameLoc, Init->getLocStart(), Init->getLocEnd())
4063                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4064                                                   InitRange.getEnd());
4065   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4066   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4067                                               Args, nullptr);
4068   if (DelegationInit.isInvalid())
4069     return true;
4070 
4071   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4072          "Delegating constructor with no target?");
4073 
4074   // C++11 [class.base.init]p7:
4075   //   The initialization of each base and member constitutes a
4076   //   full-expression.
4077   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4078                                        InitRange.getBegin());
4079   if (DelegationInit.isInvalid())
4080     return true;
4081 
4082   // If we are in a dependent context, template instantiation will
4083   // perform this type-checking again. Just save the arguments that we
4084   // received in a ParenListExpr.
4085   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4086   // of the information that we have about the base
4087   // initializer. However, deconstructing the ASTs is a dicey process,
4088   // and this approach is far more likely to get the corner cases right.
4089   if (CurContext->isDependentContext())
4090     DelegationInit = Init;
4091 
4092   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4093                                           DelegationInit.getAs<Expr>(),
4094                                           InitRange.getEnd());
4095 }
4096 
4097 MemInitResult
4098 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4099                            Expr *Init, CXXRecordDecl *ClassDecl,
4100                            SourceLocation EllipsisLoc) {
4101   SourceLocation BaseLoc
4102     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4103 
4104   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4105     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4106              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4107 
4108   // C++ [class.base.init]p2:
4109   //   [...] Unless the mem-initializer-id names a nonstatic data
4110   //   member of the constructor's class or a direct or virtual base
4111   //   of that class, the mem-initializer is ill-formed. A
4112   //   mem-initializer-list can initialize a base class using any
4113   //   name that denotes that base class type.
4114   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4115 
4116   SourceRange InitRange = Init->getSourceRange();
4117   if (EllipsisLoc.isValid()) {
4118     // This is a pack expansion.
4119     if (!BaseType->containsUnexpandedParameterPack())  {
4120       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4121         << SourceRange(BaseLoc, InitRange.getEnd());
4122 
4123       EllipsisLoc = SourceLocation();
4124     }
4125   } else {
4126     // Check for any unexpanded parameter packs.
4127     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4128       return true;
4129 
4130     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4131       return true;
4132   }
4133 
4134   // Check for direct and virtual base classes.
4135   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4136   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4137   if (!Dependent) {
4138     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4139                                        BaseType))
4140       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4141 
4142     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4143                         VirtualBaseSpec);
4144 
4145     // C++ [base.class.init]p2:
4146     // Unless the mem-initializer-id names a nonstatic data member of the
4147     // constructor's class or a direct or virtual base of that class, the
4148     // mem-initializer is ill-formed.
4149     if (!DirectBaseSpec && !VirtualBaseSpec) {
4150       // If the class has any dependent bases, then it's possible that
4151       // one of those types will resolve to the same type as
4152       // BaseType. Therefore, just treat this as a dependent base
4153       // class initialization.  FIXME: Should we try to check the
4154       // initialization anyway? It seems odd.
4155       if (ClassDecl->hasAnyDependentBases())
4156         Dependent = true;
4157       else
4158         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4159           << BaseType << Context.getTypeDeclType(ClassDecl)
4160           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4161     }
4162   }
4163 
4164   if (Dependent) {
4165     DiscardCleanupsInEvaluationContext();
4166 
4167     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4168                                             /*IsVirtual=*/false,
4169                                             InitRange.getBegin(), Init,
4170                                             InitRange.getEnd(), EllipsisLoc);
4171   }
4172 
4173   // C++ [base.class.init]p2:
4174   //   If a mem-initializer-id is ambiguous because it designates both
4175   //   a direct non-virtual base class and an inherited virtual base
4176   //   class, the mem-initializer is ill-formed.
4177   if (DirectBaseSpec && VirtualBaseSpec)
4178     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4179       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4180 
4181   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4182   if (!BaseSpec)
4183     BaseSpec = VirtualBaseSpec;
4184 
4185   // Initialize the base.
4186   bool InitList = true;
4187   MultiExprArg Args = Init;
4188   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4189     InitList = false;
4190     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4191   }
4192 
4193   InitializedEntity BaseEntity =
4194     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4195   InitializationKind Kind =
4196       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4197                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4198                                                   InitRange.getEnd());
4199   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4200   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4201   if (BaseInit.isInvalid())
4202     return true;
4203 
4204   // C++11 [class.base.init]p7:
4205   //   The initialization of each base and member constitutes a
4206   //   full-expression.
4207   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4208   if (BaseInit.isInvalid())
4209     return true;
4210 
4211   // If we are in a dependent context, template instantiation will
4212   // perform this type-checking again. Just save the arguments that we
4213   // received in a ParenListExpr.
4214   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4215   // of the information that we have about the base
4216   // initializer. However, deconstructing the ASTs is a dicey process,
4217   // and this approach is far more likely to get the corner cases right.
4218   if (CurContext->isDependentContext())
4219     BaseInit = Init;
4220 
4221   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4222                                           BaseSpec->isVirtual(),
4223                                           InitRange.getBegin(),
4224                                           BaseInit.getAs<Expr>(),
4225                                           InitRange.getEnd(), EllipsisLoc);
4226 }
4227 
4228 // Create a static_cast\<T&&>(expr).
4229 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4230   if (T.isNull()) T = E->getType();
4231   QualType TargetType = SemaRef.BuildReferenceType(
4232       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4233   SourceLocation ExprLoc = E->getLocStart();
4234   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4235       TargetType, ExprLoc);
4236 
4237   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4238                                    SourceRange(ExprLoc, ExprLoc),
4239                                    E->getSourceRange()).get();
4240 }
4241 
4242 /// ImplicitInitializerKind - How an implicit base or member initializer should
4243 /// initialize its base or member.
4244 enum ImplicitInitializerKind {
4245   IIK_Default,
4246   IIK_Copy,
4247   IIK_Move,
4248   IIK_Inherit
4249 };
4250 
4251 static bool
4252 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4253                              ImplicitInitializerKind ImplicitInitKind,
4254                              CXXBaseSpecifier *BaseSpec,
4255                              bool IsInheritedVirtualBase,
4256                              CXXCtorInitializer *&CXXBaseInit) {
4257   InitializedEntity InitEntity
4258     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4259                                         IsInheritedVirtualBase);
4260 
4261   ExprResult BaseInit;
4262 
4263   switch (ImplicitInitKind) {
4264   case IIK_Inherit:
4265   case IIK_Default: {
4266     InitializationKind InitKind
4267       = InitializationKind::CreateDefault(Constructor->getLocation());
4268     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4269     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4270     break;
4271   }
4272 
4273   case IIK_Move:
4274   case IIK_Copy: {
4275     bool Moving = ImplicitInitKind == IIK_Move;
4276     ParmVarDecl *Param = Constructor->getParamDecl(0);
4277     QualType ParamType = Param->getType().getNonReferenceType();
4278 
4279     Expr *CopyCtorArg =
4280       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4281                           SourceLocation(), Param, false,
4282                           Constructor->getLocation(), ParamType,
4283                           VK_LValue, nullptr);
4284 
4285     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4286 
4287     // Cast to the base class to avoid ambiguities.
4288     QualType ArgTy =
4289       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4290                                        ParamType.getQualifiers());
4291 
4292     if (Moving) {
4293       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4294     }
4295 
4296     CXXCastPath BasePath;
4297     BasePath.push_back(BaseSpec);
4298     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4299                                             CK_UncheckedDerivedToBase,
4300                                             Moving ? VK_XValue : VK_LValue,
4301                                             &BasePath).get();
4302 
4303     InitializationKind InitKind
4304       = InitializationKind::CreateDirect(Constructor->getLocation(),
4305                                          SourceLocation(), SourceLocation());
4306     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4307     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4308     break;
4309   }
4310   }
4311 
4312   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4313   if (BaseInit.isInvalid())
4314     return true;
4315 
4316   CXXBaseInit =
4317     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4318                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4319                                                         SourceLocation()),
4320                                              BaseSpec->isVirtual(),
4321                                              SourceLocation(),
4322                                              BaseInit.getAs<Expr>(),
4323                                              SourceLocation(),
4324                                              SourceLocation());
4325 
4326   return false;
4327 }
4328 
4329 static bool RefersToRValueRef(Expr *MemRef) {
4330   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4331   return Referenced->getType()->isRValueReferenceType();
4332 }
4333 
4334 static bool
4335 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4336                                ImplicitInitializerKind ImplicitInitKind,
4337                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4338                                CXXCtorInitializer *&CXXMemberInit) {
4339   if (Field->isInvalidDecl())
4340     return true;
4341 
4342   SourceLocation Loc = Constructor->getLocation();
4343 
4344   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4345     bool Moving = ImplicitInitKind == IIK_Move;
4346     ParmVarDecl *Param = Constructor->getParamDecl(0);
4347     QualType ParamType = Param->getType().getNonReferenceType();
4348 
4349     // Suppress copying zero-width bitfields.
4350     if (Field->isZeroLengthBitField(SemaRef.Context))
4351       return false;
4352 
4353     Expr *MemberExprBase =
4354       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4355                           SourceLocation(), Param, false,
4356                           Loc, ParamType, VK_LValue, nullptr);
4357 
4358     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4359 
4360     if (Moving) {
4361       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4362     }
4363 
4364     // Build a reference to this field within the parameter.
4365     CXXScopeSpec SS;
4366     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4367                               Sema::LookupMemberName);
4368     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4369                                   : cast<ValueDecl>(Field), AS_public);
4370     MemberLookup.resolveKind();
4371     ExprResult CtorArg
4372       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4373                                          ParamType, Loc,
4374                                          /*IsArrow=*/false,
4375                                          SS,
4376                                          /*TemplateKWLoc=*/SourceLocation(),
4377                                          /*FirstQualifierInScope=*/nullptr,
4378                                          MemberLookup,
4379                                          /*TemplateArgs=*/nullptr,
4380                                          /*S*/nullptr);
4381     if (CtorArg.isInvalid())
4382       return true;
4383 
4384     // C++11 [class.copy]p15:
4385     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4386     //     with static_cast<T&&>(x.m);
4387     if (RefersToRValueRef(CtorArg.get())) {
4388       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4389     }
4390 
4391     InitializedEntity Entity =
4392         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4393                                                        /*Implicit*/ true)
4394                  : InitializedEntity::InitializeMember(Field, nullptr,
4395                                                        /*Implicit*/ true);
4396 
4397     // Direct-initialize to use the copy constructor.
4398     InitializationKind InitKind =
4399       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4400 
4401     Expr *CtorArgE = CtorArg.getAs<Expr>();
4402     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4403     ExprResult MemberInit =
4404         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4405     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4406     if (MemberInit.isInvalid())
4407       return true;
4408 
4409     if (Indirect)
4410       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4411           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4412     else
4413       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4414           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4415     return false;
4416   }
4417 
4418   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4419          "Unhandled implicit init kind!");
4420 
4421   QualType FieldBaseElementType =
4422     SemaRef.Context.getBaseElementType(Field->getType());
4423 
4424   if (FieldBaseElementType->isRecordType()) {
4425     InitializedEntity InitEntity =
4426         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4427                                                        /*Implicit*/ true)
4428                  : InitializedEntity::InitializeMember(Field, nullptr,
4429                                                        /*Implicit*/ true);
4430     InitializationKind InitKind =
4431       InitializationKind::CreateDefault(Loc);
4432 
4433     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4434     ExprResult MemberInit =
4435       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4436 
4437     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4438     if (MemberInit.isInvalid())
4439       return true;
4440 
4441     if (Indirect)
4442       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4443                                                                Indirect, Loc,
4444                                                                Loc,
4445                                                                MemberInit.get(),
4446                                                                Loc);
4447     else
4448       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4449                                                                Field, Loc, Loc,
4450                                                                MemberInit.get(),
4451                                                                Loc);
4452     return false;
4453   }
4454 
4455   if (!Field->getParent()->isUnion()) {
4456     if (FieldBaseElementType->isReferenceType()) {
4457       SemaRef.Diag(Constructor->getLocation(),
4458                    diag::err_uninitialized_member_in_ctor)
4459       << (int)Constructor->isImplicit()
4460       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4461       << 0 << Field->getDeclName();
4462       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4463       return true;
4464     }
4465 
4466     if (FieldBaseElementType.isConstQualified()) {
4467       SemaRef.Diag(Constructor->getLocation(),
4468                    diag::err_uninitialized_member_in_ctor)
4469       << (int)Constructor->isImplicit()
4470       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4471       << 1 << Field->getDeclName();
4472       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4473       return true;
4474     }
4475   }
4476 
4477   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4478     // ARC and Weak:
4479     //   Default-initialize Objective-C pointers to NULL.
4480     CXXMemberInit
4481       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4482                                                  Loc, Loc,
4483                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4484                                                  Loc);
4485     return false;
4486   }
4487 
4488   // Nothing to initialize.
4489   CXXMemberInit = nullptr;
4490   return false;
4491 }
4492 
4493 namespace {
4494 struct BaseAndFieldInfo {
4495   Sema &S;
4496   CXXConstructorDecl *Ctor;
4497   bool AnyErrorsInInits;
4498   ImplicitInitializerKind IIK;
4499   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4500   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4501   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4502 
4503   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4504     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4505     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4506     if (Ctor->getInheritedConstructor())
4507       IIK = IIK_Inherit;
4508     else if (Generated && Ctor->isCopyConstructor())
4509       IIK = IIK_Copy;
4510     else if (Generated && Ctor->isMoveConstructor())
4511       IIK = IIK_Move;
4512     else
4513       IIK = IIK_Default;
4514   }
4515 
4516   bool isImplicitCopyOrMove() const {
4517     switch (IIK) {
4518     case IIK_Copy:
4519     case IIK_Move:
4520       return true;
4521 
4522     case IIK_Default:
4523     case IIK_Inherit:
4524       return false;
4525     }
4526 
4527     llvm_unreachable("Invalid ImplicitInitializerKind!");
4528   }
4529 
4530   bool addFieldInitializer(CXXCtorInitializer *Init) {
4531     AllToInit.push_back(Init);
4532 
4533     // Check whether this initializer makes the field "used".
4534     if (Init->getInit()->HasSideEffects(S.Context))
4535       S.UnusedPrivateFields.remove(Init->getAnyMember());
4536 
4537     return false;
4538   }
4539 
4540   bool isInactiveUnionMember(FieldDecl *Field) {
4541     RecordDecl *Record = Field->getParent();
4542     if (!Record->isUnion())
4543       return false;
4544 
4545     if (FieldDecl *Active =
4546             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4547       return Active != Field->getCanonicalDecl();
4548 
4549     // In an implicit copy or move constructor, ignore any in-class initializer.
4550     if (isImplicitCopyOrMove())
4551       return true;
4552 
4553     // If there's no explicit initialization, the field is active only if it
4554     // has an in-class initializer...
4555     if (Field->hasInClassInitializer())
4556       return false;
4557     // ... or it's an anonymous struct or union whose class has an in-class
4558     // initializer.
4559     if (!Field->isAnonymousStructOrUnion())
4560       return true;
4561     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4562     return !FieldRD->hasInClassInitializer();
4563   }
4564 
4565   /// Determine whether the given field is, or is within, a union member
4566   /// that is inactive (because there was an initializer given for a different
4567   /// member of the union, or because the union was not initialized at all).
4568   bool isWithinInactiveUnionMember(FieldDecl *Field,
4569                                    IndirectFieldDecl *Indirect) {
4570     if (!Indirect)
4571       return isInactiveUnionMember(Field);
4572 
4573     for (auto *C : Indirect->chain()) {
4574       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4575       if (Field && isInactiveUnionMember(Field))
4576         return true;
4577     }
4578     return false;
4579   }
4580 };
4581 }
4582 
4583 /// Determine whether the given type is an incomplete or zero-lenfgth
4584 /// array type.
4585 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4586   if (T->isIncompleteArrayType())
4587     return true;
4588 
4589   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4590     if (!ArrayT->getSize())
4591       return true;
4592 
4593     T = ArrayT->getElementType();
4594   }
4595 
4596   return false;
4597 }
4598 
4599 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4600                                     FieldDecl *Field,
4601                                     IndirectFieldDecl *Indirect = nullptr) {
4602   if (Field->isInvalidDecl())
4603     return false;
4604 
4605   // Overwhelmingly common case: we have a direct initializer for this field.
4606   if (CXXCtorInitializer *Init =
4607           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4608     return Info.addFieldInitializer(Init);
4609 
4610   // C++11 [class.base.init]p8:
4611   //   if the entity is a non-static data member that has a
4612   //   brace-or-equal-initializer and either
4613   //   -- the constructor's class is a union and no other variant member of that
4614   //      union is designated by a mem-initializer-id or
4615   //   -- the constructor's class is not a union, and, if the entity is a member
4616   //      of an anonymous union, no other member of that union is designated by
4617   //      a mem-initializer-id,
4618   //   the entity is initialized as specified in [dcl.init].
4619   //
4620   // We also apply the same rules to handle anonymous structs within anonymous
4621   // unions.
4622   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4623     return false;
4624 
4625   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4626     ExprResult DIE =
4627         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4628     if (DIE.isInvalid())
4629       return true;
4630     CXXCtorInitializer *Init;
4631     if (Indirect)
4632       Init = new (SemaRef.Context)
4633           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4634                              SourceLocation(), DIE.get(), SourceLocation());
4635     else
4636       Init = new (SemaRef.Context)
4637           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4638                              SourceLocation(), DIE.get(), SourceLocation());
4639     return Info.addFieldInitializer(Init);
4640   }
4641 
4642   // Don't initialize incomplete or zero-length arrays.
4643   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4644     return false;
4645 
4646   // Don't try to build an implicit initializer if there were semantic
4647   // errors in any of the initializers (and therefore we might be
4648   // missing some that the user actually wrote).
4649   if (Info.AnyErrorsInInits)
4650     return false;
4651 
4652   CXXCtorInitializer *Init = nullptr;
4653   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4654                                      Indirect, Init))
4655     return true;
4656 
4657   if (!Init)
4658     return false;
4659 
4660   return Info.addFieldInitializer(Init);
4661 }
4662 
4663 bool
4664 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4665                                CXXCtorInitializer *Initializer) {
4666   assert(Initializer->isDelegatingInitializer());
4667   Constructor->setNumCtorInitializers(1);
4668   CXXCtorInitializer **initializer =
4669     new (Context) CXXCtorInitializer*[1];
4670   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4671   Constructor->setCtorInitializers(initializer);
4672 
4673   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4674     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4675     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4676   }
4677 
4678   DelegatingCtorDecls.push_back(Constructor);
4679 
4680   DiagnoseUninitializedFields(*this, Constructor);
4681 
4682   return false;
4683 }
4684 
4685 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4686                                ArrayRef<CXXCtorInitializer *> Initializers) {
4687   if (Constructor->isDependentContext()) {
4688     // Just store the initializers as written, they will be checked during
4689     // instantiation.
4690     if (!Initializers.empty()) {
4691       Constructor->setNumCtorInitializers(Initializers.size());
4692       CXXCtorInitializer **baseOrMemberInitializers =
4693         new (Context) CXXCtorInitializer*[Initializers.size()];
4694       memcpy(baseOrMemberInitializers, Initializers.data(),
4695              Initializers.size() * sizeof(CXXCtorInitializer*));
4696       Constructor->setCtorInitializers(baseOrMemberInitializers);
4697     }
4698 
4699     // Let template instantiation know whether we had errors.
4700     if (AnyErrors)
4701       Constructor->setInvalidDecl();
4702 
4703     return false;
4704   }
4705 
4706   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4707 
4708   // We need to build the initializer AST according to order of construction
4709   // and not what user specified in the Initializers list.
4710   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4711   if (!ClassDecl)
4712     return true;
4713 
4714   bool HadError = false;
4715 
4716   for (unsigned i = 0; i < Initializers.size(); i++) {
4717     CXXCtorInitializer *Member = Initializers[i];
4718 
4719     if (Member->isBaseInitializer())
4720       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4721     else {
4722       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4723 
4724       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4725         for (auto *C : F->chain()) {
4726           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4727           if (FD && FD->getParent()->isUnion())
4728             Info.ActiveUnionMember.insert(std::make_pair(
4729                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4730         }
4731       } else if (FieldDecl *FD = Member->getMember()) {
4732         if (FD->getParent()->isUnion())
4733           Info.ActiveUnionMember.insert(std::make_pair(
4734               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4735       }
4736     }
4737   }
4738 
4739   // Keep track of the direct virtual bases.
4740   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4741   for (auto &I : ClassDecl->bases()) {
4742     if (I.isVirtual())
4743       DirectVBases.insert(&I);
4744   }
4745 
4746   // Push virtual bases before others.
4747   for (auto &VBase : ClassDecl->vbases()) {
4748     if (CXXCtorInitializer *Value
4749         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4750       // [class.base.init]p7, per DR257:
4751       //   A mem-initializer where the mem-initializer-id names a virtual base
4752       //   class is ignored during execution of a constructor of any class that
4753       //   is not the most derived class.
4754       if (ClassDecl->isAbstract()) {
4755         // FIXME: Provide a fixit to remove the base specifier. This requires
4756         // tracking the location of the associated comma for a base specifier.
4757         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4758           << VBase.getType() << ClassDecl;
4759         DiagnoseAbstractType(ClassDecl);
4760       }
4761 
4762       Info.AllToInit.push_back(Value);
4763     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4764       // [class.base.init]p8, per DR257:
4765       //   If a given [...] base class is not named by a mem-initializer-id
4766       //   [...] and the entity is not a virtual base class of an abstract
4767       //   class, then [...] the entity is default-initialized.
4768       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4769       CXXCtorInitializer *CXXBaseInit;
4770       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4771                                        &VBase, IsInheritedVirtualBase,
4772                                        CXXBaseInit)) {
4773         HadError = true;
4774         continue;
4775       }
4776 
4777       Info.AllToInit.push_back(CXXBaseInit);
4778     }
4779   }
4780 
4781   // Non-virtual bases.
4782   for (auto &Base : ClassDecl->bases()) {
4783     // Virtuals are in the virtual base list and already constructed.
4784     if (Base.isVirtual())
4785       continue;
4786 
4787     if (CXXCtorInitializer *Value
4788           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4789       Info.AllToInit.push_back(Value);
4790     } else if (!AnyErrors) {
4791       CXXCtorInitializer *CXXBaseInit;
4792       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4793                                        &Base, /*IsInheritedVirtualBase=*/false,
4794                                        CXXBaseInit)) {
4795         HadError = true;
4796         continue;
4797       }
4798 
4799       Info.AllToInit.push_back(CXXBaseInit);
4800     }
4801   }
4802 
4803   // Fields.
4804   for (auto *Mem : ClassDecl->decls()) {
4805     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4806       // C++ [class.bit]p2:
4807       //   A declaration for a bit-field that omits the identifier declares an
4808       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4809       //   initialized.
4810       if (F->isUnnamedBitfield())
4811         continue;
4812 
4813       // If we're not generating the implicit copy/move constructor, then we'll
4814       // handle anonymous struct/union fields based on their individual
4815       // indirect fields.
4816       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4817         continue;
4818 
4819       if (CollectFieldInitializer(*this, Info, F))
4820         HadError = true;
4821       continue;
4822     }
4823 
4824     // Beyond this point, we only consider default initialization.
4825     if (Info.isImplicitCopyOrMove())
4826       continue;
4827 
4828     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4829       if (F->getType()->isIncompleteArrayType()) {
4830         assert(ClassDecl->hasFlexibleArrayMember() &&
4831                "Incomplete array type is not valid");
4832         continue;
4833       }
4834 
4835       // Initialize each field of an anonymous struct individually.
4836       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4837         HadError = true;
4838 
4839       continue;
4840     }
4841   }
4842 
4843   unsigned NumInitializers = Info.AllToInit.size();
4844   if (NumInitializers > 0) {
4845     Constructor->setNumCtorInitializers(NumInitializers);
4846     CXXCtorInitializer **baseOrMemberInitializers =
4847       new (Context) CXXCtorInitializer*[NumInitializers];
4848     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4849            NumInitializers * sizeof(CXXCtorInitializer*));
4850     Constructor->setCtorInitializers(baseOrMemberInitializers);
4851 
4852     // Constructors implicitly reference the base and member
4853     // destructors.
4854     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4855                                            Constructor->getParent());
4856   }
4857 
4858   return HadError;
4859 }
4860 
4861 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4862   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4863     const RecordDecl *RD = RT->getDecl();
4864     if (RD->isAnonymousStructOrUnion()) {
4865       for (auto *Field : RD->fields())
4866         PopulateKeysForFields(Field, IdealInits);
4867       return;
4868     }
4869   }
4870   IdealInits.push_back(Field->getCanonicalDecl());
4871 }
4872 
4873 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4874   return Context.getCanonicalType(BaseType).getTypePtr();
4875 }
4876 
4877 static const void *GetKeyForMember(ASTContext &Context,
4878                                    CXXCtorInitializer *Member) {
4879   if (!Member->isAnyMemberInitializer())
4880     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4881 
4882   return Member->getAnyMember()->getCanonicalDecl();
4883 }
4884 
4885 static void DiagnoseBaseOrMemInitializerOrder(
4886     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4887     ArrayRef<CXXCtorInitializer *> Inits) {
4888   if (Constructor->getDeclContext()->isDependentContext())
4889     return;
4890 
4891   // Don't check initializers order unless the warning is enabled at the
4892   // location of at least one initializer.
4893   bool ShouldCheckOrder = false;
4894   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4895     CXXCtorInitializer *Init = Inits[InitIndex];
4896     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4897                                  Init->getSourceLocation())) {
4898       ShouldCheckOrder = true;
4899       break;
4900     }
4901   }
4902   if (!ShouldCheckOrder)
4903     return;
4904 
4905   // Build the list of bases and members in the order that they'll
4906   // actually be initialized.  The explicit initializers should be in
4907   // this same order but may be missing things.
4908   SmallVector<const void*, 32> IdealInitKeys;
4909 
4910   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4911 
4912   // 1. Virtual bases.
4913   for (const auto &VBase : ClassDecl->vbases())
4914     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4915 
4916   // 2. Non-virtual bases.
4917   for (const auto &Base : ClassDecl->bases()) {
4918     if (Base.isVirtual())
4919       continue;
4920     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4921   }
4922 
4923   // 3. Direct fields.
4924   for (auto *Field : ClassDecl->fields()) {
4925     if (Field->isUnnamedBitfield())
4926       continue;
4927 
4928     PopulateKeysForFields(Field, IdealInitKeys);
4929   }
4930 
4931   unsigned NumIdealInits = IdealInitKeys.size();
4932   unsigned IdealIndex = 0;
4933 
4934   CXXCtorInitializer *PrevInit = nullptr;
4935   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4936     CXXCtorInitializer *Init = Inits[InitIndex];
4937     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4938 
4939     // Scan forward to try to find this initializer in the idealized
4940     // initializers list.
4941     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4942       if (InitKey == IdealInitKeys[IdealIndex])
4943         break;
4944 
4945     // If we didn't find this initializer, it must be because we
4946     // scanned past it on a previous iteration.  That can only
4947     // happen if we're out of order;  emit a warning.
4948     if (IdealIndex == NumIdealInits && PrevInit) {
4949       Sema::SemaDiagnosticBuilder D =
4950         SemaRef.Diag(PrevInit->getSourceLocation(),
4951                      diag::warn_initializer_out_of_order);
4952 
4953       if (PrevInit->isAnyMemberInitializer())
4954         D << 0 << PrevInit->getAnyMember()->getDeclName();
4955       else
4956         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4957 
4958       if (Init->isAnyMemberInitializer())
4959         D << 0 << Init->getAnyMember()->getDeclName();
4960       else
4961         D << 1 << Init->getTypeSourceInfo()->getType();
4962 
4963       // Move back to the initializer's location in the ideal list.
4964       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4965         if (InitKey == IdealInitKeys[IdealIndex])
4966           break;
4967 
4968       assert(IdealIndex < NumIdealInits &&
4969              "initializer not found in initializer list");
4970     }
4971 
4972     PrevInit = Init;
4973   }
4974 }
4975 
4976 namespace {
4977 bool CheckRedundantInit(Sema &S,
4978                         CXXCtorInitializer *Init,
4979                         CXXCtorInitializer *&PrevInit) {
4980   if (!PrevInit) {
4981     PrevInit = Init;
4982     return false;
4983   }
4984 
4985   if (FieldDecl *Field = Init->getAnyMember())
4986     S.Diag(Init->getSourceLocation(),
4987            diag::err_multiple_mem_initialization)
4988       << Field->getDeclName()
4989       << Init->getSourceRange();
4990   else {
4991     const Type *BaseClass = Init->getBaseClass();
4992     assert(BaseClass && "neither field nor base");
4993     S.Diag(Init->getSourceLocation(),
4994            diag::err_multiple_base_initialization)
4995       << QualType(BaseClass, 0)
4996       << Init->getSourceRange();
4997   }
4998   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4999     << 0 << PrevInit->getSourceRange();
5000 
5001   return true;
5002 }
5003 
5004 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5005 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5006 
5007 bool CheckRedundantUnionInit(Sema &S,
5008                              CXXCtorInitializer *Init,
5009                              RedundantUnionMap &Unions) {
5010   FieldDecl *Field = Init->getAnyMember();
5011   RecordDecl *Parent = Field->getParent();
5012   NamedDecl *Child = Field;
5013 
5014   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5015     if (Parent->isUnion()) {
5016       UnionEntry &En = Unions[Parent];
5017       if (En.first && En.first != Child) {
5018         S.Diag(Init->getSourceLocation(),
5019                diag::err_multiple_mem_union_initialization)
5020           << Field->getDeclName()
5021           << Init->getSourceRange();
5022         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5023           << 0 << En.second->getSourceRange();
5024         return true;
5025       }
5026       if (!En.first) {
5027         En.first = Child;
5028         En.second = Init;
5029       }
5030       if (!Parent->isAnonymousStructOrUnion())
5031         return false;
5032     }
5033 
5034     Child = Parent;
5035     Parent = cast<RecordDecl>(Parent->getDeclContext());
5036   }
5037 
5038   return false;
5039 }
5040 }
5041 
5042 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5043 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5044                                 SourceLocation ColonLoc,
5045                                 ArrayRef<CXXCtorInitializer*> MemInits,
5046                                 bool AnyErrors) {
5047   if (!ConstructorDecl)
5048     return;
5049 
5050   AdjustDeclIfTemplate(ConstructorDecl);
5051 
5052   CXXConstructorDecl *Constructor
5053     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5054 
5055   if (!Constructor) {
5056     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5057     return;
5058   }
5059 
5060   // Mapping for the duplicate initializers check.
5061   // For member initializers, this is keyed with a FieldDecl*.
5062   // For base initializers, this is keyed with a Type*.
5063   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5064 
5065   // Mapping for the inconsistent anonymous-union initializers check.
5066   RedundantUnionMap MemberUnions;
5067 
5068   bool HadError = false;
5069   for (unsigned i = 0; i < MemInits.size(); i++) {
5070     CXXCtorInitializer *Init = MemInits[i];
5071 
5072     // Set the source order index.
5073     Init->setSourceOrder(i);
5074 
5075     if (Init->isAnyMemberInitializer()) {
5076       const void *Key = GetKeyForMember(Context, Init);
5077       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5078           CheckRedundantUnionInit(*this, Init, MemberUnions))
5079         HadError = true;
5080     } else if (Init->isBaseInitializer()) {
5081       const void *Key = GetKeyForMember(Context, Init);
5082       if (CheckRedundantInit(*this, Init, Members[Key]))
5083         HadError = true;
5084     } else {
5085       assert(Init->isDelegatingInitializer());
5086       // This must be the only initializer
5087       if (MemInits.size() != 1) {
5088         Diag(Init->getSourceLocation(),
5089              diag::err_delegating_initializer_alone)
5090           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5091         // We will treat this as being the only initializer.
5092       }
5093       SetDelegatingInitializer(Constructor, MemInits[i]);
5094       // Return immediately as the initializer is set.
5095       return;
5096     }
5097   }
5098 
5099   if (HadError)
5100     return;
5101 
5102   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5103 
5104   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5105 
5106   DiagnoseUninitializedFields(*this, Constructor);
5107 }
5108 
5109 void
5110 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5111                                              CXXRecordDecl *ClassDecl) {
5112   // Ignore dependent contexts. Also ignore unions, since their members never
5113   // have destructors implicitly called.
5114   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5115     return;
5116 
5117   // FIXME: all the access-control diagnostics are positioned on the
5118   // field/base declaration.  That's probably good; that said, the
5119   // user might reasonably want to know why the destructor is being
5120   // emitted, and we currently don't say.
5121 
5122   // Non-static data members.
5123   for (auto *Field : ClassDecl->fields()) {
5124     if (Field->isInvalidDecl())
5125       continue;
5126 
5127     // Don't destroy incomplete or zero-length arrays.
5128     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5129       continue;
5130 
5131     QualType FieldType = Context.getBaseElementType(Field->getType());
5132 
5133     const RecordType* RT = FieldType->getAs<RecordType>();
5134     if (!RT)
5135       continue;
5136 
5137     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5138     if (FieldClassDecl->isInvalidDecl())
5139       continue;
5140     if (FieldClassDecl->hasIrrelevantDestructor())
5141       continue;
5142     // The destructor for an implicit anonymous union member is never invoked.
5143     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5144       continue;
5145 
5146     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5147     assert(Dtor && "No dtor found for FieldClassDecl!");
5148     CheckDestructorAccess(Field->getLocation(), Dtor,
5149                           PDiag(diag::err_access_dtor_field)
5150                             << Field->getDeclName()
5151                             << FieldType);
5152 
5153     MarkFunctionReferenced(Location, Dtor);
5154     DiagnoseUseOfDecl(Dtor, Location);
5155   }
5156 
5157   // We only potentially invoke the destructors of potentially constructed
5158   // subobjects.
5159   bool VisitVirtualBases = !ClassDecl->isAbstract();
5160 
5161   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5162 
5163   // Bases.
5164   for (const auto &Base : ClassDecl->bases()) {
5165     // Bases are always records in a well-formed non-dependent class.
5166     const RecordType *RT = Base.getType()->getAs<RecordType>();
5167 
5168     // Remember direct virtual bases.
5169     if (Base.isVirtual()) {
5170       if (!VisitVirtualBases)
5171         continue;
5172       DirectVirtualBases.insert(RT);
5173     }
5174 
5175     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5176     // If our base class is invalid, we probably can't get its dtor anyway.
5177     if (BaseClassDecl->isInvalidDecl())
5178       continue;
5179     if (BaseClassDecl->hasIrrelevantDestructor())
5180       continue;
5181 
5182     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5183     assert(Dtor && "No dtor found for BaseClassDecl!");
5184 
5185     // FIXME: caret should be on the start of the class name
5186     CheckDestructorAccess(Base.getLocStart(), Dtor,
5187                           PDiag(diag::err_access_dtor_base)
5188                             << Base.getType()
5189                             << Base.getSourceRange(),
5190                           Context.getTypeDeclType(ClassDecl));
5191 
5192     MarkFunctionReferenced(Location, Dtor);
5193     DiagnoseUseOfDecl(Dtor, Location);
5194   }
5195 
5196   if (!VisitVirtualBases)
5197     return;
5198 
5199   // Virtual bases.
5200   for (const auto &VBase : ClassDecl->vbases()) {
5201     // Bases are always records in a well-formed non-dependent class.
5202     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5203 
5204     // Ignore direct virtual bases.
5205     if (DirectVirtualBases.count(RT))
5206       continue;
5207 
5208     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5209     // If our base class is invalid, we probably can't get its dtor anyway.
5210     if (BaseClassDecl->isInvalidDecl())
5211       continue;
5212     if (BaseClassDecl->hasIrrelevantDestructor())
5213       continue;
5214 
5215     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5216     assert(Dtor && "No dtor found for BaseClassDecl!");
5217     if (CheckDestructorAccess(
5218             ClassDecl->getLocation(), Dtor,
5219             PDiag(diag::err_access_dtor_vbase)
5220                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5221             Context.getTypeDeclType(ClassDecl)) ==
5222         AR_accessible) {
5223       CheckDerivedToBaseConversion(
5224           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5225           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5226           SourceRange(), DeclarationName(), nullptr);
5227     }
5228 
5229     MarkFunctionReferenced(Location, Dtor);
5230     DiagnoseUseOfDecl(Dtor, Location);
5231   }
5232 }
5233 
5234 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5235   if (!CDtorDecl)
5236     return;
5237 
5238   if (CXXConstructorDecl *Constructor
5239       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5240     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5241     DiagnoseUninitializedFields(*this, Constructor);
5242   }
5243 }
5244 
5245 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5246   if (!getLangOpts().CPlusPlus)
5247     return false;
5248 
5249   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5250   if (!RD)
5251     return false;
5252 
5253   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5254   // class template specialization here, but doing so breaks a lot of code.
5255 
5256   // We can't answer whether something is abstract until it has a
5257   // definition. If it's currently being defined, we'll walk back
5258   // over all the declarations when we have a full definition.
5259   const CXXRecordDecl *Def = RD->getDefinition();
5260   if (!Def || Def->isBeingDefined())
5261     return false;
5262 
5263   return RD->isAbstract();
5264 }
5265 
5266 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5267                                   TypeDiagnoser &Diagnoser) {
5268   if (!isAbstractType(Loc, T))
5269     return false;
5270 
5271   T = Context.getBaseElementType(T);
5272   Diagnoser.diagnose(*this, Loc, T);
5273   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5274   return true;
5275 }
5276 
5277 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5278   // Check if we've already emitted the list of pure virtual functions
5279   // for this class.
5280   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5281     return;
5282 
5283   // If the diagnostic is suppressed, don't emit the notes. We're only
5284   // going to emit them once, so try to attach them to a diagnostic we're
5285   // actually going to show.
5286   if (Diags.isLastDiagnosticIgnored())
5287     return;
5288 
5289   CXXFinalOverriderMap FinalOverriders;
5290   RD->getFinalOverriders(FinalOverriders);
5291 
5292   // Keep a set of seen pure methods so we won't diagnose the same method
5293   // more than once.
5294   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5295 
5296   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5297                                    MEnd = FinalOverriders.end();
5298        M != MEnd;
5299        ++M) {
5300     for (OverridingMethods::iterator SO = M->second.begin(),
5301                                   SOEnd = M->second.end();
5302          SO != SOEnd; ++SO) {
5303       // C++ [class.abstract]p4:
5304       //   A class is abstract if it contains or inherits at least one
5305       //   pure virtual function for which the final overrider is pure
5306       //   virtual.
5307 
5308       //
5309       if (SO->second.size() != 1)
5310         continue;
5311 
5312       if (!SO->second.front().Method->isPure())
5313         continue;
5314 
5315       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5316         continue;
5317 
5318       Diag(SO->second.front().Method->getLocation(),
5319            diag::note_pure_virtual_function)
5320         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5321     }
5322   }
5323 
5324   if (!PureVirtualClassDiagSet)
5325     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5326   PureVirtualClassDiagSet->insert(RD);
5327 }
5328 
5329 namespace {
5330 struct AbstractUsageInfo {
5331   Sema &S;
5332   CXXRecordDecl *Record;
5333   CanQualType AbstractType;
5334   bool Invalid;
5335 
5336   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5337     : S(S), Record(Record),
5338       AbstractType(S.Context.getCanonicalType(
5339                    S.Context.getTypeDeclType(Record))),
5340       Invalid(false) {}
5341 
5342   void DiagnoseAbstractType() {
5343     if (Invalid) return;
5344     S.DiagnoseAbstractType(Record);
5345     Invalid = true;
5346   }
5347 
5348   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5349 };
5350 
5351 struct CheckAbstractUsage {
5352   AbstractUsageInfo &Info;
5353   const NamedDecl *Ctx;
5354 
5355   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5356     : Info(Info), Ctx(Ctx) {}
5357 
5358   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5359     switch (TL.getTypeLocClass()) {
5360 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5361 #define TYPELOC(CLASS, PARENT) \
5362     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5363 #include "clang/AST/TypeLocNodes.def"
5364     }
5365   }
5366 
5367   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5368     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5369     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5370       if (!TL.getParam(I))
5371         continue;
5372 
5373       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5374       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5375     }
5376   }
5377 
5378   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5379     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5380   }
5381 
5382   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5383     // Visit the type parameters from a permissive context.
5384     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5385       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5386       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5387         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5388           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5389       // TODO: other template argument types?
5390     }
5391   }
5392 
5393   // Visit pointee types from a permissive context.
5394 #define CheckPolymorphic(Type) \
5395   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5396     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5397   }
5398   CheckPolymorphic(PointerTypeLoc)
5399   CheckPolymorphic(ReferenceTypeLoc)
5400   CheckPolymorphic(MemberPointerTypeLoc)
5401   CheckPolymorphic(BlockPointerTypeLoc)
5402   CheckPolymorphic(AtomicTypeLoc)
5403 
5404   /// Handle all the types we haven't given a more specific
5405   /// implementation for above.
5406   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5407     // Every other kind of type that we haven't called out already
5408     // that has an inner type is either (1) sugar or (2) contains that
5409     // inner type in some way as a subobject.
5410     if (TypeLoc Next = TL.getNextTypeLoc())
5411       return Visit(Next, Sel);
5412 
5413     // If there's no inner type and we're in a permissive context,
5414     // don't diagnose.
5415     if (Sel == Sema::AbstractNone) return;
5416 
5417     // Check whether the type matches the abstract type.
5418     QualType T = TL.getType();
5419     if (T->isArrayType()) {
5420       Sel = Sema::AbstractArrayType;
5421       T = Info.S.Context.getBaseElementType(T);
5422     }
5423     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5424     if (CT != Info.AbstractType) return;
5425 
5426     // It matched; do some magic.
5427     if (Sel == Sema::AbstractArrayType) {
5428       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5429         << T << TL.getSourceRange();
5430     } else {
5431       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5432         << Sel << T << TL.getSourceRange();
5433     }
5434     Info.DiagnoseAbstractType();
5435   }
5436 };
5437 
5438 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5439                                   Sema::AbstractDiagSelID Sel) {
5440   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5441 }
5442 
5443 }
5444 
5445 /// Check for invalid uses of an abstract type in a method declaration.
5446 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5447                                     CXXMethodDecl *MD) {
5448   // No need to do the check on definitions, which require that
5449   // the return/param types be complete.
5450   if (MD->doesThisDeclarationHaveABody())
5451     return;
5452 
5453   // For safety's sake, just ignore it if we don't have type source
5454   // information.  This should never happen for non-implicit methods,
5455   // but...
5456   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5457     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5458 }
5459 
5460 /// Check for invalid uses of an abstract type within a class definition.
5461 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5462                                     CXXRecordDecl *RD) {
5463   for (auto *D : RD->decls()) {
5464     if (D->isImplicit()) continue;
5465 
5466     // Methods and method templates.
5467     if (isa<CXXMethodDecl>(D)) {
5468       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5469     } else if (isa<FunctionTemplateDecl>(D)) {
5470       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5471       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5472 
5473     // Fields and static variables.
5474     } else if (isa<FieldDecl>(D)) {
5475       FieldDecl *FD = cast<FieldDecl>(D);
5476       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5477         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5478     } else if (isa<VarDecl>(D)) {
5479       VarDecl *VD = cast<VarDecl>(D);
5480       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5481         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5482 
5483     // Nested classes and class templates.
5484     } else if (isa<CXXRecordDecl>(D)) {
5485       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5486     } else if (isa<ClassTemplateDecl>(D)) {
5487       CheckAbstractClassUsage(Info,
5488                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5489     }
5490   }
5491 }
5492 
5493 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5494   Attr *ClassAttr = getDLLAttr(Class);
5495   if (!ClassAttr)
5496     return;
5497 
5498   assert(ClassAttr->getKind() == attr::DLLExport);
5499 
5500   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5501 
5502   if (TSK == TSK_ExplicitInstantiationDeclaration)
5503     // Don't go any further if this is just an explicit instantiation
5504     // declaration.
5505     return;
5506 
5507   for (Decl *Member : Class->decls()) {
5508     // Defined static variables that are members of an exported base
5509     // class must be marked export too.
5510     auto *VD = dyn_cast<VarDecl>(Member);
5511     if (VD && Member->getAttr<DLLExportAttr>() &&
5512         VD->getStorageClass() == SC_Static &&
5513         TSK == TSK_ImplicitInstantiation)
5514       S.MarkVariableReferenced(VD->getLocation(), VD);
5515 
5516     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5517     if (!MD)
5518       continue;
5519 
5520     if (Member->getAttr<DLLExportAttr>()) {
5521       if (MD->isUserProvided()) {
5522         // Instantiate non-default class member functions ...
5523 
5524         // .. except for certain kinds of template specializations.
5525         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5526           continue;
5527 
5528         S.MarkFunctionReferenced(Class->getLocation(), MD);
5529 
5530         // The function will be passed to the consumer when its definition is
5531         // encountered.
5532       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5533                  MD->isCopyAssignmentOperator() ||
5534                  MD->isMoveAssignmentOperator()) {
5535         // Synthesize and instantiate non-trivial implicit methods, explicitly
5536         // defaulted methods, and the copy and move assignment operators. The
5537         // latter are exported even if they are trivial, because the address of
5538         // an operator can be taken and should compare equal across libraries.
5539         DiagnosticErrorTrap Trap(S.Diags);
5540         S.MarkFunctionReferenced(Class->getLocation(), MD);
5541         if (Trap.hasErrorOccurred()) {
5542           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5543               << Class << !S.getLangOpts().CPlusPlus11;
5544           break;
5545         }
5546 
5547         // There is no later point when we will see the definition of this
5548         // function, so pass it to the consumer now.
5549         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5550       }
5551     }
5552   }
5553 }
5554 
5555 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5556                                                         CXXRecordDecl *Class) {
5557   // Only the MS ABI has default constructor closures, so we don't need to do
5558   // this semantic checking anywhere else.
5559   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5560     return;
5561 
5562   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5563   for (Decl *Member : Class->decls()) {
5564     // Look for exported default constructors.
5565     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5566     if (!CD || !CD->isDefaultConstructor())
5567       continue;
5568     auto *Attr = CD->getAttr<DLLExportAttr>();
5569     if (!Attr)
5570       continue;
5571 
5572     // If the class is non-dependent, mark the default arguments as ODR-used so
5573     // that we can properly codegen the constructor closure.
5574     if (!Class->isDependentContext()) {
5575       for (ParmVarDecl *PD : CD->parameters()) {
5576         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5577         S.DiscardCleanupsInEvaluationContext();
5578       }
5579     }
5580 
5581     if (LastExportedDefaultCtor) {
5582       S.Diag(LastExportedDefaultCtor->getLocation(),
5583              diag::err_attribute_dll_ambiguous_default_ctor)
5584           << Class;
5585       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5586           << CD->getDeclName();
5587       return;
5588     }
5589     LastExportedDefaultCtor = CD;
5590   }
5591 }
5592 
5593 void Sema::checkClassLevelSectionAttribute(CXXRecordDecl *Class) {
5594   // Mark any compiler-generated routines with the implicit Section attribute.
5595   for (auto *Method : Class->methods()) {
5596     if (Method->isUserProvided())
5597       continue;
5598     if (Attr *A = getImplicitSectionAttrForFunction(Method))
5599       Method->addAttr(A);
5600   }
5601 }
5602 
5603 /// Check class-level dllimport/dllexport attribute.
5604 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5605   Attr *ClassAttr = getDLLAttr(Class);
5606 
5607   // MSVC inherits DLL attributes to partial class template specializations.
5608   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5609     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5610       if (Attr *TemplateAttr =
5611               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5612         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5613         A->setInherited(true);
5614         ClassAttr = A;
5615       }
5616     }
5617   }
5618 
5619   if (!ClassAttr)
5620     return;
5621 
5622   if (!Class->isExternallyVisible()) {
5623     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5624         << Class << ClassAttr;
5625     return;
5626   }
5627 
5628   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5629       !ClassAttr->isInherited()) {
5630     // Diagnose dll attributes on members of class with dll attribute.
5631     for (Decl *Member : Class->decls()) {
5632       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5633         continue;
5634       InheritableAttr *MemberAttr = getDLLAttr(Member);
5635       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5636         continue;
5637 
5638       Diag(MemberAttr->getLocation(),
5639              diag::err_attribute_dll_member_of_dll_class)
5640           << MemberAttr << ClassAttr;
5641       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5642       Member->setInvalidDecl();
5643     }
5644   }
5645 
5646   if (Class->getDescribedClassTemplate())
5647     // Don't inherit dll attribute until the template is instantiated.
5648     return;
5649 
5650   // The class is either imported or exported.
5651   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5652 
5653   // Check if this was a dllimport attribute propagated from a derived class to
5654   // a base class template specialization. We don't apply these attributes to
5655   // static data members.
5656   const bool PropagatedImport =
5657       !ClassExported &&
5658       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5659 
5660   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5661 
5662   // Ignore explicit dllexport on explicit class template instantiation declarations.
5663   if (ClassExported && !ClassAttr->isInherited() &&
5664       TSK == TSK_ExplicitInstantiationDeclaration) {
5665     Class->dropAttr<DLLExportAttr>();
5666     return;
5667   }
5668 
5669   // Force declaration of implicit members so they can inherit the attribute.
5670   ForceDeclarationOfImplicitMembers(Class);
5671 
5672   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5673   // seem to be true in practice?
5674 
5675   for (Decl *Member : Class->decls()) {
5676     VarDecl *VD = dyn_cast<VarDecl>(Member);
5677     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5678 
5679     // Only methods and static fields inherit the attributes.
5680     if (!VD && !MD)
5681       continue;
5682 
5683     if (MD) {
5684       // Don't process deleted methods.
5685       if (MD->isDeleted())
5686         continue;
5687 
5688       if (MD->isInlined()) {
5689         // MinGW does not import or export inline methods.
5690         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5691             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5692           continue;
5693 
5694         // MSVC versions before 2015 don't export the move assignment operators
5695         // and move constructor, so don't attempt to import/export them if
5696         // we have a definition.
5697         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5698         if ((MD->isMoveAssignmentOperator() ||
5699              (Ctor && Ctor->isMoveConstructor())) &&
5700             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5701           continue;
5702 
5703         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5704         // operator is exported anyway.
5705         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5706             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5707           continue;
5708       }
5709     }
5710 
5711     // Don't apply dllimport attributes to static data members of class template
5712     // instantiations when the attribute is propagated from a derived class.
5713     if (VD && PropagatedImport)
5714       continue;
5715 
5716     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5717       continue;
5718 
5719     if (!getDLLAttr(Member)) {
5720       auto *NewAttr =
5721           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5722       NewAttr->setInherited(true);
5723       Member->addAttr(NewAttr);
5724 
5725       if (MD) {
5726         // Propagate DLLAttr to friend re-declarations of MD that have already
5727         // been constructed.
5728         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5729              FD = FD->getPreviousDecl()) {
5730           if (FD->getFriendObjectKind() == Decl::FOK_None)
5731             continue;
5732           assert(!getDLLAttr(FD) &&
5733                  "friend re-decl should not already have a DLLAttr");
5734           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5735           NewAttr->setInherited(true);
5736           FD->addAttr(NewAttr);
5737         }
5738       }
5739     }
5740   }
5741 
5742   if (ClassExported)
5743     DelayedDllExportClasses.push_back(Class);
5744 }
5745 
5746 /// Perform propagation of DLL attributes from a derived class to a
5747 /// templated base class for MS compatibility.
5748 void Sema::propagateDLLAttrToBaseClassTemplate(
5749     CXXRecordDecl *Class, Attr *ClassAttr,
5750     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5751   if (getDLLAttr(
5752           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5753     // If the base class template has a DLL attribute, don't try to change it.
5754     return;
5755   }
5756 
5757   auto TSK = BaseTemplateSpec->getSpecializationKind();
5758   if (!getDLLAttr(BaseTemplateSpec) &&
5759       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5760        TSK == TSK_ImplicitInstantiation)) {
5761     // The template hasn't been instantiated yet (or it has, but only as an
5762     // explicit instantiation declaration or implicit instantiation, which means
5763     // we haven't codegenned any members yet), so propagate the attribute.
5764     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5765     NewAttr->setInherited(true);
5766     BaseTemplateSpec->addAttr(NewAttr);
5767 
5768     // If this was an import, mark that we propagated it from a derived class to
5769     // a base class template specialization.
5770     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5771       ImportAttr->setPropagatedToBaseTemplate();
5772 
5773     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5774     // needs to be run again to work see the new attribute. Otherwise this will
5775     // get run whenever the template is instantiated.
5776     if (TSK != TSK_Undeclared)
5777       checkClassLevelDLLAttribute(BaseTemplateSpec);
5778 
5779     return;
5780   }
5781 
5782   if (getDLLAttr(BaseTemplateSpec)) {
5783     // The template has already been specialized or instantiated with an
5784     // attribute, explicitly or through propagation. We should not try to change
5785     // it.
5786     return;
5787   }
5788 
5789   // The template was previously instantiated or explicitly specialized without
5790   // a dll attribute, It's too late for us to add an attribute, so warn that
5791   // this is unsupported.
5792   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5793       << BaseTemplateSpec->isExplicitSpecialization();
5794   Diag(ClassAttr->getLocation(), diag::note_attribute);
5795   if (BaseTemplateSpec->isExplicitSpecialization()) {
5796     Diag(BaseTemplateSpec->getLocation(),
5797            diag::note_template_class_explicit_specialization_was_here)
5798         << BaseTemplateSpec;
5799   } else {
5800     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5801            diag::note_template_class_instantiation_was_here)
5802         << BaseTemplateSpec;
5803   }
5804 }
5805 
5806 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5807                                         SourceLocation DefaultLoc) {
5808   switch (S.getSpecialMember(MD)) {
5809   case Sema::CXXDefaultConstructor:
5810     S.DefineImplicitDefaultConstructor(DefaultLoc,
5811                                        cast<CXXConstructorDecl>(MD));
5812     break;
5813   case Sema::CXXCopyConstructor:
5814     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5815     break;
5816   case Sema::CXXCopyAssignment:
5817     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5818     break;
5819   case Sema::CXXDestructor:
5820     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5821     break;
5822   case Sema::CXXMoveConstructor:
5823     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5824     break;
5825   case Sema::CXXMoveAssignment:
5826     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5827     break;
5828   case Sema::CXXInvalid:
5829     llvm_unreachable("Invalid special member.");
5830   }
5831 }
5832 
5833 /// Determine whether a type is permitted to be passed or returned in
5834 /// registers, per C++ [class.temporary]p3.
5835 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5836                                TargetInfo::CallingConvKind CCK) {
5837   if (D->isDependentType() || D->isInvalidDecl())
5838     return false;
5839 
5840   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5841   // The PS4 platform ABI follows the behavior of Clang 3.2.
5842   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5843     return !D->hasNonTrivialDestructorForCall() &&
5844            !D->hasNonTrivialCopyConstructorForCall();
5845 
5846   if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
5847     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5848     bool DtorIsTrivialForCall = false;
5849 
5850     // If a class has at least one non-deleted, trivial copy constructor, it
5851     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5852     //
5853     // Note: This permits classes with non-trivial copy or move ctors to be
5854     // passed in registers, so long as they *also* have a trivial copy ctor,
5855     // which is non-conforming.
5856     if (D->needsImplicitCopyConstructor()) {
5857       if (!D->defaultedCopyConstructorIsDeleted()) {
5858         if (D->hasTrivialCopyConstructor())
5859           CopyCtorIsTrivial = true;
5860         if (D->hasTrivialCopyConstructorForCall())
5861           CopyCtorIsTrivialForCall = true;
5862       }
5863     } else {
5864       for (const CXXConstructorDecl *CD : D->ctors()) {
5865         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5866           if (CD->isTrivial())
5867             CopyCtorIsTrivial = true;
5868           if (CD->isTrivialForCall())
5869             CopyCtorIsTrivialForCall = true;
5870         }
5871       }
5872     }
5873 
5874     if (D->needsImplicitDestructor()) {
5875       if (!D->defaultedDestructorIsDeleted() &&
5876           D->hasTrivialDestructorForCall())
5877         DtorIsTrivialForCall = true;
5878     } else if (const auto *DD = D->getDestructor()) {
5879       if (!DD->isDeleted() && DD->isTrivialForCall())
5880         DtorIsTrivialForCall = true;
5881     }
5882 
5883     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5884     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5885       return true;
5886 
5887     // If a class has a destructor, we'd really like to pass it indirectly
5888     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5889     // impossible for small types, which it will pass in a single register or
5890     // stack slot. Most objects with dtors are large-ish, so handle that early.
5891     // We can't call out all large objects as being indirect because there are
5892     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5893     // how we pass large POD types.
5894 
5895     // Note: This permits small classes with nontrivial destructors to be
5896     // passed in registers, which is non-conforming.
5897     if (CopyCtorIsTrivial &&
5898         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5899       return true;
5900     return false;
5901   }
5902 
5903   // Per C++ [class.temporary]p3, the relevant condition is:
5904   //   each copy constructor, move constructor, and destructor of X is
5905   //   either trivial or deleted, and X has at least one non-deleted copy
5906   //   or move constructor
5907   bool HasNonDeletedCopyOrMove = false;
5908 
5909   if (D->needsImplicitCopyConstructor() &&
5910       !D->defaultedCopyConstructorIsDeleted()) {
5911     if (!D->hasTrivialCopyConstructorForCall())
5912       return false;
5913     HasNonDeletedCopyOrMove = true;
5914   }
5915 
5916   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5917       !D->defaultedMoveConstructorIsDeleted()) {
5918     if (!D->hasTrivialMoveConstructorForCall())
5919       return false;
5920     HasNonDeletedCopyOrMove = true;
5921   }
5922 
5923   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5924       !D->hasTrivialDestructorForCall())
5925     return false;
5926 
5927   for (const CXXMethodDecl *MD : D->methods()) {
5928     if (MD->isDeleted())
5929       continue;
5930 
5931     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5932     if (CD && CD->isCopyOrMoveConstructor())
5933       HasNonDeletedCopyOrMove = true;
5934     else if (!isa<CXXDestructorDecl>(MD))
5935       continue;
5936 
5937     if (!MD->isTrivialForCall())
5938       return false;
5939   }
5940 
5941   return HasNonDeletedCopyOrMove;
5942 }
5943 
5944 /// Perform semantic checks on a class definition that has been
5945 /// completing, introducing implicitly-declared members, checking for
5946 /// abstract types, etc.
5947 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5948   if (!Record)
5949     return;
5950 
5951   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5952     AbstractUsageInfo Info(*this, Record);
5953     CheckAbstractClassUsage(Info, Record);
5954   }
5955 
5956   // If this is not an aggregate type and has no user-declared constructor,
5957   // complain about any non-static data members of reference or const scalar
5958   // type, since they will never get initializers.
5959   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5960       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5961       !Record->isLambda()) {
5962     bool Complained = false;
5963     for (const auto *F : Record->fields()) {
5964       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5965         continue;
5966 
5967       if (F->getType()->isReferenceType() ||
5968           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5969         if (!Complained) {
5970           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5971             << Record->getTagKind() << Record;
5972           Complained = true;
5973         }
5974 
5975         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5976           << F->getType()->isReferenceType()
5977           << F->getDeclName();
5978       }
5979     }
5980   }
5981 
5982   if (Record->getIdentifier()) {
5983     // C++ [class.mem]p13:
5984     //   If T is the name of a class, then each of the following shall have a
5985     //   name different from T:
5986     //     - every member of every anonymous union that is a member of class T.
5987     //
5988     // C++ [class.mem]p14:
5989     //   In addition, if class T has a user-declared constructor (12.1), every
5990     //   non-static data member of class T shall have a name different from T.
5991     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5992     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5993          ++I) {
5994       NamedDecl *D = *I;
5995       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5996           isa<IndirectFieldDecl>(D)) {
5997         Diag(D->getLocation(), diag::err_member_name_of_class)
5998           << D->getDeclName();
5999         break;
6000       }
6001     }
6002   }
6003 
6004   // Warn if the class has virtual methods but non-virtual public destructor.
6005   if (Record->isPolymorphic() && !Record->isDependentType()) {
6006     CXXDestructorDecl *dtor = Record->getDestructor();
6007     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6008         !Record->hasAttr<FinalAttr>())
6009       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6010            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6011   }
6012 
6013   if (Record->isAbstract()) {
6014     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6015       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6016         << FA->isSpelledAsSealed();
6017       DiagnoseAbstractType(Record);
6018     }
6019   }
6020 
6021   // Set HasTrivialSpecialMemberForCall if the record has attribute
6022   // "trivial_abi".
6023   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6024 
6025   if (HasTrivialABI)
6026     Record->setHasTrivialSpecialMemberForCall();
6027 
6028   bool HasMethodWithOverrideControl = false,
6029        HasOverridingMethodWithoutOverrideControl = false;
6030   if (!Record->isDependentType()) {
6031     for (auto *M : Record->methods()) {
6032       // See if a method overloads virtual methods in a base
6033       // class without overriding any.
6034       if (!M->isStatic())
6035         DiagnoseHiddenVirtualMethods(M);
6036       if (M->hasAttr<OverrideAttr>())
6037         HasMethodWithOverrideControl = true;
6038       else if (M->size_overridden_methods() > 0)
6039         HasOverridingMethodWithoutOverrideControl = true;
6040       // Check whether the explicitly-defaulted special members are valid.
6041       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6042         CheckExplicitlyDefaultedSpecialMember(M);
6043 
6044       // For an explicitly defaulted or deleted special member, we defer
6045       // determining triviality until the class is complete. That time is now!
6046       CXXSpecialMember CSM = getSpecialMember(M);
6047       if (!M->isImplicit() && !M->isUserProvided()) {
6048         if (CSM != CXXInvalid) {
6049           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6050           // Inform the class that we've finished declaring this member.
6051           Record->finishedDefaultedOrDeletedMember(M);
6052           M->setTrivialForCall(
6053               HasTrivialABI ||
6054               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6055           Record->setTrivialForCallFlags(M);
6056         }
6057       }
6058 
6059       // Set triviality for the purpose of calls if this is a user-provided
6060       // copy/move constructor or destructor.
6061       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6062            CSM == CXXDestructor) && M->isUserProvided()) {
6063         M->setTrivialForCall(HasTrivialABI);
6064         Record->setTrivialForCallFlags(M);
6065       }
6066 
6067       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6068           M->hasAttr<DLLExportAttr>()) {
6069         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6070             M->isTrivial() &&
6071             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6072              CSM == CXXDestructor))
6073           M->dropAttr<DLLExportAttr>();
6074 
6075         if (M->hasAttr<DLLExportAttr>()) {
6076           DefineImplicitSpecialMember(*this, M, M->getLocation());
6077           ActOnFinishInlineFunctionDef(M);
6078         }
6079       }
6080     }
6081   }
6082 
6083   if (HasMethodWithOverrideControl &&
6084       HasOverridingMethodWithoutOverrideControl) {
6085     // At least one method has the 'override' control declared.
6086     // Diagnose all other overridden methods which do not have 'override' specified on them.
6087     for (auto *M : Record->methods())
6088       DiagnoseAbsenceOfOverrideControl(M);
6089   }
6090 
6091   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6092   // whether this class uses any C++ features that are implemented
6093   // completely differently in MSVC, and if so, emit a diagnostic.
6094   // That diagnostic defaults to an error, but we allow projects to
6095   // map it down to a warning (or ignore it).  It's a fairly common
6096   // practice among users of the ms_struct pragma to mass-annotate
6097   // headers, sweeping up a bunch of types that the project doesn't
6098   // really rely on MSVC-compatible layout for.  We must therefore
6099   // support "ms_struct except for C++ stuff" as a secondary ABI.
6100   if (Record->isMsStruct(Context) &&
6101       (Record->isPolymorphic() || Record->getNumBases())) {
6102     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6103   }
6104 
6105   checkClassLevelDLLAttribute(Record);
6106   checkClassLevelSectionAttribute(Record);
6107 
6108   bool ClangABICompat4 =
6109       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6110   TargetInfo::CallingConvKind CCK =
6111       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6112   bool CanPass = canPassInRegisters(*this, Record, CCK);
6113 
6114   // Do not change ArgPassingRestrictions if it has already been set to
6115   // APK_CanNeverPassInRegs.
6116   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6117     Record->setArgPassingRestrictions(CanPass
6118                                           ? RecordDecl::APK_CanPassInRegs
6119                                           : RecordDecl::APK_CannotPassInRegs);
6120 
6121   // If canPassInRegisters returns true despite the record having a non-trivial
6122   // destructor, the record is destructed in the callee. This happens only when
6123   // the record or one of its subobjects has a field annotated with trivial_abi
6124   // or a field qualified with ObjC __strong/__weak.
6125   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6126     Record->setParamDestroyedInCallee(true);
6127   else if (Record->hasNonTrivialDestructor())
6128     Record->setParamDestroyedInCallee(CanPass);
6129 }
6130 
6131 /// Look up the special member function that would be called by a special
6132 /// member function for a subobject of class type.
6133 ///
6134 /// \param Class The class type of the subobject.
6135 /// \param CSM The kind of special member function.
6136 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6137 /// \param ConstRHS True if this is a copy operation with a const object
6138 ///        on its RHS, that is, if the argument to the outer special member
6139 ///        function is 'const' and this is not a field marked 'mutable'.
6140 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6141     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6142     unsigned FieldQuals, bool ConstRHS) {
6143   unsigned LHSQuals = 0;
6144   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6145     LHSQuals = FieldQuals;
6146 
6147   unsigned RHSQuals = FieldQuals;
6148   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6149     RHSQuals = 0;
6150   else if (ConstRHS)
6151     RHSQuals |= Qualifiers::Const;
6152 
6153   return S.LookupSpecialMember(Class, CSM,
6154                                RHSQuals & Qualifiers::Const,
6155                                RHSQuals & Qualifiers::Volatile,
6156                                false,
6157                                LHSQuals & Qualifiers::Const,
6158                                LHSQuals & Qualifiers::Volatile);
6159 }
6160 
6161 class Sema::InheritedConstructorInfo {
6162   Sema &S;
6163   SourceLocation UseLoc;
6164 
6165   /// A mapping from the base classes through which the constructor was
6166   /// inherited to the using shadow declaration in that base class (or a null
6167   /// pointer if the constructor was declared in that base class).
6168   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6169       InheritedFromBases;
6170 
6171 public:
6172   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6173                            ConstructorUsingShadowDecl *Shadow)
6174       : S(S), UseLoc(UseLoc) {
6175     bool DiagnosedMultipleConstructedBases = false;
6176     CXXRecordDecl *ConstructedBase = nullptr;
6177     UsingDecl *ConstructedBaseUsing = nullptr;
6178 
6179     // Find the set of such base class subobjects and check that there's a
6180     // unique constructed subobject.
6181     for (auto *D : Shadow->redecls()) {
6182       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6183       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6184       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6185 
6186       InheritedFromBases.insert(
6187           std::make_pair(DNominatedBase->getCanonicalDecl(),
6188                          DShadow->getNominatedBaseClassShadowDecl()));
6189       if (DShadow->constructsVirtualBase())
6190         InheritedFromBases.insert(
6191             std::make_pair(DConstructedBase->getCanonicalDecl(),
6192                            DShadow->getConstructedBaseClassShadowDecl()));
6193       else
6194         assert(DNominatedBase == DConstructedBase);
6195 
6196       // [class.inhctor.init]p2:
6197       //   If the constructor was inherited from multiple base class subobjects
6198       //   of type B, the program is ill-formed.
6199       if (!ConstructedBase) {
6200         ConstructedBase = DConstructedBase;
6201         ConstructedBaseUsing = D->getUsingDecl();
6202       } else if (ConstructedBase != DConstructedBase &&
6203                  !Shadow->isInvalidDecl()) {
6204         if (!DiagnosedMultipleConstructedBases) {
6205           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6206               << Shadow->getTargetDecl();
6207           S.Diag(ConstructedBaseUsing->getLocation(),
6208                diag::note_ambiguous_inherited_constructor_using)
6209               << ConstructedBase;
6210           DiagnosedMultipleConstructedBases = true;
6211         }
6212         S.Diag(D->getUsingDecl()->getLocation(),
6213                diag::note_ambiguous_inherited_constructor_using)
6214             << DConstructedBase;
6215       }
6216     }
6217 
6218     if (DiagnosedMultipleConstructedBases)
6219       Shadow->setInvalidDecl();
6220   }
6221 
6222   /// Find the constructor to use for inherited construction of a base class,
6223   /// and whether that base class constructor inherits the constructor from a
6224   /// virtual base class (in which case it won't actually invoke it).
6225   std::pair<CXXConstructorDecl *, bool>
6226   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6227     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6228     if (It == InheritedFromBases.end())
6229       return std::make_pair(nullptr, false);
6230 
6231     // This is an intermediary class.
6232     if (It->second)
6233       return std::make_pair(
6234           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6235           It->second->constructsVirtualBase());
6236 
6237     // This is the base class from which the constructor was inherited.
6238     return std::make_pair(Ctor, false);
6239   }
6240 };
6241 
6242 /// Is the special member function which would be selected to perform the
6243 /// specified operation on the specified class type a constexpr constructor?
6244 static bool
6245 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6246                          Sema::CXXSpecialMember CSM, unsigned Quals,
6247                          bool ConstRHS,
6248                          CXXConstructorDecl *InheritedCtor = nullptr,
6249                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6250   // If we're inheriting a constructor, see if we need to call it for this base
6251   // class.
6252   if (InheritedCtor) {
6253     assert(CSM == Sema::CXXDefaultConstructor);
6254     auto BaseCtor =
6255         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6256     if (BaseCtor)
6257       return BaseCtor->isConstexpr();
6258   }
6259 
6260   if (CSM == Sema::CXXDefaultConstructor)
6261     return ClassDecl->hasConstexprDefaultConstructor();
6262 
6263   Sema::SpecialMemberOverloadResult SMOR =
6264       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6265   if (!SMOR.getMethod())
6266     // A constructor we wouldn't select can't be "involved in initializing"
6267     // anything.
6268     return true;
6269   return SMOR.getMethod()->isConstexpr();
6270 }
6271 
6272 /// Determine whether the specified special member function would be constexpr
6273 /// if it were implicitly defined.
6274 static bool defaultedSpecialMemberIsConstexpr(
6275     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6276     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6277     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6278   if (!S.getLangOpts().CPlusPlus11)
6279     return false;
6280 
6281   // C++11 [dcl.constexpr]p4:
6282   // In the definition of a constexpr constructor [...]
6283   bool Ctor = true;
6284   switch (CSM) {
6285   case Sema::CXXDefaultConstructor:
6286     if (Inherited)
6287       break;
6288     // Since default constructor lookup is essentially trivial (and cannot
6289     // involve, for instance, template instantiation), we compute whether a
6290     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6291     //
6292     // This is important for performance; we need to know whether the default
6293     // constructor is constexpr to determine whether the type is a literal type.
6294     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6295 
6296   case Sema::CXXCopyConstructor:
6297   case Sema::CXXMoveConstructor:
6298     // For copy or move constructors, we need to perform overload resolution.
6299     break;
6300 
6301   case Sema::CXXCopyAssignment:
6302   case Sema::CXXMoveAssignment:
6303     if (!S.getLangOpts().CPlusPlus14)
6304       return false;
6305     // In C++1y, we need to perform overload resolution.
6306     Ctor = false;
6307     break;
6308 
6309   case Sema::CXXDestructor:
6310   case Sema::CXXInvalid:
6311     return false;
6312   }
6313 
6314   //   -- if the class is a non-empty union, or for each non-empty anonymous
6315   //      union member of a non-union class, exactly one non-static data member
6316   //      shall be initialized; [DR1359]
6317   //
6318   // If we squint, this is guaranteed, since exactly one non-static data member
6319   // will be initialized (if the constructor isn't deleted), we just don't know
6320   // which one.
6321   if (Ctor && ClassDecl->isUnion())
6322     return CSM == Sema::CXXDefaultConstructor
6323                ? ClassDecl->hasInClassInitializer() ||
6324                      !ClassDecl->hasVariantMembers()
6325                : true;
6326 
6327   //   -- the class shall not have any virtual base classes;
6328   if (Ctor && ClassDecl->getNumVBases())
6329     return false;
6330 
6331   // C++1y [class.copy]p26:
6332   //   -- [the class] is a literal type, and
6333   if (!Ctor && !ClassDecl->isLiteral())
6334     return false;
6335 
6336   //   -- every constructor involved in initializing [...] base class
6337   //      sub-objects shall be a constexpr constructor;
6338   //   -- the assignment operator selected to copy/move each direct base
6339   //      class is a constexpr function, and
6340   for (const auto &B : ClassDecl->bases()) {
6341     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6342     if (!BaseType) continue;
6343 
6344     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6345     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6346                                   InheritedCtor, Inherited))
6347       return false;
6348   }
6349 
6350   //   -- every constructor involved in initializing non-static data members
6351   //      [...] shall be a constexpr constructor;
6352   //   -- every non-static data member and base class sub-object shall be
6353   //      initialized
6354   //   -- for each non-static data member of X that is of class type (or array
6355   //      thereof), the assignment operator selected to copy/move that member is
6356   //      a constexpr function
6357   for (const auto *F : ClassDecl->fields()) {
6358     if (F->isInvalidDecl())
6359       continue;
6360     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6361       continue;
6362     QualType BaseType = S.Context.getBaseElementType(F->getType());
6363     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6364       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6365       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6366                                     BaseType.getCVRQualifiers(),
6367                                     ConstArg && !F->isMutable()))
6368         return false;
6369     } else if (CSM == Sema::CXXDefaultConstructor) {
6370       return false;
6371     }
6372   }
6373 
6374   // All OK, it's constexpr!
6375   return true;
6376 }
6377 
6378 static Sema::ImplicitExceptionSpecification
6379 ComputeDefaultedSpecialMemberExceptionSpec(
6380     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6381     Sema::InheritedConstructorInfo *ICI);
6382 
6383 static Sema::ImplicitExceptionSpecification
6384 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6385   auto CSM = S.getSpecialMember(MD);
6386   if (CSM != Sema::CXXInvalid)
6387     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6388 
6389   auto *CD = cast<CXXConstructorDecl>(MD);
6390   assert(CD->getInheritedConstructor() &&
6391          "only special members have implicit exception specs");
6392   Sema::InheritedConstructorInfo ICI(
6393       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6394   return ComputeDefaultedSpecialMemberExceptionSpec(
6395       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6396 }
6397 
6398 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6399                                                             CXXMethodDecl *MD) {
6400   FunctionProtoType::ExtProtoInfo EPI;
6401 
6402   // Build an exception specification pointing back at this member.
6403   EPI.ExceptionSpec.Type = EST_Unevaluated;
6404   EPI.ExceptionSpec.SourceDecl = MD;
6405 
6406   // Set the calling convention to the default for C++ instance methods.
6407   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6408       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6409                                             /*IsCXXMethod=*/true));
6410   return EPI;
6411 }
6412 
6413 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6414   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6415   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6416     return;
6417 
6418   // Evaluate the exception specification.
6419   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6420   auto ESI = IES.getExceptionSpec();
6421 
6422   // Update the type of the special member to use it.
6423   UpdateExceptionSpec(MD, ESI);
6424 
6425   // A user-provided destructor can be defined outside the class. When that
6426   // happens, be sure to update the exception specification on both
6427   // declarations.
6428   const FunctionProtoType *CanonicalFPT =
6429     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6430   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6431     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6432 }
6433 
6434 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6435   CXXRecordDecl *RD = MD->getParent();
6436   CXXSpecialMember CSM = getSpecialMember(MD);
6437 
6438   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6439          "not an explicitly-defaulted special member");
6440 
6441   // Whether this was the first-declared instance of the constructor.
6442   // This affects whether we implicitly add an exception spec and constexpr.
6443   bool First = MD == MD->getCanonicalDecl();
6444 
6445   bool HadError = false;
6446 
6447   // C++11 [dcl.fct.def.default]p1:
6448   //   A function that is explicitly defaulted shall
6449   //     -- be a special member function (checked elsewhere),
6450   //     -- have the same type (except for ref-qualifiers, and except that a
6451   //        copy operation can take a non-const reference) as an implicit
6452   //        declaration, and
6453   //     -- not have default arguments.
6454   unsigned ExpectedParams = 1;
6455   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6456     ExpectedParams = 0;
6457   if (MD->getNumParams() != ExpectedParams) {
6458     // This also checks for default arguments: a copy or move constructor with a
6459     // default argument is classified as a default constructor, and assignment
6460     // operations and destructors can't have default arguments.
6461     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6462       << CSM << MD->getSourceRange();
6463     HadError = true;
6464   } else if (MD->isVariadic()) {
6465     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6466       << CSM << MD->getSourceRange();
6467     HadError = true;
6468   }
6469 
6470   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6471 
6472   bool CanHaveConstParam = false;
6473   if (CSM == CXXCopyConstructor)
6474     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6475   else if (CSM == CXXCopyAssignment)
6476     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6477 
6478   QualType ReturnType = Context.VoidTy;
6479   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6480     // Check for return type matching.
6481     ReturnType = Type->getReturnType();
6482     QualType ExpectedReturnType =
6483         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6484     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6485       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6486         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6487       HadError = true;
6488     }
6489 
6490     // A defaulted special member cannot have cv-qualifiers.
6491     if (Type->getTypeQuals()) {
6492       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6493         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6494       HadError = true;
6495     }
6496   }
6497 
6498   // Check for parameter type matching.
6499   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6500   bool HasConstParam = false;
6501   if (ExpectedParams && ArgType->isReferenceType()) {
6502     // Argument must be reference to possibly-const T.
6503     QualType ReferentType = ArgType->getPointeeType();
6504     HasConstParam = ReferentType.isConstQualified();
6505 
6506     if (ReferentType.isVolatileQualified()) {
6507       Diag(MD->getLocation(),
6508            diag::err_defaulted_special_member_volatile_param) << CSM;
6509       HadError = true;
6510     }
6511 
6512     if (HasConstParam && !CanHaveConstParam) {
6513       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6514         Diag(MD->getLocation(),
6515              diag::err_defaulted_special_member_copy_const_param)
6516           << (CSM == CXXCopyAssignment);
6517         // FIXME: Explain why this special member can't be const.
6518       } else {
6519         Diag(MD->getLocation(),
6520              diag::err_defaulted_special_member_move_const_param)
6521           << (CSM == CXXMoveAssignment);
6522       }
6523       HadError = true;
6524     }
6525   } else if (ExpectedParams) {
6526     // A copy assignment operator can take its argument by value, but a
6527     // defaulted one cannot.
6528     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6529     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6530     HadError = true;
6531   }
6532 
6533   // C++11 [dcl.fct.def.default]p2:
6534   //   An explicitly-defaulted function may be declared constexpr only if it
6535   //   would have been implicitly declared as constexpr,
6536   // Do not apply this rule to members of class templates, since core issue 1358
6537   // makes such functions always instantiate to constexpr functions. For
6538   // functions which cannot be constexpr (for non-constructors in C++11 and for
6539   // destructors in C++1y), this is checked elsewhere.
6540   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6541                                                      HasConstParam);
6542   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6543                                  : isa<CXXConstructorDecl>(MD)) &&
6544       MD->isConstexpr() && !Constexpr &&
6545       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6546     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6547     // FIXME: Explain why the special member can't be constexpr.
6548     HadError = true;
6549   }
6550 
6551   //   and may have an explicit exception-specification only if it is compatible
6552   //   with the exception-specification on the implicit declaration.
6553   if (Type->hasExceptionSpec()) {
6554     // Delay the check if this is the first declaration of the special member,
6555     // since we may not have parsed some necessary in-class initializers yet.
6556     if (First) {
6557       // If the exception specification needs to be instantiated, do so now,
6558       // before we clobber it with an EST_Unevaluated specification below.
6559       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6560         InstantiateExceptionSpec(MD->getLocStart(), MD);
6561         Type = MD->getType()->getAs<FunctionProtoType>();
6562       }
6563       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6564     } else
6565       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6566   }
6567 
6568   //   If a function is explicitly defaulted on its first declaration,
6569   if (First) {
6570     //  -- it is implicitly considered to be constexpr if the implicit
6571     //     definition would be,
6572     MD->setConstexpr(Constexpr);
6573 
6574     //  -- it is implicitly considered to have the same exception-specification
6575     //     as if it had been implicitly declared,
6576     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6577     EPI.ExceptionSpec.Type = EST_Unevaluated;
6578     EPI.ExceptionSpec.SourceDecl = MD;
6579     MD->setType(Context.getFunctionType(ReturnType,
6580                                         llvm::makeArrayRef(&ArgType,
6581                                                            ExpectedParams),
6582                                         EPI));
6583   }
6584 
6585   if (ShouldDeleteSpecialMember(MD, CSM)) {
6586     if (First) {
6587       SetDeclDeleted(MD, MD->getLocation());
6588     } else {
6589       // C++11 [dcl.fct.def.default]p4:
6590       //   [For a] user-provided explicitly-defaulted function [...] if such a
6591       //   function is implicitly defined as deleted, the program is ill-formed.
6592       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6593       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6594       HadError = true;
6595     }
6596   }
6597 
6598   if (HadError)
6599     MD->setInvalidDecl();
6600 }
6601 
6602 /// Check whether the exception specification provided for an
6603 /// explicitly-defaulted special member matches the exception specification
6604 /// that would have been generated for an implicit special member, per
6605 /// C++11 [dcl.fct.def.default]p2.
6606 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6607     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6608   // If the exception specification was explicitly specified but hadn't been
6609   // parsed when the method was defaulted, grab it now.
6610   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6611     SpecifiedType =
6612         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6613 
6614   // Compute the implicit exception specification.
6615   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6616                                                        /*IsCXXMethod=*/true);
6617   FunctionProtoType::ExtProtoInfo EPI(CC);
6618   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6619   EPI.ExceptionSpec = IES.getExceptionSpec();
6620   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6621     Context.getFunctionType(Context.VoidTy, None, EPI));
6622 
6623   // Ensure that it matches.
6624   CheckEquivalentExceptionSpec(
6625     PDiag(diag::err_incorrect_defaulted_exception_spec)
6626       << getSpecialMember(MD), PDiag(),
6627     ImplicitType, SourceLocation(),
6628     SpecifiedType, MD->getLocation());
6629 }
6630 
6631 void Sema::CheckDelayedMemberExceptionSpecs() {
6632   decltype(DelayedExceptionSpecChecks) Checks;
6633   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6634 
6635   std::swap(Checks, DelayedExceptionSpecChecks);
6636   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6637 
6638   // Perform any deferred checking of exception specifications for virtual
6639   // destructors.
6640   for (auto &Check : Checks)
6641     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6642 
6643   // Check that any explicitly-defaulted methods have exception specifications
6644   // compatible with their implicit exception specifications.
6645   for (auto &Spec : Specs)
6646     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6647 }
6648 
6649 namespace {
6650 /// CRTP base class for visiting operations performed by a special member
6651 /// function (or inherited constructor).
6652 template<typename Derived>
6653 struct SpecialMemberVisitor {
6654   Sema &S;
6655   CXXMethodDecl *MD;
6656   Sema::CXXSpecialMember CSM;
6657   Sema::InheritedConstructorInfo *ICI;
6658 
6659   // Properties of the special member, computed for convenience.
6660   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6661 
6662   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6663                        Sema::InheritedConstructorInfo *ICI)
6664       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6665     switch (CSM) {
6666     case Sema::CXXDefaultConstructor:
6667     case Sema::CXXCopyConstructor:
6668     case Sema::CXXMoveConstructor:
6669       IsConstructor = true;
6670       break;
6671     case Sema::CXXCopyAssignment:
6672     case Sema::CXXMoveAssignment:
6673       IsAssignment = true;
6674       break;
6675     case Sema::CXXDestructor:
6676       break;
6677     case Sema::CXXInvalid:
6678       llvm_unreachable("invalid special member kind");
6679     }
6680 
6681     if (MD->getNumParams()) {
6682       if (const ReferenceType *RT =
6683               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6684         ConstArg = RT->getPointeeType().isConstQualified();
6685     }
6686   }
6687 
6688   Derived &getDerived() { return static_cast<Derived&>(*this); }
6689 
6690   /// Is this a "move" special member?
6691   bool isMove() const {
6692     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6693   }
6694 
6695   /// Look up the corresponding special member in the given class.
6696   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6697                                              unsigned Quals, bool IsMutable) {
6698     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6699                                        ConstArg && !IsMutable);
6700   }
6701 
6702   /// Look up the constructor for the specified base class to see if it's
6703   /// overridden due to this being an inherited constructor.
6704   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6705     if (!ICI)
6706       return {};
6707     assert(CSM == Sema::CXXDefaultConstructor);
6708     auto *BaseCtor =
6709       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6710     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6711       return MD;
6712     return {};
6713   }
6714 
6715   /// A base or member subobject.
6716   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6717 
6718   /// Get the location to use for a subobject in diagnostics.
6719   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6720     // FIXME: For an indirect virtual base, the direct base leading to
6721     // the indirect virtual base would be a more useful choice.
6722     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6723       return B->getBaseTypeLoc();
6724     else
6725       return Subobj.get<FieldDecl*>()->getLocation();
6726   }
6727 
6728   enum BasesToVisit {
6729     /// Visit all non-virtual (direct) bases.
6730     VisitNonVirtualBases,
6731     /// Visit all direct bases, virtual or not.
6732     VisitDirectBases,
6733     /// Visit all non-virtual bases, and all virtual bases if the class
6734     /// is not abstract.
6735     VisitPotentiallyConstructedBases,
6736     /// Visit all direct or virtual bases.
6737     VisitAllBases
6738   };
6739 
6740   // Visit the bases and members of the class.
6741   bool visit(BasesToVisit Bases) {
6742     CXXRecordDecl *RD = MD->getParent();
6743 
6744     if (Bases == VisitPotentiallyConstructedBases)
6745       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6746 
6747     for (auto &B : RD->bases())
6748       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6749           getDerived().visitBase(&B))
6750         return true;
6751 
6752     if (Bases == VisitAllBases)
6753       for (auto &B : RD->vbases())
6754         if (getDerived().visitBase(&B))
6755           return true;
6756 
6757     for (auto *F : RD->fields())
6758       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6759           getDerived().visitField(F))
6760         return true;
6761 
6762     return false;
6763   }
6764 };
6765 }
6766 
6767 namespace {
6768 struct SpecialMemberDeletionInfo
6769     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6770   bool Diagnose;
6771 
6772   SourceLocation Loc;
6773 
6774   bool AllFieldsAreConst;
6775 
6776   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6777                             Sema::CXXSpecialMember CSM,
6778                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6779       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6780         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6781 
6782   bool inUnion() const { return MD->getParent()->isUnion(); }
6783 
6784   Sema::CXXSpecialMember getEffectiveCSM() {
6785     return ICI ? Sema::CXXInvalid : CSM;
6786   }
6787 
6788   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6789   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6790 
6791   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6792   bool shouldDeleteForField(FieldDecl *FD);
6793   bool shouldDeleteForAllConstMembers();
6794 
6795   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6796                                      unsigned Quals);
6797   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6798                                     Sema::SpecialMemberOverloadResult SMOR,
6799                                     bool IsDtorCallInCtor);
6800 
6801   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6802 };
6803 }
6804 
6805 /// Is the given special member inaccessible when used on the given
6806 /// sub-object.
6807 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6808                                              CXXMethodDecl *target) {
6809   /// If we're operating on a base class, the object type is the
6810   /// type of this special member.
6811   QualType objectTy;
6812   AccessSpecifier access = target->getAccess();
6813   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6814     objectTy = S.Context.getTypeDeclType(MD->getParent());
6815     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6816 
6817   // If we're operating on a field, the object type is the type of the field.
6818   } else {
6819     objectTy = S.Context.getTypeDeclType(target->getParent());
6820   }
6821 
6822   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6823 }
6824 
6825 /// Check whether we should delete a special member due to the implicit
6826 /// definition containing a call to a special member of a subobject.
6827 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6828     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6829     bool IsDtorCallInCtor) {
6830   CXXMethodDecl *Decl = SMOR.getMethod();
6831   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6832 
6833   int DiagKind = -1;
6834 
6835   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6836     DiagKind = !Decl ? 0 : 1;
6837   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6838     DiagKind = 2;
6839   else if (!isAccessible(Subobj, Decl))
6840     DiagKind = 3;
6841   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6842            !Decl->isTrivial()) {
6843     // A member of a union must have a trivial corresponding special member.
6844     // As a weird special case, a destructor call from a union's constructor
6845     // must be accessible and non-deleted, but need not be trivial. Such a
6846     // destructor is never actually called, but is semantically checked as
6847     // if it were.
6848     DiagKind = 4;
6849   }
6850 
6851   if (DiagKind == -1)
6852     return false;
6853 
6854   if (Diagnose) {
6855     if (Field) {
6856       S.Diag(Field->getLocation(),
6857              diag::note_deleted_special_member_class_subobject)
6858         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6859         << Field << DiagKind << IsDtorCallInCtor;
6860     } else {
6861       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6862       S.Diag(Base->getLocStart(),
6863              diag::note_deleted_special_member_class_subobject)
6864         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6865         << Base->getType() << DiagKind << IsDtorCallInCtor;
6866     }
6867 
6868     if (DiagKind == 1)
6869       S.NoteDeletedFunction(Decl);
6870     // FIXME: Explain inaccessibility if DiagKind == 3.
6871   }
6872 
6873   return true;
6874 }
6875 
6876 /// Check whether we should delete a special member function due to having a
6877 /// direct or virtual base class or non-static data member of class type M.
6878 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6879     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6880   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6881   bool IsMutable = Field && Field->isMutable();
6882 
6883   // C++11 [class.ctor]p5:
6884   // -- any direct or virtual base class, or non-static data member with no
6885   //    brace-or-equal-initializer, has class type M (or array thereof) and
6886   //    either M has no default constructor or overload resolution as applied
6887   //    to M's default constructor results in an ambiguity or in a function
6888   //    that is deleted or inaccessible
6889   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6890   // -- a direct or virtual base class B that cannot be copied/moved because
6891   //    overload resolution, as applied to B's corresponding special member,
6892   //    results in an ambiguity or a function that is deleted or inaccessible
6893   //    from the defaulted special member
6894   // C++11 [class.dtor]p5:
6895   // -- any direct or virtual base class [...] has a type with a destructor
6896   //    that is deleted or inaccessible
6897   if (!(CSM == Sema::CXXDefaultConstructor &&
6898         Field && Field->hasInClassInitializer()) &&
6899       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6900                                    false))
6901     return true;
6902 
6903   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6904   // -- any direct or virtual base class or non-static data member has a
6905   //    type with a destructor that is deleted or inaccessible
6906   if (IsConstructor) {
6907     Sema::SpecialMemberOverloadResult SMOR =
6908         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6909                               false, false, false, false, false);
6910     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6911       return true;
6912   }
6913 
6914   return false;
6915 }
6916 
6917 /// Check whether we should delete a special member function due to the class
6918 /// having a particular direct or virtual base class.
6919 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6920   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6921   // If program is correct, BaseClass cannot be null, but if it is, the error
6922   // must be reported elsewhere.
6923   if (!BaseClass)
6924     return false;
6925   // If we have an inheriting constructor, check whether we're calling an
6926   // inherited constructor instead of a default constructor.
6927   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6928   if (auto *BaseCtor = SMOR.getMethod()) {
6929     // Note that we do not check access along this path; other than that,
6930     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6931     // FIXME: Check that the base has a usable destructor! Sink this into
6932     // shouldDeleteForClassSubobject.
6933     if (BaseCtor->isDeleted() && Diagnose) {
6934       S.Diag(Base->getLocStart(),
6935              diag::note_deleted_special_member_class_subobject)
6936         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6937         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6938       S.NoteDeletedFunction(BaseCtor);
6939     }
6940     return BaseCtor->isDeleted();
6941   }
6942   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6943 }
6944 
6945 /// Check whether we should delete a special member function due to the class
6946 /// having a particular non-static data member.
6947 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6948   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6949   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6950 
6951   if (CSM == Sema::CXXDefaultConstructor) {
6952     // For a default constructor, all references must be initialized in-class
6953     // and, if a union, it must have a non-const member.
6954     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6955       if (Diagnose)
6956         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6957           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6958       return true;
6959     }
6960     // C++11 [class.ctor]p5: any non-variant non-static data member of
6961     // const-qualified type (or array thereof) with no
6962     // brace-or-equal-initializer does not have a user-provided default
6963     // constructor.
6964     if (!inUnion() && FieldType.isConstQualified() &&
6965         !FD->hasInClassInitializer() &&
6966         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6967       if (Diagnose)
6968         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6969           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6970       return true;
6971     }
6972 
6973     if (inUnion() && !FieldType.isConstQualified())
6974       AllFieldsAreConst = false;
6975   } else if (CSM == Sema::CXXCopyConstructor) {
6976     // For a copy constructor, data members must not be of rvalue reference
6977     // type.
6978     if (FieldType->isRValueReferenceType()) {
6979       if (Diagnose)
6980         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6981           << MD->getParent() << FD << FieldType;
6982       return true;
6983     }
6984   } else if (IsAssignment) {
6985     // For an assignment operator, data members must not be of reference type.
6986     if (FieldType->isReferenceType()) {
6987       if (Diagnose)
6988         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6989           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6990       return true;
6991     }
6992     if (!FieldRecord && FieldType.isConstQualified()) {
6993       // C++11 [class.copy]p23:
6994       // -- a non-static data member of const non-class type (or array thereof)
6995       if (Diagnose)
6996         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6997           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6998       return true;
6999     }
7000   }
7001 
7002   if (FieldRecord) {
7003     // Some additional restrictions exist on the variant members.
7004     if (!inUnion() && FieldRecord->isUnion() &&
7005         FieldRecord->isAnonymousStructOrUnion()) {
7006       bool AllVariantFieldsAreConst = true;
7007 
7008       // FIXME: Handle anonymous unions declared within anonymous unions.
7009       for (auto *UI : FieldRecord->fields()) {
7010         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7011 
7012         if (!UnionFieldType.isConstQualified())
7013           AllVariantFieldsAreConst = false;
7014 
7015         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7016         if (UnionFieldRecord &&
7017             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7018                                           UnionFieldType.getCVRQualifiers()))
7019           return true;
7020       }
7021 
7022       // At least one member in each anonymous union must be non-const
7023       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7024           !FieldRecord->field_empty()) {
7025         if (Diagnose)
7026           S.Diag(FieldRecord->getLocation(),
7027                  diag::note_deleted_default_ctor_all_const)
7028             << !!ICI << MD->getParent() << /*anonymous union*/1;
7029         return true;
7030       }
7031 
7032       // Don't check the implicit member of the anonymous union type.
7033       // This is technically non-conformant, but sanity demands it.
7034       return false;
7035     }
7036 
7037     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7038                                       FieldType.getCVRQualifiers()))
7039       return true;
7040   }
7041 
7042   return false;
7043 }
7044 
7045 /// C++11 [class.ctor] p5:
7046 ///   A defaulted default constructor for a class X is defined as deleted if
7047 /// X is a union and all of its variant members are of const-qualified type.
7048 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7049   // This is a silly definition, because it gives an empty union a deleted
7050   // default constructor. Don't do that.
7051   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7052     bool AnyFields = false;
7053     for (auto *F : MD->getParent()->fields())
7054       if ((AnyFields = !F->isUnnamedBitfield()))
7055         break;
7056     if (!AnyFields)
7057       return false;
7058     if (Diagnose)
7059       S.Diag(MD->getParent()->getLocation(),
7060              diag::note_deleted_default_ctor_all_const)
7061         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7062     return true;
7063   }
7064   return false;
7065 }
7066 
7067 /// Determine whether a defaulted special member function should be defined as
7068 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7069 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7070 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7071                                      InheritedConstructorInfo *ICI,
7072                                      bool Diagnose) {
7073   if (MD->isInvalidDecl())
7074     return false;
7075   CXXRecordDecl *RD = MD->getParent();
7076   assert(!RD->isDependentType() && "do deletion after instantiation");
7077   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7078     return false;
7079 
7080   // C++11 [expr.lambda.prim]p19:
7081   //   The closure type associated with a lambda-expression has a
7082   //   deleted (8.4.3) default constructor and a deleted copy
7083   //   assignment operator.
7084   if (RD->isLambda() &&
7085       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7086     if (Diagnose)
7087       Diag(RD->getLocation(), diag::note_lambda_decl);
7088     return true;
7089   }
7090 
7091   // For an anonymous struct or union, the copy and assignment special members
7092   // will never be used, so skip the check. For an anonymous union declared at
7093   // namespace scope, the constructor and destructor are used.
7094   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7095       RD->isAnonymousStructOrUnion())
7096     return false;
7097 
7098   // C++11 [class.copy]p7, p18:
7099   //   If the class definition declares a move constructor or move assignment
7100   //   operator, an implicitly declared copy constructor or copy assignment
7101   //   operator is defined as deleted.
7102   if (MD->isImplicit() &&
7103       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7104     CXXMethodDecl *UserDeclaredMove = nullptr;
7105 
7106     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7107     // deletion of the corresponding copy operation, not both copy operations.
7108     // MSVC 2015 has adopted the standards conforming behavior.
7109     bool DeletesOnlyMatchingCopy =
7110         getLangOpts().MSVCCompat &&
7111         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7112 
7113     if (RD->hasUserDeclaredMoveConstructor() &&
7114         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7115       if (!Diagnose) return true;
7116 
7117       // Find any user-declared move constructor.
7118       for (auto *I : RD->ctors()) {
7119         if (I->isMoveConstructor()) {
7120           UserDeclaredMove = I;
7121           break;
7122         }
7123       }
7124       assert(UserDeclaredMove);
7125     } else if (RD->hasUserDeclaredMoveAssignment() &&
7126                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7127       if (!Diagnose) return true;
7128 
7129       // Find any user-declared move assignment operator.
7130       for (auto *I : RD->methods()) {
7131         if (I->isMoveAssignmentOperator()) {
7132           UserDeclaredMove = I;
7133           break;
7134         }
7135       }
7136       assert(UserDeclaredMove);
7137     }
7138 
7139     if (UserDeclaredMove) {
7140       Diag(UserDeclaredMove->getLocation(),
7141            diag::note_deleted_copy_user_declared_move)
7142         << (CSM == CXXCopyAssignment) << RD
7143         << UserDeclaredMove->isMoveAssignmentOperator();
7144       return true;
7145     }
7146   }
7147 
7148   // Do access control from the special member function
7149   ContextRAII MethodContext(*this, MD);
7150 
7151   // C++11 [class.dtor]p5:
7152   // -- for a virtual destructor, lookup of the non-array deallocation function
7153   //    results in an ambiguity or in a function that is deleted or inaccessible
7154   if (CSM == CXXDestructor && MD->isVirtual()) {
7155     FunctionDecl *OperatorDelete = nullptr;
7156     DeclarationName Name =
7157       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7158     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7159                                  OperatorDelete, /*Diagnose*/false)) {
7160       if (Diagnose)
7161         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7162       return true;
7163     }
7164   }
7165 
7166   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7167 
7168   // Per DR1611, do not consider virtual bases of constructors of abstract
7169   // classes, since we are not going to construct them.
7170   // Per DR1658, do not consider virtual bases of destructors of abstract
7171   // classes either.
7172   // Per DR2180, for assignment operators we only assign (and thus only
7173   // consider) direct bases.
7174   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7175                                  : SMI.VisitPotentiallyConstructedBases))
7176     return true;
7177 
7178   if (SMI.shouldDeleteForAllConstMembers())
7179     return true;
7180 
7181   if (getLangOpts().CUDA) {
7182     // We should delete the special member in CUDA mode if target inference
7183     // failed.
7184     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7185                                                    Diagnose);
7186   }
7187 
7188   return false;
7189 }
7190 
7191 /// Perform lookup for a special member of the specified kind, and determine
7192 /// whether it is trivial. If the triviality can be determined without the
7193 /// lookup, skip it. This is intended for use when determining whether a
7194 /// special member of a containing object is trivial, and thus does not ever
7195 /// perform overload resolution for default constructors.
7196 ///
7197 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7198 /// member that was most likely to be intended to be trivial, if any.
7199 ///
7200 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7201 /// determine whether the special member is trivial.
7202 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7203                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7204                                      bool ConstRHS,
7205                                      Sema::TrivialABIHandling TAH,
7206                                      CXXMethodDecl **Selected) {
7207   if (Selected)
7208     *Selected = nullptr;
7209 
7210   switch (CSM) {
7211   case Sema::CXXInvalid:
7212     llvm_unreachable("not a special member");
7213 
7214   case Sema::CXXDefaultConstructor:
7215     // C++11 [class.ctor]p5:
7216     //   A default constructor is trivial if:
7217     //    - all the [direct subobjects] have trivial default constructors
7218     //
7219     // Note, no overload resolution is performed in this case.
7220     if (RD->hasTrivialDefaultConstructor())
7221       return true;
7222 
7223     if (Selected) {
7224       // If there's a default constructor which could have been trivial, dig it
7225       // out. Otherwise, if there's any user-provided default constructor, point
7226       // to that as an example of why there's not a trivial one.
7227       CXXConstructorDecl *DefCtor = nullptr;
7228       if (RD->needsImplicitDefaultConstructor())
7229         S.DeclareImplicitDefaultConstructor(RD);
7230       for (auto *CI : RD->ctors()) {
7231         if (!CI->isDefaultConstructor())
7232           continue;
7233         DefCtor = CI;
7234         if (!DefCtor->isUserProvided())
7235           break;
7236       }
7237 
7238       *Selected = DefCtor;
7239     }
7240 
7241     return false;
7242 
7243   case Sema::CXXDestructor:
7244     // C++11 [class.dtor]p5:
7245     //   A destructor is trivial if:
7246     //    - all the direct [subobjects] have trivial destructors
7247     if (RD->hasTrivialDestructor() ||
7248         (TAH == Sema::TAH_ConsiderTrivialABI &&
7249          RD->hasTrivialDestructorForCall()))
7250       return true;
7251 
7252     if (Selected) {
7253       if (RD->needsImplicitDestructor())
7254         S.DeclareImplicitDestructor(RD);
7255       *Selected = RD->getDestructor();
7256     }
7257 
7258     return false;
7259 
7260   case Sema::CXXCopyConstructor:
7261     // C++11 [class.copy]p12:
7262     //   A copy constructor is trivial if:
7263     //    - the constructor selected to copy each direct [subobject] is trivial
7264     if (RD->hasTrivialCopyConstructor() ||
7265         (TAH == Sema::TAH_ConsiderTrivialABI &&
7266          RD->hasTrivialCopyConstructorForCall())) {
7267       if (Quals == Qualifiers::Const)
7268         // We must either select the trivial copy constructor or reach an
7269         // ambiguity; no need to actually perform overload resolution.
7270         return true;
7271     } else if (!Selected) {
7272       return false;
7273     }
7274     // In C++98, we are not supposed to perform overload resolution here, but we
7275     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7276     // cases like B as having a non-trivial copy constructor:
7277     //   struct A { template<typename T> A(T&); };
7278     //   struct B { mutable A a; };
7279     goto NeedOverloadResolution;
7280 
7281   case Sema::CXXCopyAssignment:
7282     // C++11 [class.copy]p25:
7283     //   A copy assignment operator is trivial if:
7284     //    - the assignment operator selected to copy each direct [subobject] is
7285     //      trivial
7286     if (RD->hasTrivialCopyAssignment()) {
7287       if (Quals == Qualifiers::Const)
7288         return true;
7289     } else if (!Selected) {
7290       return false;
7291     }
7292     // In C++98, we are not supposed to perform overload resolution here, but we
7293     // treat that as a language defect.
7294     goto NeedOverloadResolution;
7295 
7296   case Sema::CXXMoveConstructor:
7297   case Sema::CXXMoveAssignment:
7298   NeedOverloadResolution:
7299     Sema::SpecialMemberOverloadResult SMOR =
7300         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7301 
7302     // The standard doesn't describe how to behave if the lookup is ambiguous.
7303     // We treat it as not making the member non-trivial, just like the standard
7304     // mandates for the default constructor. This should rarely matter, because
7305     // the member will also be deleted.
7306     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7307       return true;
7308 
7309     if (!SMOR.getMethod()) {
7310       assert(SMOR.getKind() ==
7311              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7312       return false;
7313     }
7314 
7315     // We deliberately don't check if we found a deleted special member. We're
7316     // not supposed to!
7317     if (Selected)
7318       *Selected = SMOR.getMethod();
7319 
7320     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7321         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7322       return SMOR.getMethod()->isTrivialForCall();
7323     return SMOR.getMethod()->isTrivial();
7324   }
7325 
7326   llvm_unreachable("unknown special method kind");
7327 }
7328 
7329 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7330   for (auto *CI : RD->ctors())
7331     if (!CI->isImplicit())
7332       return CI;
7333 
7334   // Look for constructor templates.
7335   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7336   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7337     if (CXXConstructorDecl *CD =
7338           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7339       return CD;
7340   }
7341 
7342   return nullptr;
7343 }
7344 
7345 /// The kind of subobject we are checking for triviality. The values of this
7346 /// enumeration are used in diagnostics.
7347 enum TrivialSubobjectKind {
7348   /// The subobject is a base class.
7349   TSK_BaseClass,
7350   /// The subobject is a non-static data member.
7351   TSK_Field,
7352   /// The object is actually the complete object.
7353   TSK_CompleteObject
7354 };
7355 
7356 /// Check whether the special member selected for a given type would be trivial.
7357 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7358                                       QualType SubType, bool ConstRHS,
7359                                       Sema::CXXSpecialMember CSM,
7360                                       TrivialSubobjectKind Kind,
7361                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7362   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7363   if (!SubRD)
7364     return true;
7365 
7366   CXXMethodDecl *Selected;
7367   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7368                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7369     return true;
7370 
7371   if (Diagnose) {
7372     if (ConstRHS)
7373       SubType.addConst();
7374 
7375     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7376       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7377         << Kind << SubType.getUnqualifiedType();
7378       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7379         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7380     } else if (!Selected)
7381       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7382         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7383     else if (Selected->isUserProvided()) {
7384       if (Kind == TSK_CompleteObject)
7385         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7386           << Kind << SubType.getUnqualifiedType() << CSM;
7387       else {
7388         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7389           << Kind << SubType.getUnqualifiedType() << CSM;
7390         S.Diag(Selected->getLocation(), diag::note_declared_at);
7391       }
7392     } else {
7393       if (Kind != TSK_CompleteObject)
7394         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7395           << Kind << SubType.getUnqualifiedType() << CSM;
7396 
7397       // Explain why the defaulted or deleted special member isn't trivial.
7398       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7399                                Diagnose);
7400     }
7401   }
7402 
7403   return false;
7404 }
7405 
7406 /// Check whether the members of a class type allow a special member to be
7407 /// trivial.
7408 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7409                                      Sema::CXXSpecialMember CSM,
7410                                      bool ConstArg,
7411                                      Sema::TrivialABIHandling TAH,
7412                                      bool Diagnose) {
7413   for (const auto *FI : RD->fields()) {
7414     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7415       continue;
7416 
7417     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7418 
7419     // Pretend anonymous struct or union members are members of this class.
7420     if (FI->isAnonymousStructOrUnion()) {
7421       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7422                                     CSM, ConstArg, TAH, Diagnose))
7423         return false;
7424       continue;
7425     }
7426 
7427     // C++11 [class.ctor]p5:
7428     //   A default constructor is trivial if [...]
7429     //    -- no non-static data member of its class has a
7430     //       brace-or-equal-initializer
7431     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7432       if (Diagnose)
7433         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7434       return false;
7435     }
7436 
7437     // Objective C ARC 4.3.5:
7438     //   [...] nontrivally ownership-qualified types are [...] not trivially
7439     //   default constructible, copy constructible, move constructible, copy
7440     //   assignable, move assignable, or destructible [...]
7441     if (FieldType.hasNonTrivialObjCLifetime()) {
7442       if (Diagnose)
7443         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7444           << RD << FieldType.getObjCLifetime();
7445       return false;
7446     }
7447 
7448     bool ConstRHS = ConstArg && !FI->isMutable();
7449     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7450                                    CSM, TSK_Field, TAH, Diagnose))
7451       return false;
7452   }
7453 
7454   return true;
7455 }
7456 
7457 /// Diagnose why the specified class does not have a trivial special member of
7458 /// the given kind.
7459 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7460   QualType Ty = Context.getRecordType(RD);
7461 
7462   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7463   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7464                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7465                             /*Diagnose*/true);
7466 }
7467 
7468 /// Determine whether a defaulted or deleted special member function is trivial,
7469 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7470 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7471 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7472                                   TrivialABIHandling TAH, bool Diagnose) {
7473   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7474 
7475   CXXRecordDecl *RD = MD->getParent();
7476 
7477   bool ConstArg = false;
7478 
7479   // C++11 [class.copy]p12, p25: [DR1593]
7480   //   A [special member] is trivial if [...] its parameter-type-list is
7481   //   equivalent to the parameter-type-list of an implicit declaration [...]
7482   switch (CSM) {
7483   case CXXDefaultConstructor:
7484   case CXXDestructor:
7485     // Trivial default constructors and destructors cannot have parameters.
7486     break;
7487 
7488   case CXXCopyConstructor:
7489   case CXXCopyAssignment: {
7490     // Trivial copy operations always have const, non-volatile parameter types.
7491     ConstArg = true;
7492     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7493     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7494     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7495       if (Diagnose)
7496         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7497           << Param0->getSourceRange() << Param0->getType()
7498           << Context.getLValueReferenceType(
7499                Context.getRecordType(RD).withConst());
7500       return false;
7501     }
7502     break;
7503   }
7504 
7505   case CXXMoveConstructor:
7506   case CXXMoveAssignment: {
7507     // Trivial move operations always have non-cv-qualified parameters.
7508     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7509     const RValueReferenceType *RT =
7510       Param0->getType()->getAs<RValueReferenceType>();
7511     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7512       if (Diagnose)
7513         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7514           << Param0->getSourceRange() << Param0->getType()
7515           << Context.getRValueReferenceType(Context.getRecordType(RD));
7516       return false;
7517     }
7518     break;
7519   }
7520 
7521   case CXXInvalid:
7522     llvm_unreachable("not a special member");
7523   }
7524 
7525   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7526     if (Diagnose)
7527       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7528            diag::note_nontrivial_default_arg)
7529         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7530     return false;
7531   }
7532   if (MD->isVariadic()) {
7533     if (Diagnose)
7534       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7535     return false;
7536   }
7537 
7538   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7539   //   A copy/move [constructor or assignment operator] is trivial if
7540   //    -- the [member] selected to copy/move each direct base class subobject
7541   //       is trivial
7542   //
7543   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7544   //   A [default constructor or destructor] is trivial if
7545   //    -- all the direct base classes have trivial [default constructors or
7546   //       destructors]
7547   for (const auto &BI : RD->bases())
7548     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7549                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7550       return false;
7551 
7552   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7553   //   A copy/move [constructor or assignment operator] for a class X is
7554   //   trivial if
7555   //    -- for each non-static data member of X that is of class type (or array
7556   //       thereof), the constructor selected to copy/move that member is
7557   //       trivial
7558   //
7559   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7560   //   A [default constructor or destructor] is trivial if
7561   //    -- for all of the non-static data members of its class that are of class
7562   //       type (or array thereof), each such class has a trivial [default
7563   //       constructor or destructor]
7564   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7565     return false;
7566 
7567   // C++11 [class.dtor]p5:
7568   //   A destructor is trivial if [...]
7569   //    -- the destructor is not virtual
7570   if (CSM == CXXDestructor && MD->isVirtual()) {
7571     if (Diagnose)
7572       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7573     return false;
7574   }
7575 
7576   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7577   //   A [special member] for class X is trivial if [...]
7578   //    -- class X has no virtual functions and no virtual base classes
7579   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7580     if (!Diagnose)
7581       return false;
7582 
7583     if (RD->getNumVBases()) {
7584       // Check for virtual bases. We already know that the corresponding
7585       // member in all bases is trivial, so vbases must all be direct.
7586       CXXBaseSpecifier &BS = *RD->vbases_begin();
7587       assert(BS.isVirtual());
7588       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7589       return false;
7590     }
7591 
7592     // Must have a virtual method.
7593     for (const auto *MI : RD->methods()) {
7594       if (MI->isVirtual()) {
7595         SourceLocation MLoc = MI->getLocStart();
7596         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7597         return false;
7598       }
7599     }
7600 
7601     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7602   }
7603 
7604   // Looks like it's trivial!
7605   return true;
7606 }
7607 
7608 namespace {
7609 struct FindHiddenVirtualMethod {
7610   Sema *S;
7611   CXXMethodDecl *Method;
7612   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7613   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7614 
7615 private:
7616   /// Check whether any most overriden method from MD in Methods
7617   static bool CheckMostOverridenMethods(
7618       const CXXMethodDecl *MD,
7619       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7620     if (MD->size_overridden_methods() == 0)
7621       return Methods.count(MD->getCanonicalDecl());
7622     for (const CXXMethodDecl *O : MD->overridden_methods())
7623       if (CheckMostOverridenMethods(O, Methods))
7624         return true;
7625     return false;
7626   }
7627 
7628 public:
7629   /// Member lookup function that determines whether a given C++
7630   /// method overloads virtual methods in a base class without overriding any,
7631   /// to be used with CXXRecordDecl::lookupInBases().
7632   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7633     RecordDecl *BaseRecord =
7634         Specifier->getType()->getAs<RecordType>()->getDecl();
7635 
7636     DeclarationName Name = Method->getDeclName();
7637     assert(Name.getNameKind() == DeclarationName::Identifier);
7638 
7639     bool foundSameNameMethod = false;
7640     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7641     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7642          Path.Decls = Path.Decls.slice(1)) {
7643       NamedDecl *D = Path.Decls.front();
7644       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7645         MD = MD->getCanonicalDecl();
7646         foundSameNameMethod = true;
7647         // Interested only in hidden virtual methods.
7648         if (!MD->isVirtual())
7649           continue;
7650         // If the method we are checking overrides a method from its base
7651         // don't warn about the other overloaded methods. Clang deviates from
7652         // GCC by only diagnosing overloads of inherited virtual functions that
7653         // do not override any other virtual functions in the base. GCC's
7654         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7655         // function from a base class. These cases may be better served by a
7656         // warning (not specific to virtual functions) on call sites when the
7657         // call would select a different function from the base class, were it
7658         // visible.
7659         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7660         if (!S->IsOverload(Method, MD, false))
7661           return true;
7662         // Collect the overload only if its hidden.
7663         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7664           overloadedMethods.push_back(MD);
7665       }
7666     }
7667 
7668     if (foundSameNameMethod)
7669       OverloadedMethods.append(overloadedMethods.begin(),
7670                                overloadedMethods.end());
7671     return foundSameNameMethod;
7672   }
7673 };
7674 } // end anonymous namespace
7675 
7676 /// Add the most overriden methods from MD to Methods
7677 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7678                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7679   if (MD->size_overridden_methods() == 0)
7680     Methods.insert(MD->getCanonicalDecl());
7681   else
7682     for (const CXXMethodDecl *O : MD->overridden_methods())
7683       AddMostOverridenMethods(O, Methods);
7684 }
7685 
7686 /// Check if a method overloads virtual methods in a base class without
7687 /// overriding any.
7688 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7689                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7690   if (!MD->getDeclName().isIdentifier())
7691     return;
7692 
7693   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7694                      /*bool RecordPaths=*/false,
7695                      /*bool DetectVirtual=*/false);
7696   FindHiddenVirtualMethod FHVM;
7697   FHVM.Method = MD;
7698   FHVM.S = this;
7699 
7700   // Keep the base methods that were overriden or introduced in the subclass
7701   // by 'using' in a set. A base method not in this set is hidden.
7702   CXXRecordDecl *DC = MD->getParent();
7703   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7704   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7705     NamedDecl *ND = *I;
7706     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7707       ND = shad->getTargetDecl();
7708     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7709       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7710   }
7711 
7712   if (DC->lookupInBases(FHVM, Paths))
7713     OverloadedMethods = FHVM.OverloadedMethods;
7714 }
7715 
7716 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7717                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7718   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7719     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7720     PartialDiagnostic PD = PDiag(
7721          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7722     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7723     Diag(overloadedMD->getLocation(), PD);
7724   }
7725 }
7726 
7727 /// Diagnose methods which overload virtual methods in a base class
7728 /// without overriding any.
7729 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7730   if (MD->isInvalidDecl())
7731     return;
7732 
7733   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7734     return;
7735 
7736   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7737   FindHiddenVirtualMethods(MD, OverloadedMethods);
7738   if (!OverloadedMethods.empty()) {
7739     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7740       << MD << (OverloadedMethods.size() > 1);
7741 
7742     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7743   }
7744 }
7745 
7746 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7747   auto PrintDiagAndRemoveAttr = [&]() {
7748     // No diagnostics if this is a template instantiation.
7749     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7750       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7751            diag::ext_cannot_use_trivial_abi) << &RD;
7752     RD.dropAttr<TrivialABIAttr>();
7753   };
7754 
7755   // Ill-formed if the struct has virtual functions.
7756   if (RD.isPolymorphic()) {
7757     PrintDiagAndRemoveAttr();
7758     return;
7759   }
7760 
7761   for (const auto &B : RD.bases()) {
7762     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7763     // virtual base.
7764     if ((!B.getType()->isDependentType() &&
7765          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7766         B.isVirtual()) {
7767       PrintDiagAndRemoveAttr();
7768       return;
7769     }
7770   }
7771 
7772   for (const auto *FD : RD.fields()) {
7773     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7774     // non-trivial for the purpose of calls.
7775     QualType FT = FD->getType();
7776     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7777       PrintDiagAndRemoveAttr();
7778       return;
7779     }
7780 
7781     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7782       if (!RT->isDependentType() &&
7783           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7784         PrintDiagAndRemoveAttr();
7785         return;
7786       }
7787   }
7788 }
7789 
7790 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7791                                              Decl *TagDecl,
7792                                              SourceLocation LBrac,
7793                                              SourceLocation RBrac,
7794                                              AttributeList *AttrList) {
7795   if (!TagDecl)
7796     return;
7797 
7798   AdjustDeclIfTemplate(TagDecl);
7799 
7800   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7801     if (l->getKind() != AttributeList::AT_Visibility)
7802       continue;
7803     l->setInvalid();
7804     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7805       l->getName();
7806   }
7807 
7808   // See if trivial_abi has to be dropped.
7809   auto *RD = dyn_cast<CXXRecordDecl>(TagDecl);
7810   if (RD && RD->hasAttr<TrivialABIAttr>())
7811     checkIllFormedTrivialABIStruct(*RD);
7812 
7813   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7814               // strict aliasing violation!
7815               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7816               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7817 
7818   CheckCompletedCXXClass(RD);
7819 }
7820 
7821 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7822 /// special functions, such as the default constructor, copy
7823 /// constructor, or destructor, to the given C++ class (C++
7824 /// [special]p1).  This routine can only be executed just before the
7825 /// definition of the class is complete.
7826 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7827   if (ClassDecl->needsImplicitDefaultConstructor()) {
7828     ++ASTContext::NumImplicitDefaultConstructors;
7829 
7830     if (ClassDecl->hasInheritedConstructor())
7831       DeclareImplicitDefaultConstructor(ClassDecl);
7832   }
7833 
7834   if (ClassDecl->needsImplicitCopyConstructor()) {
7835     ++ASTContext::NumImplicitCopyConstructors;
7836 
7837     // If the properties or semantics of the copy constructor couldn't be
7838     // determined while the class was being declared, force a declaration
7839     // of it now.
7840     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7841         ClassDecl->hasInheritedConstructor())
7842       DeclareImplicitCopyConstructor(ClassDecl);
7843     // For the MS ABI we need to know whether the copy ctor is deleted. A
7844     // prerequisite for deleting the implicit copy ctor is that the class has a
7845     // move ctor or move assignment that is either user-declared or whose
7846     // semantics are inherited from a subobject. FIXME: We should provide a more
7847     // direct way for CodeGen to ask whether the constructor was deleted.
7848     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7849              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7850               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7851               ClassDecl->hasUserDeclaredMoveAssignment() ||
7852               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7853       DeclareImplicitCopyConstructor(ClassDecl);
7854   }
7855 
7856   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7857     ++ASTContext::NumImplicitMoveConstructors;
7858 
7859     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7860         ClassDecl->hasInheritedConstructor())
7861       DeclareImplicitMoveConstructor(ClassDecl);
7862   }
7863 
7864   if (ClassDecl->needsImplicitCopyAssignment()) {
7865     ++ASTContext::NumImplicitCopyAssignmentOperators;
7866 
7867     // If we have a dynamic class, then the copy assignment operator may be
7868     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7869     // it shows up in the right place in the vtable and that we diagnose
7870     // problems with the implicit exception specification.
7871     if (ClassDecl->isDynamicClass() ||
7872         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7873         ClassDecl->hasInheritedAssignment())
7874       DeclareImplicitCopyAssignment(ClassDecl);
7875   }
7876 
7877   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7878     ++ASTContext::NumImplicitMoveAssignmentOperators;
7879 
7880     // Likewise for the move assignment operator.
7881     if (ClassDecl->isDynamicClass() ||
7882         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7883         ClassDecl->hasInheritedAssignment())
7884       DeclareImplicitMoveAssignment(ClassDecl);
7885   }
7886 
7887   if (ClassDecl->needsImplicitDestructor()) {
7888     ++ASTContext::NumImplicitDestructors;
7889 
7890     // If we have a dynamic class, then the destructor may be virtual, so we
7891     // have to declare the destructor immediately. This ensures that, e.g., it
7892     // shows up in the right place in the vtable and that we diagnose problems
7893     // with the implicit exception specification.
7894     if (ClassDecl->isDynamicClass() ||
7895         ClassDecl->needsOverloadResolutionForDestructor())
7896       DeclareImplicitDestructor(ClassDecl);
7897   }
7898 }
7899 
7900 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7901   if (!D)
7902     return 0;
7903 
7904   // The order of template parameters is not important here. All names
7905   // get added to the same scope.
7906   SmallVector<TemplateParameterList *, 4> ParameterLists;
7907 
7908   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7909     D = TD->getTemplatedDecl();
7910 
7911   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7912     ParameterLists.push_back(PSD->getTemplateParameters());
7913 
7914   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7915     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7916       ParameterLists.push_back(DD->getTemplateParameterList(i));
7917 
7918     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7919       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7920         ParameterLists.push_back(FTD->getTemplateParameters());
7921     }
7922   }
7923 
7924   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7925     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7926       ParameterLists.push_back(TD->getTemplateParameterList(i));
7927 
7928     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7929       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7930         ParameterLists.push_back(CTD->getTemplateParameters());
7931     }
7932   }
7933 
7934   unsigned Count = 0;
7935   for (TemplateParameterList *Params : ParameterLists) {
7936     if (Params->size() > 0)
7937       // Ignore explicit specializations; they don't contribute to the template
7938       // depth.
7939       ++Count;
7940     for (NamedDecl *Param : *Params) {
7941       if (Param->getDeclName()) {
7942         S->AddDecl(Param);
7943         IdResolver.AddDecl(Param);
7944       }
7945     }
7946   }
7947 
7948   return Count;
7949 }
7950 
7951 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7952   if (!RecordD) return;
7953   AdjustDeclIfTemplate(RecordD);
7954   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7955   PushDeclContext(S, Record);
7956 }
7957 
7958 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7959   if (!RecordD) return;
7960   PopDeclContext();
7961 }
7962 
7963 /// This is used to implement the constant expression evaluation part of the
7964 /// attribute enable_if extension. There is nothing in standard C++ which would
7965 /// require reentering parameters.
7966 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7967   if (!Param)
7968     return;
7969 
7970   S->AddDecl(Param);
7971   if (Param->getDeclName())
7972     IdResolver.AddDecl(Param);
7973 }
7974 
7975 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7976 /// parsing a top-level (non-nested) C++ class, and we are now
7977 /// parsing those parts of the given Method declaration that could
7978 /// not be parsed earlier (C++ [class.mem]p2), such as default
7979 /// arguments. This action should enter the scope of the given
7980 /// Method declaration as if we had just parsed the qualified method
7981 /// name. However, it should not bring the parameters into scope;
7982 /// that will be performed by ActOnDelayedCXXMethodParameter.
7983 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7984 }
7985 
7986 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7987 /// C++ method declaration. We're (re-)introducing the given
7988 /// function parameter into scope for use in parsing later parts of
7989 /// the method declaration. For example, we could see an
7990 /// ActOnParamDefaultArgument event for this parameter.
7991 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7992   if (!ParamD)
7993     return;
7994 
7995   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7996 
7997   // If this parameter has an unparsed default argument, clear it out
7998   // to make way for the parsed default argument.
7999   if (Param->hasUnparsedDefaultArg())
8000     Param->setDefaultArg(nullptr);
8001 
8002   S->AddDecl(Param);
8003   if (Param->getDeclName())
8004     IdResolver.AddDecl(Param);
8005 }
8006 
8007 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8008 /// processing the delayed method declaration for Method. The method
8009 /// declaration is now considered finished. There may be a separate
8010 /// ActOnStartOfFunctionDef action later (not necessarily
8011 /// immediately!) for this method, if it was also defined inside the
8012 /// class body.
8013 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8014   if (!MethodD)
8015     return;
8016 
8017   AdjustDeclIfTemplate(MethodD);
8018 
8019   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8020 
8021   // Now that we have our default arguments, check the constructor
8022   // again. It could produce additional diagnostics or affect whether
8023   // the class has implicitly-declared destructors, among other
8024   // things.
8025   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8026     CheckConstructor(Constructor);
8027 
8028   // Check the default arguments, which we may have added.
8029   if (!Method->isInvalidDecl())
8030     CheckCXXDefaultArguments(Method);
8031 }
8032 
8033 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8034 /// the well-formedness of the constructor declarator @p D with type @p
8035 /// R. If there are any errors in the declarator, this routine will
8036 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8037 /// will be updated to reflect a well-formed type for the constructor and
8038 /// returned.
8039 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8040                                           StorageClass &SC) {
8041   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8042 
8043   // C++ [class.ctor]p3:
8044   //   A constructor shall not be virtual (10.3) or static (9.4). A
8045   //   constructor can be invoked for a const, volatile or const
8046   //   volatile object. A constructor shall not be declared const,
8047   //   volatile, or const volatile (9.3.2).
8048   if (isVirtual) {
8049     if (!D.isInvalidType())
8050       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8051         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8052         << SourceRange(D.getIdentifierLoc());
8053     D.setInvalidType();
8054   }
8055   if (SC == SC_Static) {
8056     if (!D.isInvalidType())
8057       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8058         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8059         << SourceRange(D.getIdentifierLoc());
8060     D.setInvalidType();
8061     SC = SC_None;
8062   }
8063 
8064   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8065     diagnoseIgnoredQualifiers(
8066         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8067         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8068         D.getDeclSpec().getRestrictSpecLoc(),
8069         D.getDeclSpec().getAtomicSpecLoc());
8070     D.setInvalidType();
8071   }
8072 
8073   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8074   if (FTI.TypeQuals != 0) {
8075     if (FTI.TypeQuals & Qualifiers::Const)
8076       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8077         << "const" << SourceRange(D.getIdentifierLoc());
8078     if (FTI.TypeQuals & Qualifiers::Volatile)
8079       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8080         << "volatile" << SourceRange(D.getIdentifierLoc());
8081     if (FTI.TypeQuals & Qualifiers::Restrict)
8082       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8083         << "restrict" << SourceRange(D.getIdentifierLoc());
8084     D.setInvalidType();
8085   }
8086 
8087   // C++0x [class.ctor]p4:
8088   //   A constructor shall not be declared with a ref-qualifier.
8089   if (FTI.hasRefQualifier()) {
8090     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8091       << FTI.RefQualifierIsLValueRef
8092       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8093     D.setInvalidType();
8094   }
8095 
8096   // Rebuild the function type "R" without any type qualifiers (in
8097   // case any of the errors above fired) and with "void" as the
8098   // return type, since constructors don't have return types.
8099   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8100   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8101     return R;
8102 
8103   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8104   EPI.TypeQuals = 0;
8105   EPI.RefQualifier = RQ_None;
8106 
8107   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8108 }
8109 
8110 /// CheckConstructor - Checks a fully-formed constructor for
8111 /// well-formedness, issuing any diagnostics required. Returns true if
8112 /// the constructor declarator is invalid.
8113 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8114   CXXRecordDecl *ClassDecl
8115     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8116   if (!ClassDecl)
8117     return Constructor->setInvalidDecl();
8118 
8119   // C++ [class.copy]p3:
8120   //   A declaration of a constructor for a class X is ill-formed if
8121   //   its first parameter is of type (optionally cv-qualified) X and
8122   //   either there are no other parameters or else all other
8123   //   parameters have default arguments.
8124   if (!Constructor->isInvalidDecl() &&
8125       ((Constructor->getNumParams() == 1) ||
8126        (Constructor->getNumParams() > 1 &&
8127         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8128       Constructor->getTemplateSpecializationKind()
8129                                               != TSK_ImplicitInstantiation) {
8130     QualType ParamType = Constructor->getParamDecl(0)->getType();
8131     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8132     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8133       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8134       const char *ConstRef
8135         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8136                                                         : " const &";
8137       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8138         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8139 
8140       // FIXME: Rather that making the constructor invalid, we should endeavor
8141       // to fix the type.
8142       Constructor->setInvalidDecl();
8143     }
8144   }
8145 }
8146 
8147 /// CheckDestructor - Checks a fully-formed destructor definition for
8148 /// well-formedness, issuing any diagnostics required.  Returns true
8149 /// on error.
8150 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8151   CXXRecordDecl *RD = Destructor->getParent();
8152 
8153   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8154     SourceLocation Loc;
8155 
8156     if (!Destructor->isImplicit())
8157       Loc = Destructor->getLocation();
8158     else
8159       Loc = RD->getLocation();
8160 
8161     // If we have a virtual destructor, look up the deallocation function
8162     if (FunctionDecl *OperatorDelete =
8163             FindDeallocationFunctionForDestructor(Loc, RD)) {
8164       Expr *ThisArg = nullptr;
8165 
8166       // If the notional 'delete this' expression requires a non-trivial
8167       // conversion from 'this' to the type of a destroying operator delete's
8168       // first parameter, perform that conversion now.
8169       if (OperatorDelete->isDestroyingOperatorDelete()) {
8170         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8171         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8172           // C++ [class.dtor]p13:
8173           //   ... as if for the expression 'delete this' appearing in a
8174           //   non-virtual destructor of the destructor's class.
8175           ContextRAII SwitchContext(*this, Destructor);
8176           ExprResult This =
8177               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8178           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8179           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8180           if (This.isInvalid()) {
8181             // FIXME: Register this as a context note so that it comes out
8182             // in the right order.
8183             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8184             return true;
8185           }
8186           ThisArg = This.get();
8187         }
8188       }
8189 
8190       MarkFunctionReferenced(Loc, OperatorDelete);
8191       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8192     }
8193   }
8194 
8195   return false;
8196 }
8197 
8198 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8199 /// the well-formednes of the destructor declarator @p D with type @p
8200 /// R. If there are any errors in the declarator, this routine will
8201 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8202 /// will be updated to reflect a well-formed type for the destructor and
8203 /// returned.
8204 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8205                                          StorageClass& SC) {
8206   // C++ [class.dtor]p1:
8207   //   [...] A typedef-name that names a class is a class-name
8208   //   (7.1.3); however, a typedef-name that names a class shall not
8209   //   be used as the identifier in the declarator for a destructor
8210   //   declaration.
8211   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8212   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8213     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8214       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8215   else if (const TemplateSpecializationType *TST =
8216              DeclaratorType->getAs<TemplateSpecializationType>())
8217     if (TST->isTypeAlias())
8218       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8219         << DeclaratorType << 1;
8220 
8221   // C++ [class.dtor]p2:
8222   //   A destructor is used to destroy objects of its class type. A
8223   //   destructor takes no parameters, and no return type can be
8224   //   specified for it (not even void). The address of a destructor
8225   //   shall not be taken. A destructor shall not be static. A
8226   //   destructor can be invoked for a const, volatile or const
8227   //   volatile object. A destructor shall not be declared const,
8228   //   volatile or const volatile (9.3.2).
8229   if (SC == SC_Static) {
8230     if (!D.isInvalidType())
8231       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8232         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8233         << SourceRange(D.getIdentifierLoc())
8234         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8235 
8236     SC = SC_None;
8237   }
8238   if (!D.isInvalidType()) {
8239     // Destructors don't have return types, but the parser will
8240     // happily parse something like:
8241     //
8242     //   class X {
8243     //     float ~X();
8244     //   };
8245     //
8246     // The return type will be eliminated later.
8247     if (D.getDeclSpec().hasTypeSpecifier())
8248       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8249         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8250         << SourceRange(D.getIdentifierLoc());
8251     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8252       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8253                                 SourceLocation(),
8254                                 D.getDeclSpec().getConstSpecLoc(),
8255                                 D.getDeclSpec().getVolatileSpecLoc(),
8256                                 D.getDeclSpec().getRestrictSpecLoc(),
8257                                 D.getDeclSpec().getAtomicSpecLoc());
8258       D.setInvalidType();
8259     }
8260   }
8261 
8262   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8263   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8264     if (FTI.TypeQuals & Qualifiers::Const)
8265       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8266         << "const" << SourceRange(D.getIdentifierLoc());
8267     if (FTI.TypeQuals & Qualifiers::Volatile)
8268       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8269         << "volatile" << SourceRange(D.getIdentifierLoc());
8270     if (FTI.TypeQuals & Qualifiers::Restrict)
8271       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8272         << "restrict" << SourceRange(D.getIdentifierLoc());
8273     D.setInvalidType();
8274   }
8275 
8276   // C++0x [class.dtor]p2:
8277   //   A destructor shall not be declared with a ref-qualifier.
8278   if (FTI.hasRefQualifier()) {
8279     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8280       << FTI.RefQualifierIsLValueRef
8281       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8282     D.setInvalidType();
8283   }
8284 
8285   // Make sure we don't have any parameters.
8286   if (FTIHasNonVoidParameters(FTI)) {
8287     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8288 
8289     // Delete the parameters.
8290     FTI.freeParams();
8291     D.setInvalidType();
8292   }
8293 
8294   // Make sure the destructor isn't variadic.
8295   if (FTI.isVariadic) {
8296     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8297     D.setInvalidType();
8298   }
8299 
8300   // Rebuild the function type "R" without any type qualifiers or
8301   // parameters (in case any of the errors above fired) and with
8302   // "void" as the return type, since destructors don't have return
8303   // types.
8304   if (!D.isInvalidType())
8305     return R;
8306 
8307   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8308   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8309   EPI.Variadic = false;
8310   EPI.TypeQuals = 0;
8311   EPI.RefQualifier = RQ_None;
8312   return Context.getFunctionType(Context.VoidTy, None, EPI);
8313 }
8314 
8315 static void extendLeft(SourceRange &R, SourceRange Before) {
8316   if (Before.isInvalid())
8317     return;
8318   R.setBegin(Before.getBegin());
8319   if (R.getEnd().isInvalid())
8320     R.setEnd(Before.getEnd());
8321 }
8322 
8323 static void extendRight(SourceRange &R, SourceRange After) {
8324   if (After.isInvalid())
8325     return;
8326   if (R.getBegin().isInvalid())
8327     R.setBegin(After.getBegin());
8328   R.setEnd(After.getEnd());
8329 }
8330 
8331 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8332 /// well-formednes of the conversion function declarator @p D with
8333 /// type @p R. If there are any errors in the declarator, this routine
8334 /// will emit diagnostics and return true. Otherwise, it will return
8335 /// false. Either way, the type @p R will be updated to reflect a
8336 /// well-formed type for the conversion operator.
8337 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8338                                      StorageClass& SC) {
8339   // C++ [class.conv.fct]p1:
8340   //   Neither parameter types nor return type can be specified. The
8341   //   type of a conversion function (8.3.5) is "function taking no
8342   //   parameter returning conversion-type-id."
8343   if (SC == SC_Static) {
8344     if (!D.isInvalidType())
8345       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8346         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8347         << D.getName().getSourceRange();
8348     D.setInvalidType();
8349     SC = SC_None;
8350   }
8351 
8352   TypeSourceInfo *ConvTSI = nullptr;
8353   QualType ConvType =
8354       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8355 
8356   const DeclSpec &DS = D.getDeclSpec();
8357   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8358     // Conversion functions don't have return types, but the parser will
8359     // happily parse something like:
8360     //
8361     //   class X {
8362     //     float operator bool();
8363     //   };
8364     //
8365     // The return type will be changed later anyway.
8366     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8367       << SourceRange(DS.getTypeSpecTypeLoc())
8368       << SourceRange(D.getIdentifierLoc());
8369     D.setInvalidType();
8370   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8371     // It's also plausible that the user writes type qualifiers in the wrong
8372     // place, such as:
8373     //   struct S { const operator int(); };
8374     // FIXME: we could provide a fixit to move the qualifiers onto the
8375     // conversion type.
8376     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8377         << SourceRange(D.getIdentifierLoc()) << 0;
8378     D.setInvalidType();
8379   }
8380 
8381   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8382 
8383   // Make sure we don't have any parameters.
8384   if (Proto->getNumParams() > 0) {
8385     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8386 
8387     // Delete the parameters.
8388     D.getFunctionTypeInfo().freeParams();
8389     D.setInvalidType();
8390   } else if (Proto->isVariadic()) {
8391     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8392     D.setInvalidType();
8393   }
8394 
8395   // Diagnose "&operator bool()" and other such nonsense.  This
8396   // is actually a gcc extension which we don't support.
8397   if (Proto->getReturnType() != ConvType) {
8398     bool NeedsTypedef = false;
8399     SourceRange Before, After;
8400 
8401     // Walk the chunks and extract information on them for our diagnostic.
8402     bool PastFunctionChunk = false;
8403     for (auto &Chunk : D.type_objects()) {
8404       switch (Chunk.Kind) {
8405       case DeclaratorChunk::Function:
8406         if (!PastFunctionChunk) {
8407           if (Chunk.Fun.HasTrailingReturnType) {
8408             TypeSourceInfo *TRT = nullptr;
8409             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8410             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8411           }
8412           PastFunctionChunk = true;
8413           break;
8414         }
8415         LLVM_FALLTHROUGH;
8416       case DeclaratorChunk::Array:
8417         NeedsTypedef = true;
8418         extendRight(After, Chunk.getSourceRange());
8419         break;
8420 
8421       case DeclaratorChunk::Pointer:
8422       case DeclaratorChunk::BlockPointer:
8423       case DeclaratorChunk::Reference:
8424       case DeclaratorChunk::MemberPointer:
8425       case DeclaratorChunk::Pipe:
8426         extendLeft(Before, Chunk.getSourceRange());
8427         break;
8428 
8429       case DeclaratorChunk::Paren:
8430         extendLeft(Before, Chunk.Loc);
8431         extendRight(After, Chunk.EndLoc);
8432         break;
8433       }
8434     }
8435 
8436     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8437                          After.isValid()  ? After.getBegin() :
8438                                             D.getIdentifierLoc();
8439     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8440     DB << Before << After;
8441 
8442     if (!NeedsTypedef) {
8443       DB << /*don't need a typedef*/0;
8444 
8445       // If we can provide a correct fix-it hint, do so.
8446       if (After.isInvalid() && ConvTSI) {
8447         SourceLocation InsertLoc =
8448             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8449         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8450            << FixItHint::CreateInsertionFromRange(
8451                   InsertLoc, CharSourceRange::getTokenRange(Before))
8452            << FixItHint::CreateRemoval(Before);
8453       }
8454     } else if (!Proto->getReturnType()->isDependentType()) {
8455       DB << /*typedef*/1 << Proto->getReturnType();
8456     } else if (getLangOpts().CPlusPlus11) {
8457       DB << /*alias template*/2 << Proto->getReturnType();
8458     } else {
8459       DB << /*might not be fixable*/3;
8460     }
8461 
8462     // Recover by incorporating the other type chunks into the result type.
8463     // Note, this does *not* change the name of the function. This is compatible
8464     // with the GCC extension:
8465     //   struct S { &operator int(); } s;
8466     //   int &r = s.operator int(); // ok in GCC
8467     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8468     ConvType = Proto->getReturnType();
8469   }
8470 
8471   // C++ [class.conv.fct]p4:
8472   //   The conversion-type-id shall not represent a function type nor
8473   //   an array type.
8474   if (ConvType->isArrayType()) {
8475     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8476     ConvType = Context.getPointerType(ConvType);
8477     D.setInvalidType();
8478   } else if (ConvType->isFunctionType()) {
8479     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8480     ConvType = Context.getPointerType(ConvType);
8481     D.setInvalidType();
8482   }
8483 
8484   // Rebuild the function type "R" without any parameters (in case any
8485   // of the errors above fired) and with the conversion type as the
8486   // return type.
8487   if (D.isInvalidType())
8488     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8489 
8490   // C++0x explicit conversion operators.
8491   if (DS.isExplicitSpecified())
8492     Diag(DS.getExplicitSpecLoc(),
8493          getLangOpts().CPlusPlus11
8494              ? diag::warn_cxx98_compat_explicit_conversion_functions
8495              : diag::ext_explicit_conversion_functions)
8496         << SourceRange(DS.getExplicitSpecLoc());
8497 }
8498 
8499 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8500 /// the declaration of the given C++ conversion function. This routine
8501 /// is responsible for recording the conversion function in the C++
8502 /// class, if possible.
8503 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8504   assert(Conversion && "Expected to receive a conversion function declaration");
8505 
8506   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8507 
8508   // Make sure we aren't redeclaring the conversion function.
8509   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8510 
8511   // C++ [class.conv.fct]p1:
8512   //   [...] A conversion function is never used to convert a
8513   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8514   //   same object type (or a reference to it), to a (possibly
8515   //   cv-qualified) base class of that type (or a reference to it),
8516   //   or to (possibly cv-qualified) void.
8517   // FIXME: Suppress this warning if the conversion function ends up being a
8518   // virtual function that overrides a virtual function in a base class.
8519   QualType ClassType
8520     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8521   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8522     ConvType = ConvTypeRef->getPointeeType();
8523   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8524       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8525     /* Suppress diagnostics for instantiations. */;
8526   else if (ConvType->isRecordType()) {
8527     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8528     if (ConvType == ClassType)
8529       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8530         << ClassType;
8531     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8532       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8533         <<  ClassType << ConvType;
8534   } else if (ConvType->isVoidType()) {
8535     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8536       << ClassType << ConvType;
8537   }
8538 
8539   if (FunctionTemplateDecl *ConversionTemplate
8540                                 = Conversion->getDescribedFunctionTemplate())
8541     return ConversionTemplate;
8542 
8543   return Conversion;
8544 }
8545 
8546 namespace {
8547 /// Utility class to accumulate and print a diagnostic listing the invalid
8548 /// specifier(s) on a declaration.
8549 struct BadSpecifierDiagnoser {
8550   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8551       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8552   ~BadSpecifierDiagnoser() {
8553     Diagnostic << Specifiers;
8554   }
8555 
8556   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8557     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8558   }
8559   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8560     return check(SpecLoc,
8561                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8562   }
8563   void check(SourceLocation SpecLoc, const char *Spec) {
8564     if (SpecLoc.isInvalid()) return;
8565     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8566     if (!Specifiers.empty()) Specifiers += " ";
8567     Specifiers += Spec;
8568   }
8569 
8570   Sema &S;
8571   Sema::SemaDiagnosticBuilder Diagnostic;
8572   std::string Specifiers;
8573 };
8574 }
8575 
8576 /// Check the validity of a declarator that we parsed for a deduction-guide.
8577 /// These aren't actually declarators in the grammar, so we need to check that
8578 /// the user didn't specify any pieces that are not part of the deduction-guide
8579 /// grammar.
8580 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8581                                          StorageClass &SC) {
8582   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8583   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8584   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8585 
8586   // C++ [temp.deduct.guide]p3:
8587   //   A deduction-gide shall be declared in the same scope as the
8588   //   corresponding class template.
8589   if (!CurContext->getRedeclContext()->Equals(
8590           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8591     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8592       << GuidedTemplateDecl;
8593     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8594   }
8595 
8596   auto &DS = D.getMutableDeclSpec();
8597   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8598   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8599       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8600       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8601     BadSpecifierDiagnoser Diagnoser(
8602         *this, D.getIdentifierLoc(),
8603         diag::err_deduction_guide_invalid_specifier);
8604 
8605     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8606     DS.ClearStorageClassSpecs();
8607     SC = SC_None;
8608 
8609     // 'explicit' is permitted.
8610     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8611     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8612     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8613     DS.ClearConstexprSpec();
8614 
8615     Diagnoser.check(DS.getConstSpecLoc(), "const");
8616     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8617     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8618     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8619     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8620     DS.ClearTypeQualifiers();
8621 
8622     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8623     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8624     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8625     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8626     DS.ClearTypeSpecType();
8627   }
8628 
8629   if (D.isInvalidType())
8630     return;
8631 
8632   // Check the declarator is simple enough.
8633   bool FoundFunction = false;
8634   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8635     if (Chunk.Kind == DeclaratorChunk::Paren)
8636       continue;
8637     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8638       Diag(D.getDeclSpec().getLocStart(),
8639           diag::err_deduction_guide_with_complex_decl)
8640         << D.getSourceRange();
8641       break;
8642     }
8643     if (!Chunk.Fun.hasTrailingReturnType()) {
8644       Diag(D.getName().getLocStart(),
8645            diag::err_deduction_guide_no_trailing_return_type);
8646       break;
8647     }
8648 
8649     // Check that the return type is written as a specialization of
8650     // the template specified as the deduction-guide's name.
8651     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8652     TypeSourceInfo *TSI = nullptr;
8653     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8654     assert(TSI && "deduction guide has valid type but invalid return type?");
8655     bool AcceptableReturnType = false;
8656     bool MightInstantiateToSpecialization = false;
8657     if (auto RetTST =
8658             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8659       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8660       bool TemplateMatches =
8661           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8662       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8663         AcceptableReturnType = true;
8664       else {
8665         // This could still instantiate to the right type, unless we know it
8666         // names the wrong class template.
8667         auto *TD = SpecifiedName.getAsTemplateDecl();
8668         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8669                                              !TemplateMatches);
8670       }
8671     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8672       MightInstantiateToSpecialization = true;
8673     }
8674 
8675     if (!AcceptableReturnType) {
8676       Diag(TSI->getTypeLoc().getLocStart(),
8677            diag::err_deduction_guide_bad_trailing_return_type)
8678         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8679         << TSI->getTypeLoc().getSourceRange();
8680     }
8681 
8682     // Keep going to check that we don't have any inner declarator pieces (we
8683     // could still have a function returning a pointer to a function).
8684     FoundFunction = true;
8685   }
8686 
8687   if (D.isFunctionDefinition())
8688     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8689 }
8690 
8691 //===----------------------------------------------------------------------===//
8692 // Namespace Handling
8693 //===----------------------------------------------------------------------===//
8694 
8695 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8696 /// reopened.
8697 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8698                                             SourceLocation Loc,
8699                                             IdentifierInfo *II, bool *IsInline,
8700                                             NamespaceDecl *PrevNS) {
8701   assert(*IsInline != PrevNS->isInline());
8702 
8703   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8704   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8705   // inline namespaces, with the intention of bringing names into namespace std.
8706   //
8707   // We support this just well enough to get that case working; this is not
8708   // sufficient to support reopening namespaces as inline in general.
8709   if (*IsInline && II && II->getName().startswith("__atomic") &&
8710       S.getSourceManager().isInSystemHeader(Loc)) {
8711     // Mark all prior declarations of the namespace as inline.
8712     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8713          NS = NS->getPreviousDecl())
8714       NS->setInline(*IsInline);
8715     // Patch up the lookup table for the containing namespace. This isn't really
8716     // correct, but it's good enough for this particular case.
8717     for (auto *I : PrevNS->decls())
8718       if (auto *ND = dyn_cast<NamedDecl>(I))
8719         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8720     return;
8721   }
8722 
8723   if (PrevNS->isInline())
8724     // The user probably just forgot the 'inline', so suggest that it
8725     // be added back.
8726     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8727       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8728   else
8729     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8730 
8731   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8732   *IsInline = PrevNS->isInline();
8733 }
8734 
8735 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8736 /// definition.
8737 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8738                                    SourceLocation InlineLoc,
8739                                    SourceLocation NamespaceLoc,
8740                                    SourceLocation IdentLoc,
8741                                    IdentifierInfo *II,
8742                                    SourceLocation LBrace,
8743                                    AttributeList *AttrList,
8744                                    UsingDirectiveDecl *&UD) {
8745   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8746   // For anonymous namespace, take the location of the left brace.
8747   SourceLocation Loc = II ? IdentLoc : LBrace;
8748   bool IsInline = InlineLoc.isValid();
8749   bool IsInvalid = false;
8750   bool IsStd = false;
8751   bool AddToKnown = false;
8752   Scope *DeclRegionScope = NamespcScope->getParent();
8753 
8754   NamespaceDecl *PrevNS = nullptr;
8755   if (II) {
8756     // C++ [namespace.def]p2:
8757     //   The identifier in an original-namespace-definition shall not
8758     //   have been previously defined in the declarative region in
8759     //   which the original-namespace-definition appears. The
8760     //   identifier in an original-namespace-definition is the name of
8761     //   the namespace. Subsequently in that declarative region, it is
8762     //   treated as an original-namespace-name.
8763     //
8764     // Since namespace names are unique in their scope, and we don't
8765     // look through using directives, just look for any ordinary names
8766     // as if by qualified name lookup.
8767     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8768                    ForExternalRedeclaration);
8769     LookupQualifiedName(R, CurContext->getRedeclContext());
8770     NamedDecl *PrevDecl =
8771         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8772     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8773 
8774     if (PrevNS) {
8775       // This is an extended namespace definition.
8776       if (IsInline != PrevNS->isInline())
8777         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8778                                         &IsInline, PrevNS);
8779     } else if (PrevDecl) {
8780       // This is an invalid name redefinition.
8781       Diag(Loc, diag::err_redefinition_different_kind)
8782         << II;
8783       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8784       IsInvalid = true;
8785       // Continue on to push Namespc as current DeclContext and return it.
8786     } else if (II->isStr("std") &&
8787                CurContext->getRedeclContext()->isTranslationUnit()) {
8788       // This is the first "real" definition of the namespace "std", so update
8789       // our cache of the "std" namespace to point at this definition.
8790       PrevNS = getStdNamespace();
8791       IsStd = true;
8792       AddToKnown = !IsInline;
8793     } else {
8794       // We've seen this namespace for the first time.
8795       AddToKnown = !IsInline;
8796     }
8797   } else {
8798     // Anonymous namespaces.
8799 
8800     // Determine whether the parent already has an anonymous namespace.
8801     DeclContext *Parent = CurContext->getRedeclContext();
8802     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8803       PrevNS = TU->getAnonymousNamespace();
8804     } else {
8805       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8806       PrevNS = ND->getAnonymousNamespace();
8807     }
8808 
8809     if (PrevNS && IsInline != PrevNS->isInline())
8810       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8811                                       &IsInline, PrevNS);
8812   }
8813 
8814   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8815                                                  StartLoc, Loc, II, PrevNS);
8816   if (IsInvalid)
8817     Namespc->setInvalidDecl();
8818 
8819   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8820   AddPragmaAttributes(DeclRegionScope, Namespc);
8821 
8822   // FIXME: Should we be merging attributes?
8823   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8824     PushNamespaceVisibilityAttr(Attr, Loc);
8825 
8826   if (IsStd)
8827     StdNamespace = Namespc;
8828   if (AddToKnown)
8829     KnownNamespaces[Namespc] = false;
8830 
8831   if (II) {
8832     PushOnScopeChains(Namespc, DeclRegionScope);
8833   } else {
8834     // Link the anonymous namespace into its parent.
8835     DeclContext *Parent = CurContext->getRedeclContext();
8836     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8837       TU->setAnonymousNamespace(Namespc);
8838     } else {
8839       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8840     }
8841 
8842     CurContext->addDecl(Namespc);
8843 
8844     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8845     //   behaves as if it were replaced by
8846     //     namespace unique { /* empty body */ }
8847     //     using namespace unique;
8848     //     namespace unique { namespace-body }
8849     //   where all occurrences of 'unique' in a translation unit are
8850     //   replaced by the same identifier and this identifier differs
8851     //   from all other identifiers in the entire program.
8852 
8853     // We just create the namespace with an empty name and then add an
8854     // implicit using declaration, just like the standard suggests.
8855     //
8856     // CodeGen enforces the "universally unique" aspect by giving all
8857     // declarations semantically contained within an anonymous
8858     // namespace internal linkage.
8859 
8860     if (!PrevNS) {
8861       UD = UsingDirectiveDecl::Create(Context, Parent,
8862                                       /* 'using' */ LBrace,
8863                                       /* 'namespace' */ SourceLocation(),
8864                                       /* qualifier */ NestedNameSpecifierLoc(),
8865                                       /* identifier */ SourceLocation(),
8866                                       Namespc,
8867                                       /* Ancestor */ Parent);
8868       UD->setImplicit();
8869       Parent->addDecl(UD);
8870     }
8871   }
8872 
8873   ActOnDocumentableDecl(Namespc);
8874 
8875   // Although we could have an invalid decl (i.e. the namespace name is a
8876   // redefinition), push it as current DeclContext and try to continue parsing.
8877   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8878   // for the namespace has the declarations that showed up in that particular
8879   // namespace definition.
8880   PushDeclContext(NamespcScope, Namespc);
8881   return Namespc;
8882 }
8883 
8884 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8885 /// is a namespace alias, returns the namespace it points to.
8886 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8887   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8888     return AD->getNamespace();
8889   return dyn_cast_or_null<NamespaceDecl>(D);
8890 }
8891 
8892 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8893 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8894 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8895   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8896   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8897   Namespc->setRBraceLoc(RBrace);
8898   PopDeclContext();
8899   if (Namespc->hasAttr<VisibilityAttr>())
8900     PopPragmaVisibility(true, RBrace);
8901 }
8902 
8903 CXXRecordDecl *Sema::getStdBadAlloc() const {
8904   return cast_or_null<CXXRecordDecl>(
8905                                   StdBadAlloc.get(Context.getExternalSource()));
8906 }
8907 
8908 EnumDecl *Sema::getStdAlignValT() const {
8909   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8910 }
8911 
8912 NamespaceDecl *Sema::getStdNamespace() const {
8913   return cast_or_null<NamespaceDecl>(
8914                                  StdNamespace.get(Context.getExternalSource()));
8915 }
8916 
8917 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8918   if (!StdExperimentalNamespaceCache) {
8919     if (auto Std = getStdNamespace()) {
8920       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8921                           SourceLocation(), LookupNamespaceName);
8922       if (!LookupQualifiedName(Result, Std) ||
8923           !(StdExperimentalNamespaceCache =
8924                 Result.getAsSingle<NamespaceDecl>()))
8925         Result.suppressDiagnostics();
8926     }
8927   }
8928   return StdExperimentalNamespaceCache;
8929 }
8930 
8931 namespace {
8932 
8933 enum UnsupportedSTLSelect {
8934   USS_InvalidMember,
8935   USS_MissingMember,
8936   USS_NonTrivial,
8937   USS_Other
8938 };
8939 
8940 struct InvalidSTLDiagnoser {
8941   Sema &S;
8942   SourceLocation Loc;
8943   QualType TyForDiags;
8944 
8945   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8946                       const VarDecl *VD = nullptr) {
8947     {
8948       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8949                << TyForDiags << ((int)Sel);
8950       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8951         assert(!Name.empty());
8952         D << Name;
8953       }
8954     }
8955     if (Sel == USS_InvalidMember) {
8956       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8957           << VD << VD->getSourceRange();
8958     }
8959     return QualType();
8960   }
8961 };
8962 } // namespace
8963 
8964 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
8965                                            SourceLocation Loc) {
8966   assert(getLangOpts().CPlusPlus &&
8967          "Looking for comparison category type outside of C++.");
8968 
8969   // Check if we've already successfully checked the comparison category type
8970   // before. If so, skip checking it again.
8971   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
8972   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
8973     return Info->getType();
8974 
8975   // If lookup failed
8976   if (!Info) {
8977     std::string NameForDiags = "std::";
8978     NameForDiags += ComparisonCategories::getCategoryString(Kind);
8979     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
8980         << NameForDiags;
8981     return QualType();
8982   }
8983 
8984   assert(Info->Kind == Kind);
8985   assert(Info->Record);
8986 
8987   // Update the Record decl in case we encountered a forward declaration on our
8988   // first pass. FIXME: This is a bit of a hack.
8989   if (Info->Record->hasDefinition())
8990     Info->Record = Info->Record->getDefinition();
8991 
8992   // Use an elaborated type for diagnostics which has a name containing the
8993   // prepended 'std' namespace but not any inline namespace names.
8994   QualType TyForDiags = [&]() {
8995     auto *NNS =
8996         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
8997     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
8998   }();
8999 
9000   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9001     return QualType();
9002 
9003   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9004 
9005   if (!Info->Record->isTriviallyCopyable())
9006     return UnsupportedSTLError(USS_NonTrivial);
9007 
9008   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9009     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9010     // Tolerate empty base classes.
9011     if (Base->isEmpty())
9012       continue;
9013     // Reject STL implementations which have at least one non-empty base.
9014     return UnsupportedSTLError();
9015   }
9016 
9017   // Check that the STL has implemented the types using a single integer field.
9018   // This expectation allows better codegen for builtin operators. We require:
9019   //   (1) The class has exactly one field.
9020   //   (2) The field is an integral or enumeration type.
9021   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9022   if (std::distance(FIt, FEnd) != 1 ||
9023       !FIt->getType()->isIntegralOrEnumerationType()) {
9024     return UnsupportedSTLError();
9025   }
9026 
9027   // Build each of the require values and store them in Info.
9028   for (ComparisonCategoryResult CCR :
9029        ComparisonCategories::getPossibleResultsForType(Kind)) {
9030     StringRef MemName = ComparisonCategories::getResultString(CCR);
9031     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9032 
9033     if (!ValInfo)
9034       return UnsupportedSTLError(USS_MissingMember, MemName);
9035 
9036     VarDecl *VD = ValInfo->VD;
9037     assert(VD && "should not be null!");
9038 
9039     // Attempt to diagnose reasons why the STL definition of this type
9040     // might be foobar, including it failing to be a constant expression.
9041     // TODO Handle more ways the lookup or result can be invalid.
9042     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9043         !VD->checkInitIsICE())
9044       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9045 
9046     // Attempt to evaluate the var decl as a constant expression and extract
9047     // the value of its first field as a ICE. If this fails, the STL
9048     // implementation is not supported.
9049     if (!ValInfo->hasValidIntValue())
9050       return UnsupportedSTLError();
9051 
9052     MarkVariableReferenced(Loc, VD);
9053   }
9054 
9055   // We've successfully built the required types and expressions. Update
9056   // the cache and return the newly cached value.
9057   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9058   return Info->getType();
9059 }
9060 
9061 /// Retrieve the special "std" namespace, which may require us to
9062 /// implicitly define the namespace.
9063 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9064   if (!StdNamespace) {
9065     // The "std" namespace has not yet been defined, so build one implicitly.
9066     StdNamespace = NamespaceDecl::Create(Context,
9067                                          Context.getTranslationUnitDecl(),
9068                                          /*Inline=*/false,
9069                                          SourceLocation(), SourceLocation(),
9070                                          &PP.getIdentifierTable().get("std"),
9071                                          /*PrevDecl=*/nullptr);
9072     getStdNamespace()->setImplicit(true);
9073   }
9074 
9075   return getStdNamespace();
9076 }
9077 
9078 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9079   assert(getLangOpts().CPlusPlus &&
9080          "Looking for std::initializer_list outside of C++.");
9081 
9082   // We're looking for implicit instantiations of
9083   // template <typename E> class std::initializer_list.
9084 
9085   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9086     return false;
9087 
9088   ClassTemplateDecl *Template = nullptr;
9089   const TemplateArgument *Arguments = nullptr;
9090 
9091   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9092 
9093     ClassTemplateSpecializationDecl *Specialization =
9094         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9095     if (!Specialization)
9096       return false;
9097 
9098     Template = Specialization->getSpecializedTemplate();
9099     Arguments = Specialization->getTemplateArgs().data();
9100   } else if (const TemplateSpecializationType *TST =
9101                  Ty->getAs<TemplateSpecializationType>()) {
9102     Template = dyn_cast_or_null<ClassTemplateDecl>(
9103         TST->getTemplateName().getAsTemplateDecl());
9104     Arguments = TST->getArgs();
9105   }
9106   if (!Template)
9107     return false;
9108 
9109   if (!StdInitializerList) {
9110     // Haven't recognized std::initializer_list yet, maybe this is it.
9111     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9112     if (TemplateClass->getIdentifier() !=
9113             &PP.getIdentifierTable().get("initializer_list") ||
9114         !getStdNamespace()->InEnclosingNamespaceSetOf(
9115             TemplateClass->getDeclContext()))
9116       return false;
9117     // This is a template called std::initializer_list, but is it the right
9118     // template?
9119     TemplateParameterList *Params = Template->getTemplateParameters();
9120     if (Params->getMinRequiredArguments() != 1)
9121       return false;
9122     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9123       return false;
9124 
9125     // It's the right template.
9126     StdInitializerList = Template;
9127   }
9128 
9129   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9130     return false;
9131 
9132   // This is an instance of std::initializer_list. Find the argument type.
9133   if (Element)
9134     *Element = Arguments[0].getAsType();
9135   return true;
9136 }
9137 
9138 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9139   NamespaceDecl *Std = S.getStdNamespace();
9140   if (!Std) {
9141     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9142     return nullptr;
9143   }
9144 
9145   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9146                       Loc, Sema::LookupOrdinaryName);
9147   if (!S.LookupQualifiedName(Result, Std)) {
9148     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9149     return nullptr;
9150   }
9151   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9152   if (!Template) {
9153     Result.suppressDiagnostics();
9154     // We found something weird. Complain about the first thing we found.
9155     NamedDecl *Found = *Result.begin();
9156     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9157     return nullptr;
9158   }
9159 
9160   // We found some template called std::initializer_list. Now verify that it's
9161   // correct.
9162   TemplateParameterList *Params = Template->getTemplateParameters();
9163   if (Params->getMinRequiredArguments() != 1 ||
9164       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9165     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9166     return nullptr;
9167   }
9168 
9169   return Template;
9170 }
9171 
9172 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9173   if (!StdInitializerList) {
9174     StdInitializerList = LookupStdInitializerList(*this, Loc);
9175     if (!StdInitializerList)
9176       return QualType();
9177   }
9178 
9179   TemplateArgumentListInfo Args(Loc, Loc);
9180   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9181                                        Context.getTrivialTypeSourceInfo(Element,
9182                                                                         Loc)));
9183   return Context.getCanonicalType(
9184       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9185 }
9186 
9187 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9188   // C++ [dcl.init.list]p2:
9189   //   A constructor is an initializer-list constructor if its first parameter
9190   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9191   //   std::initializer_list<E> for some type E, and either there are no other
9192   //   parameters or else all other parameters have default arguments.
9193   if (Ctor->getNumParams() < 1 ||
9194       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9195     return false;
9196 
9197   QualType ArgType = Ctor->getParamDecl(0)->getType();
9198   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9199     ArgType = RT->getPointeeType().getUnqualifiedType();
9200 
9201   return isStdInitializerList(ArgType, nullptr);
9202 }
9203 
9204 /// Determine whether a using statement is in a context where it will be
9205 /// apply in all contexts.
9206 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9207   switch (CurContext->getDeclKind()) {
9208     case Decl::TranslationUnit:
9209       return true;
9210     case Decl::LinkageSpec:
9211       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9212     default:
9213       return false;
9214   }
9215 }
9216 
9217 namespace {
9218 
9219 // Callback to only accept typo corrections that are namespaces.
9220 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9221 public:
9222   bool ValidateCandidate(const TypoCorrection &candidate) override {
9223     if (NamedDecl *ND = candidate.getCorrectionDecl())
9224       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9225     return false;
9226   }
9227 };
9228 
9229 }
9230 
9231 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9232                                        CXXScopeSpec &SS,
9233                                        SourceLocation IdentLoc,
9234                                        IdentifierInfo *Ident) {
9235   R.clear();
9236   if (TypoCorrection Corrected =
9237           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9238                         llvm::make_unique<NamespaceValidatorCCC>(),
9239                         Sema::CTK_ErrorRecovery)) {
9240     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9241       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9242       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9243                               Ident->getName().equals(CorrectedStr);
9244       S.diagnoseTypo(Corrected,
9245                      S.PDiag(diag::err_using_directive_member_suggest)
9246                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9247                      S.PDiag(diag::note_namespace_defined_here));
9248     } else {
9249       S.diagnoseTypo(Corrected,
9250                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9251                      S.PDiag(diag::note_namespace_defined_here));
9252     }
9253     R.addDecl(Corrected.getFoundDecl());
9254     return true;
9255   }
9256   return false;
9257 }
9258 
9259 Decl *Sema::ActOnUsingDirective(Scope *S,
9260                                           SourceLocation UsingLoc,
9261                                           SourceLocation NamespcLoc,
9262                                           CXXScopeSpec &SS,
9263                                           SourceLocation IdentLoc,
9264                                           IdentifierInfo *NamespcName,
9265                                           AttributeList *AttrList) {
9266   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9267   assert(NamespcName && "Invalid NamespcName.");
9268   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9269 
9270   // This can only happen along a recovery path.
9271   while (S->isTemplateParamScope())
9272     S = S->getParent();
9273   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9274 
9275   UsingDirectiveDecl *UDir = nullptr;
9276   NestedNameSpecifier *Qualifier = nullptr;
9277   if (SS.isSet())
9278     Qualifier = SS.getScopeRep();
9279 
9280   // Lookup namespace name.
9281   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9282   LookupParsedName(R, S, &SS);
9283   if (R.isAmbiguous())
9284     return nullptr;
9285 
9286   if (R.empty()) {
9287     R.clear();
9288     // Allow "using namespace std;" or "using namespace ::std;" even if
9289     // "std" hasn't been defined yet, for GCC compatibility.
9290     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9291         NamespcName->isStr("std")) {
9292       Diag(IdentLoc, diag::ext_using_undefined_std);
9293       R.addDecl(getOrCreateStdNamespace());
9294       R.resolveKind();
9295     }
9296     // Otherwise, attempt typo correction.
9297     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9298   }
9299 
9300   if (!R.empty()) {
9301     NamedDecl *Named = R.getRepresentativeDecl();
9302     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9303     assert(NS && "expected namespace decl");
9304 
9305     // The use of a nested name specifier may trigger deprecation warnings.
9306     DiagnoseUseOfDecl(Named, IdentLoc);
9307 
9308     // C++ [namespace.udir]p1:
9309     //   A using-directive specifies that the names in the nominated
9310     //   namespace can be used in the scope in which the
9311     //   using-directive appears after the using-directive. During
9312     //   unqualified name lookup (3.4.1), the names appear as if they
9313     //   were declared in the nearest enclosing namespace which
9314     //   contains both the using-directive and the nominated
9315     //   namespace. [Note: in this context, "contains" means "contains
9316     //   directly or indirectly". ]
9317 
9318     // Find enclosing context containing both using-directive and
9319     // nominated namespace.
9320     DeclContext *CommonAncestor = NS;
9321     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9322       CommonAncestor = CommonAncestor->getParent();
9323 
9324     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9325                                       SS.getWithLocInContext(Context),
9326                                       IdentLoc, Named, CommonAncestor);
9327 
9328     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9329         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9330       Diag(IdentLoc, diag::warn_using_directive_in_header);
9331     }
9332 
9333     PushUsingDirective(S, UDir);
9334   } else {
9335     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9336   }
9337 
9338   if (UDir)
9339     ProcessDeclAttributeList(S, UDir, AttrList);
9340 
9341   return UDir;
9342 }
9343 
9344 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9345   // If the scope has an associated entity and the using directive is at
9346   // namespace or translation unit scope, add the UsingDirectiveDecl into
9347   // its lookup structure so qualified name lookup can find it.
9348   DeclContext *Ctx = S->getEntity();
9349   if (Ctx && !Ctx->isFunctionOrMethod())
9350     Ctx->addDecl(UDir);
9351   else
9352     // Otherwise, it is at block scope. The using-directives will affect lookup
9353     // only to the end of the scope.
9354     S->PushUsingDirective(UDir);
9355 }
9356 
9357 
9358 Decl *Sema::ActOnUsingDeclaration(Scope *S,
9359                                   AccessSpecifier AS,
9360                                   SourceLocation UsingLoc,
9361                                   SourceLocation TypenameLoc,
9362                                   CXXScopeSpec &SS,
9363                                   UnqualifiedId &Name,
9364                                   SourceLocation EllipsisLoc,
9365                                   AttributeList *AttrList) {
9366   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9367 
9368   if (SS.isEmpty()) {
9369     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9370     return nullptr;
9371   }
9372 
9373   switch (Name.getKind()) {
9374   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9375   case UnqualifiedIdKind::IK_Identifier:
9376   case UnqualifiedIdKind::IK_OperatorFunctionId:
9377   case UnqualifiedIdKind::IK_LiteralOperatorId:
9378   case UnqualifiedIdKind::IK_ConversionFunctionId:
9379     break;
9380 
9381   case UnqualifiedIdKind::IK_ConstructorName:
9382   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9383     // C++11 inheriting constructors.
9384     Diag(Name.getLocStart(),
9385          getLangOpts().CPlusPlus11 ?
9386            diag::warn_cxx98_compat_using_decl_constructor :
9387            diag::err_using_decl_constructor)
9388       << SS.getRange();
9389 
9390     if (getLangOpts().CPlusPlus11) break;
9391 
9392     return nullptr;
9393 
9394   case UnqualifiedIdKind::IK_DestructorName:
9395     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9396       << SS.getRange();
9397     return nullptr;
9398 
9399   case UnqualifiedIdKind::IK_TemplateId:
9400     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9401       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9402     return nullptr;
9403 
9404   case UnqualifiedIdKind::IK_DeductionGuideName:
9405     llvm_unreachable("cannot parse qualified deduction guide name");
9406   }
9407 
9408   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9409   DeclarationName TargetName = TargetNameInfo.getName();
9410   if (!TargetName)
9411     return nullptr;
9412 
9413   // Warn about access declarations.
9414   if (UsingLoc.isInvalid()) {
9415     Diag(Name.getLocStart(),
9416          getLangOpts().CPlusPlus11 ? diag::err_access_decl
9417                                    : diag::warn_access_decl_deprecated)
9418       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9419   }
9420 
9421   if (EllipsisLoc.isInvalid()) {
9422     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9423         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9424       return nullptr;
9425   } else {
9426     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9427         !TargetNameInfo.containsUnexpandedParameterPack()) {
9428       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9429         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9430       EllipsisLoc = SourceLocation();
9431     }
9432   }
9433 
9434   NamedDecl *UD =
9435       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9436                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9437                             /*IsInstantiation*/false);
9438   if (UD)
9439     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9440 
9441   return UD;
9442 }
9443 
9444 /// Determine whether a using declaration considers the given
9445 /// declarations as "equivalent", e.g., if they are redeclarations of
9446 /// the same entity or are both typedefs of the same type.
9447 static bool
9448 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9449   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9450     return true;
9451 
9452   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9453     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9454       return Context.hasSameType(TD1->getUnderlyingType(),
9455                                  TD2->getUnderlyingType());
9456 
9457   return false;
9458 }
9459 
9460 
9461 /// Determines whether to create a using shadow decl for a particular
9462 /// decl, given the set of decls existing prior to this using lookup.
9463 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9464                                 const LookupResult &Previous,
9465                                 UsingShadowDecl *&PrevShadow) {
9466   // Diagnose finding a decl which is not from a base class of the
9467   // current class.  We do this now because there are cases where this
9468   // function will silently decide not to build a shadow decl, which
9469   // will pre-empt further diagnostics.
9470   //
9471   // We don't need to do this in C++11 because we do the check once on
9472   // the qualifier.
9473   //
9474   // FIXME: diagnose the following if we care enough:
9475   //   struct A { int foo; };
9476   //   struct B : A { using A::foo; };
9477   //   template <class T> struct C : A {};
9478   //   template <class T> struct D : C<T> { using B::foo; } // <---
9479   // This is invalid (during instantiation) in C++03 because B::foo
9480   // resolves to the using decl in B, which is not a base class of D<T>.
9481   // We can't diagnose it immediately because C<T> is an unknown
9482   // specialization.  The UsingShadowDecl in D<T> then points directly
9483   // to A::foo, which will look well-formed when we instantiate.
9484   // The right solution is to not collapse the shadow-decl chain.
9485   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9486     DeclContext *OrigDC = Orig->getDeclContext();
9487 
9488     // Handle enums and anonymous structs.
9489     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9490     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9491     while (OrigRec->isAnonymousStructOrUnion())
9492       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9493 
9494     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9495       if (OrigDC == CurContext) {
9496         Diag(Using->getLocation(),
9497              diag::err_using_decl_nested_name_specifier_is_current_class)
9498           << Using->getQualifierLoc().getSourceRange();
9499         Diag(Orig->getLocation(), diag::note_using_decl_target);
9500         Using->setInvalidDecl();
9501         return true;
9502       }
9503 
9504       Diag(Using->getQualifierLoc().getBeginLoc(),
9505            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9506         << Using->getQualifier()
9507         << cast<CXXRecordDecl>(CurContext)
9508         << Using->getQualifierLoc().getSourceRange();
9509       Diag(Orig->getLocation(), diag::note_using_decl_target);
9510       Using->setInvalidDecl();
9511       return true;
9512     }
9513   }
9514 
9515   if (Previous.empty()) return false;
9516 
9517   NamedDecl *Target = Orig;
9518   if (isa<UsingShadowDecl>(Target))
9519     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9520 
9521   // If the target happens to be one of the previous declarations, we
9522   // don't have a conflict.
9523   //
9524   // FIXME: but we might be increasing its access, in which case we
9525   // should redeclare it.
9526   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9527   bool FoundEquivalentDecl = false;
9528   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9529          I != E; ++I) {
9530     NamedDecl *D = (*I)->getUnderlyingDecl();
9531     // We can have UsingDecls in our Previous results because we use the same
9532     // LookupResult for checking whether the UsingDecl itself is a valid
9533     // redeclaration.
9534     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9535       continue;
9536 
9537     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9538       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9539         PrevShadow = Shadow;
9540       FoundEquivalentDecl = true;
9541     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9542       // We don't conflict with an existing using shadow decl of an equivalent
9543       // declaration, but we're not a redeclaration of it.
9544       FoundEquivalentDecl = true;
9545     }
9546 
9547     if (isVisible(D))
9548       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9549   }
9550 
9551   if (FoundEquivalentDecl)
9552     return false;
9553 
9554   if (FunctionDecl *FD = Target->getAsFunction()) {
9555     NamedDecl *OldDecl = nullptr;
9556     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9557                           /*IsForUsingDecl*/ true)) {
9558     case Ovl_Overload:
9559       return false;
9560 
9561     case Ovl_NonFunction:
9562       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9563       break;
9564 
9565     // We found a decl with the exact signature.
9566     case Ovl_Match:
9567       // If we're in a record, we want to hide the target, so we
9568       // return true (without a diagnostic) to tell the caller not to
9569       // build a shadow decl.
9570       if (CurContext->isRecord())
9571         return true;
9572 
9573       // If we're not in a record, this is an error.
9574       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9575       break;
9576     }
9577 
9578     Diag(Target->getLocation(), diag::note_using_decl_target);
9579     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9580     Using->setInvalidDecl();
9581     return true;
9582   }
9583 
9584   // Target is not a function.
9585 
9586   if (isa<TagDecl>(Target)) {
9587     // No conflict between a tag and a non-tag.
9588     if (!Tag) return false;
9589 
9590     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9591     Diag(Target->getLocation(), diag::note_using_decl_target);
9592     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9593     Using->setInvalidDecl();
9594     return true;
9595   }
9596 
9597   // No conflict between a tag and a non-tag.
9598   if (!NonTag) return false;
9599 
9600   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9601   Diag(Target->getLocation(), diag::note_using_decl_target);
9602   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9603   Using->setInvalidDecl();
9604   return true;
9605 }
9606 
9607 /// Determine whether a direct base class is a virtual base class.
9608 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9609   if (!Derived->getNumVBases())
9610     return false;
9611   for (auto &B : Derived->bases())
9612     if (B.getType()->getAsCXXRecordDecl() == Base)
9613       return B.isVirtual();
9614   llvm_unreachable("not a direct base class");
9615 }
9616 
9617 /// Builds a shadow declaration corresponding to a 'using' declaration.
9618 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9619                                             UsingDecl *UD,
9620                                             NamedDecl *Orig,
9621                                             UsingShadowDecl *PrevDecl) {
9622   // If we resolved to another shadow declaration, just coalesce them.
9623   NamedDecl *Target = Orig;
9624   if (isa<UsingShadowDecl>(Target)) {
9625     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9626     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9627   }
9628 
9629   NamedDecl *NonTemplateTarget = Target;
9630   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9631     NonTemplateTarget = TargetTD->getTemplatedDecl();
9632 
9633   UsingShadowDecl *Shadow;
9634   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9635     bool IsVirtualBase =
9636         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9637                             UD->getQualifier()->getAsRecordDecl());
9638     Shadow = ConstructorUsingShadowDecl::Create(
9639         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9640   } else {
9641     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9642                                      Target);
9643   }
9644   UD->addShadowDecl(Shadow);
9645 
9646   Shadow->setAccess(UD->getAccess());
9647   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9648     Shadow->setInvalidDecl();
9649 
9650   Shadow->setPreviousDecl(PrevDecl);
9651 
9652   if (S)
9653     PushOnScopeChains(Shadow, S);
9654   else
9655     CurContext->addDecl(Shadow);
9656 
9657 
9658   return Shadow;
9659 }
9660 
9661 /// Hides a using shadow declaration.  This is required by the current
9662 /// using-decl implementation when a resolvable using declaration in a
9663 /// class is followed by a declaration which would hide or override
9664 /// one or more of the using decl's targets; for example:
9665 ///
9666 ///   struct Base { void foo(int); };
9667 ///   struct Derived : Base {
9668 ///     using Base::foo;
9669 ///     void foo(int);
9670 ///   };
9671 ///
9672 /// The governing language is C++03 [namespace.udecl]p12:
9673 ///
9674 ///   When a using-declaration brings names from a base class into a
9675 ///   derived class scope, member functions in the derived class
9676 ///   override and/or hide member functions with the same name and
9677 ///   parameter types in a base class (rather than conflicting).
9678 ///
9679 /// There are two ways to implement this:
9680 ///   (1) optimistically create shadow decls when they're not hidden
9681 ///       by existing declarations, or
9682 ///   (2) don't create any shadow decls (or at least don't make them
9683 ///       visible) until we've fully parsed/instantiated the class.
9684 /// The problem with (1) is that we might have to retroactively remove
9685 /// a shadow decl, which requires several O(n) operations because the
9686 /// decl structures are (very reasonably) not designed for removal.
9687 /// (2) avoids this but is very fiddly and phase-dependent.
9688 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9689   if (Shadow->getDeclName().getNameKind() ==
9690         DeclarationName::CXXConversionFunctionName)
9691     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9692 
9693   // Remove it from the DeclContext...
9694   Shadow->getDeclContext()->removeDecl(Shadow);
9695 
9696   // ...and the scope, if applicable...
9697   if (S) {
9698     S->RemoveDecl(Shadow);
9699     IdResolver.RemoveDecl(Shadow);
9700   }
9701 
9702   // ...and the using decl.
9703   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9704 
9705   // TODO: complain somehow if Shadow was used.  It shouldn't
9706   // be possible for this to happen, because...?
9707 }
9708 
9709 /// Find the base specifier for a base class with the given type.
9710 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9711                                                 QualType DesiredBase,
9712                                                 bool &AnyDependentBases) {
9713   // Check whether the named type is a direct base class.
9714   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9715   for (auto &Base : Derived->bases()) {
9716     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9717     if (CanonicalDesiredBase == BaseType)
9718       return &Base;
9719     if (BaseType->isDependentType())
9720       AnyDependentBases = true;
9721   }
9722   return nullptr;
9723 }
9724 
9725 namespace {
9726 class UsingValidatorCCC : public CorrectionCandidateCallback {
9727 public:
9728   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9729                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9730       : HasTypenameKeyword(HasTypenameKeyword),
9731         IsInstantiation(IsInstantiation), OldNNS(NNS),
9732         RequireMemberOf(RequireMemberOf) {}
9733 
9734   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9735     NamedDecl *ND = Candidate.getCorrectionDecl();
9736 
9737     // Keywords are not valid here.
9738     if (!ND || isa<NamespaceDecl>(ND))
9739       return false;
9740 
9741     // Completely unqualified names are invalid for a 'using' declaration.
9742     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9743       return false;
9744 
9745     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9746     // reject.
9747 
9748     if (RequireMemberOf) {
9749       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9750       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9751         // No-one ever wants a using-declaration to name an injected-class-name
9752         // of a base class, unless they're declaring an inheriting constructor.
9753         ASTContext &Ctx = ND->getASTContext();
9754         if (!Ctx.getLangOpts().CPlusPlus11)
9755           return false;
9756         QualType FoundType = Ctx.getRecordType(FoundRecord);
9757 
9758         // Check that the injected-class-name is named as a member of its own
9759         // type; we don't want to suggest 'using Derived::Base;', since that
9760         // means something else.
9761         NestedNameSpecifier *Specifier =
9762             Candidate.WillReplaceSpecifier()
9763                 ? Candidate.getCorrectionSpecifier()
9764                 : OldNNS;
9765         if (!Specifier->getAsType() ||
9766             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9767           return false;
9768 
9769         // Check that this inheriting constructor declaration actually names a
9770         // direct base class of the current class.
9771         bool AnyDependentBases = false;
9772         if (!findDirectBaseWithType(RequireMemberOf,
9773                                     Ctx.getRecordType(FoundRecord),
9774                                     AnyDependentBases) &&
9775             !AnyDependentBases)
9776           return false;
9777       } else {
9778         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9779         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9780           return false;
9781 
9782         // FIXME: Check that the base class member is accessible?
9783       }
9784     } else {
9785       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9786       if (FoundRecord && FoundRecord->isInjectedClassName())
9787         return false;
9788     }
9789 
9790     if (isa<TypeDecl>(ND))
9791       return HasTypenameKeyword || !IsInstantiation;
9792 
9793     return !HasTypenameKeyword;
9794   }
9795 
9796 private:
9797   bool HasTypenameKeyword;
9798   bool IsInstantiation;
9799   NestedNameSpecifier *OldNNS;
9800   CXXRecordDecl *RequireMemberOf;
9801 };
9802 } // end anonymous namespace
9803 
9804 /// Builds a using declaration.
9805 ///
9806 /// \param IsInstantiation - Whether this call arises from an
9807 ///   instantiation of an unresolved using declaration.  We treat
9808 ///   the lookup differently for these declarations.
9809 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9810                                        SourceLocation UsingLoc,
9811                                        bool HasTypenameKeyword,
9812                                        SourceLocation TypenameLoc,
9813                                        CXXScopeSpec &SS,
9814                                        DeclarationNameInfo NameInfo,
9815                                        SourceLocation EllipsisLoc,
9816                                        AttributeList *AttrList,
9817                                        bool IsInstantiation) {
9818   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9819   SourceLocation IdentLoc = NameInfo.getLoc();
9820   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9821 
9822   // FIXME: We ignore attributes for now.
9823 
9824   // For an inheriting constructor declaration, the name of the using
9825   // declaration is the name of a constructor in this class, not in the
9826   // base class.
9827   DeclarationNameInfo UsingName = NameInfo;
9828   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9829     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9830       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9831           Context.getCanonicalType(Context.getRecordType(RD))));
9832 
9833   // Do the redeclaration lookup in the current scope.
9834   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9835                         ForVisibleRedeclaration);
9836   Previous.setHideTags(false);
9837   if (S) {
9838     LookupName(Previous, S);
9839 
9840     // It is really dumb that we have to do this.
9841     LookupResult::Filter F = Previous.makeFilter();
9842     while (F.hasNext()) {
9843       NamedDecl *D = F.next();
9844       if (!isDeclInScope(D, CurContext, S))
9845         F.erase();
9846       // If we found a local extern declaration that's not ordinarily visible,
9847       // and this declaration is being added to a non-block scope, ignore it.
9848       // We're only checking for scope conflicts here, not also for violations
9849       // of the linkage rules.
9850       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9851                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9852         F.erase();
9853     }
9854     F.done();
9855   } else {
9856     assert(IsInstantiation && "no scope in non-instantiation");
9857     if (CurContext->isRecord())
9858       LookupQualifiedName(Previous, CurContext);
9859     else {
9860       // No redeclaration check is needed here; in non-member contexts we
9861       // diagnosed all possible conflicts with other using-declarations when
9862       // building the template:
9863       //
9864       // For a dependent non-type using declaration, the only valid case is
9865       // if we instantiate to a single enumerator. We check for conflicts
9866       // between shadow declarations we introduce, and we check in the template
9867       // definition for conflicts between a non-type using declaration and any
9868       // other declaration, which together covers all cases.
9869       //
9870       // A dependent typename using declaration will never successfully
9871       // instantiate, since it will always name a class member, so we reject
9872       // that in the template definition.
9873     }
9874   }
9875 
9876   // Check for invalid redeclarations.
9877   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9878                                   SS, IdentLoc, Previous))
9879     return nullptr;
9880 
9881   // Check for bad qualifiers.
9882   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9883                               IdentLoc))
9884     return nullptr;
9885 
9886   DeclContext *LookupContext = computeDeclContext(SS);
9887   NamedDecl *D;
9888   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9889   if (!LookupContext || EllipsisLoc.isValid()) {
9890     if (HasTypenameKeyword) {
9891       // FIXME: not all declaration name kinds are legal here
9892       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9893                                               UsingLoc, TypenameLoc,
9894                                               QualifierLoc,
9895                                               IdentLoc, NameInfo.getName(),
9896                                               EllipsisLoc);
9897     } else {
9898       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9899                                            QualifierLoc, NameInfo, EllipsisLoc);
9900     }
9901     D->setAccess(AS);
9902     CurContext->addDecl(D);
9903     return D;
9904   }
9905 
9906   auto Build = [&](bool Invalid) {
9907     UsingDecl *UD =
9908         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9909                           UsingName, HasTypenameKeyword);
9910     UD->setAccess(AS);
9911     CurContext->addDecl(UD);
9912     UD->setInvalidDecl(Invalid);
9913     return UD;
9914   };
9915   auto BuildInvalid = [&]{ return Build(true); };
9916   auto BuildValid = [&]{ return Build(false); };
9917 
9918   if (RequireCompleteDeclContext(SS, LookupContext))
9919     return BuildInvalid();
9920 
9921   // Look up the target name.
9922   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9923 
9924   // Unlike most lookups, we don't always want to hide tag
9925   // declarations: tag names are visible through the using declaration
9926   // even if hidden by ordinary names, *except* in a dependent context
9927   // where it's important for the sanity of two-phase lookup.
9928   if (!IsInstantiation)
9929     R.setHideTags(false);
9930 
9931   // For the purposes of this lookup, we have a base object type
9932   // equal to that of the current context.
9933   if (CurContext->isRecord()) {
9934     R.setBaseObjectType(
9935                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9936   }
9937 
9938   LookupQualifiedName(R, LookupContext);
9939 
9940   // Try to correct typos if possible. If constructor name lookup finds no
9941   // results, that means the named class has no explicit constructors, and we
9942   // suppressed declaring implicit ones (probably because it's dependent or
9943   // invalid).
9944   if (R.empty() &&
9945       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9946     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9947     // it will believe that glibc provides a ::gets in cases where it does not,
9948     // and will try to pull it into namespace std with a using-declaration.
9949     // Just ignore the using-declaration in that case.
9950     auto *II = NameInfo.getName().getAsIdentifierInfo();
9951     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9952         CurContext->isStdNamespace() &&
9953         isa<TranslationUnitDecl>(LookupContext) &&
9954         getSourceManager().isInSystemHeader(UsingLoc))
9955       return nullptr;
9956     if (TypoCorrection Corrected = CorrectTypo(
9957             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9958             llvm::make_unique<UsingValidatorCCC>(
9959                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9960                 dyn_cast<CXXRecordDecl>(CurContext)),
9961             CTK_ErrorRecovery)) {
9962       // We reject candidates where DroppedSpecifier == true, hence the
9963       // literal '0' below.
9964       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9965                                 << NameInfo.getName() << LookupContext << 0
9966                                 << SS.getRange());
9967 
9968       // If we picked a correction with no attached Decl we can't do anything
9969       // useful with it, bail out.
9970       NamedDecl *ND = Corrected.getCorrectionDecl();
9971       if (!ND)
9972         return BuildInvalid();
9973 
9974       // If we corrected to an inheriting constructor, handle it as one.
9975       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9976       if (RD && RD->isInjectedClassName()) {
9977         // The parent of the injected class name is the class itself.
9978         RD = cast<CXXRecordDecl>(RD->getParent());
9979 
9980         // Fix up the information we'll use to build the using declaration.
9981         if (Corrected.WillReplaceSpecifier()) {
9982           NestedNameSpecifierLocBuilder Builder;
9983           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9984                               QualifierLoc.getSourceRange());
9985           QualifierLoc = Builder.getWithLocInContext(Context);
9986         }
9987 
9988         // In this case, the name we introduce is the name of a derived class
9989         // constructor.
9990         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9991         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9992             Context.getCanonicalType(Context.getRecordType(CurClass))));
9993         UsingName.setNamedTypeInfo(nullptr);
9994         for (auto *Ctor : LookupConstructors(RD))
9995           R.addDecl(Ctor);
9996         R.resolveKind();
9997       } else {
9998         // FIXME: Pick up all the declarations if we found an overloaded
9999         // function.
10000         UsingName.setName(ND->getDeclName());
10001         R.addDecl(ND);
10002       }
10003     } else {
10004       Diag(IdentLoc, diag::err_no_member)
10005         << NameInfo.getName() << LookupContext << SS.getRange();
10006       return BuildInvalid();
10007     }
10008   }
10009 
10010   if (R.isAmbiguous())
10011     return BuildInvalid();
10012 
10013   if (HasTypenameKeyword) {
10014     // If we asked for a typename and got a non-type decl, error out.
10015     if (!R.getAsSingle<TypeDecl>()) {
10016       Diag(IdentLoc, diag::err_using_typename_non_type);
10017       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10018         Diag((*I)->getUnderlyingDecl()->getLocation(),
10019              diag::note_using_decl_target);
10020       return BuildInvalid();
10021     }
10022   } else {
10023     // If we asked for a non-typename and we got a type, error out,
10024     // but only if this is an instantiation of an unresolved using
10025     // decl.  Otherwise just silently find the type name.
10026     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10027       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10028       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10029       return BuildInvalid();
10030     }
10031   }
10032 
10033   // C++14 [namespace.udecl]p6:
10034   // A using-declaration shall not name a namespace.
10035   if (R.getAsSingle<NamespaceDecl>()) {
10036     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10037       << SS.getRange();
10038     return BuildInvalid();
10039   }
10040 
10041   // C++14 [namespace.udecl]p7:
10042   // A using-declaration shall not name a scoped enumerator.
10043   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10044     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10045       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10046         << SS.getRange();
10047       return BuildInvalid();
10048     }
10049   }
10050 
10051   UsingDecl *UD = BuildValid();
10052 
10053   // Some additional rules apply to inheriting constructors.
10054   if (UsingName.getName().getNameKind() ==
10055         DeclarationName::CXXConstructorName) {
10056     // Suppress access diagnostics; the access check is instead performed at the
10057     // point of use for an inheriting constructor.
10058     R.suppressDiagnostics();
10059     if (CheckInheritingConstructorUsingDecl(UD))
10060       return UD;
10061   }
10062 
10063   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10064     UsingShadowDecl *PrevDecl = nullptr;
10065     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10066       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10067   }
10068 
10069   return UD;
10070 }
10071 
10072 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10073                                     ArrayRef<NamedDecl *> Expansions) {
10074   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10075          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10076          isa<UsingPackDecl>(InstantiatedFrom));
10077 
10078   auto *UPD =
10079       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10080   UPD->setAccess(InstantiatedFrom->getAccess());
10081   CurContext->addDecl(UPD);
10082   return UPD;
10083 }
10084 
10085 /// Additional checks for a using declaration referring to a constructor name.
10086 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10087   assert(!UD->hasTypename() && "expecting a constructor name");
10088 
10089   const Type *SourceType = UD->getQualifier()->getAsType();
10090   assert(SourceType &&
10091          "Using decl naming constructor doesn't have type in scope spec.");
10092   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10093 
10094   // Check whether the named type is a direct base class.
10095   bool AnyDependentBases = false;
10096   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10097                                       AnyDependentBases);
10098   if (!Base && !AnyDependentBases) {
10099     Diag(UD->getUsingLoc(),
10100          diag::err_using_decl_constructor_not_in_direct_base)
10101       << UD->getNameInfo().getSourceRange()
10102       << QualType(SourceType, 0) << TargetClass;
10103     UD->setInvalidDecl();
10104     return true;
10105   }
10106 
10107   if (Base)
10108     Base->setInheritConstructors();
10109 
10110   return false;
10111 }
10112 
10113 /// Checks that the given using declaration is not an invalid
10114 /// redeclaration.  Note that this is checking only for the using decl
10115 /// itself, not for any ill-formedness among the UsingShadowDecls.
10116 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10117                                        bool HasTypenameKeyword,
10118                                        const CXXScopeSpec &SS,
10119                                        SourceLocation NameLoc,
10120                                        const LookupResult &Prev) {
10121   NestedNameSpecifier *Qual = SS.getScopeRep();
10122 
10123   // C++03 [namespace.udecl]p8:
10124   // C++0x [namespace.udecl]p10:
10125   //   A using-declaration is a declaration and can therefore be used
10126   //   repeatedly where (and only where) multiple declarations are
10127   //   allowed.
10128   //
10129   // That's in non-member contexts.
10130   if (!CurContext->getRedeclContext()->isRecord()) {
10131     // A dependent qualifier outside a class can only ever resolve to an
10132     // enumeration type. Therefore it conflicts with any other non-type
10133     // declaration in the same scope.
10134     // FIXME: How should we check for dependent type-type conflicts at block
10135     // scope?
10136     if (Qual->isDependent() && !HasTypenameKeyword) {
10137       for (auto *D : Prev) {
10138         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10139           bool OldCouldBeEnumerator =
10140               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10141           Diag(NameLoc,
10142                OldCouldBeEnumerator ? diag::err_redefinition
10143                                     : diag::err_redefinition_different_kind)
10144               << Prev.getLookupName();
10145           Diag(D->getLocation(), diag::note_previous_definition);
10146           return true;
10147         }
10148       }
10149     }
10150     return false;
10151   }
10152 
10153   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10154     NamedDecl *D = *I;
10155 
10156     bool DTypename;
10157     NestedNameSpecifier *DQual;
10158     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10159       DTypename = UD->hasTypename();
10160       DQual = UD->getQualifier();
10161     } else if (UnresolvedUsingValueDecl *UD
10162                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10163       DTypename = false;
10164       DQual = UD->getQualifier();
10165     } else if (UnresolvedUsingTypenameDecl *UD
10166                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10167       DTypename = true;
10168       DQual = UD->getQualifier();
10169     } else continue;
10170 
10171     // using decls differ if one says 'typename' and the other doesn't.
10172     // FIXME: non-dependent using decls?
10173     if (HasTypenameKeyword != DTypename) continue;
10174 
10175     // using decls differ if they name different scopes (but note that
10176     // template instantiation can cause this check to trigger when it
10177     // didn't before instantiation).
10178     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10179         Context.getCanonicalNestedNameSpecifier(DQual))
10180       continue;
10181 
10182     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10183     Diag(D->getLocation(), diag::note_using_decl) << 1;
10184     return true;
10185   }
10186 
10187   return false;
10188 }
10189 
10190 
10191 /// Checks that the given nested-name qualifier used in a using decl
10192 /// in the current context is appropriately related to the current
10193 /// scope.  If an error is found, diagnoses it and returns true.
10194 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10195                                    bool HasTypename,
10196                                    const CXXScopeSpec &SS,
10197                                    const DeclarationNameInfo &NameInfo,
10198                                    SourceLocation NameLoc) {
10199   DeclContext *NamedContext = computeDeclContext(SS);
10200 
10201   if (!CurContext->isRecord()) {
10202     // C++03 [namespace.udecl]p3:
10203     // C++0x [namespace.udecl]p8:
10204     //   A using-declaration for a class member shall be a member-declaration.
10205 
10206     // If we weren't able to compute a valid scope, it might validly be a
10207     // dependent class scope or a dependent enumeration unscoped scope. If
10208     // we have a 'typename' keyword, the scope must resolve to a class type.
10209     if ((HasTypename && !NamedContext) ||
10210         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10211       auto *RD = NamedContext
10212                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10213                      : nullptr;
10214       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10215         RD = nullptr;
10216 
10217       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10218         << SS.getRange();
10219 
10220       // If we have a complete, non-dependent source type, try to suggest a
10221       // way to get the same effect.
10222       if (!RD)
10223         return true;
10224 
10225       // Find what this using-declaration was referring to.
10226       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10227       R.setHideTags(false);
10228       R.suppressDiagnostics();
10229       LookupQualifiedName(R, RD);
10230 
10231       if (R.getAsSingle<TypeDecl>()) {
10232         if (getLangOpts().CPlusPlus11) {
10233           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10234           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10235             << 0 // alias declaration
10236             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10237                                           NameInfo.getName().getAsString() +
10238                                               " = ");
10239         } else {
10240           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10241           SourceLocation InsertLoc =
10242               getLocForEndOfToken(NameInfo.getLocEnd());
10243           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10244             << 1 // typedef declaration
10245             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10246             << FixItHint::CreateInsertion(
10247                    InsertLoc, " " + NameInfo.getName().getAsString());
10248         }
10249       } else if (R.getAsSingle<VarDecl>()) {
10250         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10251         // repeating the type of the static data member here.
10252         FixItHint FixIt;
10253         if (getLangOpts().CPlusPlus11) {
10254           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10255           FixIt = FixItHint::CreateReplacement(
10256               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10257         }
10258 
10259         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10260           << 2 // reference declaration
10261           << FixIt;
10262       } else if (R.getAsSingle<EnumConstantDecl>()) {
10263         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10264         // repeating the type of the enumeration here, and we can't do so if
10265         // the type is anonymous.
10266         FixItHint FixIt;
10267         if (getLangOpts().CPlusPlus11) {
10268           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10269           FixIt = FixItHint::CreateReplacement(
10270               UsingLoc,
10271               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10272         }
10273 
10274         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10275           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10276           << FixIt;
10277       }
10278       return true;
10279     }
10280 
10281     // Otherwise, this might be valid.
10282     return false;
10283   }
10284 
10285   // The current scope is a record.
10286 
10287   // If the named context is dependent, we can't decide much.
10288   if (!NamedContext) {
10289     // FIXME: in C++0x, we can diagnose if we can prove that the
10290     // nested-name-specifier does not refer to a base class, which is
10291     // still possible in some cases.
10292 
10293     // Otherwise we have to conservatively report that things might be
10294     // okay.
10295     return false;
10296   }
10297 
10298   if (!NamedContext->isRecord()) {
10299     // Ideally this would point at the last name in the specifier,
10300     // but we don't have that level of source info.
10301     Diag(SS.getRange().getBegin(),
10302          diag::err_using_decl_nested_name_specifier_is_not_class)
10303       << SS.getScopeRep() << SS.getRange();
10304     return true;
10305   }
10306 
10307   if (!NamedContext->isDependentContext() &&
10308       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10309     return true;
10310 
10311   if (getLangOpts().CPlusPlus11) {
10312     // C++11 [namespace.udecl]p3:
10313     //   In a using-declaration used as a member-declaration, the
10314     //   nested-name-specifier shall name a base class of the class
10315     //   being defined.
10316 
10317     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10318                                  cast<CXXRecordDecl>(NamedContext))) {
10319       if (CurContext == NamedContext) {
10320         Diag(NameLoc,
10321              diag::err_using_decl_nested_name_specifier_is_current_class)
10322           << SS.getRange();
10323         return true;
10324       }
10325 
10326       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10327         Diag(SS.getRange().getBegin(),
10328              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10329           << SS.getScopeRep()
10330           << cast<CXXRecordDecl>(CurContext)
10331           << SS.getRange();
10332       }
10333       return true;
10334     }
10335 
10336     return false;
10337   }
10338 
10339   // C++03 [namespace.udecl]p4:
10340   //   A using-declaration used as a member-declaration shall refer
10341   //   to a member of a base class of the class being defined [etc.].
10342 
10343   // Salient point: SS doesn't have to name a base class as long as
10344   // lookup only finds members from base classes.  Therefore we can
10345   // diagnose here only if we can prove that that can't happen,
10346   // i.e. if the class hierarchies provably don't intersect.
10347 
10348   // TODO: it would be nice if "definitely valid" results were cached
10349   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10350   // need to be repeated.
10351 
10352   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10353   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10354     Bases.insert(Base);
10355     return true;
10356   };
10357 
10358   // Collect all bases. Return false if we find a dependent base.
10359   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10360     return false;
10361 
10362   // Returns true if the base is dependent or is one of the accumulated base
10363   // classes.
10364   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10365     return !Bases.count(Base);
10366   };
10367 
10368   // Return false if the class has a dependent base or if it or one
10369   // of its bases is present in the base set of the current context.
10370   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10371       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10372     return false;
10373 
10374   Diag(SS.getRange().getBegin(),
10375        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10376     << SS.getScopeRep()
10377     << cast<CXXRecordDecl>(CurContext)
10378     << SS.getRange();
10379 
10380   return true;
10381 }
10382 
10383 Decl *Sema::ActOnAliasDeclaration(Scope *S,
10384                                   AccessSpecifier AS,
10385                                   MultiTemplateParamsArg TemplateParamLists,
10386                                   SourceLocation UsingLoc,
10387                                   UnqualifiedId &Name,
10388                                   AttributeList *AttrList,
10389                                   TypeResult Type,
10390                                   Decl *DeclFromDeclSpec) {
10391   // Skip up to the relevant declaration scope.
10392   while (S->isTemplateParamScope())
10393     S = S->getParent();
10394   assert((S->getFlags() & Scope::DeclScope) &&
10395          "got alias-declaration outside of declaration scope");
10396 
10397   if (Type.isInvalid())
10398     return nullptr;
10399 
10400   bool Invalid = false;
10401   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10402   TypeSourceInfo *TInfo = nullptr;
10403   GetTypeFromParser(Type.get(), &TInfo);
10404 
10405   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10406     return nullptr;
10407 
10408   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10409                                       UPPC_DeclarationType)) {
10410     Invalid = true;
10411     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10412                                              TInfo->getTypeLoc().getBeginLoc());
10413   }
10414 
10415   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10416                         TemplateParamLists.size()
10417                             ? forRedeclarationInCurContext()
10418                             : ForVisibleRedeclaration);
10419   LookupName(Previous, S);
10420 
10421   // Warn about shadowing the name of a template parameter.
10422   if (Previous.isSingleResult() &&
10423       Previous.getFoundDecl()->isTemplateParameter()) {
10424     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10425     Previous.clear();
10426   }
10427 
10428   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10429          "name in alias declaration must be an identifier");
10430   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10431                                                Name.StartLocation,
10432                                                Name.Identifier, TInfo);
10433 
10434   NewTD->setAccess(AS);
10435 
10436   if (Invalid)
10437     NewTD->setInvalidDecl();
10438 
10439   ProcessDeclAttributeList(S, NewTD, AttrList);
10440   AddPragmaAttributes(S, NewTD);
10441 
10442   CheckTypedefForVariablyModifiedType(S, NewTD);
10443   Invalid |= NewTD->isInvalidDecl();
10444 
10445   bool Redeclaration = false;
10446 
10447   NamedDecl *NewND;
10448   if (TemplateParamLists.size()) {
10449     TypeAliasTemplateDecl *OldDecl = nullptr;
10450     TemplateParameterList *OldTemplateParams = nullptr;
10451 
10452     if (TemplateParamLists.size() != 1) {
10453       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10454         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10455          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10456     }
10457     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10458 
10459     // Check that we can declare a template here.
10460     if (CheckTemplateDeclScope(S, TemplateParams))
10461       return nullptr;
10462 
10463     // Only consider previous declarations in the same scope.
10464     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10465                          /*ExplicitInstantiationOrSpecialization*/false);
10466     if (!Previous.empty()) {
10467       Redeclaration = true;
10468 
10469       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10470       if (!OldDecl && !Invalid) {
10471         Diag(UsingLoc, diag::err_redefinition_different_kind)
10472           << Name.Identifier;
10473 
10474         NamedDecl *OldD = Previous.getRepresentativeDecl();
10475         if (OldD->getLocation().isValid())
10476           Diag(OldD->getLocation(), diag::note_previous_definition);
10477 
10478         Invalid = true;
10479       }
10480 
10481       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10482         if (TemplateParameterListsAreEqual(TemplateParams,
10483                                            OldDecl->getTemplateParameters(),
10484                                            /*Complain=*/true,
10485                                            TPL_TemplateMatch))
10486           OldTemplateParams = OldDecl->getTemplateParameters();
10487         else
10488           Invalid = true;
10489 
10490         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10491         if (!Invalid &&
10492             !Context.hasSameType(OldTD->getUnderlyingType(),
10493                                  NewTD->getUnderlyingType())) {
10494           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10495           // but we can't reasonably accept it.
10496           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10497             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10498           if (OldTD->getLocation().isValid())
10499             Diag(OldTD->getLocation(), diag::note_previous_definition);
10500           Invalid = true;
10501         }
10502       }
10503     }
10504 
10505     // Merge any previous default template arguments into our parameters,
10506     // and check the parameter list.
10507     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10508                                    TPC_TypeAliasTemplate))
10509       return nullptr;
10510 
10511     TypeAliasTemplateDecl *NewDecl =
10512       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10513                                     Name.Identifier, TemplateParams,
10514                                     NewTD);
10515     NewTD->setDescribedAliasTemplate(NewDecl);
10516 
10517     NewDecl->setAccess(AS);
10518 
10519     if (Invalid)
10520       NewDecl->setInvalidDecl();
10521     else if (OldDecl) {
10522       NewDecl->setPreviousDecl(OldDecl);
10523       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10524     }
10525 
10526     NewND = NewDecl;
10527   } else {
10528     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10529       setTagNameForLinkagePurposes(TD, NewTD);
10530       handleTagNumbering(TD, S);
10531     }
10532     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10533     NewND = NewTD;
10534   }
10535 
10536   PushOnScopeChains(NewND, S);
10537   ActOnDocumentableDecl(NewND);
10538   return NewND;
10539 }
10540 
10541 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10542                                    SourceLocation AliasLoc,
10543                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10544                                    SourceLocation IdentLoc,
10545                                    IdentifierInfo *Ident) {
10546 
10547   // Lookup the namespace name.
10548   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10549   LookupParsedName(R, S, &SS);
10550 
10551   if (R.isAmbiguous())
10552     return nullptr;
10553 
10554   if (R.empty()) {
10555     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10556       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10557       return nullptr;
10558     }
10559   }
10560   assert(!R.isAmbiguous() && !R.empty());
10561   NamedDecl *ND = R.getRepresentativeDecl();
10562 
10563   // Check if we have a previous declaration with the same name.
10564   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10565                      ForVisibleRedeclaration);
10566   LookupName(PrevR, S);
10567 
10568   // Check we're not shadowing a template parameter.
10569   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10570     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10571     PrevR.clear();
10572   }
10573 
10574   // Filter out any other lookup result from an enclosing scope.
10575   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10576                        /*AllowInlineNamespace*/false);
10577 
10578   // Find the previous declaration and check that we can redeclare it.
10579   NamespaceAliasDecl *Prev = nullptr;
10580   if (PrevR.isSingleResult()) {
10581     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10582     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10583       // We already have an alias with the same name that points to the same
10584       // namespace; check that it matches.
10585       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10586         Prev = AD;
10587       } else if (isVisible(PrevDecl)) {
10588         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10589           << Alias;
10590         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10591           << AD->getNamespace();
10592         return nullptr;
10593       }
10594     } else if (isVisible(PrevDecl)) {
10595       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10596                             ? diag::err_redefinition
10597                             : diag::err_redefinition_different_kind;
10598       Diag(AliasLoc, DiagID) << Alias;
10599       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10600       return nullptr;
10601     }
10602   }
10603 
10604   // The use of a nested name specifier may trigger deprecation warnings.
10605   DiagnoseUseOfDecl(ND, IdentLoc);
10606 
10607   NamespaceAliasDecl *AliasDecl =
10608     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10609                                Alias, SS.getWithLocInContext(Context),
10610                                IdentLoc, ND);
10611   if (Prev)
10612     AliasDecl->setPreviousDecl(Prev);
10613 
10614   PushOnScopeChains(AliasDecl, S);
10615   return AliasDecl;
10616 }
10617 
10618 namespace {
10619 struct SpecialMemberExceptionSpecInfo
10620     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10621   SourceLocation Loc;
10622   Sema::ImplicitExceptionSpecification ExceptSpec;
10623 
10624   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10625                                  Sema::CXXSpecialMember CSM,
10626                                  Sema::InheritedConstructorInfo *ICI,
10627                                  SourceLocation Loc)
10628       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10629 
10630   bool visitBase(CXXBaseSpecifier *Base);
10631   bool visitField(FieldDecl *FD);
10632 
10633   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10634                            unsigned Quals);
10635 
10636   void visitSubobjectCall(Subobject Subobj,
10637                           Sema::SpecialMemberOverloadResult SMOR);
10638 };
10639 }
10640 
10641 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10642   auto *RT = Base->getType()->getAs<RecordType>();
10643   if (!RT)
10644     return false;
10645 
10646   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10647   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10648   if (auto *BaseCtor = SMOR.getMethod()) {
10649     visitSubobjectCall(Base, BaseCtor);
10650     return false;
10651   }
10652 
10653   visitClassSubobject(BaseClass, Base, 0);
10654   return false;
10655 }
10656 
10657 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10658   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10659     Expr *E = FD->getInClassInitializer();
10660     if (!E)
10661       // FIXME: It's a little wasteful to build and throw away a
10662       // CXXDefaultInitExpr here.
10663       // FIXME: We should have a single context note pointing at Loc, and
10664       // this location should be MD->getLocation() instead, since that's
10665       // the location where we actually use the default init expression.
10666       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10667     if (E)
10668       ExceptSpec.CalledExpr(E);
10669   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10670                             ->getAs<RecordType>()) {
10671     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10672                         FD->getType().getCVRQualifiers());
10673   }
10674   return false;
10675 }
10676 
10677 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10678                                                          Subobject Subobj,
10679                                                          unsigned Quals) {
10680   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10681   bool IsMutable = Field && Field->isMutable();
10682   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10683 }
10684 
10685 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10686     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10687   // Note, if lookup fails, it doesn't matter what exception specification we
10688   // choose because the special member will be deleted.
10689   if (CXXMethodDecl *MD = SMOR.getMethod())
10690     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10691 }
10692 
10693 static Sema::ImplicitExceptionSpecification
10694 ComputeDefaultedSpecialMemberExceptionSpec(
10695     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10696     Sema::InheritedConstructorInfo *ICI) {
10697   CXXRecordDecl *ClassDecl = MD->getParent();
10698 
10699   // C++ [except.spec]p14:
10700   //   An implicitly declared special member function (Clause 12) shall have an
10701   //   exception-specification. [...]
10702   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10703   if (ClassDecl->isInvalidDecl())
10704     return Info.ExceptSpec;
10705 
10706   // C++1z [except.spec]p7:
10707   //   [Look for exceptions thrown by] a constructor selected [...] to
10708   //   initialize a potentially constructed subobject,
10709   // C++1z [except.spec]p8:
10710   //   The exception specification for an implicitly-declared destructor, or a
10711   //   destructor without a noexcept-specifier, is potentially-throwing if and
10712   //   only if any of the destructors for any of its potentially constructed
10713   //   subojects is potentially throwing.
10714   // FIXME: We respect the first rule but ignore the "potentially constructed"
10715   // in the second rule to resolve a core issue (no number yet) that would have
10716   // us reject:
10717   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10718   //   struct B : A {};
10719   //   struct C : B { void f(); };
10720   // ... due to giving B::~B() a non-throwing exception specification.
10721   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10722                                 : Info.VisitAllBases);
10723 
10724   return Info.ExceptSpec;
10725 }
10726 
10727 namespace {
10728 /// RAII object to register a special member as being currently declared.
10729 struct DeclaringSpecialMember {
10730   Sema &S;
10731   Sema::SpecialMemberDecl D;
10732   Sema::ContextRAII SavedContext;
10733   bool WasAlreadyBeingDeclared;
10734 
10735   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10736       : S(S), D(RD, CSM), SavedContext(S, RD) {
10737     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10738     if (WasAlreadyBeingDeclared)
10739       // This almost never happens, but if it does, ensure that our cache
10740       // doesn't contain a stale result.
10741       S.SpecialMemberCache.clear();
10742     else {
10743       // Register a note to be produced if we encounter an error while
10744       // declaring the special member.
10745       Sema::CodeSynthesisContext Ctx;
10746       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10747       // FIXME: We don't have a location to use here. Using the class's
10748       // location maintains the fiction that we declare all special members
10749       // with the class, but (1) it's not clear that lying about that helps our
10750       // users understand what's going on, and (2) there may be outer contexts
10751       // on the stack (some of which are relevant) and printing them exposes
10752       // our lies.
10753       Ctx.PointOfInstantiation = RD->getLocation();
10754       Ctx.Entity = RD;
10755       Ctx.SpecialMember = CSM;
10756       S.pushCodeSynthesisContext(Ctx);
10757     }
10758   }
10759   ~DeclaringSpecialMember() {
10760     if (!WasAlreadyBeingDeclared) {
10761       S.SpecialMembersBeingDeclared.erase(D);
10762       S.popCodeSynthesisContext();
10763     }
10764   }
10765 
10766   /// Are we already trying to declare this special member?
10767   bool isAlreadyBeingDeclared() const {
10768     return WasAlreadyBeingDeclared;
10769   }
10770 };
10771 }
10772 
10773 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10774   // Look up any existing declarations, but don't trigger declaration of all
10775   // implicit special members with this name.
10776   DeclarationName Name = FD->getDeclName();
10777   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10778                  ForExternalRedeclaration);
10779   for (auto *D : FD->getParent()->lookup(Name))
10780     if (auto *Acceptable = R.getAcceptableDecl(D))
10781       R.addDecl(Acceptable);
10782   R.resolveKind();
10783   R.suppressDiagnostics();
10784 
10785   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10786 }
10787 
10788 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10789                                                      CXXRecordDecl *ClassDecl) {
10790   // C++ [class.ctor]p5:
10791   //   A default constructor for a class X is a constructor of class X
10792   //   that can be called without an argument. If there is no
10793   //   user-declared constructor for class X, a default constructor is
10794   //   implicitly declared. An implicitly-declared default constructor
10795   //   is an inline public member of its class.
10796   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10797          "Should not build implicit default constructor!");
10798 
10799   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10800   if (DSM.isAlreadyBeingDeclared())
10801     return nullptr;
10802 
10803   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10804                                                      CXXDefaultConstructor,
10805                                                      false);
10806 
10807   // Create the actual constructor declaration.
10808   CanQualType ClassType
10809     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10810   SourceLocation ClassLoc = ClassDecl->getLocation();
10811   DeclarationName Name
10812     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10813   DeclarationNameInfo NameInfo(Name, ClassLoc);
10814   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10815       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10816       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10817       /*isImplicitlyDeclared=*/true, Constexpr);
10818   DefaultCon->setAccess(AS_public);
10819   DefaultCon->setDefaulted();
10820 
10821   if (getLangOpts().CUDA) {
10822     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10823                                             DefaultCon,
10824                                             /* ConstRHS */ false,
10825                                             /* Diagnose */ false);
10826   }
10827 
10828   // Build an exception specification pointing back at this constructor.
10829   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10830   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10831 
10832   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10833   // constructors is easy to compute.
10834   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10835 
10836   // Note that we have declared this constructor.
10837   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10838 
10839   Scope *S = getScopeForContext(ClassDecl);
10840   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10841 
10842   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10843     SetDeclDeleted(DefaultCon, ClassLoc);
10844 
10845   if (S)
10846     PushOnScopeChains(DefaultCon, S, false);
10847   ClassDecl->addDecl(DefaultCon);
10848 
10849   return DefaultCon;
10850 }
10851 
10852 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10853                                             CXXConstructorDecl *Constructor) {
10854   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10855           !Constructor->doesThisDeclarationHaveABody() &&
10856           !Constructor->isDeleted()) &&
10857     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10858   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10859     return;
10860 
10861   CXXRecordDecl *ClassDecl = Constructor->getParent();
10862   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10863 
10864   SynthesizedFunctionScope Scope(*this, Constructor);
10865 
10866   // The exception specification is needed because we are defining the
10867   // function.
10868   ResolveExceptionSpec(CurrentLocation,
10869                        Constructor->getType()->castAs<FunctionProtoType>());
10870   MarkVTableUsed(CurrentLocation, ClassDecl);
10871 
10872   // Add a context note for diagnostics produced after this point.
10873   Scope.addContextNote(CurrentLocation);
10874 
10875   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10876     Constructor->setInvalidDecl();
10877     return;
10878   }
10879 
10880   SourceLocation Loc = Constructor->getLocEnd().isValid()
10881                            ? Constructor->getLocEnd()
10882                            : Constructor->getLocation();
10883   Constructor->setBody(new (Context) CompoundStmt(Loc));
10884   Constructor->markUsed(Context);
10885 
10886   if (ASTMutationListener *L = getASTMutationListener()) {
10887     L->CompletedImplicitDefinition(Constructor);
10888   }
10889 
10890   DiagnoseUninitializedFields(*this, Constructor);
10891 }
10892 
10893 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10894   // Perform any delayed checks on exception specifications.
10895   CheckDelayedMemberExceptionSpecs();
10896 }
10897 
10898 /// Find or create the fake constructor we synthesize to model constructing an
10899 /// object of a derived class via a constructor of a base class.
10900 CXXConstructorDecl *
10901 Sema::findInheritingConstructor(SourceLocation Loc,
10902                                 CXXConstructorDecl *BaseCtor,
10903                                 ConstructorUsingShadowDecl *Shadow) {
10904   CXXRecordDecl *Derived = Shadow->getParent();
10905   SourceLocation UsingLoc = Shadow->getLocation();
10906 
10907   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10908   // For now we use the name of the base class constructor as a member of the
10909   // derived class to indicate a (fake) inherited constructor name.
10910   DeclarationName Name = BaseCtor->getDeclName();
10911 
10912   // Check to see if we already have a fake constructor for this inherited
10913   // constructor call.
10914   for (NamedDecl *Ctor : Derived->lookup(Name))
10915     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10916                                ->getInheritedConstructor()
10917                                .getConstructor(),
10918                            BaseCtor))
10919       return cast<CXXConstructorDecl>(Ctor);
10920 
10921   DeclarationNameInfo NameInfo(Name, UsingLoc);
10922   TypeSourceInfo *TInfo =
10923       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10924   FunctionProtoTypeLoc ProtoLoc =
10925       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10926 
10927   // Check the inherited constructor is valid and find the list of base classes
10928   // from which it was inherited.
10929   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10930 
10931   bool Constexpr =
10932       BaseCtor->isConstexpr() &&
10933       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10934                                         false, BaseCtor, &ICI);
10935 
10936   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10937       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10938       BaseCtor->isExplicit(), /*Inline=*/true,
10939       /*ImplicitlyDeclared=*/true, Constexpr,
10940       InheritedConstructor(Shadow, BaseCtor));
10941   if (Shadow->isInvalidDecl())
10942     DerivedCtor->setInvalidDecl();
10943 
10944   // Build an unevaluated exception specification for this fake constructor.
10945   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10946   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10947   EPI.ExceptionSpec.Type = EST_Unevaluated;
10948   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10949   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10950                                                FPT->getParamTypes(), EPI));
10951 
10952   // Build the parameter declarations.
10953   SmallVector<ParmVarDecl *, 16> ParamDecls;
10954   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10955     TypeSourceInfo *TInfo =
10956         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10957     ParmVarDecl *PD = ParmVarDecl::Create(
10958         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10959         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10960     PD->setScopeInfo(0, I);
10961     PD->setImplicit();
10962     // Ensure attributes are propagated onto parameters (this matters for
10963     // format, pass_object_size, ...).
10964     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10965     ParamDecls.push_back(PD);
10966     ProtoLoc.setParam(I, PD);
10967   }
10968 
10969   // Set up the new constructor.
10970   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10971   DerivedCtor->setAccess(BaseCtor->getAccess());
10972   DerivedCtor->setParams(ParamDecls);
10973   Derived->addDecl(DerivedCtor);
10974 
10975   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10976     SetDeclDeleted(DerivedCtor, UsingLoc);
10977 
10978   return DerivedCtor;
10979 }
10980 
10981 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10982   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10983                                Ctor->getInheritedConstructor().getShadowDecl());
10984   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10985                             /*Diagnose*/true);
10986 }
10987 
10988 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10989                                        CXXConstructorDecl *Constructor) {
10990   CXXRecordDecl *ClassDecl = Constructor->getParent();
10991   assert(Constructor->getInheritedConstructor() &&
10992          !Constructor->doesThisDeclarationHaveABody() &&
10993          !Constructor->isDeleted());
10994   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10995     return;
10996 
10997   // Initializations are performed "as if by a defaulted default constructor",
10998   // so enter the appropriate scope.
10999   SynthesizedFunctionScope Scope(*this, Constructor);
11000 
11001   // The exception specification is needed because we are defining the
11002   // function.
11003   ResolveExceptionSpec(CurrentLocation,
11004                        Constructor->getType()->castAs<FunctionProtoType>());
11005   MarkVTableUsed(CurrentLocation, ClassDecl);
11006 
11007   // Add a context note for diagnostics produced after this point.
11008   Scope.addContextNote(CurrentLocation);
11009 
11010   ConstructorUsingShadowDecl *Shadow =
11011       Constructor->getInheritedConstructor().getShadowDecl();
11012   CXXConstructorDecl *InheritedCtor =
11013       Constructor->getInheritedConstructor().getConstructor();
11014 
11015   // [class.inhctor.init]p1:
11016   //   initialization proceeds as if a defaulted default constructor is used to
11017   //   initialize the D object and each base class subobject from which the
11018   //   constructor was inherited
11019 
11020   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11021   CXXRecordDecl *RD = Shadow->getParent();
11022   SourceLocation InitLoc = Shadow->getLocation();
11023 
11024   // Build explicit initializers for all base classes from which the
11025   // constructor was inherited.
11026   SmallVector<CXXCtorInitializer*, 8> Inits;
11027   for (bool VBase : {false, true}) {
11028     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11029       if (B.isVirtual() != VBase)
11030         continue;
11031 
11032       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11033       if (!BaseRD)
11034         continue;
11035 
11036       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11037       if (!BaseCtor.first)
11038         continue;
11039 
11040       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11041       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11042           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11043 
11044       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11045       Inits.push_back(new (Context) CXXCtorInitializer(
11046           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11047           SourceLocation()));
11048     }
11049   }
11050 
11051   // We now proceed as if for a defaulted default constructor, with the relevant
11052   // initializers replaced.
11053 
11054   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11055     Constructor->setInvalidDecl();
11056     return;
11057   }
11058 
11059   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11060   Constructor->markUsed(Context);
11061 
11062   if (ASTMutationListener *L = getASTMutationListener()) {
11063     L->CompletedImplicitDefinition(Constructor);
11064   }
11065 
11066   DiagnoseUninitializedFields(*this, Constructor);
11067 }
11068 
11069 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11070   // C++ [class.dtor]p2:
11071   //   If a class has no user-declared destructor, a destructor is
11072   //   declared implicitly. An implicitly-declared destructor is an
11073   //   inline public member of its class.
11074   assert(ClassDecl->needsImplicitDestructor());
11075 
11076   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11077   if (DSM.isAlreadyBeingDeclared())
11078     return nullptr;
11079 
11080   // Create the actual destructor declaration.
11081   CanQualType ClassType
11082     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11083   SourceLocation ClassLoc = ClassDecl->getLocation();
11084   DeclarationName Name
11085     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11086   DeclarationNameInfo NameInfo(Name, ClassLoc);
11087   CXXDestructorDecl *Destructor
11088       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11089                                   QualType(), nullptr, /*isInline=*/true,
11090                                   /*isImplicitlyDeclared=*/true);
11091   Destructor->setAccess(AS_public);
11092   Destructor->setDefaulted();
11093 
11094   if (getLangOpts().CUDA) {
11095     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11096                                             Destructor,
11097                                             /* ConstRHS */ false,
11098                                             /* Diagnose */ false);
11099   }
11100 
11101   // Build an exception specification pointing back at this destructor.
11102   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11103   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11104 
11105   // We don't need to use SpecialMemberIsTrivial here; triviality for
11106   // destructors is easy to compute.
11107   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11108   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11109                                 ClassDecl->hasTrivialDestructorForCall());
11110 
11111   // Note that we have declared this destructor.
11112   ++ASTContext::NumImplicitDestructorsDeclared;
11113 
11114   Scope *S = getScopeForContext(ClassDecl);
11115   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11116 
11117   // We can't check whether an implicit destructor is deleted before we complete
11118   // the definition of the class, because its validity depends on the alignment
11119   // of the class. We'll check this from ActOnFields once the class is complete.
11120   if (ClassDecl->isCompleteDefinition() &&
11121       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11122     SetDeclDeleted(Destructor, ClassLoc);
11123 
11124   // Introduce this destructor into its scope.
11125   if (S)
11126     PushOnScopeChains(Destructor, S, false);
11127   ClassDecl->addDecl(Destructor);
11128 
11129   return Destructor;
11130 }
11131 
11132 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11133                                     CXXDestructorDecl *Destructor) {
11134   assert((Destructor->isDefaulted() &&
11135           !Destructor->doesThisDeclarationHaveABody() &&
11136           !Destructor->isDeleted()) &&
11137          "DefineImplicitDestructor - call it for implicit default dtor");
11138   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11139     return;
11140 
11141   CXXRecordDecl *ClassDecl = Destructor->getParent();
11142   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11143 
11144   SynthesizedFunctionScope Scope(*this, Destructor);
11145 
11146   // The exception specification is needed because we are defining the
11147   // function.
11148   ResolveExceptionSpec(CurrentLocation,
11149                        Destructor->getType()->castAs<FunctionProtoType>());
11150   MarkVTableUsed(CurrentLocation, ClassDecl);
11151 
11152   // Add a context note for diagnostics produced after this point.
11153   Scope.addContextNote(CurrentLocation);
11154 
11155   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11156                                          Destructor->getParent());
11157 
11158   if (CheckDestructor(Destructor)) {
11159     Destructor->setInvalidDecl();
11160     return;
11161   }
11162 
11163   SourceLocation Loc = Destructor->getLocEnd().isValid()
11164                            ? Destructor->getLocEnd()
11165                            : Destructor->getLocation();
11166   Destructor->setBody(new (Context) CompoundStmt(Loc));
11167   Destructor->markUsed(Context);
11168 
11169   if (ASTMutationListener *L = getASTMutationListener()) {
11170     L->CompletedImplicitDefinition(Destructor);
11171   }
11172 }
11173 
11174 /// Perform any semantic analysis which needs to be delayed until all
11175 /// pending class member declarations have been parsed.
11176 void Sema::ActOnFinishCXXMemberDecls() {
11177   // If the context is an invalid C++ class, just suppress these checks.
11178   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11179     if (Record->isInvalidDecl()) {
11180       DelayedDefaultedMemberExceptionSpecs.clear();
11181       DelayedExceptionSpecChecks.clear();
11182       return;
11183     }
11184     checkForMultipleExportedDefaultConstructors(*this, Record);
11185   }
11186 }
11187 
11188 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11189   referenceDLLExportedClassMethods();
11190 }
11191 
11192 void Sema::referenceDLLExportedClassMethods() {
11193   if (!DelayedDllExportClasses.empty()) {
11194     // Calling ReferenceDllExportedMembers might cause the current function to
11195     // be called again, so use a local copy of DelayedDllExportClasses.
11196     SmallVector<CXXRecordDecl *, 4> WorkList;
11197     std::swap(DelayedDllExportClasses, WorkList);
11198     for (CXXRecordDecl *Class : WorkList)
11199       ReferenceDllExportedMembers(*this, Class);
11200   }
11201 }
11202 
11203 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11204                                          CXXDestructorDecl *Destructor) {
11205   assert(getLangOpts().CPlusPlus11 &&
11206          "adjusting dtor exception specs was introduced in c++11");
11207 
11208   // C++11 [class.dtor]p3:
11209   //   A declaration of a destructor that does not have an exception-
11210   //   specification is implicitly considered to have the same exception-
11211   //   specification as an implicit declaration.
11212   const FunctionProtoType *DtorType = Destructor->getType()->
11213                                         getAs<FunctionProtoType>();
11214   if (DtorType->hasExceptionSpec())
11215     return;
11216 
11217   // Replace the destructor's type, building off the existing one. Fortunately,
11218   // the only thing of interest in the destructor type is its extended info.
11219   // The return and arguments are fixed.
11220   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11221   EPI.ExceptionSpec.Type = EST_Unevaluated;
11222   EPI.ExceptionSpec.SourceDecl = Destructor;
11223   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11224 
11225   // FIXME: If the destructor has a body that could throw, and the newly created
11226   // spec doesn't allow exceptions, we should emit a warning, because this
11227   // change in behavior can break conforming C++03 programs at runtime.
11228   // However, we don't have a body or an exception specification yet, so it
11229   // needs to be done somewhere else.
11230 }
11231 
11232 namespace {
11233 /// An abstract base class for all helper classes used in building the
11234 //  copy/move operators. These classes serve as factory functions and help us
11235 //  avoid using the same Expr* in the AST twice.
11236 class ExprBuilder {
11237   ExprBuilder(const ExprBuilder&) = delete;
11238   ExprBuilder &operator=(const ExprBuilder&) = delete;
11239 
11240 protected:
11241   static Expr *assertNotNull(Expr *E) {
11242     assert(E && "Expression construction must not fail.");
11243     return E;
11244   }
11245 
11246 public:
11247   ExprBuilder() {}
11248   virtual ~ExprBuilder() {}
11249 
11250   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11251 };
11252 
11253 class RefBuilder: public ExprBuilder {
11254   VarDecl *Var;
11255   QualType VarType;
11256 
11257 public:
11258   Expr *build(Sema &S, SourceLocation Loc) const override {
11259     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11260   }
11261 
11262   RefBuilder(VarDecl *Var, QualType VarType)
11263       : Var(Var), VarType(VarType) {}
11264 };
11265 
11266 class ThisBuilder: public ExprBuilder {
11267 public:
11268   Expr *build(Sema &S, SourceLocation Loc) const override {
11269     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11270   }
11271 };
11272 
11273 class CastBuilder: public ExprBuilder {
11274   const ExprBuilder &Builder;
11275   QualType Type;
11276   ExprValueKind Kind;
11277   const CXXCastPath &Path;
11278 
11279 public:
11280   Expr *build(Sema &S, SourceLocation Loc) const override {
11281     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11282                                              CK_UncheckedDerivedToBase, Kind,
11283                                              &Path).get());
11284   }
11285 
11286   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11287               const CXXCastPath &Path)
11288       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11289 };
11290 
11291 class DerefBuilder: public ExprBuilder {
11292   const ExprBuilder &Builder;
11293 
11294 public:
11295   Expr *build(Sema &S, SourceLocation Loc) const override {
11296     return assertNotNull(
11297         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11298   }
11299 
11300   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11301 };
11302 
11303 class MemberBuilder: public ExprBuilder {
11304   const ExprBuilder &Builder;
11305   QualType Type;
11306   CXXScopeSpec SS;
11307   bool IsArrow;
11308   LookupResult &MemberLookup;
11309 
11310 public:
11311   Expr *build(Sema &S, SourceLocation Loc) const override {
11312     return assertNotNull(S.BuildMemberReferenceExpr(
11313         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11314         nullptr, MemberLookup, nullptr, nullptr).get());
11315   }
11316 
11317   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11318                 LookupResult &MemberLookup)
11319       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11320         MemberLookup(MemberLookup) {}
11321 };
11322 
11323 class MoveCastBuilder: public ExprBuilder {
11324   const ExprBuilder &Builder;
11325 
11326 public:
11327   Expr *build(Sema &S, SourceLocation Loc) const override {
11328     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11329   }
11330 
11331   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11332 };
11333 
11334 class LvalueConvBuilder: public ExprBuilder {
11335   const ExprBuilder &Builder;
11336 
11337 public:
11338   Expr *build(Sema &S, SourceLocation Loc) const override {
11339     return assertNotNull(
11340         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11341   }
11342 
11343   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11344 };
11345 
11346 class SubscriptBuilder: public ExprBuilder {
11347   const ExprBuilder &Base;
11348   const ExprBuilder &Index;
11349 
11350 public:
11351   Expr *build(Sema &S, SourceLocation Loc) const override {
11352     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11353         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11354   }
11355 
11356   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11357       : Base(Base), Index(Index) {}
11358 };
11359 
11360 } // end anonymous namespace
11361 
11362 /// When generating a defaulted copy or move assignment operator, if a field
11363 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11364 /// do so. This optimization only applies for arrays of scalars, and for arrays
11365 /// of class type where the selected copy/move-assignment operator is trivial.
11366 static StmtResult
11367 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11368                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11369   // Compute the size of the memory buffer to be copied.
11370   QualType SizeType = S.Context.getSizeType();
11371   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11372                    S.Context.getTypeSizeInChars(T).getQuantity());
11373 
11374   // Take the address of the field references for "from" and "to". We
11375   // directly construct UnaryOperators here because semantic analysis
11376   // does not permit us to take the address of an xvalue.
11377   Expr *From = FromB.build(S, Loc);
11378   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11379                          S.Context.getPointerType(From->getType()),
11380                          VK_RValue, OK_Ordinary, Loc, false);
11381   Expr *To = ToB.build(S, Loc);
11382   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11383                        S.Context.getPointerType(To->getType()),
11384                        VK_RValue, OK_Ordinary, Loc, false);
11385 
11386   const Type *E = T->getBaseElementTypeUnsafe();
11387   bool NeedsCollectableMemCpy =
11388     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11389 
11390   // Create a reference to the __builtin_objc_memmove_collectable function
11391   StringRef MemCpyName = NeedsCollectableMemCpy ?
11392     "__builtin_objc_memmove_collectable" :
11393     "__builtin_memcpy";
11394   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11395                  Sema::LookupOrdinaryName);
11396   S.LookupName(R, S.TUScope, true);
11397 
11398   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11399   if (!MemCpy)
11400     // Something went horribly wrong earlier, and we will have complained
11401     // about it.
11402     return StmtError();
11403 
11404   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11405                                             VK_RValue, Loc, nullptr);
11406   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11407 
11408   Expr *CallArgs[] = {
11409     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11410   };
11411   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11412                                     Loc, CallArgs, Loc);
11413 
11414   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11415   return Call.getAs<Stmt>();
11416 }
11417 
11418 /// Builds a statement that copies/moves the given entity from \p From to
11419 /// \c To.
11420 ///
11421 /// This routine is used to copy/move the members of a class with an
11422 /// implicitly-declared copy/move assignment operator. When the entities being
11423 /// copied are arrays, this routine builds for loops to copy them.
11424 ///
11425 /// \param S The Sema object used for type-checking.
11426 ///
11427 /// \param Loc The location where the implicit copy/move is being generated.
11428 ///
11429 /// \param T The type of the expressions being copied/moved. Both expressions
11430 /// must have this type.
11431 ///
11432 /// \param To The expression we are copying/moving to.
11433 ///
11434 /// \param From The expression we are copying/moving from.
11435 ///
11436 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11437 /// Otherwise, it's a non-static member subobject.
11438 ///
11439 /// \param Copying Whether we're copying or moving.
11440 ///
11441 /// \param Depth Internal parameter recording the depth of the recursion.
11442 ///
11443 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11444 /// if a memcpy should be used instead.
11445 static StmtResult
11446 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11447                                  const ExprBuilder &To, const ExprBuilder &From,
11448                                  bool CopyingBaseSubobject, bool Copying,
11449                                  unsigned Depth = 0) {
11450   // C++11 [class.copy]p28:
11451   //   Each subobject is assigned in the manner appropriate to its type:
11452   //
11453   //     - if the subobject is of class type, as if by a call to operator= with
11454   //       the subobject as the object expression and the corresponding
11455   //       subobject of x as a single function argument (as if by explicit
11456   //       qualification; that is, ignoring any possible virtual overriding
11457   //       functions in more derived classes);
11458   //
11459   // C++03 [class.copy]p13:
11460   //     - if the subobject is of class type, the copy assignment operator for
11461   //       the class is used (as if by explicit qualification; that is,
11462   //       ignoring any possible virtual overriding functions in more derived
11463   //       classes);
11464   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11465     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11466 
11467     // Look for operator=.
11468     DeclarationName Name
11469       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11470     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11471     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11472 
11473     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11474     // operator.
11475     if (!S.getLangOpts().CPlusPlus11) {
11476       LookupResult::Filter F = OpLookup.makeFilter();
11477       while (F.hasNext()) {
11478         NamedDecl *D = F.next();
11479         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11480           if (Method->isCopyAssignmentOperator() ||
11481               (!Copying && Method->isMoveAssignmentOperator()))
11482             continue;
11483 
11484         F.erase();
11485       }
11486       F.done();
11487     }
11488 
11489     // Suppress the protected check (C++ [class.protected]) for each of the
11490     // assignment operators we found. This strange dance is required when
11491     // we're assigning via a base classes's copy-assignment operator. To
11492     // ensure that we're getting the right base class subobject (without
11493     // ambiguities), we need to cast "this" to that subobject type; to
11494     // ensure that we don't go through the virtual call mechanism, we need
11495     // to qualify the operator= name with the base class (see below). However,
11496     // this means that if the base class has a protected copy assignment
11497     // operator, the protected member access check will fail. So, we
11498     // rewrite "protected" access to "public" access in this case, since we
11499     // know by construction that we're calling from a derived class.
11500     if (CopyingBaseSubobject) {
11501       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11502            L != LEnd; ++L) {
11503         if (L.getAccess() == AS_protected)
11504           L.setAccess(AS_public);
11505       }
11506     }
11507 
11508     // Create the nested-name-specifier that will be used to qualify the
11509     // reference to operator=; this is required to suppress the virtual
11510     // call mechanism.
11511     CXXScopeSpec SS;
11512     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11513     SS.MakeTrivial(S.Context,
11514                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11515                                                CanonicalT),
11516                    Loc);
11517 
11518     // Create the reference to operator=.
11519     ExprResult OpEqualRef
11520       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11521                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11522                                    /*FirstQualifierInScope=*/nullptr,
11523                                    OpLookup,
11524                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11525                                    /*SuppressQualifierCheck=*/true);
11526     if (OpEqualRef.isInvalid())
11527       return StmtError();
11528 
11529     // Build the call to the assignment operator.
11530 
11531     Expr *FromInst = From.build(S, Loc);
11532     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11533                                                   OpEqualRef.getAs<Expr>(),
11534                                                   Loc, FromInst, Loc);
11535     if (Call.isInvalid())
11536       return StmtError();
11537 
11538     // If we built a call to a trivial 'operator=' while copying an array,
11539     // bail out. We'll replace the whole shebang with a memcpy.
11540     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11541     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11542       return StmtResult((Stmt*)nullptr);
11543 
11544     // Convert to an expression-statement, and clean up any produced
11545     // temporaries.
11546     return S.ActOnExprStmt(Call);
11547   }
11548 
11549   //     - if the subobject is of scalar type, the built-in assignment
11550   //       operator is used.
11551   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11552   if (!ArrayTy) {
11553     ExprResult Assignment = S.CreateBuiltinBinOp(
11554         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11555     if (Assignment.isInvalid())
11556       return StmtError();
11557     return S.ActOnExprStmt(Assignment);
11558   }
11559 
11560   //     - if the subobject is an array, each element is assigned, in the
11561   //       manner appropriate to the element type;
11562 
11563   // Construct a loop over the array bounds, e.g.,
11564   //
11565   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11566   //
11567   // that will copy each of the array elements.
11568   QualType SizeType = S.Context.getSizeType();
11569 
11570   // Create the iteration variable.
11571   IdentifierInfo *IterationVarName = nullptr;
11572   {
11573     SmallString<8> Str;
11574     llvm::raw_svector_ostream OS(Str);
11575     OS << "__i" << Depth;
11576     IterationVarName = &S.Context.Idents.get(OS.str());
11577   }
11578   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11579                                           IterationVarName, SizeType,
11580                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11581                                           SC_None);
11582 
11583   // Initialize the iteration variable to zero.
11584   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11585   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11586 
11587   // Creates a reference to the iteration variable.
11588   RefBuilder IterationVarRef(IterationVar, SizeType);
11589   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11590 
11591   // Create the DeclStmt that holds the iteration variable.
11592   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11593 
11594   // Subscript the "from" and "to" expressions with the iteration variable.
11595   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11596   MoveCastBuilder FromIndexMove(FromIndexCopy);
11597   const ExprBuilder *FromIndex;
11598   if (Copying)
11599     FromIndex = &FromIndexCopy;
11600   else
11601     FromIndex = &FromIndexMove;
11602 
11603   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11604 
11605   // Build the copy/move for an individual element of the array.
11606   StmtResult Copy =
11607     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11608                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11609                                      Copying, Depth + 1);
11610   // Bail out if copying fails or if we determined that we should use memcpy.
11611   if (Copy.isInvalid() || !Copy.get())
11612     return Copy;
11613 
11614   // Create the comparison against the array bound.
11615   llvm::APInt Upper
11616     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11617   Expr *Comparison
11618     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11619                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11620                                      BO_NE, S.Context.BoolTy,
11621                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11622 
11623   // Create the pre-increment of the iteration variable. We can determine
11624   // whether the increment will overflow based on the value of the array
11625   // bound.
11626   Expr *Increment = new (S.Context)
11627       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11628                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11629 
11630   // Construct the loop that copies all elements of this array.
11631   return S.ActOnForStmt(
11632       Loc, Loc, InitStmt,
11633       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11634       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11635 }
11636 
11637 static StmtResult
11638 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11639                       const ExprBuilder &To, const ExprBuilder &From,
11640                       bool CopyingBaseSubobject, bool Copying) {
11641   // Maybe we should use a memcpy?
11642   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11643       T.isTriviallyCopyableType(S.Context))
11644     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11645 
11646   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11647                                                      CopyingBaseSubobject,
11648                                                      Copying, 0));
11649 
11650   // If we ended up picking a trivial assignment operator for an array of a
11651   // non-trivially-copyable class type, just emit a memcpy.
11652   if (!Result.isInvalid() && !Result.get())
11653     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11654 
11655   return Result;
11656 }
11657 
11658 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11659   // Note: The following rules are largely analoguous to the copy
11660   // constructor rules. Note that virtual bases are not taken into account
11661   // for determining the argument type of the operator. Note also that
11662   // operators taking an object instead of a reference are allowed.
11663   assert(ClassDecl->needsImplicitCopyAssignment());
11664 
11665   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11666   if (DSM.isAlreadyBeingDeclared())
11667     return nullptr;
11668 
11669   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11670   QualType RetType = Context.getLValueReferenceType(ArgType);
11671   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11672   if (Const)
11673     ArgType = ArgType.withConst();
11674   ArgType = Context.getLValueReferenceType(ArgType);
11675 
11676   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11677                                                      CXXCopyAssignment,
11678                                                      Const);
11679 
11680   //   An implicitly-declared copy assignment operator is an inline public
11681   //   member of its class.
11682   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11683   SourceLocation ClassLoc = ClassDecl->getLocation();
11684   DeclarationNameInfo NameInfo(Name, ClassLoc);
11685   CXXMethodDecl *CopyAssignment =
11686       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11687                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11688                             /*isInline=*/true, Constexpr, SourceLocation());
11689   CopyAssignment->setAccess(AS_public);
11690   CopyAssignment->setDefaulted();
11691   CopyAssignment->setImplicit();
11692 
11693   if (getLangOpts().CUDA) {
11694     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11695                                             CopyAssignment,
11696                                             /* ConstRHS */ Const,
11697                                             /* Diagnose */ false);
11698   }
11699 
11700   // Build an exception specification pointing back at this member.
11701   FunctionProtoType::ExtProtoInfo EPI =
11702       getImplicitMethodEPI(*this, CopyAssignment);
11703   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11704 
11705   // Add the parameter to the operator.
11706   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11707                                                ClassLoc, ClassLoc,
11708                                                /*Id=*/nullptr, ArgType,
11709                                                /*TInfo=*/nullptr, SC_None,
11710                                                nullptr);
11711   CopyAssignment->setParams(FromParam);
11712 
11713   CopyAssignment->setTrivial(
11714     ClassDecl->needsOverloadResolutionForCopyAssignment()
11715       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11716       : ClassDecl->hasTrivialCopyAssignment());
11717 
11718   // Note that we have added this copy-assignment operator.
11719   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11720 
11721   Scope *S = getScopeForContext(ClassDecl);
11722   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11723 
11724   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11725     SetDeclDeleted(CopyAssignment, ClassLoc);
11726 
11727   if (S)
11728     PushOnScopeChains(CopyAssignment, S, false);
11729   ClassDecl->addDecl(CopyAssignment);
11730 
11731   return CopyAssignment;
11732 }
11733 
11734 /// Diagnose an implicit copy operation for a class which is odr-used, but
11735 /// which is deprecated because the class has a user-declared copy constructor,
11736 /// copy assignment operator, or destructor.
11737 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11738   assert(CopyOp->isImplicit());
11739 
11740   CXXRecordDecl *RD = CopyOp->getParent();
11741   CXXMethodDecl *UserDeclaredOperation = nullptr;
11742 
11743   // In Microsoft mode, assignment operations don't affect constructors and
11744   // vice versa.
11745   if (RD->hasUserDeclaredDestructor()) {
11746     UserDeclaredOperation = RD->getDestructor();
11747   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11748              RD->hasUserDeclaredCopyConstructor() &&
11749              !S.getLangOpts().MSVCCompat) {
11750     // Find any user-declared copy constructor.
11751     for (auto *I : RD->ctors()) {
11752       if (I->isCopyConstructor()) {
11753         UserDeclaredOperation = I;
11754         break;
11755       }
11756     }
11757     assert(UserDeclaredOperation);
11758   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11759              RD->hasUserDeclaredCopyAssignment() &&
11760              !S.getLangOpts().MSVCCompat) {
11761     // Find any user-declared move assignment operator.
11762     for (auto *I : RD->methods()) {
11763       if (I->isCopyAssignmentOperator()) {
11764         UserDeclaredOperation = I;
11765         break;
11766       }
11767     }
11768     assert(UserDeclaredOperation);
11769   }
11770 
11771   if (UserDeclaredOperation) {
11772     S.Diag(UserDeclaredOperation->getLocation(),
11773          diag::warn_deprecated_copy_operation)
11774       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11775       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11776   }
11777 }
11778 
11779 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11780                                         CXXMethodDecl *CopyAssignOperator) {
11781   assert((CopyAssignOperator->isDefaulted() &&
11782           CopyAssignOperator->isOverloadedOperator() &&
11783           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11784           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11785           !CopyAssignOperator->isDeleted()) &&
11786          "DefineImplicitCopyAssignment called for wrong function");
11787   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11788     return;
11789 
11790   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11791   if (ClassDecl->isInvalidDecl()) {
11792     CopyAssignOperator->setInvalidDecl();
11793     return;
11794   }
11795 
11796   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11797 
11798   // The exception specification is needed because we are defining the
11799   // function.
11800   ResolveExceptionSpec(CurrentLocation,
11801                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11802 
11803   // Add a context note for diagnostics produced after this point.
11804   Scope.addContextNote(CurrentLocation);
11805 
11806   // C++11 [class.copy]p18:
11807   //   The [definition of an implicitly declared copy assignment operator] is
11808   //   deprecated if the class has a user-declared copy constructor or a
11809   //   user-declared destructor.
11810   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11811     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11812 
11813   // C++0x [class.copy]p30:
11814   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11815   //   for a non-union class X performs memberwise copy assignment of its
11816   //   subobjects. The direct base classes of X are assigned first, in the
11817   //   order of their declaration in the base-specifier-list, and then the
11818   //   immediate non-static data members of X are assigned, in the order in
11819   //   which they were declared in the class definition.
11820 
11821   // The statements that form the synthesized function body.
11822   SmallVector<Stmt*, 8> Statements;
11823 
11824   // The parameter for the "other" object, which we are copying from.
11825   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11826   Qualifiers OtherQuals = Other->getType().getQualifiers();
11827   QualType OtherRefType = Other->getType();
11828   if (const LValueReferenceType *OtherRef
11829                                 = OtherRefType->getAs<LValueReferenceType>()) {
11830     OtherRefType = OtherRef->getPointeeType();
11831     OtherQuals = OtherRefType.getQualifiers();
11832   }
11833 
11834   // Our location for everything implicitly-generated.
11835   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11836                            ? CopyAssignOperator->getLocEnd()
11837                            : CopyAssignOperator->getLocation();
11838 
11839   // Builds a DeclRefExpr for the "other" object.
11840   RefBuilder OtherRef(Other, OtherRefType);
11841 
11842   // Builds the "this" pointer.
11843   ThisBuilder This;
11844 
11845   // Assign base classes.
11846   bool Invalid = false;
11847   for (auto &Base : ClassDecl->bases()) {
11848     // Form the assignment:
11849     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11850     QualType BaseType = Base.getType().getUnqualifiedType();
11851     if (!BaseType->isRecordType()) {
11852       Invalid = true;
11853       continue;
11854     }
11855 
11856     CXXCastPath BasePath;
11857     BasePath.push_back(&Base);
11858 
11859     // Construct the "from" expression, which is an implicit cast to the
11860     // appropriately-qualified base type.
11861     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11862                      VK_LValue, BasePath);
11863 
11864     // Dereference "this".
11865     DerefBuilder DerefThis(This);
11866     CastBuilder To(DerefThis,
11867                    Context.getCVRQualifiedType(
11868                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11869                    VK_LValue, BasePath);
11870 
11871     // Build the copy.
11872     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11873                                             To, From,
11874                                             /*CopyingBaseSubobject=*/true,
11875                                             /*Copying=*/true);
11876     if (Copy.isInvalid()) {
11877       CopyAssignOperator->setInvalidDecl();
11878       return;
11879     }
11880 
11881     // Success! Record the copy.
11882     Statements.push_back(Copy.getAs<Expr>());
11883   }
11884 
11885   // Assign non-static members.
11886   for (auto *Field : ClassDecl->fields()) {
11887     // FIXME: We should form some kind of AST representation for the implied
11888     // memcpy in a union copy operation.
11889     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11890       continue;
11891 
11892     if (Field->isInvalidDecl()) {
11893       Invalid = true;
11894       continue;
11895     }
11896 
11897     // Check for members of reference type; we can't copy those.
11898     if (Field->getType()->isReferenceType()) {
11899       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11900         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11901       Diag(Field->getLocation(), diag::note_declared_at);
11902       Invalid = true;
11903       continue;
11904     }
11905 
11906     // Check for members of const-qualified, non-class type.
11907     QualType BaseType = Context.getBaseElementType(Field->getType());
11908     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11909       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11910         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11911       Diag(Field->getLocation(), diag::note_declared_at);
11912       Invalid = true;
11913       continue;
11914     }
11915 
11916     // Suppress assigning zero-width bitfields.
11917     if (Field->isZeroLengthBitField(Context))
11918       continue;
11919 
11920     QualType FieldType = Field->getType().getNonReferenceType();
11921     if (FieldType->isIncompleteArrayType()) {
11922       assert(ClassDecl->hasFlexibleArrayMember() &&
11923              "Incomplete array type is not valid");
11924       continue;
11925     }
11926 
11927     // Build references to the field in the object we're copying from and to.
11928     CXXScopeSpec SS; // Intentionally empty
11929     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11930                               LookupMemberName);
11931     MemberLookup.addDecl(Field);
11932     MemberLookup.resolveKind();
11933 
11934     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11935 
11936     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11937 
11938     // Build the copy of this field.
11939     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11940                                             To, From,
11941                                             /*CopyingBaseSubobject=*/false,
11942                                             /*Copying=*/true);
11943     if (Copy.isInvalid()) {
11944       CopyAssignOperator->setInvalidDecl();
11945       return;
11946     }
11947 
11948     // Success! Record the copy.
11949     Statements.push_back(Copy.getAs<Stmt>());
11950   }
11951 
11952   if (!Invalid) {
11953     // Add a "return *this;"
11954     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11955 
11956     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11957     if (Return.isInvalid())
11958       Invalid = true;
11959     else
11960       Statements.push_back(Return.getAs<Stmt>());
11961   }
11962 
11963   if (Invalid) {
11964     CopyAssignOperator->setInvalidDecl();
11965     return;
11966   }
11967 
11968   StmtResult Body;
11969   {
11970     CompoundScopeRAII CompoundScope(*this);
11971     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11972                              /*isStmtExpr=*/false);
11973     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11974   }
11975   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11976   CopyAssignOperator->markUsed(Context);
11977 
11978   if (ASTMutationListener *L = getASTMutationListener()) {
11979     L->CompletedImplicitDefinition(CopyAssignOperator);
11980   }
11981 }
11982 
11983 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11984   assert(ClassDecl->needsImplicitMoveAssignment());
11985 
11986   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11987   if (DSM.isAlreadyBeingDeclared())
11988     return nullptr;
11989 
11990   // Note: The following rules are largely analoguous to the move
11991   // constructor rules.
11992 
11993   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11994   QualType RetType = Context.getLValueReferenceType(ArgType);
11995   ArgType = Context.getRValueReferenceType(ArgType);
11996 
11997   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11998                                                      CXXMoveAssignment,
11999                                                      false);
12000 
12001   //   An implicitly-declared move assignment operator is an inline public
12002   //   member of its class.
12003   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12004   SourceLocation ClassLoc = ClassDecl->getLocation();
12005   DeclarationNameInfo NameInfo(Name, ClassLoc);
12006   CXXMethodDecl *MoveAssignment =
12007       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12008                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12009                             /*isInline=*/true, Constexpr, SourceLocation());
12010   MoveAssignment->setAccess(AS_public);
12011   MoveAssignment->setDefaulted();
12012   MoveAssignment->setImplicit();
12013 
12014   if (getLangOpts().CUDA) {
12015     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12016                                             MoveAssignment,
12017                                             /* ConstRHS */ false,
12018                                             /* Diagnose */ false);
12019   }
12020 
12021   // Build an exception specification pointing back at this member.
12022   FunctionProtoType::ExtProtoInfo EPI =
12023       getImplicitMethodEPI(*this, MoveAssignment);
12024   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12025 
12026   // Add the parameter to the operator.
12027   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12028                                                ClassLoc, ClassLoc,
12029                                                /*Id=*/nullptr, ArgType,
12030                                                /*TInfo=*/nullptr, SC_None,
12031                                                nullptr);
12032   MoveAssignment->setParams(FromParam);
12033 
12034   MoveAssignment->setTrivial(
12035     ClassDecl->needsOverloadResolutionForMoveAssignment()
12036       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12037       : ClassDecl->hasTrivialMoveAssignment());
12038 
12039   // Note that we have added this copy-assignment operator.
12040   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12041 
12042   Scope *S = getScopeForContext(ClassDecl);
12043   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12044 
12045   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12046     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12047     SetDeclDeleted(MoveAssignment, ClassLoc);
12048   }
12049 
12050   if (S)
12051     PushOnScopeChains(MoveAssignment, S, false);
12052   ClassDecl->addDecl(MoveAssignment);
12053 
12054   return MoveAssignment;
12055 }
12056 
12057 /// Check if we're implicitly defining a move assignment operator for a class
12058 /// with virtual bases. Such a move assignment might move-assign the virtual
12059 /// base multiple times.
12060 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12061                                                SourceLocation CurrentLocation) {
12062   assert(!Class->isDependentContext() && "should not define dependent move");
12063 
12064   // Only a virtual base could get implicitly move-assigned multiple times.
12065   // Only a non-trivial move assignment can observe this. We only want to
12066   // diagnose if we implicitly define an assignment operator that assigns
12067   // two base classes, both of which move-assign the same virtual base.
12068   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12069       Class->getNumBases() < 2)
12070     return;
12071 
12072   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12073   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12074   VBaseMap VBases;
12075 
12076   for (auto &BI : Class->bases()) {
12077     Worklist.push_back(&BI);
12078     while (!Worklist.empty()) {
12079       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12080       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12081 
12082       // If the base has no non-trivial move assignment operators,
12083       // we don't care about moves from it.
12084       if (!Base->hasNonTrivialMoveAssignment())
12085         continue;
12086 
12087       // If there's nothing virtual here, skip it.
12088       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12089         continue;
12090 
12091       // If we're not actually going to call a move assignment for this base,
12092       // or the selected move assignment is trivial, skip it.
12093       Sema::SpecialMemberOverloadResult SMOR =
12094         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12095                               /*ConstArg*/false, /*VolatileArg*/false,
12096                               /*RValueThis*/true, /*ConstThis*/false,
12097                               /*VolatileThis*/false);
12098       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12099           !SMOR.getMethod()->isMoveAssignmentOperator())
12100         continue;
12101 
12102       if (BaseSpec->isVirtual()) {
12103         // We're going to move-assign this virtual base, and its move
12104         // assignment operator is not trivial. If this can happen for
12105         // multiple distinct direct bases of Class, diagnose it. (If it
12106         // only happens in one base, we'll diagnose it when synthesizing
12107         // that base class's move assignment operator.)
12108         CXXBaseSpecifier *&Existing =
12109             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12110                 .first->second;
12111         if (Existing && Existing != &BI) {
12112           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12113             << Class << Base;
12114           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
12115             << (Base->getCanonicalDecl() ==
12116                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12117             << Base << Existing->getType() << Existing->getSourceRange();
12118           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
12119             << (Base->getCanonicalDecl() ==
12120                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12121             << Base << BI.getType() << BaseSpec->getSourceRange();
12122 
12123           // Only diagnose each vbase once.
12124           Existing = nullptr;
12125         }
12126       } else {
12127         // Only walk over bases that have defaulted move assignment operators.
12128         // We assume that any user-provided move assignment operator handles
12129         // the multiple-moves-of-vbase case itself somehow.
12130         if (!SMOR.getMethod()->isDefaulted())
12131           continue;
12132 
12133         // We're going to move the base classes of Base. Add them to the list.
12134         for (auto &BI : Base->bases())
12135           Worklist.push_back(&BI);
12136       }
12137     }
12138   }
12139 }
12140 
12141 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12142                                         CXXMethodDecl *MoveAssignOperator) {
12143   assert((MoveAssignOperator->isDefaulted() &&
12144           MoveAssignOperator->isOverloadedOperator() &&
12145           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12146           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12147           !MoveAssignOperator->isDeleted()) &&
12148          "DefineImplicitMoveAssignment called for wrong function");
12149   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12150     return;
12151 
12152   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12153   if (ClassDecl->isInvalidDecl()) {
12154     MoveAssignOperator->setInvalidDecl();
12155     return;
12156   }
12157 
12158   // C++0x [class.copy]p28:
12159   //   The implicitly-defined or move assignment operator for a non-union class
12160   //   X performs memberwise move assignment of its subobjects. The direct base
12161   //   classes of X are assigned first, in the order of their declaration in the
12162   //   base-specifier-list, and then the immediate non-static data members of X
12163   //   are assigned, in the order in which they were declared in the class
12164   //   definition.
12165 
12166   // Issue a warning if our implicit move assignment operator will move
12167   // from a virtual base more than once.
12168   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12169 
12170   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12171 
12172   // The exception specification is needed because we are defining the
12173   // function.
12174   ResolveExceptionSpec(CurrentLocation,
12175                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12176 
12177   // Add a context note for diagnostics produced after this point.
12178   Scope.addContextNote(CurrentLocation);
12179 
12180   // The statements that form the synthesized function body.
12181   SmallVector<Stmt*, 8> Statements;
12182 
12183   // The parameter for the "other" object, which we are move from.
12184   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12185   QualType OtherRefType = Other->getType()->
12186       getAs<RValueReferenceType>()->getPointeeType();
12187   assert(!OtherRefType.getQualifiers() &&
12188          "Bad argument type of defaulted move assignment");
12189 
12190   // Our location for everything implicitly-generated.
12191   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
12192                            ? MoveAssignOperator->getLocEnd()
12193                            : MoveAssignOperator->getLocation();
12194 
12195   // Builds a reference to the "other" object.
12196   RefBuilder OtherRef(Other, OtherRefType);
12197   // Cast to rvalue.
12198   MoveCastBuilder MoveOther(OtherRef);
12199 
12200   // Builds the "this" pointer.
12201   ThisBuilder This;
12202 
12203   // Assign base classes.
12204   bool Invalid = false;
12205   for (auto &Base : ClassDecl->bases()) {
12206     // C++11 [class.copy]p28:
12207     //   It is unspecified whether subobjects representing virtual base classes
12208     //   are assigned more than once by the implicitly-defined copy assignment
12209     //   operator.
12210     // FIXME: Do not assign to a vbase that will be assigned by some other base
12211     // class. For a move-assignment, this can result in the vbase being moved
12212     // multiple times.
12213 
12214     // Form the assignment:
12215     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12216     QualType BaseType = Base.getType().getUnqualifiedType();
12217     if (!BaseType->isRecordType()) {
12218       Invalid = true;
12219       continue;
12220     }
12221 
12222     CXXCastPath BasePath;
12223     BasePath.push_back(&Base);
12224 
12225     // Construct the "from" expression, which is an implicit cast to the
12226     // appropriately-qualified base type.
12227     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12228 
12229     // Dereference "this".
12230     DerefBuilder DerefThis(This);
12231 
12232     // Implicitly cast "this" to the appropriately-qualified base type.
12233     CastBuilder To(DerefThis,
12234                    Context.getCVRQualifiedType(
12235                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12236                    VK_LValue, BasePath);
12237 
12238     // Build the move.
12239     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12240                                             To, From,
12241                                             /*CopyingBaseSubobject=*/true,
12242                                             /*Copying=*/false);
12243     if (Move.isInvalid()) {
12244       MoveAssignOperator->setInvalidDecl();
12245       return;
12246     }
12247 
12248     // Success! Record the move.
12249     Statements.push_back(Move.getAs<Expr>());
12250   }
12251 
12252   // Assign non-static members.
12253   for (auto *Field : ClassDecl->fields()) {
12254     // FIXME: We should form some kind of AST representation for the implied
12255     // memcpy in a union copy operation.
12256     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12257       continue;
12258 
12259     if (Field->isInvalidDecl()) {
12260       Invalid = true;
12261       continue;
12262     }
12263 
12264     // Check for members of reference type; we can't move those.
12265     if (Field->getType()->isReferenceType()) {
12266       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12267         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12268       Diag(Field->getLocation(), diag::note_declared_at);
12269       Invalid = true;
12270       continue;
12271     }
12272 
12273     // Check for members of const-qualified, non-class type.
12274     QualType BaseType = Context.getBaseElementType(Field->getType());
12275     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12276       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12277         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12278       Diag(Field->getLocation(), diag::note_declared_at);
12279       Invalid = true;
12280       continue;
12281     }
12282 
12283     // Suppress assigning zero-width bitfields.
12284     if (Field->isZeroLengthBitField(Context))
12285       continue;
12286 
12287     QualType FieldType = Field->getType().getNonReferenceType();
12288     if (FieldType->isIncompleteArrayType()) {
12289       assert(ClassDecl->hasFlexibleArrayMember() &&
12290              "Incomplete array type is not valid");
12291       continue;
12292     }
12293 
12294     // Build references to the field in the object we're copying from and to.
12295     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12296                               LookupMemberName);
12297     MemberLookup.addDecl(Field);
12298     MemberLookup.resolveKind();
12299     MemberBuilder From(MoveOther, OtherRefType,
12300                        /*IsArrow=*/false, MemberLookup);
12301     MemberBuilder To(This, getCurrentThisType(),
12302                      /*IsArrow=*/true, MemberLookup);
12303 
12304     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12305         "Member reference with rvalue base must be rvalue except for reference "
12306         "members, which aren't allowed for move assignment.");
12307 
12308     // Build the move of this field.
12309     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12310                                             To, From,
12311                                             /*CopyingBaseSubobject=*/false,
12312                                             /*Copying=*/false);
12313     if (Move.isInvalid()) {
12314       MoveAssignOperator->setInvalidDecl();
12315       return;
12316     }
12317 
12318     // Success! Record the copy.
12319     Statements.push_back(Move.getAs<Stmt>());
12320   }
12321 
12322   if (!Invalid) {
12323     // Add a "return *this;"
12324     ExprResult ThisObj =
12325         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12326 
12327     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12328     if (Return.isInvalid())
12329       Invalid = true;
12330     else
12331       Statements.push_back(Return.getAs<Stmt>());
12332   }
12333 
12334   if (Invalid) {
12335     MoveAssignOperator->setInvalidDecl();
12336     return;
12337   }
12338 
12339   StmtResult Body;
12340   {
12341     CompoundScopeRAII CompoundScope(*this);
12342     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12343                              /*isStmtExpr=*/false);
12344     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12345   }
12346   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12347   MoveAssignOperator->markUsed(Context);
12348 
12349   if (ASTMutationListener *L = getASTMutationListener()) {
12350     L->CompletedImplicitDefinition(MoveAssignOperator);
12351   }
12352 }
12353 
12354 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12355                                                     CXXRecordDecl *ClassDecl) {
12356   // C++ [class.copy]p4:
12357   //   If the class definition does not explicitly declare a copy
12358   //   constructor, one is declared implicitly.
12359   assert(ClassDecl->needsImplicitCopyConstructor());
12360 
12361   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12362   if (DSM.isAlreadyBeingDeclared())
12363     return nullptr;
12364 
12365   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12366   QualType ArgType = ClassType;
12367   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12368   if (Const)
12369     ArgType = ArgType.withConst();
12370   ArgType = Context.getLValueReferenceType(ArgType);
12371 
12372   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12373                                                      CXXCopyConstructor,
12374                                                      Const);
12375 
12376   DeclarationName Name
12377     = Context.DeclarationNames.getCXXConstructorName(
12378                                            Context.getCanonicalType(ClassType));
12379   SourceLocation ClassLoc = ClassDecl->getLocation();
12380   DeclarationNameInfo NameInfo(Name, ClassLoc);
12381 
12382   //   An implicitly-declared copy constructor is an inline public
12383   //   member of its class.
12384   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12385       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12386       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12387       Constexpr);
12388   CopyConstructor->setAccess(AS_public);
12389   CopyConstructor->setDefaulted();
12390 
12391   if (getLangOpts().CUDA) {
12392     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12393                                             CopyConstructor,
12394                                             /* ConstRHS */ Const,
12395                                             /* Diagnose */ false);
12396   }
12397 
12398   // Build an exception specification pointing back at this member.
12399   FunctionProtoType::ExtProtoInfo EPI =
12400       getImplicitMethodEPI(*this, CopyConstructor);
12401   CopyConstructor->setType(
12402       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12403 
12404   // Add the parameter to the constructor.
12405   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12406                                                ClassLoc, ClassLoc,
12407                                                /*IdentifierInfo=*/nullptr,
12408                                                ArgType, /*TInfo=*/nullptr,
12409                                                SC_None, nullptr);
12410   CopyConstructor->setParams(FromParam);
12411 
12412   CopyConstructor->setTrivial(
12413       ClassDecl->needsOverloadResolutionForCopyConstructor()
12414           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12415           : ClassDecl->hasTrivialCopyConstructor());
12416 
12417   CopyConstructor->setTrivialForCall(
12418       ClassDecl->hasAttr<TrivialABIAttr>() ||
12419       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12420            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12421              TAH_ConsiderTrivialABI)
12422            : ClassDecl->hasTrivialCopyConstructorForCall()));
12423 
12424   // Note that we have declared this constructor.
12425   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12426 
12427   Scope *S = getScopeForContext(ClassDecl);
12428   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12429 
12430   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12431     ClassDecl->setImplicitCopyConstructorIsDeleted();
12432     SetDeclDeleted(CopyConstructor, ClassLoc);
12433   }
12434 
12435   if (S)
12436     PushOnScopeChains(CopyConstructor, S, false);
12437   ClassDecl->addDecl(CopyConstructor);
12438 
12439   return CopyConstructor;
12440 }
12441 
12442 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12443                                          CXXConstructorDecl *CopyConstructor) {
12444   assert((CopyConstructor->isDefaulted() &&
12445           CopyConstructor->isCopyConstructor() &&
12446           !CopyConstructor->doesThisDeclarationHaveABody() &&
12447           !CopyConstructor->isDeleted()) &&
12448          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12449   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12450     return;
12451 
12452   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12453   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12454 
12455   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12456 
12457   // The exception specification is needed because we are defining the
12458   // function.
12459   ResolveExceptionSpec(CurrentLocation,
12460                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12461   MarkVTableUsed(CurrentLocation, ClassDecl);
12462 
12463   // Add a context note for diagnostics produced after this point.
12464   Scope.addContextNote(CurrentLocation);
12465 
12466   // C++11 [class.copy]p7:
12467   //   The [definition of an implicitly declared copy constructor] is
12468   //   deprecated if the class has a user-declared copy assignment operator
12469   //   or a user-declared destructor.
12470   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12471     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12472 
12473   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12474     CopyConstructor->setInvalidDecl();
12475   }  else {
12476     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12477                              ? CopyConstructor->getLocEnd()
12478                              : CopyConstructor->getLocation();
12479     Sema::CompoundScopeRAII CompoundScope(*this);
12480     CopyConstructor->setBody(
12481         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12482     CopyConstructor->markUsed(Context);
12483   }
12484 
12485   if (ASTMutationListener *L = getASTMutationListener()) {
12486     L->CompletedImplicitDefinition(CopyConstructor);
12487   }
12488 }
12489 
12490 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12491                                                     CXXRecordDecl *ClassDecl) {
12492   assert(ClassDecl->needsImplicitMoveConstructor());
12493 
12494   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12495   if (DSM.isAlreadyBeingDeclared())
12496     return nullptr;
12497 
12498   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12499   QualType ArgType = Context.getRValueReferenceType(ClassType);
12500 
12501   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12502                                                      CXXMoveConstructor,
12503                                                      false);
12504 
12505   DeclarationName Name
12506     = Context.DeclarationNames.getCXXConstructorName(
12507                                            Context.getCanonicalType(ClassType));
12508   SourceLocation ClassLoc = ClassDecl->getLocation();
12509   DeclarationNameInfo NameInfo(Name, ClassLoc);
12510 
12511   // C++11 [class.copy]p11:
12512   //   An implicitly-declared copy/move constructor is an inline public
12513   //   member of its class.
12514   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12515       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12516       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12517       Constexpr);
12518   MoveConstructor->setAccess(AS_public);
12519   MoveConstructor->setDefaulted();
12520 
12521   if (getLangOpts().CUDA) {
12522     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12523                                             MoveConstructor,
12524                                             /* ConstRHS */ false,
12525                                             /* Diagnose */ false);
12526   }
12527 
12528   // Build an exception specification pointing back at this member.
12529   FunctionProtoType::ExtProtoInfo EPI =
12530       getImplicitMethodEPI(*this, MoveConstructor);
12531   MoveConstructor->setType(
12532       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12533 
12534   // Add the parameter to the constructor.
12535   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12536                                                ClassLoc, ClassLoc,
12537                                                /*IdentifierInfo=*/nullptr,
12538                                                ArgType, /*TInfo=*/nullptr,
12539                                                SC_None, nullptr);
12540   MoveConstructor->setParams(FromParam);
12541 
12542   MoveConstructor->setTrivial(
12543       ClassDecl->needsOverloadResolutionForMoveConstructor()
12544           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12545           : ClassDecl->hasTrivialMoveConstructor());
12546 
12547   MoveConstructor->setTrivialForCall(
12548       ClassDecl->hasAttr<TrivialABIAttr>() ||
12549       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12550            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12551                                     TAH_ConsiderTrivialABI)
12552            : ClassDecl->hasTrivialMoveConstructorForCall()));
12553 
12554   // Note that we have declared this constructor.
12555   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12556 
12557   Scope *S = getScopeForContext(ClassDecl);
12558   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12559 
12560   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12561     ClassDecl->setImplicitMoveConstructorIsDeleted();
12562     SetDeclDeleted(MoveConstructor, ClassLoc);
12563   }
12564 
12565   if (S)
12566     PushOnScopeChains(MoveConstructor, S, false);
12567   ClassDecl->addDecl(MoveConstructor);
12568 
12569   return MoveConstructor;
12570 }
12571 
12572 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12573                                          CXXConstructorDecl *MoveConstructor) {
12574   assert((MoveConstructor->isDefaulted() &&
12575           MoveConstructor->isMoveConstructor() &&
12576           !MoveConstructor->doesThisDeclarationHaveABody() &&
12577           !MoveConstructor->isDeleted()) &&
12578          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12579   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12580     return;
12581 
12582   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12583   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12584 
12585   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12586 
12587   // The exception specification is needed because we are defining the
12588   // function.
12589   ResolveExceptionSpec(CurrentLocation,
12590                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12591   MarkVTableUsed(CurrentLocation, ClassDecl);
12592 
12593   // Add a context note for diagnostics produced after this point.
12594   Scope.addContextNote(CurrentLocation);
12595 
12596   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12597     MoveConstructor->setInvalidDecl();
12598   } else {
12599     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12600                              ? MoveConstructor->getLocEnd()
12601                              : MoveConstructor->getLocation();
12602     Sema::CompoundScopeRAII CompoundScope(*this);
12603     MoveConstructor->setBody(ActOnCompoundStmt(
12604         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12605     MoveConstructor->markUsed(Context);
12606   }
12607 
12608   if (ASTMutationListener *L = getASTMutationListener()) {
12609     L->CompletedImplicitDefinition(MoveConstructor);
12610   }
12611 }
12612 
12613 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12614   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12615 }
12616 
12617 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12618                             SourceLocation CurrentLocation,
12619                             CXXConversionDecl *Conv) {
12620   SynthesizedFunctionScope Scope(*this, Conv);
12621   assert(!Conv->getReturnType()->isUndeducedType());
12622 
12623   CXXRecordDecl *Lambda = Conv->getParent();
12624   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12625   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12626 
12627   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12628     CallOp = InstantiateFunctionDeclaration(
12629         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12630     if (!CallOp)
12631       return;
12632 
12633     Invoker = InstantiateFunctionDeclaration(
12634         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12635     if (!Invoker)
12636       return;
12637   }
12638 
12639   if (CallOp->isInvalidDecl())
12640     return;
12641 
12642   // Mark the call operator referenced (and add to pending instantiations
12643   // if necessary).
12644   // For both the conversion and static-invoker template specializations
12645   // we construct their body's in this function, so no need to add them
12646   // to the PendingInstantiations.
12647   MarkFunctionReferenced(CurrentLocation, CallOp);
12648 
12649   // Fill in the __invoke function with a dummy implementation. IR generation
12650   // will fill in the actual details. Update its type in case it contained
12651   // an 'auto'.
12652   Invoker->markUsed(Context);
12653   Invoker->setReferenced();
12654   Invoker->setType(Conv->getReturnType()->getPointeeType());
12655   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12656 
12657   // Construct the body of the conversion function { return __invoke; }.
12658   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12659                                        VK_LValue, Conv->getLocation()).get();
12660   assert(FunctionRef && "Can't refer to __invoke function?");
12661   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12662   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12663                                      Conv->getLocation()));
12664   Conv->markUsed(Context);
12665   Conv->setReferenced();
12666 
12667   if (ASTMutationListener *L = getASTMutationListener()) {
12668     L->CompletedImplicitDefinition(Conv);
12669     L->CompletedImplicitDefinition(Invoker);
12670   }
12671 }
12672 
12673 
12674 
12675 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12676        SourceLocation CurrentLocation,
12677        CXXConversionDecl *Conv)
12678 {
12679   assert(!Conv->getParent()->isGenericLambda());
12680 
12681   SynthesizedFunctionScope Scope(*this, Conv);
12682 
12683   // Copy-initialize the lambda object as needed to capture it.
12684   Expr *This = ActOnCXXThis(CurrentLocation).get();
12685   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12686 
12687   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12688                                                         Conv->getLocation(),
12689                                                         Conv, DerefThis);
12690 
12691   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12692   // behavior.  Note that only the general conversion function does this
12693   // (since it's unusable otherwise); in the case where we inline the
12694   // block literal, it has block literal lifetime semantics.
12695   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12696     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12697                                           CK_CopyAndAutoreleaseBlockObject,
12698                                           BuildBlock.get(), nullptr, VK_RValue);
12699 
12700   if (BuildBlock.isInvalid()) {
12701     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12702     Conv->setInvalidDecl();
12703     return;
12704   }
12705 
12706   // Create the return statement that returns the block from the conversion
12707   // function.
12708   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12709   if (Return.isInvalid()) {
12710     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12711     Conv->setInvalidDecl();
12712     return;
12713   }
12714 
12715   // Set the body of the conversion function.
12716   Stmt *ReturnS = Return.get();
12717   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12718                                      Conv->getLocation()));
12719   Conv->markUsed(Context);
12720 
12721   // We're done; notify the mutation listener, if any.
12722   if (ASTMutationListener *L = getASTMutationListener()) {
12723     L->CompletedImplicitDefinition(Conv);
12724   }
12725 }
12726 
12727 /// Determine whether the given list arguments contains exactly one
12728 /// "real" (non-default) argument.
12729 static bool hasOneRealArgument(MultiExprArg Args) {
12730   switch (Args.size()) {
12731   case 0:
12732     return false;
12733 
12734   default:
12735     if (!Args[1]->isDefaultArgument())
12736       return false;
12737 
12738     LLVM_FALLTHROUGH;
12739   case 1:
12740     return !Args[0]->isDefaultArgument();
12741   }
12742 
12743   return false;
12744 }
12745 
12746 ExprResult
12747 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12748                             NamedDecl *FoundDecl,
12749                             CXXConstructorDecl *Constructor,
12750                             MultiExprArg ExprArgs,
12751                             bool HadMultipleCandidates,
12752                             bool IsListInitialization,
12753                             bool IsStdInitListInitialization,
12754                             bool RequiresZeroInit,
12755                             unsigned ConstructKind,
12756                             SourceRange ParenRange) {
12757   bool Elidable = false;
12758 
12759   // C++0x [class.copy]p34:
12760   //   When certain criteria are met, an implementation is allowed to
12761   //   omit the copy/move construction of a class object, even if the
12762   //   copy/move constructor and/or destructor for the object have
12763   //   side effects. [...]
12764   //     - when a temporary class object that has not been bound to a
12765   //       reference (12.2) would be copied/moved to a class object
12766   //       with the same cv-unqualified type, the copy/move operation
12767   //       can be omitted by constructing the temporary object
12768   //       directly into the target of the omitted copy/move
12769   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12770       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12771     Expr *SubExpr = ExprArgs[0];
12772     Elidable = SubExpr->isTemporaryObject(
12773         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12774   }
12775 
12776   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12777                                FoundDecl, Constructor,
12778                                Elidable, ExprArgs, HadMultipleCandidates,
12779                                IsListInitialization,
12780                                IsStdInitListInitialization, RequiresZeroInit,
12781                                ConstructKind, ParenRange);
12782 }
12783 
12784 ExprResult
12785 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12786                             NamedDecl *FoundDecl,
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   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12797     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12798     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12799       return ExprError();
12800   }
12801 
12802   return BuildCXXConstructExpr(
12803       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12804       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12805       RequiresZeroInit, ConstructKind, ParenRange);
12806 }
12807 
12808 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12809 /// including handling of its default argument expressions.
12810 ExprResult
12811 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12812                             CXXConstructorDecl *Constructor,
12813                             bool Elidable,
12814                             MultiExprArg ExprArgs,
12815                             bool HadMultipleCandidates,
12816                             bool IsListInitialization,
12817                             bool IsStdInitListInitialization,
12818                             bool RequiresZeroInit,
12819                             unsigned ConstructKind,
12820                             SourceRange ParenRange) {
12821   assert(declaresSameEntity(
12822              Constructor->getParent(),
12823              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12824          "given constructor for wrong type");
12825   MarkFunctionReferenced(ConstructLoc, Constructor);
12826   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12827     return ExprError();
12828 
12829   return CXXConstructExpr::Create(
12830       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12831       ExprArgs, HadMultipleCandidates, IsListInitialization,
12832       IsStdInitListInitialization, RequiresZeroInit,
12833       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12834       ParenRange);
12835 }
12836 
12837 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12838   assert(Field->hasInClassInitializer());
12839 
12840   // If we already have the in-class initializer nothing needs to be done.
12841   if (Field->getInClassInitializer())
12842     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12843 
12844   // If we might have already tried and failed to instantiate, don't try again.
12845   if (Field->isInvalidDecl())
12846     return ExprError();
12847 
12848   // Maybe we haven't instantiated the in-class initializer. Go check the
12849   // pattern FieldDecl to see if it has one.
12850   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12851 
12852   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12853     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12854     DeclContext::lookup_result Lookup =
12855         ClassPattern->lookup(Field->getDeclName());
12856 
12857     // Lookup can return at most two results: the pattern for the field, or the
12858     // injected class name of the parent record. No other member can have the
12859     // same name as the field.
12860     // In modules mode, lookup can return multiple results (coming from
12861     // different modules).
12862     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12863            "more than two lookup results for field name");
12864     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12865     if (!Pattern) {
12866       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12867              "cannot have other non-field member with same name");
12868       for (auto L : Lookup)
12869         if (isa<FieldDecl>(L)) {
12870           Pattern = cast<FieldDecl>(L);
12871           break;
12872         }
12873       assert(Pattern && "We must have set the Pattern!");
12874     }
12875 
12876     if (!Pattern->hasInClassInitializer() ||
12877         InstantiateInClassInitializer(Loc, Field, Pattern,
12878                                       getTemplateInstantiationArgs(Field))) {
12879       // Don't diagnose this again.
12880       Field->setInvalidDecl();
12881       return ExprError();
12882     }
12883     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12884   }
12885 
12886   // DR1351:
12887   //   If the brace-or-equal-initializer of a non-static data member
12888   //   invokes a defaulted default constructor of its class or of an
12889   //   enclosing class in a potentially evaluated subexpression, the
12890   //   program is ill-formed.
12891   //
12892   // This resolution is unworkable: the exception specification of the
12893   // default constructor can be needed in an unevaluated context, in
12894   // particular, in the operand of a noexcept-expression, and we can be
12895   // unable to compute an exception specification for an enclosed class.
12896   //
12897   // Any attempt to resolve the exception specification of a defaulted default
12898   // constructor before the initializer is lexically complete will ultimately
12899   // come here at which point we can diagnose it.
12900   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12901   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12902       << OutermostClass << Field;
12903   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12904   // Recover by marking the field invalid, unless we're in a SFINAE context.
12905   if (!isSFINAEContext())
12906     Field->setInvalidDecl();
12907   return ExprError();
12908 }
12909 
12910 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12911   if (VD->isInvalidDecl()) return;
12912 
12913   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12914   if (ClassDecl->isInvalidDecl()) return;
12915   if (ClassDecl->hasIrrelevantDestructor()) return;
12916   if (ClassDecl->isDependentContext()) return;
12917 
12918   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12919   MarkFunctionReferenced(VD->getLocation(), Destructor);
12920   CheckDestructorAccess(VD->getLocation(), Destructor,
12921                         PDiag(diag::err_access_dtor_var)
12922                         << VD->getDeclName()
12923                         << VD->getType());
12924   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12925 
12926   if (Destructor->isTrivial()) return;
12927   if (!VD->hasGlobalStorage()) return;
12928 
12929   // Emit warning for non-trivial dtor in global scope (a real global,
12930   // class-static, function-static).
12931   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12932 
12933   // TODO: this should be re-enabled for static locals by !CXAAtExit
12934   if (!VD->isStaticLocal())
12935     Diag(VD->getLocation(), diag::warn_global_destructor);
12936 }
12937 
12938 /// Given a constructor and the set of arguments provided for the
12939 /// constructor, convert the arguments and add any required default arguments
12940 /// to form a proper call to this constructor.
12941 ///
12942 /// \returns true if an error occurred, false otherwise.
12943 bool
12944 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12945                               MultiExprArg ArgsPtr,
12946                               SourceLocation Loc,
12947                               SmallVectorImpl<Expr*> &ConvertedArgs,
12948                               bool AllowExplicit,
12949                               bool IsListInitialization) {
12950   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12951   unsigned NumArgs = ArgsPtr.size();
12952   Expr **Args = ArgsPtr.data();
12953 
12954   const FunctionProtoType *Proto
12955     = Constructor->getType()->getAs<FunctionProtoType>();
12956   assert(Proto && "Constructor without a prototype?");
12957   unsigned NumParams = Proto->getNumParams();
12958 
12959   // If too few arguments are available, we'll fill in the rest with defaults.
12960   if (NumArgs < NumParams)
12961     ConvertedArgs.reserve(NumParams);
12962   else
12963     ConvertedArgs.reserve(NumArgs);
12964 
12965   VariadicCallType CallType =
12966     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12967   SmallVector<Expr *, 8> AllArgs;
12968   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12969                                         Proto, 0,
12970                                         llvm::makeArrayRef(Args, NumArgs),
12971                                         AllArgs,
12972                                         CallType, AllowExplicit,
12973                                         IsListInitialization);
12974   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12975 
12976   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12977 
12978   CheckConstructorCall(Constructor,
12979                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12980                        Proto, Loc);
12981 
12982   return Invalid;
12983 }
12984 
12985 static inline bool
12986 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12987                                        const FunctionDecl *FnDecl) {
12988   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12989   if (isa<NamespaceDecl>(DC)) {
12990     return SemaRef.Diag(FnDecl->getLocation(),
12991                         diag::err_operator_new_delete_declared_in_namespace)
12992       << FnDecl->getDeclName();
12993   }
12994 
12995   if (isa<TranslationUnitDecl>(DC) &&
12996       FnDecl->getStorageClass() == SC_Static) {
12997     return SemaRef.Diag(FnDecl->getLocation(),
12998                         diag::err_operator_new_delete_declared_static)
12999       << FnDecl->getDeclName();
13000   }
13001 
13002   return false;
13003 }
13004 
13005 static inline bool
13006 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13007                             CanQualType ExpectedResultType,
13008                             CanQualType ExpectedFirstParamType,
13009                             unsigned DependentParamTypeDiag,
13010                             unsigned InvalidParamTypeDiag) {
13011   QualType ResultType =
13012       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13013 
13014   // Check that the result type is not dependent.
13015   if (ResultType->isDependentType())
13016     return SemaRef.Diag(FnDecl->getLocation(),
13017                         diag::err_operator_new_delete_dependent_result_type)
13018     << FnDecl->getDeclName() << ExpectedResultType;
13019 
13020   // Check that the result type is what we expect.
13021   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13022     return SemaRef.Diag(FnDecl->getLocation(),
13023                         diag::err_operator_new_delete_invalid_result_type)
13024     << FnDecl->getDeclName() << ExpectedResultType;
13025 
13026   // A function template must have at least 2 parameters.
13027   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13028     return SemaRef.Diag(FnDecl->getLocation(),
13029                       diag::err_operator_new_delete_template_too_few_parameters)
13030         << FnDecl->getDeclName();
13031 
13032   // The function decl must have at least 1 parameter.
13033   if (FnDecl->getNumParams() == 0)
13034     return SemaRef.Diag(FnDecl->getLocation(),
13035                         diag::err_operator_new_delete_too_few_parameters)
13036       << FnDecl->getDeclName();
13037 
13038   // Check the first parameter type is not dependent.
13039   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13040   if (FirstParamType->isDependentType())
13041     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13042       << FnDecl->getDeclName() << ExpectedFirstParamType;
13043 
13044   // Check that the first parameter type is what we expect.
13045   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13046       ExpectedFirstParamType)
13047     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13048     << FnDecl->getDeclName() << ExpectedFirstParamType;
13049 
13050   return false;
13051 }
13052 
13053 static bool
13054 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13055   // C++ [basic.stc.dynamic.allocation]p1:
13056   //   A program is ill-formed if an allocation function is declared in a
13057   //   namespace scope other than global scope or declared static in global
13058   //   scope.
13059   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13060     return true;
13061 
13062   CanQualType SizeTy =
13063     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13064 
13065   // C++ [basic.stc.dynamic.allocation]p1:
13066   //  The return type shall be void*. The first parameter shall have type
13067   //  std::size_t.
13068   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13069                                   SizeTy,
13070                                   diag::err_operator_new_dependent_param_type,
13071                                   diag::err_operator_new_param_type))
13072     return true;
13073 
13074   // C++ [basic.stc.dynamic.allocation]p1:
13075   //  The first parameter shall not have an associated default argument.
13076   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13077     return SemaRef.Diag(FnDecl->getLocation(),
13078                         diag::err_operator_new_default_arg)
13079       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13080 
13081   return false;
13082 }
13083 
13084 static bool
13085 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13086   // C++ [basic.stc.dynamic.deallocation]p1:
13087   //   A program is ill-formed if deallocation functions are declared in a
13088   //   namespace scope other than global scope or declared static in global
13089   //   scope.
13090   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13091     return true;
13092 
13093   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13094 
13095   // C++ P0722:
13096   //   Within a class C, the first parameter of a destroying operator delete
13097   //   shall be of type C *. The first parameter of any other deallocation
13098   //   function shall be of type void *.
13099   CanQualType ExpectedFirstParamType =
13100       MD && MD->isDestroyingOperatorDelete()
13101           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13102                 SemaRef.Context.getRecordType(MD->getParent())))
13103           : SemaRef.Context.VoidPtrTy;
13104 
13105   // C++ [basic.stc.dynamic.deallocation]p2:
13106   //   Each deallocation function shall return void
13107   if (CheckOperatorNewDeleteTypes(
13108           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13109           diag::err_operator_delete_dependent_param_type,
13110           diag::err_operator_delete_param_type))
13111     return true;
13112 
13113   // C++ P0722:
13114   //   A destroying operator delete shall be a usual deallocation function.
13115   if (MD && !MD->getParent()->isDependentContext() &&
13116       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13117     SemaRef.Diag(MD->getLocation(),
13118                  diag::err_destroying_operator_delete_not_usual);
13119     return true;
13120   }
13121 
13122   return false;
13123 }
13124 
13125 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13126 /// of this overloaded operator is well-formed. If so, returns false;
13127 /// otherwise, emits appropriate diagnostics and returns true.
13128 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13129   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13130          "Expected an overloaded operator declaration");
13131 
13132   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13133 
13134   // C++ [over.oper]p5:
13135   //   The allocation and deallocation functions, operator new,
13136   //   operator new[], operator delete and operator delete[], are
13137   //   described completely in 3.7.3. The attributes and restrictions
13138   //   found in the rest of this subclause do not apply to them unless
13139   //   explicitly stated in 3.7.3.
13140   if (Op == OO_Delete || Op == OO_Array_Delete)
13141     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13142 
13143   if (Op == OO_New || Op == OO_Array_New)
13144     return CheckOperatorNewDeclaration(*this, FnDecl);
13145 
13146   // C++ [over.oper]p6:
13147   //   An operator function shall either be a non-static member
13148   //   function or be a non-member function and have at least one
13149   //   parameter whose type is a class, a reference to a class, an
13150   //   enumeration, or a reference to an enumeration.
13151   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13152     if (MethodDecl->isStatic())
13153       return Diag(FnDecl->getLocation(),
13154                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13155   } else {
13156     bool ClassOrEnumParam = false;
13157     for (auto Param : FnDecl->parameters()) {
13158       QualType ParamType = Param->getType().getNonReferenceType();
13159       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13160           ParamType->isEnumeralType()) {
13161         ClassOrEnumParam = true;
13162         break;
13163       }
13164     }
13165 
13166     if (!ClassOrEnumParam)
13167       return Diag(FnDecl->getLocation(),
13168                   diag::err_operator_overload_needs_class_or_enum)
13169         << FnDecl->getDeclName();
13170   }
13171 
13172   // C++ [over.oper]p8:
13173   //   An operator function cannot have default arguments (8.3.6),
13174   //   except where explicitly stated below.
13175   //
13176   // Only the function-call operator allows default arguments
13177   // (C++ [over.call]p1).
13178   if (Op != OO_Call) {
13179     for (auto Param : FnDecl->parameters()) {
13180       if (Param->hasDefaultArg())
13181         return Diag(Param->getLocation(),
13182                     diag::err_operator_overload_default_arg)
13183           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13184     }
13185   }
13186 
13187   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13188     { false, false, false }
13189 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13190     , { Unary, Binary, MemberOnly }
13191 #include "clang/Basic/OperatorKinds.def"
13192   };
13193 
13194   bool CanBeUnaryOperator = OperatorUses[Op][0];
13195   bool CanBeBinaryOperator = OperatorUses[Op][1];
13196   bool MustBeMemberOperator = OperatorUses[Op][2];
13197 
13198   // C++ [over.oper]p8:
13199   //   [...] Operator functions cannot have more or fewer parameters
13200   //   than the number required for the corresponding operator, as
13201   //   described in the rest of this subclause.
13202   unsigned NumParams = FnDecl->getNumParams()
13203                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13204   if (Op != OO_Call &&
13205       ((NumParams == 1 && !CanBeUnaryOperator) ||
13206        (NumParams == 2 && !CanBeBinaryOperator) ||
13207        (NumParams < 1) || (NumParams > 2))) {
13208     // We have the wrong number of parameters.
13209     unsigned ErrorKind;
13210     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13211       ErrorKind = 2;  // 2 -> unary or binary.
13212     } else if (CanBeUnaryOperator) {
13213       ErrorKind = 0;  // 0 -> unary
13214     } else {
13215       assert(CanBeBinaryOperator &&
13216              "All non-call overloaded operators are unary or binary!");
13217       ErrorKind = 1;  // 1 -> binary
13218     }
13219 
13220     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13221       << FnDecl->getDeclName() << NumParams << ErrorKind;
13222   }
13223 
13224   // Overloaded operators other than operator() cannot be variadic.
13225   if (Op != OO_Call &&
13226       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13227     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13228       << FnDecl->getDeclName();
13229   }
13230 
13231   // Some operators must be non-static member functions.
13232   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13233     return Diag(FnDecl->getLocation(),
13234                 diag::err_operator_overload_must_be_member)
13235       << FnDecl->getDeclName();
13236   }
13237 
13238   // C++ [over.inc]p1:
13239   //   The user-defined function called operator++ implements the
13240   //   prefix and postfix ++ operator. If this function is a member
13241   //   function with no parameters, or a non-member function with one
13242   //   parameter of class or enumeration type, it defines the prefix
13243   //   increment operator ++ for objects of that type. If the function
13244   //   is a member function with one parameter (which shall be of type
13245   //   int) or a non-member function with two parameters (the second
13246   //   of which shall be of type int), it defines the postfix
13247   //   increment operator ++ for objects of that type.
13248   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13249     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13250     QualType ParamType = LastParam->getType();
13251 
13252     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13253         !ParamType->isDependentType())
13254       return Diag(LastParam->getLocation(),
13255                   diag::err_operator_overload_post_incdec_must_be_int)
13256         << LastParam->getType() << (Op == OO_MinusMinus);
13257   }
13258 
13259   return false;
13260 }
13261 
13262 static bool
13263 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13264                                           FunctionTemplateDecl *TpDecl) {
13265   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13266 
13267   // Must have one or two template parameters.
13268   if (TemplateParams->size() == 1) {
13269     NonTypeTemplateParmDecl *PmDecl =
13270         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13271 
13272     // The template parameter must be a char parameter pack.
13273     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13274         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13275       return false;
13276 
13277   } else if (TemplateParams->size() == 2) {
13278     TemplateTypeParmDecl *PmType =
13279         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13280     NonTypeTemplateParmDecl *PmArgs =
13281         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13282 
13283     // The second template parameter must be a parameter pack with the
13284     // first template parameter as its type.
13285     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13286         PmArgs->isTemplateParameterPack()) {
13287       const TemplateTypeParmType *TArgs =
13288           PmArgs->getType()->getAs<TemplateTypeParmType>();
13289       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13290           TArgs->getIndex() == PmType->getIndex()) {
13291         if (!SemaRef.inTemplateInstantiation())
13292           SemaRef.Diag(TpDecl->getLocation(),
13293                        diag::ext_string_literal_operator_template);
13294         return false;
13295       }
13296     }
13297   }
13298 
13299   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13300                diag::err_literal_operator_template)
13301       << TpDecl->getTemplateParameters()->getSourceRange();
13302   return true;
13303 }
13304 
13305 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13306 /// of this literal operator function is well-formed. If so, returns
13307 /// false; otherwise, emits appropriate diagnostics and returns true.
13308 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13309   if (isa<CXXMethodDecl>(FnDecl)) {
13310     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13311       << FnDecl->getDeclName();
13312     return true;
13313   }
13314 
13315   if (FnDecl->isExternC()) {
13316     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13317     if (const LinkageSpecDecl *LSD =
13318             FnDecl->getDeclContext()->getExternCContext())
13319       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13320     return true;
13321   }
13322 
13323   // This might be the definition of a literal operator template.
13324   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13325 
13326   // This might be a specialization of a literal operator template.
13327   if (!TpDecl)
13328     TpDecl = FnDecl->getPrimaryTemplate();
13329 
13330   // template <char...> type operator "" name() and
13331   // template <class T, T...> type operator "" name() are the only valid
13332   // template signatures, and the only valid signatures with no parameters.
13333   if (TpDecl) {
13334     if (FnDecl->param_size() != 0) {
13335       Diag(FnDecl->getLocation(),
13336            diag::err_literal_operator_template_with_params);
13337       return true;
13338     }
13339 
13340     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13341       return true;
13342 
13343   } else if (FnDecl->param_size() == 1) {
13344     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13345 
13346     QualType ParamType = Param->getType().getUnqualifiedType();
13347 
13348     // Only unsigned long long int, long double, any character type, and const
13349     // char * are allowed as the only parameters.
13350     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13351         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13352         Context.hasSameType(ParamType, Context.CharTy) ||
13353         Context.hasSameType(ParamType, Context.WideCharTy) ||
13354         Context.hasSameType(ParamType, Context.Char8Ty) ||
13355         Context.hasSameType(ParamType, Context.Char16Ty) ||
13356         Context.hasSameType(ParamType, Context.Char32Ty)) {
13357     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13358       QualType InnerType = Ptr->getPointeeType();
13359 
13360       // Pointer parameter must be a const char *.
13361       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13362                                 Context.CharTy) &&
13363             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13364         Diag(Param->getSourceRange().getBegin(),
13365              diag::err_literal_operator_param)
13366             << ParamType << "'const char *'" << Param->getSourceRange();
13367         return true;
13368       }
13369 
13370     } else if (ParamType->isRealFloatingType()) {
13371       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13372           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13373       return true;
13374 
13375     } else if (ParamType->isIntegerType()) {
13376       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13377           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13378       return true;
13379 
13380     } else {
13381       Diag(Param->getSourceRange().getBegin(),
13382            diag::err_literal_operator_invalid_param)
13383           << ParamType << Param->getSourceRange();
13384       return true;
13385     }
13386 
13387   } else if (FnDecl->param_size() == 2) {
13388     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13389 
13390     // First, verify that the first parameter is correct.
13391 
13392     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13393 
13394     // Two parameter function must have a pointer to const as a
13395     // first parameter; let's strip those qualifiers.
13396     const PointerType *PT = FirstParamType->getAs<PointerType>();
13397 
13398     if (!PT) {
13399       Diag((*Param)->getSourceRange().getBegin(),
13400            diag::err_literal_operator_param)
13401           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13402       return true;
13403     }
13404 
13405     QualType PointeeType = PT->getPointeeType();
13406     // First parameter must be const
13407     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13408       Diag((*Param)->getSourceRange().getBegin(),
13409            diag::err_literal_operator_param)
13410           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13411       return true;
13412     }
13413 
13414     QualType InnerType = PointeeType.getUnqualifiedType();
13415     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13416     // const char32_t* are allowed as the first parameter to a two-parameter
13417     // function
13418     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13419           Context.hasSameType(InnerType, Context.WideCharTy) ||
13420           Context.hasSameType(InnerType, Context.Char8Ty) ||
13421           Context.hasSameType(InnerType, Context.Char16Ty) ||
13422           Context.hasSameType(InnerType, Context.Char32Ty))) {
13423       Diag((*Param)->getSourceRange().getBegin(),
13424            diag::err_literal_operator_param)
13425           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13426       return true;
13427     }
13428 
13429     // Move on to the second and final parameter.
13430     ++Param;
13431 
13432     // The second parameter must be a std::size_t.
13433     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13434     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13435       Diag((*Param)->getSourceRange().getBegin(),
13436            diag::err_literal_operator_param)
13437           << SecondParamType << Context.getSizeType()
13438           << (*Param)->getSourceRange();
13439       return true;
13440     }
13441   } else {
13442     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13443     return true;
13444   }
13445 
13446   // Parameters are good.
13447 
13448   // A parameter-declaration-clause containing a default argument is not
13449   // equivalent to any of the permitted forms.
13450   for (auto Param : FnDecl->parameters()) {
13451     if (Param->hasDefaultArg()) {
13452       Diag(Param->getDefaultArgRange().getBegin(),
13453            diag::err_literal_operator_default_argument)
13454         << Param->getDefaultArgRange();
13455       break;
13456     }
13457   }
13458 
13459   StringRef LiteralName
13460     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13461   if (LiteralName[0] != '_' &&
13462       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13463     // C++11 [usrlit.suffix]p1:
13464     //   Literal suffix identifiers that do not start with an underscore
13465     //   are reserved for future standardization.
13466     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13467       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13468   }
13469 
13470   return false;
13471 }
13472 
13473 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13474 /// linkage specification, including the language and (if present)
13475 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13476 /// language string literal. LBraceLoc, if valid, provides the location of
13477 /// the '{' brace. Otherwise, this linkage specification does not
13478 /// have any braces.
13479 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13480                                            Expr *LangStr,
13481                                            SourceLocation LBraceLoc) {
13482   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13483   if (!Lit->isAscii()) {
13484     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13485       << LangStr->getSourceRange();
13486     return nullptr;
13487   }
13488 
13489   StringRef Lang = Lit->getString();
13490   LinkageSpecDecl::LanguageIDs Language;
13491   if (Lang == "C")
13492     Language = LinkageSpecDecl::lang_c;
13493   else if (Lang == "C++")
13494     Language = LinkageSpecDecl::lang_cxx;
13495   else {
13496     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13497       << LangStr->getSourceRange();
13498     return nullptr;
13499   }
13500 
13501   // FIXME: Add all the various semantics of linkage specifications
13502 
13503   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13504                                                LangStr->getExprLoc(), Language,
13505                                                LBraceLoc.isValid());
13506   CurContext->addDecl(D);
13507   PushDeclContext(S, D);
13508   return D;
13509 }
13510 
13511 /// ActOnFinishLinkageSpecification - Complete the definition of
13512 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13513 /// valid, it's the position of the closing '}' brace in a linkage
13514 /// specification that uses braces.
13515 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13516                                             Decl *LinkageSpec,
13517                                             SourceLocation RBraceLoc) {
13518   if (RBraceLoc.isValid()) {
13519     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13520     LSDecl->setRBraceLoc(RBraceLoc);
13521   }
13522   PopDeclContext();
13523   return LinkageSpec;
13524 }
13525 
13526 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13527                                   AttributeList *AttrList,
13528                                   SourceLocation SemiLoc) {
13529   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13530   // Attribute declarations appertain to empty declaration so we handle
13531   // them here.
13532   if (AttrList)
13533     ProcessDeclAttributeList(S, ED, AttrList);
13534 
13535   CurContext->addDecl(ED);
13536   return ED;
13537 }
13538 
13539 /// Perform semantic analysis for the variable declaration that
13540 /// occurs within a C++ catch clause, returning the newly-created
13541 /// variable.
13542 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13543                                          TypeSourceInfo *TInfo,
13544                                          SourceLocation StartLoc,
13545                                          SourceLocation Loc,
13546                                          IdentifierInfo *Name) {
13547   bool Invalid = false;
13548   QualType ExDeclType = TInfo->getType();
13549 
13550   // Arrays and functions decay.
13551   if (ExDeclType->isArrayType())
13552     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13553   else if (ExDeclType->isFunctionType())
13554     ExDeclType = Context.getPointerType(ExDeclType);
13555 
13556   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13557   // The exception-declaration shall not denote a pointer or reference to an
13558   // incomplete type, other than [cv] void*.
13559   // N2844 forbids rvalue references.
13560   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13561     Diag(Loc, diag::err_catch_rvalue_ref);
13562     Invalid = true;
13563   }
13564 
13565   if (ExDeclType->isVariablyModifiedType()) {
13566     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13567     Invalid = true;
13568   }
13569 
13570   QualType BaseType = ExDeclType;
13571   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13572   unsigned DK = diag::err_catch_incomplete;
13573   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13574     BaseType = Ptr->getPointeeType();
13575     Mode = 1;
13576     DK = diag::err_catch_incomplete_ptr;
13577   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13578     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13579     BaseType = Ref->getPointeeType();
13580     Mode = 2;
13581     DK = diag::err_catch_incomplete_ref;
13582   }
13583   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13584       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13585     Invalid = true;
13586 
13587   if (!Invalid && !ExDeclType->isDependentType() &&
13588       RequireNonAbstractType(Loc, ExDeclType,
13589                              diag::err_abstract_type_in_decl,
13590                              AbstractVariableType))
13591     Invalid = true;
13592 
13593   // Only the non-fragile NeXT runtime currently supports C++ catches
13594   // of ObjC types, and no runtime supports catching ObjC types by value.
13595   if (!Invalid && getLangOpts().ObjC1) {
13596     QualType T = ExDeclType;
13597     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13598       T = RT->getPointeeType();
13599 
13600     if (T->isObjCObjectType()) {
13601       Diag(Loc, diag::err_objc_object_catch);
13602       Invalid = true;
13603     } else if (T->isObjCObjectPointerType()) {
13604       // FIXME: should this be a test for macosx-fragile specifically?
13605       if (getLangOpts().ObjCRuntime.isFragile())
13606         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13607     }
13608   }
13609 
13610   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13611                                     ExDeclType, TInfo, SC_None);
13612   ExDecl->setExceptionVariable(true);
13613 
13614   // In ARC, infer 'retaining' for variables of retainable type.
13615   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13616     Invalid = true;
13617 
13618   if (!Invalid && !ExDeclType->isDependentType()) {
13619     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13620       // Insulate this from anything else we might currently be parsing.
13621       EnterExpressionEvaluationContext scope(
13622           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13623 
13624       // C++ [except.handle]p16:
13625       //   The object declared in an exception-declaration or, if the
13626       //   exception-declaration does not specify a name, a temporary (12.2) is
13627       //   copy-initialized (8.5) from the exception object. [...]
13628       //   The object is destroyed when the handler exits, after the destruction
13629       //   of any automatic objects initialized within the handler.
13630       //
13631       // We just pretend to initialize the object with itself, then make sure
13632       // it can be destroyed later.
13633       QualType initType = Context.getExceptionObjectType(ExDeclType);
13634 
13635       InitializedEntity entity =
13636         InitializedEntity::InitializeVariable(ExDecl);
13637       InitializationKind initKind =
13638         InitializationKind::CreateCopy(Loc, SourceLocation());
13639 
13640       Expr *opaqueValue =
13641         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13642       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13643       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13644       if (result.isInvalid())
13645         Invalid = true;
13646       else {
13647         // If the constructor used was non-trivial, set this as the
13648         // "initializer".
13649         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13650         if (!construct->getConstructor()->isTrivial()) {
13651           Expr *init = MaybeCreateExprWithCleanups(construct);
13652           ExDecl->setInit(init);
13653         }
13654 
13655         // And make sure it's destructable.
13656         FinalizeVarWithDestructor(ExDecl, recordType);
13657       }
13658     }
13659   }
13660 
13661   if (Invalid)
13662     ExDecl->setInvalidDecl();
13663 
13664   return ExDecl;
13665 }
13666 
13667 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13668 /// handler.
13669 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13670   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13671   bool Invalid = D.isInvalidType();
13672 
13673   // Check for unexpanded parameter packs.
13674   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13675                                       UPPC_ExceptionType)) {
13676     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13677                                              D.getIdentifierLoc());
13678     Invalid = true;
13679   }
13680 
13681   IdentifierInfo *II = D.getIdentifier();
13682   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13683                                              LookupOrdinaryName,
13684                                              ForVisibleRedeclaration)) {
13685     // The scope should be freshly made just for us. There is just no way
13686     // it contains any previous declaration, except for function parameters in
13687     // a function-try-block's catch statement.
13688     assert(!S->isDeclScope(PrevDecl));
13689     if (isDeclInScope(PrevDecl, CurContext, S)) {
13690       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13691         << D.getIdentifier();
13692       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13693       Invalid = true;
13694     } else if (PrevDecl->isTemplateParameter())
13695       // Maybe we will complain about the shadowed template parameter.
13696       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13697   }
13698 
13699   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13700     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13701       << D.getCXXScopeSpec().getRange();
13702     Invalid = true;
13703   }
13704 
13705   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13706                                               D.getLocStart(),
13707                                               D.getIdentifierLoc(),
13708                                               D.getIdentifier());
13709   if (Invalid)
13710     ExDecl->setInvalidDecl();
13711 
13712   // Add the exception declaration into this scope.
13713   if (II)
13714     PushOnScopeChains(ExDecl, S);
13715   else
13716     CurContext->addDecl(ExDecl);
13717 
13718   ProcessDeclAttributes(S, ExDecl, D);
13719   return ExDecl;
13720 }
13721 
13722 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13723                                          Expr *AssertExpr,
13724                                          Expr *AssertMessageExpr,
13725                                          SourceLocation RParenLoc) {
13726   StringLiteral *AssertMessage =
13727       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13728 
13729   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13730     return nullptr;
13731 
13732   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13733                                       AssertMessage, RParenLoc, false);
13734 }
13735 
13736 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13737                                          Expr *AssertExpr,
13738                                          StringLiteral *AssertMessage,
13739                                          SourceLocation RParenLoc,
13740                                          bool Failed) {
13741   assert(AssertExpr != nullptr && "Expected non-null condition");
13742   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13743       !Failed) {
13744     // In a static_assert-declaration, the constant-expression shall be a
13745     // constant expression that can be contextually converted to bool.
13746     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13747     if (Converted.isInvalid())
13748       Failed = true;
13749 
13750     llvm::APSInt Cond;
13751     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13752           diag::err_static_assert_expression_is_not_constant,
13753           /*AllowFold=*/false).isInvalid())
13754       Failed = true;
13755 
13756     if (!Failed && !Cond) {
13757       SmallString<256> MsgBuffer;
13758       llvm::raw_svector_ostream Msg(MsgBuffer);
13759       if (AssertMessage)
13760         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13761 
13762       Expr *InnerCond = nullptr;
13763       std::string InnerCondDescription;
13764       std::tie(InnerCond, InnerCondDescription) =
13765         findFailedBooleanCondition(Converted.get(),
13766                                    /*AllowTopLevelCond=*/false);
13767       if (InnerCond) {
13768         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13769           << InnerCondDescription << !AssertMessage
13770           << Msg.str() << InnerCond->getSourceRange();
13771       } else {
13772         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13773           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13774       }
13775       Failed = true;
13776     }
13777   }
13778 
13779   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13780                                                   /*DiscardedValue*/false,
13781                                                   /*IsConstexpr*/true);
13782   if (FullAssertExpr.isInvalid())
13783     Failed = true;
13784   else
13785     AssertExpr = FullAssertExpr.get();
13786 
13787   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13788                                         AssertExpr, AssertMessage, RParenLoc,
13789                                         Failed);
13790 
13791   CurContext->addDecl(Decl);
13792   return Decl;
13793 }
13794 
13795 /// Perform semantic analysis of the given friend type declaration.
13796 ///
13797 /// \returns A friend declaration that.
13798 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13799                                       SourceLocation FriendLoc,
13800                                       TypeSourceInfo *TSInfo) {
13801   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13802 
13803   QualType T = TSInfo->getType();
13804   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13805 
13806   // C++03 [class.friend]p2:
13807   //   An elaborated-type-specifier shall be used in a friend declaration
13808   //   for a class.*
13809   //
13810   //   * The class-key of the elaborated-type-specifier is required.
13811   if (!CodeSynthesisContexts.empty()) {
13812     // Do not complain about the form of friend template types during any kind
13813     // of code synthesis. For template instantiation, we will have complained
13814     // when the template was defined.
13815   } else {
13816     if (!T->isElaboratedTypeSpecifier()) {
13817       // If we evaluated the type to a record type, suggest putting
13818       // a tag in front.
13819       if (const RecordType *RT = T->getAs<RecordType>()) {
13820         RecordDecl *RD = RT->getDecl();
13821 
13822         SmallString<16> InsertionText(" ");
13823         InsertionText += RD->getKindName();
13824 
13825         Diag(TypeRange.getBegin(),
13826              getLangOpts().CPlusPlus11 ?
13827                diag::warn_cxx98_compat_unelaborated_friend_type :
13828                diag::ext_unelaborated_friend_type)
13829           << (unsigned) RD->getTagKind()
13830           << T
13831           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13832                                         InsertionText);
13833       } else {
13834         Diag(FriendLoc,
13835              getLangOpts().CPlusPlus11 ?
13836                diag::warn_cxx98_compat_nonclass_type_friend :
13837                diag::ext_nonclass_type_friend)
13838           << T
13839           << TypeRange;
13840       }
13841     } else if (T->getAs<EnumType>()) {
13842       Diag(FriendLoc,
13843            getLangOpts().CPlusPlus11 ?
13844              diag::warn_cxx98_compat_enum_friend :
13845              diag::ext_enum_friend)
13846         << T
13847         << TypeRange;
13848     }
13849 
13850     // C++11 [class.friend]p3:
13851     //   A friend declaration that does not declare a function shall have one
13852     //   of the following forms:
13853     //     friend elaborated-type-specifier ;
13854     //     friend simple-type-specifier ;
13855     //     friend typename-specifier ;
13856     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13857       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13858   }
13859 
13860   //   If the type specifier in a friend declaration designates a (possibly
13861   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13862   //   the friend declaration is ignored.
13863   return FriendDecl::Create(Context, CurContext,
13864                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13865                             FriendLoc);
13866 }
13867 
13868 /// Handle a friend tag declaration where the scope specifier was
13869 /// templated.
13870 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13871                                     unsigned TagSpec, SourceLocation TagLoc,
13872                                     CXXScopeSpec &SS,
13873                                     IdentifierInfo *Name,
13874                                     SourceLocation NameLoc,
13875                                     AttributeList *Attr,
13876                                     MultiTemplateParamsArg TempParamLists) {
13877   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13878 
13879   bool IsMemberSpecialization = false;
13880   bool Invalid = false;
13881 
13882   if (TemplateParameterList *TemplateParams =
13883           MatchTemplateParametersToScopeSpecifier(
13884               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13885               IsMemberSpecialization, Invalid)) {
13886     if (TemplateParams->size() > 0) {
13887       // This is a declaration of a class template.
13888       if (Invalid)
13889         return nullptr;
13890 
13891       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13892                                 NameLoc, Attr, TemplateParams, AS_public,
13893                                 /*ModulePrivateLoc=*/SourceLocation(),
13894                                 FriendLoc, TempParamLists.size() - 1,
13895                                 TempParamLists.data()).get();
13896     } else {
13897       // The "template<>" header is extraneous.
13898       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13899         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13900       IsMemberSpecialization = true;
13901     }
13902   }
13903 
13904   if (Invalid) return nullptr;
13905 
13906   bool isAllExplicitSpecializations = true;
13907   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13908     if (TempParamLists[I]->size()) {
13909       isAllExplicitSpecializations = false;
13910       break;
13911     }
13912   }
13913 
13914   // FIXME: don't ignore attributes.
13915 
13916   // If it's explicit specializations all the way down, just forget
13917   // about the template header and build an appropriate non-templated
13918   // friend.  TODO: for source fidelity, remember the headers.
13919   if (isAllExplicitSpecializations) {
13920     if (SS.isEmpty()) {
13921       bool Owned = false;
13922       bool IsDependent = false;
13923       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13924                       Attr, AS_public,
13925                       /*ModulePrivateLoc=*/SourceLocation(),
13926                       MultiTemplateParamsArg(), Owned, IsDependent,
13927                       /*ScopedEnumKWLoc=*/SourceLocation(),
13928                       /*ScopedEnumUsesClassTag=*/false,
13929                       /*UnderlyingType=*/TypeResult(),
13930                       /*IsTypeSpecifier=*/false,
13931                       /*IsTemplateParamOrArg=*/false);
13932     }
13933 
13934     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13935     ElaboratedTypeKeyword Keyword
13936       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13937     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13938                                    *Name, NameLoc);
13939     if (T.isNull())
13940       return nullptr;
13941 
13942     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13943     if (isa<DependentNameType>(T)) {
13944       DependentNameTypeLoc TL =
13945           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13946       TL.setElaboratedKeywordLoc(TagLoc);
13947       TL.setQualifierLoc(QualifierLoc);
13948       TL.setNameLoc(NameLoc);
13949     } else {
13950       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13951       TL.setElaboratedKeywordLoc(TagLoc);
13952       TL.setQualifierLoc(QualifierLoc);
13953       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13954     }
13955 
13956     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13957                                             TSI, FriendLoc, TempParamLists);
13958     Friend->setAccess(AS_public);
13959     CurContext->addDecl(Friend);
13960     return Friend;
13961   }
13962 
13963   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13964 
13965 
13966 
13967   // Handle the case of a templated-scope friend class.  e.g.
13968   //   template <class T> class A<T>::B;
13969   // FIXME: we don't support these right now.
13970   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13971     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13972   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13973   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13974   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13975   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13976   TL.setElaboratedKeywordLoc(TagLoc);
13977   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13978   TL.setNameLoc(NameLoc);
13979 
13980   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13981                                           TSI, FriendLoc, TempParamLists);
13982   Friend->setAccess(AS_public);
13983   Friend->setUnsupportedFriend(true);
13984   CurContext->addDecl(Friend);
13985   return Friend;
13986 }
13987 
13988 
13989 /// Handle a friend type declaration.  This works in tandem with
13990 /// ActOnTag.
13991 ///
13992 /// Notes on friend class templates:
13993 ///
13994 /// We generally treat friend class declarations as if they were
13995 /// declaring a class.  So, for example, the elaborated type specifier
13996 /// in a friend declaration is required to obey the restrictions of a
13997 /// class-head (i.e. no typedefs in the scope chain), template
13998 /// parameters are required to match up with simple template-ids, &c.
13999 /// However, unlike when declaring a template specialization, it's
14000 /// okay to refer to a template specialization without an empty
14001 /// template parameter declaration, e.g.
14002 ///   friend class A<T>::B<unsigned>;
14003 /// We permit this as a special case; if there are any template
14004 /// parameters present at all, require proper matching, i.e.
14005 ///   template <> template \<class T> friend class A<int>::B;
14006 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14007                                 MultiTemplateParamsArg TempParams) {
14008   SourceLocation Loc = DS.getLocStart();
14009 
14010   assert(DS.isFriendSpecified());
14011   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14012 
14013   // Try to convert the decl specifier to a type.  This works for
14014   // friend templates because ActOnTag never produces a ClassTemplateDecl
14015   // for a TUK_Friend.
14016   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14017   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14018   QualType T = TSI->getType();
14019   if (TheDeclarator.isInvalidType())
14020     return nullptr;
14021 
14022   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14023     return nullptr;
14024 
14025   // This is definitely an error in C++98.  It's probably meant to
14026   // be forbidden in C++0x, too, but the specification is just
14027   // poorly written.
14028   //
14029   // The problem is with declarations like the following:
14030   //   template <T> friend A<T>::foo;
14031   // where deciding whether a class C is a friend or not now hinges
14032   // on whether there exists an instantiation of A that causes
14033   // 'foo' to equal C.  There are restrictions on class-heads
14034   // (which we declare (by fiat) elaborated friend declarations to
14035   // be) that makes this tractable.
14036   //
14037   // FIXME: handle "template <> friend class A<T>;", which
14038   // is possibly well-formed?  Who even knows?
14039   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14040     Diag(Loc, diag::err_tagless_friend_type_template)
14041       << DS.getSourceRange();
14042     return nullptr;
14043   }
14044 
14045   // C++98 [class.friend]p1: A friend of a class is a function
14046   //   or class that is not a member of the class . . .
14047   // This is fixed in DR77, which just barely didn't make the C++03
14048   // deadline.  It's also a very silly restriction that seriously
14049   // affects inner classes and which nobody else seems to implement;
14050   // thus we never diagnose it, not even in -pedantic.
14051   //
14052   // But note that we could warn about it: it's always useless to
14053   // friend one of your own members (it's not, however, worthless to
14054   // friend a member of an arbitrary specialization of your template).
14055 
14056   Decl *D;
14057   if (!TempParams.empty())
14058     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14059                                    TempParams,
14060                                    TSI,
14061                                    DS.getFriendSpecLoc());
14062   else
14063     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14064 
14065   if (!D)
14066     return nullptr;
14067 
14068   D->setAccess(AS_public);
14069   CurContext->addDecl(D);
14070 
14071   return D;
14072 }
14073 
14074 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14075                                         MultiTemplateParamsArg TemplateParams) {
14076   const DeclSpec &DS = D.getDeclSpec();
14077 
14078   assert(DS.isFriendSpecified());
14079   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14080 
14081   SourceLocation Loc = D.getIdentifierLoc();
14082   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14083 
14084   // C++ [class.friend]p1
14085   //   A friend of a class is a function or class....
14086   // Note that this sees through typedefs, which is intended.
14087   // It *doesn't* see through dependent types, which is correct
14088   // according to [temp.arg.type]p3:
14089   //   If a declaration acquires a function type through a
14090   //   type dependent on a template-parameter and this causes
14091   //   a declaration that does not use the syntactic form of a
14092   //   function declarator to have a function type, the program
14093   //   is ill-formed.
14094   if (!TInfo->getType()->isFunctionType()) {
14095     Diag(Loc, diag::err_unexpected_friend);
14096 
14097     // It might be worthwhile to try to recover by creating an
14098     // appropriate declaration.
14099     return nullptr;
14100   }
14101 
14102   // C++ [namespace.memdef]p3
14103   //  - If a friend declaration in a non-local class first declares a
14104   //    class or function, the friend class or function is a member
14105   //    of the innermost enclosing namespace.
14106   //  - The name of the friend is not found by simple name lookup
14107   //    until a matching declaration is provided in that namespace
14108   //    scope (either before or after the class declaration granting
14109   //    friendship).
14110   //  - If a friend function is called, its name may be found by the
14111   //    name lookup that considers functions from namespaces and
14112   //    classes associated with the types of the function arguments.
14113   //  - When looking for a prior declaration of a class or a function
14114   //    declared as a friend, scopes outside the innermost enclosing
14115   //    namespace scope are not considered.
14116 
14117   CXXScopeSpec &SS = D.getCXXScopeSpec();
14118   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14119   DeclarationName Name = NameInfo.getName();
14120   assert(Name);
14121 
14122   // Check for unexpanded parameter packs.
14123   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14124       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14125       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14126     return nullptr;
14127 
14128   // The context we found the declaration in, or in which we should
14129   // create the declaration.
14130   DeclContext *DC;
14131   Scope *DCScope = S;
14132   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14133                         ForExternalRedeclaration);
14134 
14135   // There are five cases here.
14136   //   - There's no scope specifier and we're in a local class. Only look
14137   //     for functions declared in the immediately-enclosing block scope.
14138   // We recover from invalid scope qualifiers as if they just weren't there.
14139   FunctionDecl *FunctionContainingLocalClass = nullptr;
14140   if ((SS.isInvalid() || !SS.isSet()) &&
14141       (FunctionContainingLocalClass =
14142            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14143     // C++11 [class.friend]p11:
14144     //   If a friend declaration appears in a local class and the name
14145     //   specified is an unqualified name, a prior declaration is
14146     //   looked up without considering scopes that are outside the
14147     //   innermost enclosing non-class scope. For a friend function
14148     //   declaration, if there is no prior declaration, the program is
14149     //   ill-formed.
14150 
14151     // Find the innermost enclosing non-class scope. This is the block
14152     // scope containing the local class definition (or for a nested class,
14153     // the outer local class).
14154     DCScope = S->getFnParent();
14155 
14156     // Look up the function name in the scope.
14157     Previous.clear(LookupLocalFriendName);
14158     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14159 
14160     if (!Previous.empty()) {
14161       // All possible previous declarations must have the same context:
14162       // either they were declared at block scope or they are members of
14163       // one of the enclosing local classes.
14164       DC = Previous.getRepresentativeDecl()->getDeclContext();
14165     } else {
14166       // This is ill-formed, but provide the context that we would have
14167       // declared the function in, if we were permitted to, for error recovery.
14168       DC = FunctionContainingLocalClass;
14169     }
14170     adjustContextForLocalExternDecl(DC);
14171 
14172     // C++ [class.friend]p6:
14173     //   A function can be defined in a friend declaration of a class if and
14174     //   only if the class is a non-local class (9.8), the function name is
14175     //   unqualified, and the function has namespace scope.
14176     if (D.isFunctionDefinition()) {
14177       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14178     }
14179 
14180   //   - There's no scope specifier, in which case we just go to the
14181   //     appropriate scope and look for a function or function template
14182   //     there as appropriate.
14183   } else if (SS.isInvalid() || !SS.isSet()) {
14184     // C++11 [namespace.memdef]p3:
14185     //   If the name in a friend declaration is neither qualified nor
14186     //   a template-id and the declaration is a function or an
14187     //   elaborated-type-specifier, the lookup to determine whether
14188     //   the entity has been previously declared shall not consider
14189     //   any scopes outside the innermost enclosing namespace.
14190     bool isTemplateId =
14191         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14192 
14193     // Find the appropriate context according to the above.
14194     DC = CurContext;
14195 
14196     // Skip class contexts.  If someone can cite chapter and verse
14197     // for this behavior, that would be nice --- it's what GCC and
14198     // EDG do, and it seems like a reasonable intent, but the spec
14199     // really only says that checks for unqualified existing
14200     // declarations should stop at the nearest enclosing namespace,
14201     // not that they should only consider the nearest enclosing
14202     // namespace.
14203     while (DC->isRecord())
14204       DC = DC->getParent();
14205 
14206     DeclContext *LookupDC = DC;
14207     while (LookupDC->isTransparentContext())
14208       LookupDC = LookupDC->getParent();
14209 
14210     while (true) {
14211       LookupQualifiedName(Previous, LookupDC);
14212 
14213       if (!Previous.empty()) {
14214         DC = LookupDC;
14215         break;
14216       }
14217 
14218       if (isTemplateId) {
14219         if (isa<TranslationUnitDecl>(LookupDC)) break;
14220       } else {
14221         if (LookupDC->isFileContext()) break;
14222       }
14223       LookupDC = LookupDC->getParent();
14224     }
14225 
14226     DCScope = getScopeForDeclContext(S, DC);
14227 
14228   //   - There's a non-dependent scope specifier, in which case we
14229   //     compute it and do a previous lookup there for a function
14230   //     or function template.
14231   } else if (!SS.getScopeRep()->isDependent()) {
14232     DC = computeDeclContext(SS);
14233     if (!DC) return nullptr;
14234 
14235     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14236 
14237     LookupQualifiedName(Previous, DC);
14238 
14239     // Ignore things found implicitly in the wrong scope.
14240     // TODO: better diagnostics for this case.  Suggesting the right
14241     // qualified scope would be nice...
14242     LookupResult::Filter F = Previous.makeFilter();
14243     while (F.hasNext()) {
14244       NamedDecl *D = F.next();
14245       if (!DC->InEnclosingNamespaceSetOf(
14246               D->getDeclContext()->getRedeclContext()))
14247         F.erase();
14248     }
14249     F.done();
14250 
14251     if (Previous.empty()) {
14252       D.setInvalidType();
14253       Diag(Loc, diag::err_qualified_friend_not_found)
14254           << Name << TInfo->getType();
14255       return nullptr;
14256     }
14257 
14258     // C++ [class.friend]p1: A friend of a class is a function or
14259     //   class that is not a member of the class . . .
14260     if (DC->Equals(CurContext))
14261       Diag(DS.getFriendSpecLoc(),
14262            getLangOpts().CPlusPlus11 ?
14263              diag::warn_cxx98_compat_friend_is_member :
14264              diag::err_friend_is_member);
14265 
14266     if (D.isFunctionDefinition()) {
14267       // C++ [class.friend]p6:
14268       //   A function can be defined in a friend declaration of a class if and
14269       //   only if the class is a non-local class (9.8), the function name is
14270       //   unqualified, and the function has namespace scope.
14271       SemaDiagnosticBuilder DB
14272         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14273 
14274       DB << SS.getScopeRep();
14275       if (DC->isFileContext())
14276         DB << FixItHint::CreateRemoval(SS.getRange());
14277       SS.clear();
14278     }
14279 
14280   //   - There's a scope specifier that does not match any template
14281   //     parameter lists, in which case we use some arbitrary context,
14282   //     create a method or method template, and wait for instantiation.
14283   //   - There's a scope specifier that does match some template
14284   //     parameter lists, which we don't handle right now.
14285   } else {
14286     if (D.isFunctionDefinition()) {
14287       // C++ [class.friend]p6:
14288       //   A function can be defined in a friend declaration of a class if and
14289       //   only if the class is a non-local class (9.8), the function name is
14290       //   unqualified, and the function has namespace scope.
14291       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14292         << SS.getScopeRep();
14293     }
14294 
14295     DC = CurContext;
14296     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14297   }
14298 
14299   if (!DC->isRecord()) {
14300     int DiagArg = -1;
14301     switch (D.getName().getKind()) {
14302     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14303     case UnqualifiedIdKind::IK_ConstructorName:
14304       DiagArg = 0;
14305       break;
14306     case UnqualifiedIdKind::IK_DestructorName:
14307       DiagArg = 1;
14308       break;
14309     case UnqualifiedIdKind::IK_ConversionFunctionId:
14310       DiagArg = 2;
14311       break;
14312     case UnqualifiedIdKind::IK_DeductionGuideName:
14313       DiagArg = 3;
14314       break;
14315     case UnqualifiedIdKind::IK_Identifier:
14316     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14317     case UnqualifiedIdKind::IK_LiteralOperatorId:
14318     case UnqualifiedIdKind::IK_OperatorFunctionId:
14319     case UnqualifiedIdKind::IK_TemplateId:
14320       break;
14321     }
14322     // This implies that it has to be an operator or function.
14323     if (DiagArg >= 0) {
14324       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14325       return nullptr;
14326     }
14327   }
14328 
14329   // FIXME: This is an egregious hack to cope with cases where the scope stack
14330   // does not contain the declaration context, i.e., in an out-of-line
14331   // definition of a class.
14332   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14333   if (!DCScope) {
14334     FakeDCScope.setEntity(DC);
14335     DCScope = &FakeDCScope;
14336   }
14337 
14338   bool AddToScope = true;
14339   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14340                                           TemplateParams, AddToScope);
14341   if (!ND) return nullptr;
14342 
14343   assert(ND->getLexicalDeclContext() == CurContext);
14344 
14345   // If we performed typo correction, we might have added a scope specifier
14346   // and changed the decl context.
14347   DC = ND->getDeclContext();
14348 
14349   // Add the function declaration to the appropriate lookup tables,
14350   // adjusting the redeclarations list as necessary.  We don't
14351   // want to do this yet if the friending class is dependent.
14352   //
14353   // Also update the scope-based lookup if the target context's
14354   // lookup context is in lexical scope.
14355   if (!CurContext->isDependentContext()) {
14356     DC = DC->getRedeclContext();
14357     DC->makeDeclVisibleInContext(ND);
14358     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14359       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14360   }
14361 
14362   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14363                                        D.getIdentifierLoc(), ND,
14364                                        DS.getFriendSpecLoc());
14365   FrD->setAccess(AS_public);
14366   CurContext->addDecl(FrD);
14367 
14368   if (ND->isInvalidDecl()) {
14369     FrD->setInvalidDecl();
14370   } else {
14371     if (DC->isRecord()) CheckFriendAccess(ND);
14372 
14373     FunctionDecl *FD;
14374     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14375       FD = FTD->getTemplatedDecl();
14376     else
14377       FD = cast<FunctionDecl>(ND);
14378 
14379     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14380     // default argument expression, that declaration shall be a definition
14381     // and shall be the only declaration of the function or function
14382     // template in the translation unit.
14383     if (functionDeclHasDefaultArgument(FD)) {
14384       // We can't look at FD->getPreviousDecl() because it may not have been set
14385       // if we're in a dependent context. If the function is known to be a
14386       // redeclaration, we will have narrowed Previous down to the right decl.
14387       if (D.isRedeclaration()) {
14388         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14389         Diag(Previous.getRepresentativeDecl()->getLocation(),
14390              diag::note_previous_declaration);
14391       } else if (!D.isFunctionDefinition())
14392         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14393     }
14394 
14395     // Mark templated-scope function declarations as unsupported.
14396     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14397       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14398         << SS.getScopeRep() << SS.getRange()
14399         << cast<CXXRecordDecl>(CurContext);
14400       FrD->setUnsupportedFriend(true);
14401     }
14402   }
14403 
14404   return ND;
14405 }
14406 
14407 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14408   AdjustDeclIfTemplate(Dcl);
14409 
14410   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14411   if (!Fn) {
14412     Diag(DelLoc, diag::err_deleted_non_function);
14413     return;
14414   }
14415 
14416   // Deleted function does not have a body.
14417   Fn->setWillHaveBody(false);
14418 
14419   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14420     // Don't consider the implicit declaration we generate for explicit
14421     // specializations. FIXME: Do not generate these implicit declarations.
14422     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14423          Prev->getPreviousDecl()) &&
14424         !Prev->isDefined()) {
14425       Diag(DelLoc, diag::err_deleted_decl_not_first);
14426       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14427            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14428                               : diag::note_previous_declaration);
14429     }
14430     // If the declaration wasn't the first, we delete the function anyway for
14431     // recovery.
14432     Fn = Fn->getCanonicalDecl();
14433   }
14434 
14435   // dllimport/dllexport cannot be deleted.
14436   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14437     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14438     Fn->setInvalidDecl();
14439   }
14440 
14441   if (Fn->isDeleted())
14442     return;
14443 
14444   // See if we're deleting a function which is already known to override a
14445   // non-deleted virtual function.
14446   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14447     bool IssuedDiagnostic = false;
14448     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14449       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14450         if (!IssuedDiagnostic) {
14451           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14452           IssuedDiagnostic = true;
14453         }
14454         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14455       }
14456     }
14457     // If this function was implicitly deleted because it was defaulted,
14458     // explain why it was deleted.
14459     if (IssuedDiagnostic && MD->isDefaulted())
14460       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14461                                 /*Diagnose*/true);
14462   }
14463 
14464   // C++11 [basic.start.main]p3:
14465   //   A program that defines main as deleted [...] is ill-formed.
14466   if (Fn->isMain())
14467     Diag(DelLoc, diag::err_deleted_main);
14468 
14469   // C++11 [dcl.fct.def.delete]p4:
14470   //  A deleted function is implicitly inline.
14471   Fn->setImplicitlyInline();
14472   Fn->setDeletedAsWritten();
14473 }
14474 
14475 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14476   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14477 
14478   if (MD) {
14479     if (MD->getParent()->isDependentType()) {
14480       MD->setDefaulted();
14481       MD->setExplicitlyDefaulted();
14482       return;
14483     }
14484 
14485     CXXSpecialMember Member = getSpecialMember(MD);
14486     if (Member == CXXInvalid) {
14487       if (!MD->isInvalidDecl())
14488         Diag(DefaultLoc, diag::err_default_special_members);
14489       return;
14490     }
14491 
14492     MD->setDefaulted();
14493     MD->setExplicitlyDefaulted();
14494 
14495     // Unset that we will have a body for this function. We might not,
14496     // if it turns out to be trivial, and we don't need this marking now
14497     // that we've marked it as defaulted.
14498     MD->setWillHaveBody(false);
14499 
14500     // If this definition appears within the record, do the checking when
14501     // the record is complete.
14502     const FunctionDecl *Primary = MD;
14503     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14504       // Ask the template instantiation pattern that actually had the
14505       // '= default' on it.
14506       Primary = Pattern;
14507 
14508     // If the method was defaulted on its first declaration, we will have
14509     // already performed the checking in CheckCompletedCXXClass. Such a
14510     // declaration doesn't trigger an implicit definition.
14511     if (Primary->getCanonicalDecl()->isDefaulted())
14512       return;
14513 
14514     CheckExplicitlyDefaultedSpecialMember(MD);
14515 
14516     if (!MD->isInvalidDecl())
14517       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14518   } else {
14519     Diag(DefaultLoc, diag::err_default_special_members);
14520   }
14521 }
14522 
14523 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14524   for (Stmt *SubStmt : S->children()) {
14525     if (!SubStmt)
14526       continue;
14527     if (isa<ReturnStmt>(SubStmt))
14528       Self.Diag(SubStmt->getLocStart(),
14529            diag::err_return_in_constructor_handler);
14530     if (!isa<Expr>(SubStmt))
14531       SearchForReturnInStmt(Self, SubStmt);
14532   }
14533 }
14534 
14535 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14536   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14537     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14538     SearchForReturnInStmt(*this, Handler);
14539   }
14540 }
14541 
14542 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14543                                              const CXXMethodDecl *Old) {
14544   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14545   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14546 
14547   if (OldFT->hasExtParameterInfos()) {
14548     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14549       // A parameter of the overriding method should be annotated with noescape
14550       // if the corresponding parameter of the overridden method is annotated.
14551       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14552           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14553         Diag(New->getParamDecl(I)->getLocation(),
14554              diag::warn_overriding_method_missing_noescape);
14555         Diag(Old->getParamDecl(I)->getLocation(),
14556              diag::note_overridden_marked_noescape);
14557       }
14558   }
14559   // Virtual overrides must have the same code_seg.
14560   const auto *OldSA = Old->getAttr<SectionAttr>();
14561   const auto *NewSA = New->getAttr<SectionAttr>();
14562   if (OldSA || NewSA) {
14563     if (!OldSA || !NewSA || NewSA->getName() != OldSA->getName()) {
14564       Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14565       Diag(Old->getLocation(), diag::note_previous_declaration);
14566       return true;
14567     }
14568   }
14569 
14570   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14571 
14572   // If the calling conventions match, everything is fine
14573   if (NewCC == OldCC)
14574     return false;
14575 
14576   // If the calling conventions mismatch because the new function is static,
14577   // suppress the calling convention mismatch error; the error about static
14578   // function override (err_static_overrides_virtual from
14579   // Sema::CheckFunctionDeclaration) is more clear.
14580   if (New->getStorageClass() == SC_Static)
14581     return false;
14582 
14583   Diag(New->getLocation(),
14584        diag::err_conflicting_overriding_cc_attributes)
14585     << New->getDeclName() << New->getType() << Old->getType();
14586   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14587   return true;
14588 }
14589 
14590 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14591                                              const CXXMethodDecl *Old) {
14592   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14593   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14594 
14595   if (Context.hasSameType(NewTy, OldTy) ||
14596       NewTy->isDependentType() || OldTy->isDependentType())
14597     return false;
14598 
14599   // Check if the return types are covariant
14600   QualType NewClassTy, OldClassTy;
14601 
14602   /// Both types must be pointers or references to classes.
14603   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14604     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14605       NewClassTy = NewPT->getPointeeType();
14606       OldClassTy = OldPT->getPointeeType();
14607     }
14608   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14609     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14610       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14611         NewClassTy = NewRT->getPointeeType();
14612         OldClassTy = OldRT->getPointeeType();
14613       }
14614     }
14615   }
14616 
14617   // The return types aren't either both pointers or references to a class type.
14618   if (NewClassTy.isNull()) {
14619     Diag(New->getLocation(),
14620          diag::err_different_return_type_for_overriding_virtual_function)
14621         << New->getDeclName() << NewTy << OldTy
14622         << New->getReturnTypeSourceRange();
14623     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14624         << Old->getReturnTypeSourceRange();
14625 
14626     return true;
14627   }
14628 
14629   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14630     // C++14 [class.virtual]p8:
14631     //   If the class type in the covariant return type of D::f differs from
14632     //   that of B::f, the class type in the return type of D::f shall be
14633     //   complete at the point of declaration of D::f or shall be the class
14634     //   type D.
14635     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14636       if (!RT->isBeingDefined() &&
14637           RequireCompleteType(New->getLocation(), NewClassTy,
14638                               diag::err_covariant_return_incomplete,
14639                               New->getDeclName()))
14640         return true;
14641     }
14642 
14643     // Check if the new class derives from the old class.
14644     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14645       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14646           << New->getDeclName() << NewTy << OldTy
14647           << New->getReturnTypeSourceRange();
14648       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14649           << Old->getReturnTypeSourceRange();
14650       return true;
14651     }
14652 
14653     // Check if we the conversion from derived to base is valid.
14654     if (CheckDerivedToBaseConversion(
14655             NewClassTy, OldClassTy,
14656             diag::err_covariant_return_inaccessible_base,
14657             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14658             New->getLocation(), New->getReturnTypeSourceRange(),
14659             New->getDeclName(), nullptr)) {
14660       // FIXME: this note won't trigger for delayed access control
14661       // diagnostics, and it's impossible to get an undelayed error
14662       // here from access control during the original parse because
14663       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14664       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14665           << Old->getReturnTypeSourceRange();
14666       return true;
14667     }
14668   }
14669 
14670   // The qualifiers of the return types must be the same.
14671   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14672     Diag(New->getLocation(),
14673          diag::err_covariant_return_type_different_qualifications)
14674         << New->getDeclName() << NewTy << OldTy
14675         << New->getReturnTypeSourceRange();
14676     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14677         << Old->getReturnTypeSourceRange();
14678     return true;
14679   }
14680 
14681 
14682   // The new class type must have the same or less qualifiers as the old type.
14683   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14684     Diag(New->getLocation(),
14685          diag::err_covariant_return_type_class_type_more_qualified)
14686         << New->getDeclName() << NewTy << OldTy
14687         << New->getReturnTypeSourceRange();
14688     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14689         << Old->getReturnTypeSourceRange();
14690     return true;
14691   }
14692 
14693   return false;
14694 }
14695 
14696 /// Mark the given method pure.
14697 ///
14698 /// \param Method the method to be marked pure.
14699 ///
14700 /// \param InitRange the source range that covers the "0" initializer.
14701 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14702   SourceLocation EndLoc = InitRange.getEnd();
14703   if (EndLoc.isValid())
14704     Method->setRangeEnd(EndLoc);
14705 
14706   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14707     Method->setPure();
14708     return false;
14709   }
14710 
14711   if (!Method->isInvalidDecl())
14712     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14713       << Method->getDeclName() << InitRange;
14714   return true;
14715 }
14716 
14717 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14718   if (D->getFriendObjectKind())
14719     Diag(D->getLocation(), diag::err_pure_friend);
14720   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14721     CheckPureMethod(M, ZeroLoc);
14722   else
14723     Diag(D->getLocation(), diag::err_illegal_initializer);
14724 }
14725 
14726 /// Determine whether the given declaration is a global variable or
14727 /// static data member.
14728 static bool isNonlocalVariable(const Decl *D) {
14729   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14730     return Var->hasGlobalStorage();
14731 
14732   return false;
14733 }
14734 
14735 /// Invoked when we are about to parse an initializer for the declaration
14736 /// 'Dcl'.
14737 ///
14738 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14739 /// static data member of class X, names should be looked up in the scope of
14740 /// class X. If the declaration had a scope specifier, a scope will have
14741 /// been created and passed in for this purpose. Otherwise, S will be null.
14742 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14743   // If there is no declaration, there was an error parsing it.
14744   if (!D || D->isInvalidDecl())
14745     return;
14746 
14747   // We will always have a nested name specifier here, but this declaration
14748   // might not be out of line if the specifier names the current namespace:
14749   //   extern int n;
14750   //   int ::n = 0;
14751   if (S && D->isOutOfLine())
14752     EnterDeclaratorContext(S, D->getDeclContext());
14753 
14754   // If we are parsing the initializer for a static data member, push a
14755   // new expression evaluation context that is associated with this static
14756   // data member.
14757   if (isNonlocalVariable(D))
14758     PushExpressionEvaluationContext(
14759         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14760 }
14761 
14762 /// Invoked after we are finished parsing an initializer for the declaration D.
14763 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14764   // If there is no declaration, there was an error parsing it.
14765   if (!D || D->isInvalidDecl())
14766     return;
14767 
14768   if (isNonlocalVariable(D))
14769     PopExpressionEvaluationContext();
14770 
14771   if (S && D->isOutOfLine())
14772     ExitDeclaratorContext(S);
14773 }
14774 
14775 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14776 /// C++ if/switch/while/for statement.
14777 /// e.g: "if (int x = f()) {...}"
14778 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14779   // C++ 6.4p2:
14780   // The declarator shall not specify a function or an array.
14781   // The type-specifier-seq shall not contain typedef and shall not declare a
14782   // new class or enumeration.
14783   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14784          "Parser allowed 'typedef' as storage class of condition decl.");
14785 
14786   Decl *Dcl = ActOnDeclarator(S, D);
14787   if (!Dcl)
14788     return true;
14789 
14790   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14791     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14792       << D.getSourceRange();
14793     return true;
14794   }
14795 
14796   return Dcl;
14797 }
14798 
14799 void Sema::LoadExternalVTableUses() {
14800   if (!ExternalSource)
14801     return;
14802 
14803   SmallVector<ExternalVTableUse, 4> VTables;
14804   ExternalSource->ReadUsedVTables(VTables);
14805   SmallVector<VTableUse, 4> NewUses;
14806   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14807     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14808       = VTablesUsed.find(VTables[I].Record);
14809     // Even if a definition wasn't required before, it may be required now.
14810     if (Pos != VTablesUsed.end()) {
14811       if (!Pos->second && VTables[I].DefinitionRequired)
14812         Pos->second = true;
14813       continue;
14814     }
14815 
14816     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14817     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14818   }
14819 
14820   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14821 }
14822 
14823 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14824                           bool DefinitionRequired) {
14825   // Ignore any vtable uses in unevaluated operands or for classes that do
14826   // not have a vtable.
14827   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14828       CurContext->isDependentContext() || isUnevaluatedContext())
14829     return;
14830 
14831   // Try to insert this class into the map.
14832   LoadExternalVTableUses();
14833   Class = Class->getCanonicalDecl();
14834   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14835     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14836   if (!Pos.second) {
14837     // If we already had an entry, check to see if we are promoting this vtable
14838     // to require a definition. If so, we need to reappend to the VTableUses
14839     // list, since we may have already processed the first entry.
14840     if (DefinitionRequired && !Pos.first->second) {
14841       Pos.first->second = true;
14842     } else {
14843       // Otherwise, we can early exit.
14844       return;
14845     }
14846   } else {
14847     // The Microsoft ABI requires that we perform the destructor body
14848     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14849     // the deleting destructor is emitted with the vtable, not with the
14850     // destructor definition as in the Itanium ABI.
14851     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14852       CXXDestructorDecl *DD = Class->getDestructor();
14853       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14854         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14855           // If this is an out-of-line declaration, marking it referenced will
14856           // not do anything. Manually call CheckDestructor to look up operator
14857           // delete().
14858           ContextRAII SavedContext(*this, DD);
14859           CheckDestructor(DD);
14860         } else {
14861           MarkFunctionReferenced(Loc, Class->getDestructor());
14862         }
14863       }
14864     }
14865   }
14866 
14867   // Local classes need to have their virtual members marked
14868   // immediately. For all other classes, we mark their virtual members
14869   // at the end of the translation unit.
14870   if (Class->isLocalClass())
14871     MarkVirtualMembersReferenced(Loc, Class);
14872   else
14873     VTableUses.push_back(std::make_pair(Class, Loc));
14874 }
14875 
14876 bool Sema::DefineUsedVTables() {
14877   LoadExternalVTableUses();
14878   if (VTableUses.empty())
14879     return false;
14880 
14881   // Note: The VTableUses vector could grow as a result of marking
14882   // the members of a class as "used", so we check the size each
14883   // time through the loop and prefer indices (which are stable) to
14884   // iterators (which are not).
14885   bool DefinedAnything = false;
14886   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14887     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14888     if (!Class)
14889       continue;
14890     TemplateSpecializationKind ClassTSK =
14891         Class->getTemplateSpecializationKind();
14892 
14893     SourceLocation Loc = VTableUses[I].second;
14894 
14895     bool DefineVTable = true;
14896 
14897     // If this class has a key function, but that key function is
14898     // defined in another translation unit, we don't need to emit the
14899     // vtable even though we're using it.
14900     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14901     if (KeyFunction && !KeyFunction->hasBody()) {
14902       // The key function is in another translation unit.
14903       DefineVTable = false;
14904       TemplateSpecializationKind TSK =
14905           KeyFunction->getTemplateSpecializationKind();
14906       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14907              TSK != TSK_ImplicitInstantiation &&
14908              "Instantiations don't have key functions");
14909       (void)TSK;
14910     } else if (!KeyFunction) {
14911       // If we have a class with no key function that is the subject
14912       // of an explicit instantiation declaration, suppress the
14913       // vtable; it will live with the explicit instantiation
14914       // definition.
14915       bool IsExplicitInstantiationDeclaration =
14916           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14917       for (auto R : Class->redecls()) {
14918         TemplateSpecializationKind TSK
14919           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14920         if (TSK == TSK_ExplicitInstantiationDeclaration)
14921           IsExplicitInstantiationDeclaration = true;
14922         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14923           IsExplicitInstantiationDeclaration = false;
14924           break;
14925         }
14926       }
14927 
14928       if (IsExplicitInstantiationDeclaration)
14929         DefineVTable = false;
14930     }
14931 
14932     // The exception specifications for all virtual members may be needed even
14933     // if we are not providing an authoritative form of the vtable in this TU.
14934     // We may choose to emit it available_externally anyway.
14935     if (!DefineVTable) {
14936       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14937       continue;
14938     }
14939 
14940     // Mark all of the virtual members of this class as referenced, so
14941     // that we can build a vtable. Then, tell the AST consumer that a
14942     // vtable for this class is required.
14943     DefinedAnything = true;
14944     MarkVirtualMembersReferenced(Loc, Class);
14945     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
14946     if (VTablesUsed[Canonical])
14947       Consumer.HandleVTable(Class);
14948 
14949     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14950     // no key function or the key function is inlined. Don't warn in C++ ABIs
14951     // that lack key functions, since the user won't be able to make one.
14952     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14953         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14954       const FunctionDecl *KeyFunctionDef = nullptr;
14955       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14956                            KeyFunctionDef->isInlined())) {
14957         Diag(Class->getLocation(),
14958              ClassTSK == TSK_ExplicitInstantiationDefinition
14959                  ? diag::warn_weak_template_vtable
14960                  : diag::warn_weak_vtable)
14961             << Class;
14962       }
14963     }
14964   }
14965   VTableUses.clear();
14966 
14967   return DefinedAnything;
14968 }
14969 
14970 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14971                                                  const CXXRecordDecl *RD) {
14972   for (const auto *I : RD->methods())
14973     if (I->isVirtual() && !I->isPure())
14974       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14975 }
14976 
14977 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14978                                         const CXXRecordDecl *RD) {
14979   // Mark all functions which will appear in RD's vtable as used.
14980   CXXFinalOverriderMap FinalOverriders;
14981   RD->getFinalOverriders(FinalOverriders);
14982   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14983                                             E = FinalOverriders.end();
14984        I != E; ++I) {
14985     for (OverridingMethods::const_iterator OI = I->second.begin(),
14986                                            OE = I->second.end();
14987          OI != OE; ++OI) {
14988       assert(OI->second.size() > 0 && "no final overrider");
14989       CXXMethodDecl *Overrider = OI->second.front().Method;
14990 
14991       // C++ [basic.def.odr]p2:
14992       //   [...] A virtual member function is used if it is not pure. [...]
14993       if (!Overrider->isPure())
14994         MarkFunctionReferenced(Loc, Overrider);
14995     }
14996   }
14997 
14998   // Only classes that have virtual bases need a VTT.
14999   if (RD->getNumVBases() == 0)
15000     return;
15001 
15002   for (const auto &I : RD->bases()) {
15003     const CXXRecordDecl *Base =
15004         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15005     if (Base->getNumVBases() == 0)
15006       continue;
15007     MarkVirtualMembersReferenced(Loc, Base);
15008   }
15009 }
15010 
15011 /// SetIvarInitializers - This routine builds initialization ASTs for the
15012 /// Objective-C implementation whose ivars need be initialized.
15013 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15014   if (!getLangOpts().CPlusPlus)
15015     return;
15016   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15017     SmallVector<ObjCIvarDecl*, 8> ivars;
15018     CollectIvarsToConstructOrDestruct(OID, ivars);
15019     if (ivars.empty())
15020       return;
15021     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15022     for (unsigned i = 0; i < ivars.size(); i++) {
15023       FieldDecl *Field = ivars[i];
15024       if (Field->isInvalidDecl())
15025         continue;
15026 
15027       CXXCtorInitializer *Member;
15028       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15029       InitializationKind InitKind =
15030         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15031 
15032       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15033       ExprResult MemberInit =
15034         InitSeq.Perform(*this, InitEntity, InitKind, None);
15035       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15036       // Note, MemberInit could actually come back empty if no initialization
15037       // is required (e.g., because it would call a trivial default constructor)
15038       if (!MemberInit.get() || MemberInit.isInvalid())
15039         continue;
15040 
15041       Member =
15042         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15043                                          SourceLocation(),
15044                                          MemberInit.getAs<Expr>(),
15045                                          SourceLocation());
15046       AllToInit.push_back(Member);
15047 
15048       // Be sure that the destructor is accessible and is marked as referenced.
15049       if (const RecordType *RecordTy =
15050               Context.getBaseElementType(Field->getType())
15051                   ->getAs<RecordType>()) {
15052         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15053         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15054           MarkFunctionReferenced(Field->getLocation(), Destructor);
15055           CheckDestructorAccess(Field->getLocation(), Destructor,
15056                             PDiag(diag::err_access_dtor_ivar)
15057                               << Context.getBaseElementType(Field->getType()));
15058         }
15059       }
15060     }
15061     ObjCImplementation->setIvarInitializers(Context,
15062                                             AllToInit.data(), AllToInit.size());
15063   }
15064 }
15065 
15066 static
15067 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15068                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
15069                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
15070                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
15071                            Sema &S) {
15072   if (Ctor->isInvalidDecl())
15073     return;
15074 
15075   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15076 
15077   // Target may not be determinable yet, for instance if this is a dependent
15078   // call in an uninstantiated template.
15079   if (Target) {
15080     const FunctionDecl *FNTarget = nullptr;
15081     (void)Target->hasBody(FNTarget);
15082     Target = const_cast<CXXConstructorDecl*>(
15083       cast_or_null<CXXConstructorDecl>(FNTarget));
15084   }
15085 
15086   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15087                      // Avoid dereferencing a null pointer here.
15088                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15089 
15090   if (!Current.insert(Canonical).second)
15091     return;
15092 
15093   // We know that beyond here, we aren't chaining into a cycle.
15094   if (!Target || !Target->isDelegatingConstructor() ||
15095       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15096     Valid.insert(Current.begin(), Current.end());
15097     Current.clear();
15098   // We've hit a cycle.
15099   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15100              Current.count(TCanonical)) {
15101     // If we haven't diagnosed this cycle yet, do so now.
15102     if (!Invalid.count(TCanonical)) {
15103       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15104              diag::warn_delegating_ctor_cycle)
15105         << Ctor;
15106 
15107       // Don't add a note for a function delegating directly to itself.
15108       if (TCanonical != Canonical)
15109         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15110 
15111       CXXConstructorDecl *C = Target;
15112       while (C->getCanonicalDecl() != Canonical) {
15113         const FunctionDecl *FNTarget = nullptr;
15114         (void)C->getTargetConstructor()->hasBody(FNTarget);
15115         assert(FNTarget && "Ctor cycle through bodiless function");
15116 
15117         C = const_cast<CXXConstructorDecl*>(
15118           cast<CXXConstructorDecl>(FNTarget));
15119         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15120       }
15121     }
15122 
15123     Invalid.insert(Current.begin(), Current.end());
15124     Current.clear();
15125   } else {
15126     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15127   }
15128 }
15129 
15130 
15131 void Sema::CheckDelegatingCtorCycles() {
15132   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15133 
15134   for (DelegatingCtorDeclsType::iterator
15135          I = DelegatingCtorDecls.begin(ExternalSource),
15136          E = DelegatingCtorDecls.end();
15137        I != E; ++I)
15138     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15139 
15140   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
15141                                                          CE = Invalid.end();
15142        CI != CE; ++CI)
15143     (*CI)->setInvalidDecl();
15144 }
15145 
15146 namespace {
15147   /// AST visitor that finds references to the 'this' expression.
15148   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15149     Sema &S;
15150 
15151   public:
15152     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15153 
15154     bool VisitCXXThisExpr(CXXThisExpr *E) {
15155       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15156         << E->isImplicit();
15157       return false;
15158     }
15159   };
15160 }
15161 
15162 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15163   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15164   if (!TSInfo)
15165     return false;
15166 
15167   TypeLoc TL = TSInfo->getTypeLoc();
15168   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15169   if (!ProtoTL)
15170     return false;
15171 
15172   // C++11 [expr.prim.general]p3:
15173   //   [The expression this] shall not appear before the optional
15174   //   cv-qualifier-seq and it shall not appear within the declaration of a
15175   //   static member function (although its type and value category are defined
15176   //   within a static member function as they are within a non-static member
15177   //   function). [ Note: this is because declaration matching does not occur
15178   //  until the complete declarator is known. - end note ]
15179   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15180   FindCXXThisExpr Finder(*this);
15181 
15182   // If the return type came after the cv-qualifier-seq, check it now.
15183   if (Proto->hasTrailingReturn() &&
15184       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15185     return true;
15186 
15187   // Check the exception specification.
15188   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15189     return true;
15190 
15191   return checkThisInStaticMemberFunctionAttributes(Method);
15192 }
15193 
15194 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15195   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15196   if (!TSInfo)
15197     return false;
15198 
15199   TypeLoc TL = TSInfo->getTypeLoc();
15200   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15201   if (!ProtoTL)
15202     return false;
15203 
15204   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15205   FindCXXThisExpr Finder(*this);
15206 
15207   switch (Proto->getExceptionSpecType()) {
15208   case EST_Unparsed:
15209   case EST_Uninstantiated:
15210   case EST_Unevaluated:
15211   case EST_BasicNoexcept:
15212   case EST_DynamicNone:
15213   case EST_MSAny:
15214   case EST_None:
15215     break;
15216 
15217   case EST_DependentNoexcept:
15218   case EST_NoexceptFalse:
15219   case EST_NoexceptTrue:
15220     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15221       return true;
15222     LLVM_FALLTHROUGH;
15223 
15224   case EST_Dynamic:
15225     for (const auto &E : Proto->exceptions()) {
15226       if (!Finder.TraverseType(E))
15227         return true;
15228     }
15229     break;
15230   }
15231 
15232   return false;
15233 }
15234 
15235 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15236   FindCXXThisExpr Finder(*this);
15237 
15238   // Check attributes.
15239   for (const auto *A : Method->attrs()) {
15240     // FIXME: This should be emitted by tblgen.
15241     Expr *Arg = nullptr;
15242     ArrayRef<Expr *> Args;
15243     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15244       Arg = G->getArg();
15245     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15246       Arg = G->getArg();
15247     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15248       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15249     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15250       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15251     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15252       Arg = ETLF->getSuccessValue();
15253       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15254     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15255       Arg = STLF->getSuccessValue();
15256       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15257     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15258       Arg = LR->getArg();
15259     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15260       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15261     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15262       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15263     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15264       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15265     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15266       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15267     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15268       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15269 
15270     if (Arg && !Finder.TraverseStmt(Arg))
15271       return true;
15272 
15273     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15274       if (!Finder.TraverseStmt(Args[I]))
15275         return true;
15276     }
15277   }
15278 
15279   return false;
15280 }
15281 
15282 void Sema::checkExceptionSpecification(
15283     bool IsTopLevel, ExceptionSpecificationType EST,
15284     ArrayRef<ParsedType> DynamicExceptions,
15285     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15286     SmallVectorImpl<QualType> &Exceptions,
15287     FunctionProtoType::ExceptionSpecInfo &ESI) {
15288   Exceptions.clear();
15289   ESI.Type = EST;
15290   if (EST == EST_Dynamic) {
15291     Exceptions.reserve(DynamicExceptions.size());
15292     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15293       // FIXME: Preserve type source info.
15294       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15295 
15296       if (IsTopLevel) {
15297         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15298         collectUnexpandedParameterPacks(ET, Unexpanded);
15299         if (!Unexpanded.empty()) {
15300           DiagnoseUnexpandedParameterPacks(
15301               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15302               Unexpanded);
15303           continue;
15304         }
15305       }
15306 
15307       // Check that the type is valid for an exception spec, and
15308       // drop it if not.
15309       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15310         Exceptions.push_back(ET);
15311     }
15312     ESI.Exceptions = Exceptions;
15313     return;
15314   }
15315 
15316   if (isComputedNoexcept(EST)) {
15317     assert((NoexceptExpr->isTypeDependent() ||
15318             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15319             Context.BoolTy) &&
15320            "Parser should have made sure that the expression is boolean");
15321     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15322       ESI.Type = EST_BasicNoexcept;
15323       return;
15324     }
15325 
15326     ESI.NoexceptExpr = NoexceptExpr;
15327     return;
15328   }
15329 }
15330 
15331 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15332              ExceptionSpecificationType EST,
15333              SourceRange SpecificationRange,
15334              ArrayRef<ParsedType> DynamicExceptions,
15335              ArrayRef<SourceRange> DynamicExceptionRanges,
15336              Expr *NoexceptExpr) {
15337   if (!MethodD)
15338     return;
15339 
15340   // Dig out the method we're referring to.
15341   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15342     MethodD = FunTmpl->getTemplatedDecl();
15343 
15344   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15345   if (!Method)
15346     return;
15347 
15348   // Check the exception specification.
15349   llvm::SmallVector<QualType, 4> Exceptions;
15350   FunctionProtoType::ExceptionSpecInfo ESI;
15351   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15352                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15353                               ESI);
15354 
15355   // Update the exception specification on the function type.
15356   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15357 
15358   if (Method->isStatic())
15359     checkThisInStaticMemberFunctionExceptionSpec(Method);
15360 
15361   if (Method->isVirtual()) {
15362     // Check overrides, which we previously had to delay.
15363     for (const CXXMethodDecl *O : Method->overridden_methods())
15364       CheckOverridingFunctionExceptionSpec(Method, O);
15365   }
15366 }
15367 
15368 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15369 ///
15370 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15371                                        SourceLocation DeclStart,
15372                                        Declarator &D, Expr *BitWidth,
15373                                        InClassInitStyle InitStyle,
15374                                        AccessSpecifier AS,
15375                                        AttributeList *MSPropertyAttr) {
15376   IdentifierInfo *II = D.getIdentifier();
15377   if (!II) {
15378     Diag(DeclStart, diag::err_anonymous_property);
15379     return nullptr;
15380   }
15381   SourceLocation Loc = D.getIdentifierLoc();
15382 
15383   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15384   QualType T = TInfo->getType();
15385   if (getLangOpts().CPlusPlus) {
15386     CheckExtraCXXDefaultArguments(D);
15387 
15388     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15389                                         UPPC_DataMemberType)) {
15390       D.setInvalidType();
15391       T = Context.IntTy;
15392       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15393     }
15394   }
15395 
15396   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15397 
15398   if (D.getDeclSpec().isInlineSpecified())
15399     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15400         << getLangOpts().CPlusPlus17;
15401   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15402     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15403          diag::err_invalid_thread)
15404       << DeclSpec::getSpecifierName(TSCS);
15405 
15406   // Check to see if this name was declared as a member previously
15407   NamedDecl *PrevDecl = nullptr;
15408   LookupResult Previous(*this, II, Loc, LookupMemberName,
15409                         ForVisibleRedeclaration);
15410   LookupName(Previous, S);
15411   switch (Previous.getResultKind()) {
15412   case LookupResult::Found:
15413   case LookupResult::FoundUnresolvedValue:
15414     PrevDecl = Previous.getAsSingle<NamedDecl>();
15415     break;
15416 
15417   case LookupResult::FoundOverloaded:
15418     PrevDecl = Previous.getRepresentativeDecl();
15419     break;
15420 
15421   case LookupResult::NotFound:
15422   case LookupResult::NotFoundInCurrentInstantiation:
15423   case LookupResult::Ambiguous:
15424     break;
15425   }
15426 
15427   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15428     // Maybe we will complain about the shadowed template parameter.
15429     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15430     // Just pretend that we didn't see the previous declaration.
15431     PrevDecl = nullptr;
15432   }
15433 
15434   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15435     PrevDecl = nullptr;
15436 
15437   SourceLocation TSSL = D.getLocStart();
15438   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15439   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15440       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15441   ProcessDeclAttributes(TUScope, NewPD, D);
15442   NewPD->setAccess(AS);
15443 
15444   if (NewPD->isInvalidDecl())
15445     Record->setInvalidDecl();
15446 
15447   if (D.getDeclSpec().isModulePrivateSpecified())
15448     NewPD->setModulePrivate();
15449 
15450   if (NewPD->isInvalidDecl() && PrevDecl) {
15451     // Don't introduce NewFD into scope; there's already something
15452     // with the same name in the same scope.
15453   } else if (II) {
15454     PushOnScopeChains(NewPD, S);
15455   } else
15456     Record->addDecl(NewPD);
15457 
15458   return NewPD;
15459 }
15460