1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/ComparisonCategories.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <map>
45 #include <set>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55   /// the default argument of a parameter to determine whether it
56   /// contains any ill-formed subexpressions. For example, this will
57   /// diagnose the use of local variables or parameters within the
58   /// default argument expression.
59   class CheckDefaultArgumentVisitor
60     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61     Expr *DefaultArg;
62     Sema *S;
63 
64   public:
65     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66       : DefaultArg(defarg), S(s) {}
67 
68     bool VisitExpr(Expr *Node);
69     bool VisitDeclRefExpr(DeclRefExpr *DRE);
70     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71     bool VisitLambdaExpr(LambdaExpr *Lambda);
72     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73   };
74 
75   /// VisitExpr - Visit all of the children of this expression.
76   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77     bool IsInvalid = false;
78     for (Stmt *SubStmt : Node->children())
79       IsInvalid |= Visit(SubStmt);
80     return IsInvalid;
81   }
82 
83   /// VisitDeclRefExpr - Visit a reference to a declaration, to
84   /// determine whether this declaration can be used in the default
85   /// argument expression.
86   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87     NamedDecl *Decl = DRE->getDecl();
88     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89       // C++ [dcl.fct.default]p9
90       //   Default arguments are evaluated each time the function is
91       //   called. The order of evaluation of function arguments is
92       //   unspecified. Consequently, parameters of a function shall not
93       //   be used in default argument expressions, even if they are not
94       //   evaluated. Parameters of a function declared before a default
95       //   argument expression are in scope and can hide namespace and
96       //   class member names.
97       return S->Diag(DRE->getBeginLoc(),
98                      diag::err_param_default_argument_references_param)
99              << Param->getDeclName() << DefaultArg->getSourceRange();
100     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101       // C++ [dcl.fct.default]p7
102       //   Local variables shall not be used in default argument
103       //   expressions.
104       if (VDecl->isLocalVarDecl())
105         return S->Diag(DRE->getBeginLoc(),
106                        diag::err_param_default_argument_references_local)
107                << VDecl->getDeclName() << DefaultArg->getSourceRange();
108     }
109 
110     return false;
111   }
112 
113   /// VisitCXXThisExpr - Visit a C++ "this" expression.
114   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115     // C++ [dcl.fct.default]p8:
116     //   The keyword this shall not be used in a default argument of a
117     //   member function.
118     return S->Diag(ThisE->getBeginLoc(),
119                    diag::err_param_default_argument_references_this)
120            << ThisE->getSourceRange();
121   }
122 
123   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124     bool Invalid = false;
125     for (PseudoObjectExpr::semantics_iterator
126            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127       Expr *E = *i;
128 
129       // Look through bindings.
130       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131         E = OVE->getSourceExpr();
132         assert(E && "pseudo-object binding without source expression?");
133       }
134 
135       Invalid |= Visit(E);
136     }
137     return Invalid;
138   }
139 
140   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141     // C++11 [expr.lambda.prim]p13:
142     //   A lambda-expression appearing in a default argument shall not
143     //   implicitly or explicitly capture any entity.
144     if (Lambda->capture_begin() == Lambda->capture_end())
145       return false;
146 
147     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171     EST = EST_BasicNoexcept;
172 
173   switch (EST) {
174   case EST_Unparsed:
175   case EST_Uninstantiated:
176   case EST_Unevaluated:
177     llvm_unreachable("should not see unresolved exception specs here");
178 
179   // If this function can throw any exceptions, make a note of that.
180   case EST_MSAny:
181   case EST_None:
182     // FIXME: Whichever we see last of MSAny and None determines our result.
183     // We should make a consistent, order-independent choice here.
184     ClearExceptions();
185     ComputedEST = EST;
186     return;
187   case EST_NoexceptFalse:
188     ClearExceptions();
189     ComputedEST = EST_None;
190     return;
191   // FIXME: If the call to this decl is using any of its default arguments, we
192   // need to search them for potentially-throwing calls.
193   // If this function has a basic noexcept, it doesn't affect the outcome.
194   case EST_BasicNoexcept:
195   case EST_NoexceptTrue:
196     return;
197   // If we're still at noexcept(true) and there's a throw() callee,
198   // change to that specification.
199   case EST_DynamicNone:
200     if (ComputedEST == EST_BasicNoexcept)
201       ComputedEST = EST_DynamicNone;
202     return;
203   case EST_DependentNoexcept:
204     llvm_unreachable(
205         "should not generate implicit declarations for dependent cases");
206   case EST_Dynamic:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficient, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found the right previous declaration.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter unless the new
551       // function is a friend declaration in a template class. In the latter
552       // case the default arguments will be inherited when the friend
553       // declaration will be instantiated.
554       if (New->getFriendObjectKind() == Decl::FOK_None ||
555           !New->getLexicalDeclContext()->isDependentContext()) {
556         // It's important to use getInit() here;  getDefaultArg()
557         // strips off any top-level ExprWithCleanups.
558         NewParam->setHasInheritedDefaultArg();
559         if (OldParam->hasUnparsedDefaultArg())
560           NewParam->setUnparsedDefaultArg();
561         else if (OldParam->hasUninstantiatedDefaultArg())
562           NewParam->setUninstantiatedDefaultArg(
563                                        OldParam->getUninstantiatedDefaultArg());
564         else
565           NewParam->setDefaultArg(OldParam->getInit());
566       }
567     } else if (NewParamHasDfl) {
568       if (New->getDescribedFunctionTemplate()) {
569         // Paragraph 4, quoted above, only applies to non-template functions.
570         Diag(NewParam->getLocation(),
571              diag::err_param_default_argument_template_redecl)
572           << NewParam->getDefaultArgRange();
573         Diag(PrevForDefaultArgs->getLocation(),
574              diag::note_template_prev_declaration)
575             << false;
576       } else if (New->getTemplateSpecializationKind()
577                    != TSK_ImplicitInstantiation &&
578                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
579         // C++ [temp.expr.spec]p21:
580         //   Default function arguments shall not be specified in a declaration
581         //   or a definition for one of the following explicit specializations:
582         //     - the explicit specialization of a function template;
583         //     - the explicit specialization of a member function template;
584         //     - the explicit specialization of a member function of a class
585         //       template where the class template specialization to which the
586         //       member function specialization belongs is implicitly
587         //       instantiated.
588         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590           << New->getDeclName()
591           << NewParam->getDefaultArgRange();
592       } else if (New->getDeclContext()->isDependentContext()) {
593         // C++ [dcl.fct.default]p6 (DR217):
594         //   Default arguments for a member function of a class template shall
595         //   be specified on the initial declaration of the member function
596         //   within the class template.
597         //
598         // Reading the tea leaves a bit in DR217 and its reference to DR205
599         // leads me to the conclusion that one cannot add default function
600         // arguments for an out-of-line definition of a member function of a
601         // dependent type.
602         int WhichKind = 2;
603         if (CXXRecordDecl *Record
604               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605           if (Record->getDescribedClassTemplate())
606             WhichKind = 0;
607           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608             WhichKind = 1;
609           else
610             WhichKind = 2;
611         }
612 
613         Diag(NewParam->getLocation(),
614              diag::err_param_default_argument_member_template_redecl)
615           << WhichKind
616           << NewParam->getDefaultArgRange();
617       }
618     }
619   }
620 
621   // DR1344: If a default argument is added outside a class definition and that
622   // default argument makes the function a special member function, the program
623   // is ill-formed. This can only happen for constructors.
624   if (isa<CXXConstructorDecl>(New) &&
625       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628     if (NewSM != OldSM) {
629       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630       assert(NewParam->hasDefaultArg());
631       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632         << NewParam->getDefaultArgRange() << NewSM;
633       Diag(Old->getLocation(), diag::note_previous_declaration);
634     }
635   }
636 
637   const FunctionDecl *Def;
638   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639   // template has a constexpr specifier then all its declarations shall
640   // contain the constexpr specifier.
641   if (New->isConstexpr() != Old->isConstexpr()) {
642     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643       << New << New->isConstexpr();
644     Diag(Old->getLocation(), diag::note_previous_declaration);
645     Invalid = true;
646   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647              Old->isDefined(Def) &&
648              // If a friend function is inlined but does not have 'inline'
649              // specifier, it is a definition. Do not report attribute conflict
650              // in this case, redefinition will be diagnosed later.
651              (New->isInlineSpecified() ||
652               New->getFriendObjectKind() == Decl::FOK_None)) {
653     // C++11 [dcl.fcn.spec]p4:
654     //   If the definition of a function appears in a translation unit before its
655     //   first declaration as inline, the program is ill-formed.
656     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657     Diag(Def->getLocation(), diag::note_previous_definition);
658     Invalid = true;
659   }
660 
661   // FIXME: It's not clear what should happen if multiple declarations of a
662   // deduction guide have different explicitness. For now at least we simply
663   // reject any case where the explicitness changes.
664   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
665   if (NewGuide && NewGuide->isExplicitSpecified() !=
666                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
667     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
668       << NewGuide->isExplicitSpecified();
669     Diag(Old->getLocation(), diag::note_previous_declaration);
670   }
671 
672   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673   // argument expression, that declaration shall be a definition and shall be
674   // the only declaration of the function or function template in the
675   // translation unit.
676   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677       functionDeclHasDefaultArgument(Old)) {
678     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679     Diag(Old->getLocation(), diag::note_previous_declaration);
680     Invalid = true;
681   }
682 
683   return Invalid;
684 }
685 
686 NamedDecl *
687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688                                    MultiTemplateParamsArg TemplateParamLists) {
689   assert(D.isDecompositionDeclarator());
690   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
691 
692   // The syntax only allows a decomposition declarator as a simple-declaration,
693   // a for-range-declaration, or a condition in Clang, but we parse it in more
694   // cases than that.
695   if (!D.mayHaveDecompositionDeclarator()) {
696     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697       << Decomp.getSourceRange();
698     return nullptr;
699   }
700 
701   if (!TemplateParamLists.empty()) {
702     // FIXME: There's no rule against this, but there are also no rules that
703     // would actually make it usable, so we reject it for now.
704     Diag(TemplateParamLists.front()->getTemplateLoc(),
705          diag::err_decomp_decl_template);
706     return nullptr;
707   }
708 
709   Diag(Decomp.getLSquareLoc(),
710        !getLangOpts().CPlusPlus17
711            ? diag::ext_decomp_decl
712            : D.getContext() == DeclaratorContext::ConditionContext
713                  ? diag::ext_decomp_decl_cond
714                  : diag::warn_cxx14_compat_decomp_decl)
715       << Decomp.getSourceRange();
716 
717   // The semantic context is always just the current context.
718   DeclContext *const DC = CurContext;
719 
720   // C++1z [dcl.dcl]/8:
721   //   The decl-specifier-seq shall contain only the type-specifier auto
722   //   and cv-qualifiers.
723   auto &DS = D.getDeclSpec();
724   {
725     SmallVector<StringRef, 8> BadSpecifiers;
726     SmallVector<SourceLocation, 8> BadSpecifierLocs;
727     if (auto SCS = DS.getStorageClassSpec()) {
728       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
729       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
730     }
731     if (auto TSCS = DS.getThreadStorageClassSpec()) {
732       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
733       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
734     }
735     if (DS.isConstexprSpecified()) {
736       BadSpecifiers.push_back("constexpr");
737       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
738     }
739     if (DS.isInlineSpecified()) {
740       BadSpecifiers.push_back("inline");
741       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
742     }
743     if (!BadSpecifiers.empty()) {
744       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
745       Err << (int)BadSpecifiers.size()
746           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
747       // Don't add FixItHints to remove the specifiers; we do still respect
748       // them when building the underlying variable.
749       for (auto Loc : BadSpecifierLocs)
750         Err << SourceRange(Loc, Loc);
751     }
752     // We can't recover from it being declared as a typedef.
753     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
754       return nullptr;
755   }
756 
757   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
758   QualType R = TInfo->getType();
759 
760   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
761                                       UPPC_DeclarationType))
762     D.setInvalidType();
763 
764   // The syntax only allows a single ref-qualifier prior to the decomposition
765   // declarator. No other declarator chunks are permitted. Also check the type
766   // specifier here.
767   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
768       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
769       (D.getNumTypeObjects() == 1 &&
770        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
771     Diag(Decomp.getLSquareLoc(),
772          (D.hasGroupingParens() ||
773           (D.getNumTypeObjects() &&
774            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
775              ? diag::err_decomp_decl_parens
776              : diag::err_decomp_decl_type)
777         << R;
778 
779     // In most cases, there's no actual problem with an explicitly-specified
780     // type, but a function type won't work here, and ActOnVariableDeclarator
781     // shouldn't be called for such a type.
782     if (R->isFunctionType())
783       D.setInvalidType();
784   }
785 
786   // Build the BindingDecls.
787   SmallVector<BindingDecl*, 8> Bindings;
788 
789   // Build the BindingDecls.
790   for (auto &B : D.getDecompositionDeclarator().bindings()) {
791     // Check for name conflicts.
792     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
793     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
794                           ForVisibleRedeclaration);
795     LookupName(Previous, S,
796                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
797 
798     // It's not permitted to shadow a template parameter name.
799     if (Previous.isSingleResult() &&
800         Previous.getFoundDecl()->isTemplateParameter()) {
801       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
802                                       Previous.getFoundDecl());
803       Previous.clear();
804     }
805 
806     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
807                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
808     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
809                          /*AllowInlineNamespace*/false);
810     if (!Previous.empty()) {
811       auto *Old = Previous.getRepresentativeDecl();
812       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
813       Diag(Old->getLocation(), diag::note_previous_definition);
814     }
815 
816     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
817     PushOnScopeChains(BD, S, true);
818     Bindings.push_back(BD);
819     ParsingInitForAutoVars.insert(BD);
820   }
821 
822   // There are no prior lookup results for the variable itself, because it
823   // is unnamed.
824   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
825                                Decomp.getLSquareLoc());
826   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
827                         ForVisibleRedeclaration);
828 
829   // Build the variable that holds the non-decomposed object.
830   bool AddToScope = true;
831   NamedDecl *New =
832       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
833                               MultiTemplateParamsArg(), AddToScope, Bindings);
834   if (AddToScope) {
835     S->AddDecl(New);
836     CurContext->addHiddenDecl(New);
837   }
838 
839   if (isInOpenMPDeclareTargetContext())
840     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
841 
842   return New;
843 }
844 
845 static bool checkSimpleDecomposition(
846     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
847     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
848     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
849   if ((int64_t)Bindings.size() != NumElems) {
850     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
851         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
852         << (NumElems < Bindings.size());
853     return true;
854   }
855 
856   unsigned I = 0;
857   for (auto *B : Bindings) {
858     SourceLocation Loc = B->getLocation();
859     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
860     if (E.isInvalid())
861       return true;
862     E = GetInit(Loc, E.get(), I++);
863     if (E.isInvalid())
864       return true;
865     B->setBinding(ElemType, E.get());
866   }
867 
868   return false;
869 }
870 
871 static bool checkArrayLikeDecomposition(Sema &S,
872                                         ArrayRef<BindingDecl *> Bindings,
873                                         ValueDecl *Src, QualType DecompType,
874                                         const llvm::APSInt &NumElems,
875                                         QualType ElemType) {
876   return checkSimpleDecomposition(
877       S, Bindings, Src, DecompType, NumElems, ElemType,
878       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
879         ExprResult E = S.ActOnIntegerConstant(Loc, I);
880         if (E.isInvalid())
881           return ExprError();
882         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
883       });
884 }
885 
886 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
887                                     ValueDecl *Src, QualType DecompType,
888                                     const ConstantArrayType *CAT) {
889   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
890                                      llvm::APSInt(CAT->getSize()),
891                                      CAT->getElementType());
892 }
893 
894 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
895                                      ValueDecl *Src, QualType DecompType,
896                                      const VectorType *VT) {
897   return checkArrayLikeDecomposition(
898       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
899       S.Context.getQualifiedType(VT->getElementType(),
900                                  DecompType.getQualifiers()));
901 }
902 
903 static bool checkComplexDecomposition(Sema &S,
904                                       ArrayRef<BindingDecl *> Bindings,
905                                       ValueDecl *Src, QualType DecompType,
906                                       const ComplexType *CT) {
907   return checkSimpleDecomposition(
908       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
909       S.Context.getQualifiedType(CT->getElementType(),
910                                  DecompType.getQualifiers()),
911       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
912         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
913       });
914 }
915 
916 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
917                                      TemplateArgumentListInfo &Args) {
918   SmallString<128> SS;
919   llvm::raw_svector_ostream OS(SS);
920   bool First = true;
921   for (auto &Arg : Args.arguments()) {
922     if (!First)
923       OS << ", ";
924     Arg.getArgument().print(PrintingPolicy, OS);
925     First = false;
926   }
927   return OS.str();
928 }
929 
930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
931                                      SourceLocation Loc, StringRef Trait,
932                                      TemplateArgumentListInfo &Args,
933                                      unsigned DiagID) {
934   auto DiagnoseMissing = [&] {
935     if (DiagID)
936       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
937                                                Args);
938     return true;
939   };
940 
941   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
942   NamespaceDecl *Std = S.getStdNamespace();
943   if (!Std)
944     return DiagnoseMissing();
945 
946   // Look up the trait itself, within namespace std. We can diagnose various
947   // problems with this lookup even if we've been asked to not diagnose a
948   // missing specialization, because this can only fail if the user has been
949   // declaring their own names in namespace std or we don't support the
950   // standard library implementation in use.
951   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
952                       Loc, Sema::LookupOrdinaryName);
953   if (!S.LookupQualifiedName(Result, Std))
954     return DiagnoseMissing();
955   if (Result.isAmbiguous())
956     return true;
957 
958   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
959   if (!TraitTD) {
960     Result.suppressDiagnostics();
961     NamedDecl *Found = *Result.begin();
962     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
963     S.Diag(Found->getLocation(), diag::note_declared_at);
964     return true;
965   }
966 
967   // Build the template-id.
968   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
969   if (TraitTy.isNull())
970     return true;
971   if (!S.isCompleteType(Loc, TraitTy)) {
972     if (DiagID)
973       S.RequireCompleteType(
974           Loc, TraitTy, DiagID,
975           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
976     return true;
977   }
978 
979   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
980   assert(RD && "specialization of class template is not a class?");
981 
982   // Look up the member of the trait type.
983   S.LookupQualifiedName(TraitMemberLookup, RD);
984   return TraitMemberLookup.isAmbiguous();
985 }
986 
987 static TemplateArgumentLoc
988 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
989                                    uint64_t I) {
990   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
991   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
992 }
993 
994 static TemplateArgumentLoc
995 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
996   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
997 }
998 
999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1000 
1001 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1002                                llvm::APSInt &Size) {
1003   EnterExpressionEvaluationContext ContextRAII(
1004       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1005 
1006   DeclarationName Value = S.PP.getIdentifierInfo("value");
1007   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1008 
1009   // Form template argument list for tuple_size<T>.
1010   TemplateArgumentListInfo Args(Loc, Loc);
1011   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1012 
1013   // If there's no tuple_size specialization, it's not tuple-like.
1014   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1015     return IsTupleLike::NotTupleLike;
1016 
1017   // If we get this far, we've committed to the tuple interpretation, but
1018   // we can still fail if there actually isn't a usable ::value.
1019 
1020   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1021     LookupResult &R;
1022     TemplateArgumentListInfo &Args;
1023     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1024         : R(R), Args(Args) {}
1025     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1026       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1027           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1028     }
1029   } Diagnoser(R, Args);
1030 
1031   if (R.empty()) {
1032     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1033     return IsTupleLike::Error;
1034   }
1035 
1036   ExprResult E =
1037       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1038   if (E.isInvalid())
1039     return IsTupleLike::Error;
1040 
1041   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1042   if (E.isInvalid())
1043     return IsTupleLike::Error;
1044 
1045   return IsTupleLike::TupleLike;
1046 }
1047 
1048 /// \return std::tuple_element<I, T>::type.
1049 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1050                                         unsigned I, QualType T) {
1051   // Form template argument list for tuple_element<I, T>.
1052   TemplateArgumentListInfo Args(Loc, Loc);
1053   Args.addArgument(
1054       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1055   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1056 
1057   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1058   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1059   if (lookupStdTypeTraitMember(
1060           S, R, Loc, "tuple_element", Args,
1061           diag::err_decomp_decl_std_tuple_element_not_specialized))
1062     return QualType();
1063 
1064   auto *TD = R.getAsSingle<TypeDecl>();
1065   if (!TD) {
1066     R.suppressDiagnostics();
1067     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1068       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1069     if (!R.empty())
1070       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1071     return QualType();
1072   }
1073 
1074   return S.Context.getTypeDeclType(TD);
1075 }
1076 
1077 namespace {
1078 struct BindingDiagnosticTrap {
1079   Sema &S;
1080   DiagnosticErrorTrap Trap;
1081   BindingDecl *BD;
1082 
1083   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1084       : S(S), Trap(S.Diags), BD(BD) {}
1085   ~BindingDiagnosticTrap() {
1086     if (Trap.hasErrorOccurred())
1087       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1088   }
1089 };
1090 }
1091 
1092 static bool checkTupleLikeDecomposition(Sema &S,
1093                                         ArrayRef<BindingDecl *> Bindings,
1094                                         VarDecl *Src, QualType DecompType,
1095                                         const llvm::APSInt &TupleSize) {
1096   if ((int64_t)Bindings.size() != TupleSize) {
1097     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1098         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1099         << (TupleSize < Bindings.size());
1100     return true;
1101   }
1102 
1103   if (Bindings.empty())
1104     return false;
1105 
1106   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1107 
1108   // [dcl.decomp]p3:
1109   //   The unqualified-id get is looked up in the scope of E by class member
1110   //   access lookup ...
1111   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1112   bool UseMemberGet = false;
1113   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1114     if (auto *RD = DecompType->getAsCXXRecordDecl())
1115       S.LookupQualifiedName(MemberGet, RD);
1116     if (MemberGet.isAmbiguous())
1117       return true;
1118     //   ... and if that finds at least one declaration that is a function
1119     //   template whose first template parameter is a non-type parameter ...
1120     for (NamedDecl *D : MemberGet) {
1121       if (FunctionTemplateDecl *FTD =
1122               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1123         TemplateParameterList *TPL = FTD->getTemplateParameters();
1124         if (TPL->size() != 0 &&
1125             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1126           //   ... the initializer is e.get<i>().
1127           UseMemberGet = true;
1128           break;
1129         }
1130       }
1131     }
1132     S.FilterAcceptableTemplateNames(MemberGet);
1133   }
1134 
1135   unsigned I = 0;
1136   for (auto *B : Bindings) {
1137     BindingDiagnosticTrap Trap(S, B);
1138     SourceLocation Loc = B->getLocation();
1139 
1140     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1141     if (E.isInvalid())
1142       return true;
1143 
1144     //   e is an lvalue if the type of the entity is an lvalue reference and
1145     //   an xvalue otherwise
1146     if (!Src->getType()->isLValueReferenceType())
1147       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1148                                    E.get(), nullptr, VK_XValue);
1149 
1150     TemplateArgumentListInfo Args(Loc, Loc);
1151     Args.addArgument(
1152         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1153 
1154     if (UseMemberGet) {
1155       //   if [lookup of member get] finds at least one declaration, the
1156       //   initializer is e.get<i-1>().
1157       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1158                                      CXXScopeSpec(), SourceLocation(), nullptr,
1159                                      MemberGet, &Args, nullptr);
1160       if (E.isInvalid())
1161         return true;
1162 
1163       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1164     } else {
1165       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1166       //   in the associated namespaces.
1167       Expr *Get = UnresolvedLookupExpr::Create(
1168           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1169           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1170           UnresolvedSetIterator(), UnresolvedSetIterator());
1171 
1172       Expr *Arg = E.get();
1173       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1174     }
1175     if (E.isInvalid())
1176       return true;
1177     Expr *Init = E.get();
1178 
1179     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1180     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1181     if (T.isNull())
1182       return true;
1183 
1184     //   each vi is a variable of type "reference to T" initialized with the
1185     //   initializer, where the reference is an lvalue reference if the
1186     //   initializer is an lvalue and an rvalue reference otherwise
1187     QualType RefType =
1188         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1189     if (RefType.isNull())
1190       return true;
1191     auto *RefVD = VarDecl::Create(
1192         S.Context, Src->getDeclContext(), Loc, Loc,
1193         B->getDeclName().getAsIdentifierInfo(), RefType,
1194         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1195     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1196     RefVD->setTSCSpec(Src->getTSCSpec());
1197     RefVD->setImplicit();
1198     if (Src->isInlineSpecified())
1199       RefVD->setInlineSpecified();
1200     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1201 
1202     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1203     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1204     InitializationSequence Seq(S, Entity, Kind, Init);
1205     E = Seq.Perform(S, Entity, Kind, Init);
1206     if (E.isInvalid())
1207       return true;
1208     E = S.ActOnFinishFullExpr(E.get(), Loc);
1209     if (E.isInvalid())
1210       return true;
1211     RefVD->setInit(E.get());
1212     RefVD->checkInitIsICE();
1213 
1214     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1215                                    DeclarationNameInfo(B->getDeclName(), Loc),
1216                                    RefVD);
1217     if (E.isInvalid())
1218       return true;
1219 
1220     B->setBinding(T, E.get());
1221     I++;
1222   }
1223 
1224   return false;
1225 }
1226 
1227 /// Find the base class to decompose in a built-in decomposition of a class type.
1228 /// This base class search is, unfortunately, not quite like any other that we
1229 /// perform anywhere else in C++.
1230 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1231                                                 const CXXRecordDecl *RD,
1232                                                 CXXCastPath &BasePath) {
1233   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1234                           CXXBasePath &Path) {
1235     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1236   };
1237 
1238   const CXXRecordDecl *ClassWithFields = nullptr;
1239   AccessSpecifier AS = AS_public;
1240   if (RD->hasDirectFields())
1241     // [dcl.decomp]p4:
1242     //   Otherwise, all of E's non-static data members shall be public direct
1243     //   members of E ...
1244     ClassWithFields = RD;
1245   else {
1246     //   ... or of ...
1247     CXXBasePaths Paths;
1248     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1249     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1250       // If no classes have fields, just decompose RD itself. (This will work
1251       // if and only if zero bindings were provided.)
1252       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1253     }
1254 
1255     CXXBasePath *BestPath = nullptr;
1256     for (auto &P : Paths) {
1257       if (!BestPath)
1258         BestPath = &P;
1259       else if (!S.Context.hasSameType(P.back().Base->getType(),
1260                                       BestPath->back().Base->getType())) {
1261         //   ... the same ...
1262         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1263           << false << RD << BestPath->back().Base->getType()
1264           << P.back().Base->getType();
1265         return DeclAccessPair();
1266       } else if (P.Access < BestPath->Access) {
1267         BestPath = &P;
1268       }
1269     }
1270 
1271     //   ... unambiguous ...
1272     QualType BaseType = BestPath->back().Base->getType();
1273     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1274       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1275         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1276       return DeclAccessPair();
1277     }
1278 
1279     //   ... [accessible, implied by other rules] base class of E.
1280     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1281                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1282     AS = BestPath->Access;
1283 
1284     ClassWithFields = BaseType->getAsCXXRecordDecl();
1285     S.BuildBasePathArray(Paths, BasePath);
1286   }
1287 
1288   // The above search did not check whether the selected class itself has base
1289   // classes with fields, so check that now.
1290   CXXBasePaths Paths;
1291   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293       << (ClassWithFields == RD) << RD << ClassWithFields
1294       << Paths.front().back().Base->getType();
1295     return DeclAccessPair();
1296   }
1297 
1298   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1299 }
1300 
1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302                                      ValueDecl *Src, QualType DecompType,
1303                                      const CXXRecordDecl *OrigRD) {
1304   CXXCastPath BasePath;
1305   DeclAccessPair BasePair =
1306       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1307   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1308   if (!RD)
1309     return true;
1310   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1311                                                  DecompType.getQualifiers());
1312 
1313   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1314     unsigned NumFields =
1315         std::count_if(RD->field_begin(), RD->field_end(),
1316                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1317     assert(Bindings.size() != NumFields);
1318     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1319         << DecompType << (unsigned)Bindings.size() << NumFields
1320         << (NumFields < Bindings.size());
1321     return true;
1322   };
1323 
1324   //   all of E's non-static data members shall be [...] well-formed
1325   //   when named as e.name in the context of the structured binding,
1326   //   E shall not have an anonymous union member, ...
1327   unsigned I = 0;
1328   for (auto *FD : RD->fields()) {
1329     if (FD->isUnnamedBitfield())
1330       continue;
1331 
1332     if (FD->isAnonymousStructOrUnion()) {
1333       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1334         << DecompType << FD->getType()->isUnionType();
1335       S.Diag(FD->getLocation(), diag::note_declared_at);
1336       return true;
1337     }
1338 
1339     // We have a real field to bind.
1340     if (I >= Bindings.size())
1341       return DiagnoseBadNumberOfBindings();
1342     auto *B = Bindings[I++];
1343     SourceLocation Loc = B->getLocation();
1344 
1345     // The field must be accessible in the context of the structured binding.
1346     // We already checked that the base class is accessible.
1347     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1348     // const_cast here.
1349     S.CheckStructuredBindingMemberAccess(
1350         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1351         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1352                                      BasePair.getAccess(), FD->getAccess())));
1353 
1354     // Initialize the binding to Src.FD.
1355     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1356     if (E.isInvalid())
1357       return true;
1358     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1359                             VK_LValue, &BasePath);
1360     if (E.isInvalid())
1361       return true;
1362     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1363                                   CXXScopeSpec(), FD,
1364                                   DeclAccessPair::make(FD, FD->getAccess()),
1365                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1366     if (E.isInvalid())
1367       return true;
1368 
1369     // If the type of the member is T, the referenced type is cv T, where cv is
1370     // the cv-qualification of the decomposition expression.
1371     //
1372     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1373     // 'const' to the type of the field.
1374     Qualifiers Q = DecompType.getQualifiers();
1375     if (FD->isMutable())
1376       Q.removeConst();
1377     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1378   }
1379 
1380   if (I != Bindings.size())
1381     return DiagnoseBadNumberOfBindings();
1382 
1383   return false;
1384 }
1385 
1386 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1387   QualType DecompType = DD->getType();
1388 
1389   // If the type of the decomposition is dependent, then so is the type of
1390   // each binding.
1391   if (DecompType->isDependentType()) {
1392     for (auto *B : DD->bindings())
1393       B->setType(Context.DependentTy);
1394     return;
1395   }
1396 
1397   DecompType = DecompType.getNonReferenceType();
1398   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1399 
1400   // C++1z [dcl.decomp]/2:
1401   //   If E is an array type [...]
1402   // As an extension, we also support decomposition of built-in complex and
1403   // vector types.
1404   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1405     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1406       DD->setInvalidDecl();
1407     return;
1408   }
1409   if (auto *VT = DecompType->getAs<VectorType>()) {
1410     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1411       DD->setInvalidDecl();
1412     return;
1413   }
1414   if (auto *CT = DecompType->getAs<ComplexType>()) {
1415     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1416       DD->setInvalidDecl();
1417     return;
1418   }
1419 
1420   // C++1z [dcl.decomp]/3:
1421   //   if the expression std::tuple_size<E>::value is a well-formed integral
1422   //   constant expression, [...]
1423   llvm::APSInt TupleSize(32);
1424   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1425   case IsTupleLike::Error:
1426     DD->setInvalidDecl();
1427     return;
1428 
1429   case IsTupleLike::TupleLike:
1430     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1431       DD->setInvalidDecl();
1432     return;
1433 
1434   case IsTupleLike::NotTupleLike:
1435     break;
1436   }
1437 
1438   // C++1z [dcl.dcl]/8:
1439   //   [E shall be of array or non-union class type]
1440   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1441   if (!RD || RD->isUnion()) {
1442     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1443         << DD << !RD << DecompType;
1444     DD->setInvalidDecl();
1445     return;
1446   }
1447 
1448   // C++1z [dcl.decomp]/4:
1449   //   all of E's non-static data members shall be [...] direct members of
1450   //   E or of the same unambiguous public base class of E, ...
1451   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1452     DD->setInvalidDecl();
1453 }
1454 
1455 /// Merge the exception specifications of two variable declarations.
1456 ///
1457 /// This is called when there's a redeclaration of a VarDecl. The function
1458 /// checks if the redeclaration might have an exception specification and
1459 /// validates compatibility and merges the specs if necessary.
1460 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1461   // Shortcut if exceptions are disabled.
1462   if (!getLangOpts().CXXExceptions)
1463     return;
1464 
1465   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1466          "Should only be called if types are otherwise the same.");
1467 
1468   QualType NewType = New->getType();
1469   QualType OldType = Old->getType();
1470 
1471   // We're only interested in pointers and references to functions, as well
1472   // as pointers to member functions.
1473   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1474     NewType = R->getPointeeType();
1475     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1476   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1477     NewType = P->getPointeeType();
1478     OldType = OldType->getAs<PointerType>()->getPointeeType();
1479   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1480     NewType = M->getPointeeType();
1481     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1482   }
1483 
1484   if (!NewType->isFunctionProtoType())
1485     return;
1486 
1487   // There's lots of special cases for functions. For function pointers, system
1488   // libraries are hopefully not as broken so that we don't need these
1489   // workarounds.
1490   if (CheckEquivalentExceptionSpec(
1491         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1492         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1493     New->setInvalidDecl();
1494   }
1495 }
1496 
1497 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1498 /// function declaration are well-formed according to C++
1499 /// [dcl.fct.default].
1500 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1501   unsigned NumParams = FD->getNumParams();
1502   unsigned p;
1503 
1504   // Find first parameter with a default argument
1505   for (p = 0; p < NumParams; ++p) {
1506     ParmVarDecl *Param = FD->getParamDecl(p);
1507     if (Param->hasDefaultArg())
1508       break;
1509   }
1510 
1511   // C++11 [dcl.fct.default]p4:
1512   //   In a given function declaration, each parameter subsequent to a parameter
1513   //   with a default argument shall have a default argument supplied in this or
1514   //   a previous declaration or shall be a function parameter pack. A default
1515   //   argument shall not be redefined by a later declaration (not even to the
1516   //   same value).
1517   unsigned LastMissingDefaultArg = 0;
1518   for (; p < NumParams; ++p) {
1519     ParmVarDecl *Param = FD->getParamDecl(p);
1520     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1521       if (Param->isInvalidDecl())
1522         /* We already complained about this parameter. */;
1523       else if (Param->getIdentifier())
1524         Diag(Param->getLocation(),
1525              diag::err_param_default_argument_missing_name)
1526           << Param->getIdentifier();
1527       else
1528         Diag(Param->getLocation(),
1529              diag::err_param_default_argument_missing);
1530 
1531       LastMissingDefaultArg = p;
1532     }
1533   }
1534 
1535   if (LastMissingDefaultArg > 0) {
1536     // Some default arguments were missing. Clear out all of the
1537     // default arguments up to (and including) the last missing
1538     // default argument, so that we leave the function parameters
1539     // in a semantically valid state.
1540     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1541       ParmVarDecl *Param = FD->getParamDecl(p);
1542       if (Param->hasDefaultArg()) {
1543         Param->setDefaultArg(nullptr);
1544       }
1545     }
1546   }
1547 }
1548 
1549 // CheckConstexprParameterTypes - Check whether a function's parameter types
1550 // are all literal types. If so, return true. If not, produce a suitable
1551 // diagnostic and return false.
1552 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1553                                          const FunctionDecl *FD) {
1554   unsigned ArgIndex = 0;
1555   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1556   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1557                                               e = FT->param_type_end();
1558        i != e; ++i, ++ArgIndex) {
1559     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1560     SourceLocation ParamLoc = PD->getLocation();
1561     if (!(*i)->isDependentType() &&
1562         SemaRef.RequireLiteralType(ParamLoc, *i,
1563                                    diag::err_constexpr_non_literal_param,
1564                                    ArgIndex+1, PD->getSourceRange(),
1565                                    isa<CXXConstructorDecl>(FD)))
1566       return false;
1567   }
1568   return true;
1569 }
1570 
1571 /// Get diagnostic %select index for tag kind for
1572 /// record diagnostic message.
1573 /// WARNING: Indexes apply to particular diagnostics only!
1574 ///
1575 /// \returns diagnostic %select index.
1576 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1577   switch (Tag) {
1578   case TTK_Struct: return 0;
1579   case TTK_Interface: return 1;
1580   case TTK_Class:  return 2;
1581   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1582   }
1583 }
1584 
1585 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1586 // the requirements of a constexpr function definition or a constexpr
1587 // constructor definition. If so, return true. If not, produce appropriate
1588 // diagnostics and return false.
1589 //
1590 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1591 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1592   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1593   if (MD && MD->isInstance()) {
1594     // C++11 [dcl.constexpr]p4:
1595     //  The definition of a constexpr constructor shall satisfy the following
1596     //  constraints:
1597     //  - the class shall not have any virtual base classes;
1598     const CXXRecordDecl *RD = MD->getParent();
1599     if (RD->getNumVBases()) {
1600       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1601         << isa<CXXConstructorDecl>(NewFD)
1602         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1603       for (const auto &I : RD->vbases())
1604         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1605             << I.getSourceRange();
1606       return false;
1607     }
1608   }
1609 
1610   if (!isa<CXXConstructorDecl>(NewFD)) {
1611     // C++11 [dcl.constexpr]p3:
1612     //  The definition of a constexpr function shall satisfy the following
1613     //  constraints:
1614     // - it shall not be virtual;
1615     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1616     if (Method && Method->isVirtual()) {
1617       Method = Method->getCanonicalDecl();
1618       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1619 
1620       // If it's not obvious why this function is virtual, find an overridden
1621       // function which uses the 'virtual' keyword.
1622       const CXXMethodDecl *WrittenVirtual = Method;
1623       while (!WrittenVirtual->isVirtualAsWritten())
1624         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1625       if (WrittenVirtual != Method)
1626         Diag(WrittenVirtual->getLocation(),
1627              diag::note_overridden_virtual_function);
1628       return false;
1629     }
1630 
1631     // - its return type shall be a literal type;
1632     QualType RT = NewFD->getReturnType();
1633     if (!RT->isDependentType() &&
1634         RequireLiteralType(NewFD->getLocation(), RT,
1635                            diag::err_constexpr_non_literal_return))
1636       return false;
1637   }
1638 
1639   // - each of its parameter types shall be a literal type;
1640   if (!CheckConstexprParameterTypes(*this, NewFD))
1641     return false;
1642 
1643   return true;
1644 }
1645 
1646 /// Check the given declaration statement is legal within a constexpr function
1647 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1648 ///
1649 /// \return true if the body is OK (maybe only as an extension), false if we
1650 ///         have diagnosed a problem.
1651 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1652                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1653   // C++11 [dcl.constexpr]p3 and p4:
1654   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1655   //  contain only
1656   for (const auto *DclIt : DS->decls()) {
1657     switch (DclIt->getKind()) {
1658     case Decl::StaticAssert:
1659     case Decl::Using:
1660     case Decl::UsingShadow:
1661     case Decl::UsingDirective:
1662     case Decl::UnresolvedUsingTypename:
1663     case Decl::UnresolvedUsingValue:
1664       //   - static_assert-declarations
1665       //   - using-declarations,
1666       //   - using-directives,
1667       continue;
1668 
1669     case Decl::Typedef:
1670     case Decl::TypeAlias: {
1671       //   - typedef declarations and alias-declarations that do not define
1672       //     classes or enumerations,
1673       const auto *TN = cast<TypedefNameDecl>(DclIt);
1674       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1675         // Don't allow variably-modified types in constexpr functions.
1676         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1677         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1678           << TL.getSourceRange() << TL.getType()
1679           << isa<CXXConstructorDecl>(Dcl);
1680         return false;
1681       }
1682       continue;
1683     }
1684 
1685     case Decl::Enum:
1686     case Decl::CXXRecord:
1687       // C++1y allows types to be defined, not just declared.
1688       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1689         SemaRef.Diag(DS->getBeginLoc(),
1690                      SemaRef.getLangOpts().CPlusPlus14
1691                          ? diag::warn_cxx11_compat_constexpr_type_definition
1692                          : diag::ext_constexpr_type_definition)
1693             << isa<CXXConstructorDecl>(Dcl);
1694       continue;
1695 
1696     case Decl::EnumConstant:
1697     case Decl::IndirectField:
1698     case Decl::ParmVar:
1699       // These can only appear with other declarations which are banned in
1700       // C++11 and permitted in C++1y, so ignore them.
1701       continue;
1702 
1703     case Decl::Var:
1704     case Decl::Decomposition: {
1705       // C++1y [dcl.constexpr]p3 allows anything except:
1706       //   a definition of a variable of non-literal type or of static or
1707       //   thread storage duration or for which no initialization is performed.
1708       const auto *VD = cast<VarDecl>(DclIt);
1709       if (VD->isThisDeclarationADefinition()) {
1710         if (VD->isStaticLocal()) {
1711           SemaRef.Diag(VD->getLocation(),
1712                        diag::err_constexpr_local_var_static)
1713             << isa<CXXConstructorDecl>(Dcl)
1714             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1715           return false;
1716         }
1717         if (!VD->getType()->isDependentType() &&
1718             SemaRef.RequireLiteralType(
1719               VD->getLocation(), VD->getType(),
1720               diag::err_constexpr_local_var_non_literal_type,
1721               isa<CXXConstructorDecl>(Dcl)))
1722           return false;
1723         if (!VD->getType()->isDependentType() &&
1724             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1725           SemaRef.Diag(VD->getLocation(),
1726                        diag::err_constexpr_local_var_no_init)
1727             << isa<CXXConstructorDecl>(Dcl);
1728           return false;
1729         }
1730       }
1731       SemaRef.Diag(VD->getLocation(),
1732                    SemaRef.getLangOpts().CPlusPlus14
1733                     ? diag::warn_cxx11_compat_constexpr_local_var
1734                     : diag::ext_constexpr_local_var)
1735         << isa<CXXConstructorDecl>(Dcl);
1736       continue;
1737     }
1738 
1739     case Decl::NamespaceAlias:
1740     case Decl::Function:
1741       // These are disallowed in C++11 and permitted in C++1y. Allow them
1742       // everywhere as an extension.
1743       if (!Cxx1yLoc.isValid())
1744         Cxx1yLoc = DS->getBeginLoc();
1745       continue;
1746 
1747     default:
1748       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1749           << isa<CXXConstructorDecl>(Dcl);
1750       return false;
1751     }
1752   }
1753 
1754   return true;
1755 }
1756 
1757 /// Check that the given field is initialized within a constexpr constructor.
1758 ///
1759 /// \param Dcl The constexpr constructor being checked.
1760 /// \param Field The field being checked. This may be a member of an anonymous
1761 ///        struct or union nested within the class being checked.
1762 /// \param Inits All declarations, including anonymous struct/union members and
1763 ///        indirect members, for which any initialization was provided.
1764 /// \param Diagnosed Set to true if an error is produced.
1765 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1766                                           const FunctionDecl *Dcl,
1767                                           FieldDecl *Field,
1768                                           llvm::SmallSet<Decl*, 16> &Inits,
1769                                           bool &Diagnosed) {
1770   if (Field->isInvalidDecl())
1771     return;
1772 
1773   if (Field->isUnnamedBitfield())
1774     return;
1775 
1776   // Anonymous unions with no variant members and empty anonymous structs do not
1777   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1778   // indirect fields don't need initializing.
1779   if (Field->isAnonymousStructOrUnion() &&
1780       (Field->getType()->isUnionType()
1781            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1782            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1783     return;
1784 
1785   if (!Inits.count(Field)) {
1786     if (!Diagnosed) {
1787       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1788       Diagnosed = true;
1789     }
1790     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1791   } else if (Field->isAnonymousStructOrUnion()) {
1792     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1793     for (auto *I : RD->fields())
1794       // If an anonymous union contains an anonymous struct of which any member
1795       // is initialized, all members must be initialized.
1796       if (!RD->isUnion() || Inits.count(I))
1797         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1798   }
1799 }
1800 
1801 /// Check the provided statement is allowed in a constexpr function
1802 /// definition.
1803 static bool
1804 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1805                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1806                            SourceLocation &Cxx1yLoc) {
1807   // - its function-body shall be [...] a compound-statement that contains only
1808   switch (S->getStmtClass()) {
1809   case Stmt::NullStmtClass:
1810     //   - null statements,
1811     return true;
1812 
1813   case Stmt::DeclStmtClass:
1814     //   - static_assert-declarations
1815     //   - using-declarations,
1816     //   - using-directives,
1817     //   - typedef declarations and alias-declarations that do not define
1818     //     classes or enumerations,
1819     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1820       return false;
1821     return true;
1822 
1823   case Stmt::ReturnStmtClass:
1824     //   - and exactly one return statement;
1825     if (isa<CXXConstructorDecl>(Dcl)) {
1826       // C++1y allows return statements in constexpr constructors.
1827       if (!Cxx1yLoc.isValid())
1828         Cxx1yLoc = S->getBeginLoc();
1829       return true;
1830     }
1831 
1832     ReturnStmts.push_back(S->getBeginLoc());
1833     return true;
1834 
1835   case Stmt::CompoundStmtClass: {
1836     // C++1y allows compound-statements.
1837     if (!Cxx1yLoc.isValid())
1838       Cxx1yLoc = S->getBeginLoc();
1839 
1840     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1841     for (auto *BodyIt : CompStmt->body()) {
1842       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1843                                       Cxx1yLoc))
1844         return false;
1845     }
1846     return true;
1847   }
1848 
1849   case Stmt::AttributedStmtClass:
1850     if (!Cxx1yLoc.isValid())
1851       Cxx1yLoc = S->getBeginLoc();
1852     return true;
1853 
1854   case Stmt::IfStmtClass: {
1855     // C++1y allows if-statements.
1856     if (!Cxx1yLoc.isValid())
1857       Cxx1yLoc = S->getBeginLoc();
1858 
1859     IfStmt *If = cast<IfStmt>(S);
1860     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1861                                     Cxx1yLoc))
1862       return false;
1863     if (If->getElse() &&
1864         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1865                                     Cxx1yLoc))
1866       return false;
1867     return true;
1868   }
1869 
1870   case Stmt::WhileStmtClass:
1871   case Stmt::DoStmtClass:
1872   case Stmt::ForStmtClass:
1873   case Stmt::CXXForRangeStmtClass:
1874   case Stmt::ContinueStmtClass:
1875     // C++1y allows all of these. We don't allow them as extensions in C++11,
1876     // because they don't make sense without variable mutation.
1877     if (!SemaRef.getLangOpts().CPlusPlus14)
1878       break;
1879     if (!Cxx1yLoc.isValid())
1880       Cxx1yLoc = S->getBeginLoc();
1881     for (Stmt *SubStmt : S->children())
1882       if (SubStmt &&
1883           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1884                                       Cxx1yLoc))
1885         return false;
1886     return true;
1887 
1888   case Stmt::SwitchStmtClass:
1889   case Stmt::CaseStmtClass:
1890   case Stmt::DefaultStmtClass:
1891   case Stmt::BreakStmtClass:
1892     // C++1y allows switch-statements, and since they don't need variable
1893     // mutation, we can reasonably allow them in C++11 as an extension.
1894     if (!Cxx1yLoc.isValid())
1895       Cxx1yLoc = S->getBeginLoc();
1896     for (Stmt *SubStmt : S->children())
1897       if (SubStmt &&
1898           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1899                                       Cxx1yLoc))
1900         return false;
1901     return true;
1902 
1903   default:
1904     if (!isa<Expr>(S))
1905       break;
1906 
1907     // C++1y allows expression-statements.
1908     if (!Cxx1yLoc.isValid())
1909       Cxx1yLoc = S->getBeginLoc();
1910     return true;
1911   }
1912 
1913   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1914       << isa<CXXConstructorDecl>(Dcl);
1915   return false;
1916 }
1917 
1918 /// Check the body for the given constexpr function declaration only contains
1919 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1920 ///
1921 /// \return true if the body is OK, false if we have diagnosed a problem.
1922 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1923   if (isa<CXXTryStmt>(Body)) {
1924     // C++11 [dcl.constexpr]p3:
1925     //  The definition of a constexpr function shall satisfy the following
1926     //  constraints: [...]
1927     // - its function-body shall be = delete, = default, or a
1928     //   compound-statement
1929     //
1930     // C++11 [dcl.constexpr]p4:
1931     //  In the definition of a constexpr constructor, [...]
1932     // - its function-body shall not be a function-try-block;
1933     Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block)
1934         << isa<CXXConstructorDecl>(Dcl);
1935     return false;
1936   }
1937 
1938   SmallVector<SourceLocation, 4> ReturnStmts;
1939 
1940   // - its function-body shall be [...] a compound-statement that contains only
1941   //   [... list of cases ...]
1942   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1943   SourceLocation Cxx1yLoc;
1944   for (auto *BodyIt : CompBody->body()) {
1945     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1946       return false;
1947   }
1948 
1949   if (Cxx1yLoc.isValid())
1950     Diag(Cxx1yLoc,
1951          getLangOpts().CPlusPlus14
1952            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1953            : diag::ext_constexpr_body_invalid_stmt)
1954       << isa<CXXConstructorDecl>(Dcl);
1955 
1956   if (const CXXConstructorDecl *Constructor
1957         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1958     const CXXRecordDecl *RD = Constructor->getParent();
1959     // DR1359:
1960     // - every non-variant non-static data member and base class sub-object
1961     //   shall be initialized;
1962     // DR1460:
1963     // - if the class is a union having variant members, exactly one of them
1964     //   shall be initialized;
1965     if (RD->isUnion()) {
1966       if (Constructor->getNumCtorInitializers() == 0 &&
1967           RD->hasVariantMembers()) {
1968         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1969         return false;
1970       }
1971     } else if (!Constructor->isDependentContext() &&
1972                !Constructor->isDelegatingConstructor()) {
1973       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1974 
1975       // Skip detailed checking if we have enough initializers, and we would
1976       // allow at most one initializer per member.
1977       bool AnyAnonStructUnionMembers = false;
1978       unsigned Fields = 0;
1979       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1980            E = RD->field_end(); I != E; ++I, ++Fields) {
1981         if (I->isAnonymousStructOrUnion()) {
1982           AnyAnonStructUnionMembers = true;
1983           break;
1984         }
1985       }
1986       // DR1460:
1987       // - if the class is a union-like class, but is not a union, for each of
1988       //   its anonymous union members having variant members, exactly one of
1989       //   them shall be initialized;
1990       if (AnyAnonStructUnionMembers ||
1991           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1992         // Check initialization of non-static data members. Base classes are
1993         // always initialized so do not need to be checked. Dependent bases
1994         // might not have initializers in the member initializer list.
1995         llvm::SmallSet<Decl*, 16> Inits;
1996         for (const auto *I: Constructor->inits()) {
1997           if (FieldDecl *FD = I->getMember())
1998             Inits.insert(FD);
1999           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2000             Inits.insert(ID->chain_begin(), ID->chain_end());
2001         }
2002 
2003         bool Diagnosed = false;
2004         for (auto *I : RD->fields())
2005           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2006         if (Diagnosed)
2007           return false;
2008       }
2009     }
2010   } else {
2011     if (ReturnStmts.empty()) {
2012       // C++1y doesn't require constexpr functions to contain a 'return'
2013       // statement. We still do, unless the return type might be void, because
2014       // otherwise if there's no return statement, the function cannot
2015       // be used in a core constant expression.
2016       bool OK = getLangOpts().CPlusPlus14 &&
2017                 (Dcl->getReturnType()->isVoidType() ||
2018                  Dcl->getReturnType()->isDependentType());
2019       Diag(Dcl->getLocation(),
2020            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2021               : diag::err_constexpr_body_no_return);
2022       if (!OK)
2023         return false;
2024     } else if (ReturnStmts.size() > 1) {
2025       Diag(ReturnStmts.back(),
2026            getLangOpts().CPlusPlus14
2027              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2028              : diag::ext_constexpr_body_multiple_return);
2029       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2030         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2031     }
2032   }
2033 
2034   // C++11 [dcl.constexpr]p5:
2035   //   if no function argument values exist such that the function invocation
2036   //   substitution would produce a constant expression, the program is
2037   //   ill-formed; no diagnostic required.
2038   // C++11 [dcl.constexpr]p3:
2039   //   - every constructor call and implicit conversion used in initializing the
2040   //     return value shall be one of those allowed in a constant expression.
2041   // C++11 [dcl.constexpr]p4:
2042   //   - every constructor involved in initializing non-static data members and
2043   //     base class sub-objects shall be a constexpr constructor.
2044   SmallVector<PartialDiagnosticAt, 8> Diags;
2045   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2046     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2047       << isa<CXXConstructorDecl>(Dcl);
2048     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2049       Diag(Diags[I].first, Diags[I].second);
2050     // Don't return false here: we allow this for compatibility in
2051     // system headers.
2052   }
2053 
2054   return true;
2055 }
2056 
2057 /// Get the class that is directly named by the current context. This is the
2058 /// class for which an unqualified-id in this scope could name a constructor
2059 /// or destructor.
2060 ///
2061 /// If the scope specifier denotes a class, this will be that class.
2062 /// If the scope specifier is empty, this will be the class whose
2063 /// member-specification we are currently within. Otherwise, there
2064 /// is no such class.
2065 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2066   assert(getLangOpts().CPlusPlus && "No class names in C!");
2067 
2068   if (SS && SS->isInvalid())
2069     return nullptr;
2070 
2071   if (SS && SS->isNotEmpty()) {
2072     DeclContext *DC = computeDeclContext(*SS, true);
2073     return dyn_cast_or_null<CXXRecordDecl>(DC);
2074   }
2075 
2076   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2077 }
2078 
2079 /// isCurrentClassName - Determine whether the identifier II is the
2080 /// name of the class type currently being defined. In the case of
2081 /// nested classes, this will only return true if II is the name of
2082 /// the innermost class.
2083 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2084                               const CXXScopeSpec *SS) {
2085   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2086   return CurDecl && &II == CurDecl->getIdentifier();
2087 }
2088 
2089 /// Determine whether the identifier II is a typo for the name of
2090 /// the class type currently being defined. If so, update it to the identifier
2091 /// that should have been used.
2092 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2093   assert(getLangOpts().CPlusPlus && "No class names in C!");
2094 
2095   if (!getLangOpts().SpellChecking)
2096     return false;
2097 
2098   CXXRecordDecl *CurDecl;
2099   if (SS && SS->isSet() && !SS->isInvalid()) {
2100     DeclContext *DC = computeDeclContext(*SS, true);
2101     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2102   } else
2103     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2104 
2105   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2106       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2107           < II->getLength()) {
2108     II = CurDecl->getIdentifier();
2109     return true;
2110   }
2111 
2112   return false;
2113 }
2114 
2115 /// Determine whether the given class is a base class of the given
2116 /// class, including looking at dependent bases.
2117 static bool findCircularInheritance(const CXXRecordDecl *Class,
2118                                     const CXXRecordDecl *Current) {
2119   SmallVector<const CXXRecordDecl*, 8> Queue;
2120 
2121   Class = Class->getCanonicalDecl();
2122   while (true) {
2123     for (const auto &I : Current->bases()) {
2124       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2125       if (!Base)
2126         continue;
2127 
2128       Base = Base->getDefinition();
2129       if (!Base)
2130         continue;
2131 
2132       if (Base->getCanonicalDecl() == Class)
2133         return true;
2134 
2135       Queue.push_back(Base);
2136     }
2137 
2138     if (Queue.empty())
2139       return false;
2140 
2141     Current = Queue.pop_back_val();
2142   }
2143 
2144   return false;
2145 }
2146 
2147 /// Check the validity of a C++ base class specifier.
2148 ///
2149 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2150 /// and returns NULL otherwise.
2151 CXXBaseSpecifier *
2152 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2153                          SourceRange SpecifierRange,
2154                          bool Virtual, AccessSpecifier Access,
2155                          TypeSourceInfo *TInfo,
2156                          SourceLocation EllipsisLoc) {
2157   QualType BaseType = TInfo->getType();
2158 
2159   // C++ [class.union]p1:
2160   //   A union shall not have base classes.
2161   if (Class->isUnion()) {
2162     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2163       << SpecifierRange;
2164     return nullptr;
2165   }
2166 
2167   if (EllipsisLoc.isValid() &&
2168       !TInfo->getType()->containsUnexpandedParameterPack()) {
2169     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2170       << TInfo->getTypeLoc().getSourceRange();
2171     EllipsisLoc = SourceLocation();
2172   }
2173 
2174   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2175 
2176   if (BaseType->isDependentType()) {
2177     // Make sure that we don't have circular inheritance among our dependent
2178     // bases. For non-dependent bases, the check for completeness below handles
2179     // this.
2180     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2181       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2182           ((BaseDecl = BaseDecl->getDefinition()) &&
2183            findCircularInheritance(Class, BaseDecl))) {
2184         Diag(BaseLoc, diag::err_circular_inheritance)
2185           << BaseType << Context.getTypeDeclType(Class);
2186 
2187         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2188           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2189             << BaseType;
2190 
2191         return nullptr;
2192       }
2193     }
2194 
2195     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2196                                           Class->getTagKind() == TTK_Class,
2197                                           Access, TInfo, EllipsisLoc);
2198   }
2199 
2200   // Base specifiers must be record types.
2201   if (!BaseType->isRecordType()) {
2202     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2203     return nullptr;
2204   }
2205 
2206   // C++ [class.union]p1:
2207   //   A union shall not be used as a base class.
2208   if (BaseType->isUnionType()) {
2209     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2210     return nullptr;
2211   }
2212 
2213   // For the MS ABI, propagate DLL attributes to base class templates.
2214   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2215     if (Attr *ClassAttr = getDLLAttr(Class)) {
2216       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2217               BaseType->getAsCXXRecordDecl())) {
2218         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2219                                             BaseLoc);
2220       }
2221     }
2222   }
2223 
2224   // C++ [class.derived]p2:
2225   //   The class-name in a base-specifier shall not be an incompletely
2226   //   defined class.
2227   if (RequireCompleteType(BaseLoc, BaseType,
2228                           diag::err_incomplete_base_class, SpecifierRange)) {
2229     Class->setInvalidDecl();
2230     return nullptr;
2231   }
2232 
2233   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2234   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2235   assert(BaseDecl && "Record type has no declaration");
2236   BaseDecl = BaseDecl->getDefinition();
2237   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2238   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2239   assert(CXXBaseDecl && "Base type is not a C++ type");
2240 
2241   // Microsoft docs say:
2242   // "If a base-class has a code_seg attribute, derived classes must have the
2243   // same attribute."
2244   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2245   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2246   if ((DerivedCSA || BaseCSA) &&
2247       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2248     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2249     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2250       << CXXBaseDecl;
2251     return nullptr;
2252   }
2253 
2254   // A class which contains a flexible array member is not suitable for use as a
2255   // base class:
2256   //   - If the layout determines that a base comes before another base,
2257   //     the flexible array member would index into the subsequent base.
2258   //   - If the layout determines that base comes before the derived class,
2259   //     the flexible array member would index into the derived class.
2260   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2261     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2262       << CXXBaseDecl->getDeclName();
2263     return nullptr;
2264   }
2265 
2266   // C++ [class]p3:
2267   //   If a class is marked final and it appears as a base-type-specifier in
2268   //   base-clause, the program is ill-formed.
2269   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2270     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2271       << CXXBaseDecl->getDeclName()
2272       << FA->isSpelledAsSealed();
2273     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2274         << CXXBaseDecl->getDeclName() << FA->getRange();
2275     return nullptr;
2276   }
2277 
2278   if (BaseDecl->isInvalidDecl())
2279     Class->setInvalidDecl();
2280 
2281   // Create the base specifier.
2282   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2283                                         Class->getTagKind() == TTK_Class,
2284                                         Access, TInfo, EllipsisLoc);
2285 }
2286 
2287 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2288 /// one entry in the base class list of a class specifier, for
2289 /// example:
2290 ///    class foo : public bar, virtual private baz {
2291 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2292 BaseResult
2293 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2294                          ParsedAttributes &Attributes,
2295                          bool Virtual, AccessSpecifier Access,
2296                          ParsedType basetype, SourceLocation BaseLoc,
2297                          SourceLocation EllipsisLoc) {
2298   if (!classdecl)
2299     return true;
2300 
2301   AdjustDeclIfTemplate(classdecl);
2302   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2303   if (!Class)
2304     return true;
2305 
2306   // We haven't yet attached the base specifiers.
2307   Class->setIsParsingBaseSpecifiers();
2308 
2309   // We do not support any C++11 attributes on base-specifiers yet.
2310   // Diagnose any attributes we see.
2311   for (const ParsedAttr &AL : Attributes) {
2312     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2313       continue;
2314     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2315                           ? diag::warn_unknown_attribute_ignored
2316                           : diag::err_base_specifier_attribute)
2317         << AL.getName();
2318   }
2319 
2320   TypeSourceInfo *TInfo = nullptr;
2321   GetTypeFromParser(basetype, &TInfo);
2322 
2323   if (EllipsisLoc.isInvalid() &&
2324       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2325                                       UPPC_BaseType))
2326     return true;
2327 
2328   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2329                                                       Virtual, Access, TInfo,
2330                                                       EllipsisLoc))
2331     return BaseSpec;
2332   else
2333     Class->setInvalidDecl();
2334 
2335   return true;
2336 }
2337 
2338 /// Use small set to collect indirect bases.  As this is only used
2339 /// locally, there's no need to abstract the small size parameter.
2340 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2341 
2342 /// Recursively add the bases of Type.  Don't add Type itself.
2343 static void
2344 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2345                   const QualType &Type)
2346 {
2347   // Even though the incoming type is a base, it might not be
2348   // a class -- it could be a template parm, for instance.
2349   if (auto Rec = Type->getAs<RecordType>()) {
2350     auto Decl = Rec->getAsCXXRecordDecl();
2351 
2352     // Iterate over its bases.
2353     for (const auto &BaseSpec : Decl->bases()) {
2354       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2355         .getUnqualifiedType();
2356       if (Set.insert(Base).second)
2357         // If we've not already seen it, recurse.
2358         NoteIndirectBases(Context, Set, Base);
2359     }
2360   }
2361 }
2362 
2363 /// Performs the actual work of attaching the given base class
2364 /// specifiers to a C++ class.
2365 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2366                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2367  if (Bases.empty())
2368     return false;
2369 
2370   // Used to keep track of which base types we have already seen, so
2371   // that we can properly diagnose redundant direct base types. Note
2372   // that the key is always the unqualified canonical type of the base
2373   // class.
2374   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2375 
2376   // Used to track indirect bases so we can see if a direct base is
2377   // ambiguous.
2378   IndirectBaseSet IndirectBaseTypes;
2379 
2380   // Copy non-redundant base specifiers into permanent storage.
2381   unsigned NumGoodBases = 0;
2382   bool Invalid = false;
2383   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2384     QualType NewBaseType
2385       = Context.getCanonicalType(Bases[idx]->getType());
2386     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2387 
2388     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2389     if (KnownBase) {
2390       // C++ [class.mi]p3:
2391       //   A class shall not be specified as a direct base class of a
2392       //   derived class more than once.
2393       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2394           << KnownBase->getType() << Bases[idx]->getSourceRange();
2395 
2396       // Delete the duplicate base class specifier; we're going to
2397       // overwrite its pointer later.
2398       Context.Deallocate(Bases[idx]);
2399 
2400       Invalid = true;
2401     } else {
2402       // Okay, add this new base class.
2403       KnownBase = Bases[idx];
2404       Bases[NumGoodBases++] = Bases[idx];
2405 
2406       // Note this base's direct & indirect bases, if there could be ambiguity.
2407       if (Bases.size() > 1)
2408         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2409 
2410       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2411         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2412         if (Class->isInterface() &&
2413               (!RD->isInterfaceLike() ||
2414                KnownBase->getAccessSpecifier() != AS_public)) {
2415           // The Microsoft extension __interface does not permit bases that
2416           // are not themselves public interfaces.
2417           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2418               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2419               << RD->getSourceRange();
2420           Invalid = true;
2421         }
2422         if (RD->hasAttr<WeakAttr>())
2423           Class->addAttr(WeakAttr::CreateImplicit(Context));
2424       }
2425     }
2426   }
2427 
2428   // Attach the remaining base class specifiers to the derived class.
2429   Class->setBases(Bases.data(), NumGoodBases);
2430 
2431   // Check that the only base classes that are duplicate are virtual.
2432   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2433     // Check whether this direct base is inaccessible due to ambiguity.
2434     QualType BaseType = Bases[idx]->getType();
2435 
2436     // Skip all dependent types in templates being used as base specifiers.
2437     // Checks below assume that the base specifier is a CXXRecord.
2438     if (BaseType->isDependentType())
2439       continue;
2440 
2441     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2442       .getUnqualifiedType();
2443 
2444     if (IndirectBaseTypes.count(CanonicalBase)) {
2445       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2446                          /*DetectVirtual=*/true);
2447       bool found
2448         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2449       assert(found);
2450       (void)found;
2451 
2452       if (Paths.isAmbiguous(CanonicalBase))
2453         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2454             << BaseType << getAmbiguousPathsDisplayString(Paths)
2455             << Bases[idx]->getSourceRange();
2456       else
2457         assert(Bases[idx]->isVirtual());
2458     }
2459 
2460     // Delete the base class specifier, since its data has been copied
2461     // into the CXXRecordDecl.
2462     Context.Deallocate(Bases[idx]);
2463   }
2464 
2465   return Invalid;
2466 }
2467 
2468 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2469 /// class, after checking whether there are any duplicate base
2470 /// classes.
2471 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2472                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2473   if (!ClassDecl || Bases.empty())
2474     return;
2475 
2476   AdjustDeclIfTemplate(ClassDecl);
2477   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2478 }
2479 
2480 /// Determine whether the type \p Derived is a C++ class that is
2481 /// derived from the type \p Base.
2482 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2483   if (!getLangOpts().CPlusPlus)
2484     return false;
2485 
2486   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2487   if (!DerivedRD)
2488     return false;
2489 
2490   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2491   if (!BaseRD)
2492     return false;
2493 
2494   // If either the base or the derived type is invalid, don't try to
2495   // check whether one is derived from the other.
2496   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2497     return false;
2498 
2499   // FIXME: In a modules build, do we need the entire path to be visible for us
2500   // to be able to use the inheritance relationship?
2501   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2502     return false;
2503 
2504   return DerivedRD->isDerivedFrom(BaseRD);
2505 }
2506 
2507 /// Determine whether the type \p Derived is a C++ class that is
2508 /// derived from the type \p Base.
2509 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2510                          CXXBasePaths &Paths) {
2511   if (!getLangOpts().CPlusPlus)
2512     return false;
2513 
2514   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2515   if (!DerivedRD)
2516     return false;
2517 
2518   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2519   if (!BaseRD)
2520     return false;
2521 
2522   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2523     return false;
2524 
2525   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2526 }
2527 
2528 static void BuildBasePathArray(const CXXBasePath &Path,
2529                                CXXCastPath &BasePathArray) {
2530   // We first go backward and check if we have a virtual base.
2531   // FIXME: It would be better if CXXBasePath had the base specifier for
2532   // the nearest virtual base.
2533   unsigned Start = 0;
2534   for (unsigned I = Path.size(); I != 0; --I) {
2535     if (Path[I - 1].Base->isVirtual()) {
2536       Start = I - 1;
2537       break;
2538     }
2539   }
2540 
2541   // Now add all bases.
2542   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2543     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2544 }
2545 
2546 
2547 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2548                               CXXCastPath &BasePathArray) {
2549   assert(BasePathArray.empty() && "Base path array must be empty!");
2550   assert(Paths.isRecordingPaths() && "Must record paths!");
2551   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2552 }
2553 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2554 /// conversion (where Derived and Base are class types) is
2555 /// well-formed, meaning that the conversion is unambiguous (and
2556 /// that all of the base classes are accessible). Returns true
2557 /// and emits a diagnostic if the code is ill-formed, returns false
2558 /// otherwise. Loc is the location where this routine should point to
2559 /// if there is an error, and Range is the source range to highlight
2560 /// if there is an error.
2561 ///
2562 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2563 /// diagnostic for the respective type of error will be suppressed, but the
2564 /// check for ill-formed code will still be performed.
2565 bool
2566 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2567                                    unsigned InaccessibleBaseID,
2568                                    unsigned AmbigiousBaseConvID,
2569                                    SourceLocation Loc, SourceRange Range,
2570                                    DeclarationName Name,
2571                                    CXXCastPath *BasePath,
2572                                    bool IgnoreAccess) {
2573   // First, determine whether the path from Derived to Base is
2574   // ambiguous. This is slightly more expensive than checking whether
2575   // the Derived to Base conversion exists, because here we need to
2576   // explore multiple paths to determine if there is an ambiguity.
2577   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2578                      /*DetectVirtual=*/false);
2579   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2580   if (!DerivationOkay)
2581     return true;
2582 
2583   const CXXBasePath *Path = nullptr;
2584   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2585     Path = &Paths.front();
2586 
2587   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2588   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2589   // user to access such bases.
2590   if (!Path && getLangOpts().MSVCCompat) {
2591     for (const CXXBasePath &PossiblePath : Paths) {
2592       if (PossiblePath.size() == 1) {
2593         Path = &PossiblePath;
2594         if (AmbigiousBaseConvID)
2595           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2596               << Base << Derived << Range;
2597         break;
2598       }
2599     }
2600   }
2601 
2602   if (Path) {
2603     if (!IgnoreAccess) {
2604       // Check that the base class can be accessed.
2605       switch (
2606           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2607       case AR_inaccessible:
2608         return true;
2609       case AR_accessible:
2610       case AR_dependent:
2611       case AR_delayed:
2612         break;
2613       }
2614     }
2615 
2616     // Build a base path if necessary.
2617     if (BasePath)
2618       ::BuildBasePathArray(*Path, *BasePath);
2619     return false;
2620   }
2621 
2622   if (AmbigiousBaseConvID) {
2623     // We know that the derived-to-base conversion is ambiguous, and
2624     // we're going to produce a diagnostic. Perform the derived-to-base
2625     // search just one more time to compute all of the possible paths so
2626     // that we can print them out. This is more expensive than any of
2627     // the previous derived-to-base checks we've done, but at this point
2628     // performance isn't as much of an issue.
2629     Paths.clear();
2630     Paths.setRecordingPaths(true);
2631     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2632     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2633     (void)StillOkay;
2634 
2635     // Build up a textual representation of the ambiguous paths, e.g.,
2636     // D -> B -> A, that will be used to illustrate the ambiguous
2637     // conversions in the diagnostic. We only print one of the paths
2638     // to each base class subobject.
2639     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2640 
2641     Diag(Loc, AmbigiousBaseConvID)
2642     << Derived << Base << PathDisplayStr << Range << Name;
2643   }
2644   return true;
2645 }
2646 
2647 bool
2648 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2649                                    SourceLocation Loc, SourceRange Range,
2650                                    CXXCastPath *BasePath,
2651                                    bool IgnoreAccess) {
2652   return CheckDerivedToBaseConversion(
2653       Derived, Base, diag::err_upcast_to_inaccessible_base,
2654       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2655       BasePath, IgnoreAccess);
2656 }
2657 
2658 
2659 /// Builds a string representing ambiguous paths from a
2660 /// specific derived class to different subobjects of the same base
2661 /// class.
2662 ///
2663 /// This function builds a string that can be used in error messages
2664 /// to show the different paths that one can take through the
2665 /// inheritance hierarchy to go from the derived class to different
2666 /// subobjects of a base class. The result looks something like this:
2667 /// @code
2668 /// struct D -> struct B -> struct A
2669 /// struct D -> struct C -> struct A
2670 /// @endcode
2671 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2672   std::string PathDisplayStr;
2673   std::set<unsigned> DisplayedPaths;
2674   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2675        Path != Paths.end(); ++Path) {
2676     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2677       // We haven't displayed a path to this particular base
2678       // class subobject yet.
2679       PathDisplayStr += "\n    ";
2680       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2681       for (CXXBasePath::const_iterator Element = Path->begin();
2682            Element != Path->end(); ++Element)
2683         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2684     }
2685   }
2686 
2687   return PathDisplayStr;
2688 }
2689 
2690 //===----------------------------------------------------------------------===//
2691 // C++ class member Handling
2692 //===----------------------------------------------------------------------===//
2693 
2694 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2695 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2696                                 SourceLocation ColonLoc,
2697                                 const ParsedAttributesView &Attrs) {
2698   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2699   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2700                                                   ASLoc, ColonLoc);
2701   CurContext->addHiddenDecl(ASDecl);
2702   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2703 }
2704 
2705 /// CheckOverrideControl - Check C++11 override control semantics.
2706 void Sema::CheckOverrideControl(NamedDecl *D) {
2707   if (D->isInvalidDecl())
2708     return;
2709 
2710   // We only care about "override" and "final" declarations.
2711   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2712     return;
2713 
2714   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2715 
2716   // We can't check dependent instance methods.
2717   if (MD && MD->isInstance() &&
2718       (MD->getParent()->hasAnyDependentBases() ||
2719        MD->getType()->isDependentType()))
2720     return;
2721 
2722   if (MD && !MD->isVirtual()) {
2723     // If we have a non-virtual method, check if if hides a virtual method.
2724     // (In that case, it's most likely the method has the wrong type.)
2725     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2726     FindHiddenVirtualMethods(MD, OverloadedMethods);
2727 
2728     if (!OverloadedMethods.empty()) {
2729       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2730         Diag(OA->getLocation(),
2731              diag::override_keyword_hides_virtual_member_function)
2732           << "override" << (OverloadedMethods.size() > 1);
2733       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2734         Diag(FA->getLocation(),
2735              diag::override_keyword_hides_virtual_member_function)
2736           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2737           << (OverloadedMethods.size() > 1);
2738       }
2739       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2740       MD->setInvalidDecl();
2741       return;
2742     }
2743     // Fall through into the general case diagnostic.
2744     // FIXME: We might want to attempt typo correction here.
2745   }
2746 
2747   if (!MD || !MD->isVirtual()) {
2748     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2749       Diag(OA->getLocation(),
2750            diag::override_keyword_only_allowed_on_virtual_member_functions)
2751         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2752       D->dropAttr<OverrideAttr>();
2753     }
2754     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2755       Diag(FA->getLocation(),
2756            diag::override_keyword_only_allowed_on_virtual_member_functions)
2757         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2758         << FixItHint::CreateRemoval(FA->getLocation());
2759       D->dropAttr<FinalAttr>();
2760     }
2761     return;
2762   }
2763 
2764   // C++11 [class.virtual]p5:
2765   //   If a function is marked with the virt-specifier override and
2766   //   does not override a member function of a base class, the program is
2767   //   ill-formed.
2768   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2769   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2770     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2771       << MD->getDeclName();
2772 }
2773 
2774 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2775   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2776     return;
2777   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2778   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2779     return;
2780 
2781   SourceLocation Loc = MD->getLocation();
2782   SourceLocation SpellingLoc = Loc;
2783   if (getSourceManager().isMacroArgExpansion(Loc))
2784     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2785   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2786   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2787       return;
2788 
2789   if (MD->size_overridden_methods() > 0) {
2790     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2791                           ? diag::warn_destructor_marked_not_override_overriding
2792                           : diag::warn_function_marked_not_override_overriding;
2793     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2794     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2795     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2796   }
2797 }
2798 
2799 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2800 /// function overrides a virtual member function marked 'final', according to
2801 /// C++11 [class.virtual]p4.
2802 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2803                                                   const CXXMethodDecl *Old) {
2804   FinalAttr *FA = Old->getAttr<FinalAttr>();
2805   if (!FA)
2806     return false;
2807 
2808   Diag(New->getLocation(), diag::err_final_function_overridden)
2809     << New->getDeclName()
2810     << FA->isSpelledAsSealed();
2811   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2812   return true;
2813 }
2814 
2815 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2816   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2817   // FIXME: Destruction of ObjC lifetime types has side-effects.
2818   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2819     return !RD->isCompleteDefinition() ||
2820            !RD->hasTrivialDefaultConstructor() ||
2821            !RD->hasTrivialDestructor();
2822   return false;
2823 }
2824 
2825 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2826   ParsedAttributesView::const_iterator Itr =
2827       llvm::find_if(list, [](const ParsedAttr &AL) {
2828         return AL.isDeclspecPropertyAttribute();
2829       });
2830   if (Itr != list.end())
2831     return &*Itr;
2832   return nullptr;
2833 }
2834 
2835 // Check if there is a field shadowing.
2836 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2837                                       DeclarationName FieldName,
2838                                       const CXXRecordDecl *RD,
2839                                       bool DeclIsField) {
2840   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2841     return;
2842 
2843   // To record a shadowed field in a base
2844   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2845   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2846                            CXXBasePath &Path) {
2847     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2848     // Record an ambiguous path directly
2849     if (Bases.find(Base) != Bases.end())
2850       return true;
2851     for (const auto Field : Base->lookup(FieldName)) {
2852       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2853           Field->getAccess() != AS_private) {
2854         assert(Field->getAccess() != AS_none);
2855         assert(Bases.find(Base) == Bases.end());
2856         Bases[Base] = Field;
2857         return true;
2858       }
2859     }
2860     return false;
2861   };
2862 
2863   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2864                      /*DetectVirtual=*/true);
2865   if (!RD->lookupInBases(FieldShadowed, Paths))
2866     return;
2867 
2868   for (const auto &P : Paths) {
2869     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2870     auto It = Bases.find(Base);
2871     // Skip duplicated bases
2872     if (It == Bases.end())
2873       continue;
2874     auto BaseField = It->second;
2875     assert(BaseField->getAccess() != AS_private);
2876     if (AS_none !=
2877         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2878       Diag(Loc, diag::warn_shadow_field)
2879         << FieldName << RD << Base << DeclIsField;
2880       Diag(BaseField->getLocation(), diag::note_shadow_field);
2881       Bases.erase(It);
2882     }
2883   }
2884 }
2885 
2886 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2887 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2888 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2889 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2890 /// present (but parsing it has been deferred).
2891 NamedDecl *
2892 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2893                                MultiTemplateParamsArg TemplateParameterLists,
2894                                Expr *BW, const VirtSpecifiers &VS,
2895                                InClassInitStyle InitStyle) {
2896   const DeclSpec &DS = D.getDeclSpec();
2897   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2898   DeclarationName Name = NameInfo.getName();
2899   SourceLocation Loc = NameInfo.getLoc();
2900 
2901   // For anonymous bitfields, the location should point to the type.
2902   if (Loc.isInvalid())
2903     Loc = D.getBeginLoc();
2904 
2905   Expr *BitWidth = static_cast<Expr*>(BW);
2906 
2907   assert(isa<CXXRecordDecl>(CurContext));
2908   assert(!DS.isFriendSpecified());
2909 
2910   bool isFunc = D.isDeclarationOfFunction();
2911   const ParsedAttr *MSPropertyAttr =
2912       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2913 
2914   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2915     // The Microsoft extension __interface only permits public member functions
2916     // and prohibits constructors, destructors, operators, non-public member
2917     // functions, static methods and data members.
2918     unsigned InvalidDecl;
2919     bool ShowDeclName = true;
2920     if (!isFunc &&
2921         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2922       InvalidDecl = 0;
2923     else if (!isFunc)
2924       InvalidDecl = 1;
2925     else if (AS != AS_public)
2926       InvalidDecl = 2;
2927     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2928       InvalidDecl = 3;
2929     else switch (Name.getNameKind()) {
2930       case DeclarationName::CXXConstructorName:
2931         InvalidDecl = 4;
2932         ShowDeclName = false;
2933         break;
2934 
2935       case DeclarationName::CXXDestructorName:
2936         InvalidDecl = 5;
2937         ShowDeclName = false;
2938         break;
2939 
2940       case DeclarationName::CXXOperatorName:
2941       case DeclarationName::CXXConversionFunctionName:
2942         InvalidDecl = 6;
2943         break;
2944 
2945       default:
2946         InvalidDecl = 0;
2947         break;
2948     }
2949 
2950     if (InvalidDecl) {
2951       if (ShowDeclName)
2952         Diag(Loc, diag::err_invalid_member_in_interface)
2953           << (InvalidDecl-1) << Name;
2954       else
2955         Diag(Loc, diag::err_invalid_member_in_interface)
2956           << (InvalidDecl-1) << "";
2957       return nullptr;
2958     }
2959   }
2960 
2961   // C++ 9.2p6: A member shall not be declared to have automatic storage
2962   // duration (auto, register) or with the extern storage-class-specifier.
2963   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2964   // data members and cannot be applied to names declared const or static,
2965   // and cannot be applied to reference members.
2966   switch (DS.getStorageClassSpec()) {
2967   case DeclSpec::SCS_unspecified:
2968   case DeclSpec::SCS_typedef:
2969   case DeclSpec::SCS_static:
2970     break;
2971   case DeclSpec::SCS_mutable:
2972     if (isFunc) {
2973       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2974 
2975       // FIXME: It would be nicer if the keyword was ignored only for this
2976       // declarator. Otherwise we could get follow-up errors.
2977       D.getMutableDeclSpec().ClearStorageClassSpecs();
2978     }
2979     break;
2980   default:
2981     Diag(DS.getStorageClassSpecLoc(),
2982          diag::err_storageclass_invalid_for_member);
2983     D.getMutableDeclSpec().ClearStorageClassSpecs();
2984     break;
2985   }
2986 
2987   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2988                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2989                       !isFunc);
2990 
2991   if (DS.isConstexprSpecified() && isInstField) {
2992     SemaDiagnosticBuilder B =
2993         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2994     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2995     if (InitStyle == ICIS_NoInit) {
2996       B << 0 << 0;
2997       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2998         B << FixItHint::CreateRemoval(ConstexprLoc);
2999       else {
3000         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3001         D.getMutableDeclSpec().ClearConstexprSpec();
3002         const char *PrevSpec;
3003         unsigned DiagID;
3004         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3005             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3006         (void)Failed;
3007         assert(!Failed && "Making a constexpr member const shouldn't fail");
3008       }
3009     } else {
3010       B << 1;
3011       const char *PrevSpec;
3012       unsigned DiagID;
3013       if (D.getMutableDeclSpec().SetStorageClassSpec(
3014           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3015           Context.getPrintingPolicy())) {
3016         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3017                "This is the only DeclSpec that should fail to be applied");
3018         B << 1;
3019       } else {
3020         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3021         isInstField = false;
3022       }
3023     }
3024   }
3025 
3026   NamedDecl *Member;
3027   if (isInstField) {
3028     CXXScopeSpec &SS = D.getCXXScopeSpec();
3029 
3030     // Data members must have identifiers for names.
3031     if (!Name.isIdentifier()) {
3032       Diag(Loc, diag::err_bad_variable_name)
3033         << Name;
3034       return nullptr;
3035     }
3036 
3037     IdentifierInfo *II = Name.getAsIdentifierInfo();
3038 
3039     // Member field could not be with "template" keyword.
3040     // So TemplateParameterLists should be empty in this case.
3041     if (TemplateParameterLists.size()) {
3042       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3043       if (TemplateParams->size()) {
3044         // There is no such thing as a member field template.
3045         Diag(D.getIdentifierLoc(), diag::err_template_member)
3046             << II
3047             << SourceRange(TemplateParams->getTemplateLoc(),
3048                 TemplateParams->getRAngleLoc());
3049       } else {
3050         // There is an extraneous 'template<>' for this member.
3051         Diag(TemplateParams->getTemplateLoc(),
3052             diag::err_template_member_noparams)
3053             << II
3054             << SourceRange(TemplateParams->getTemplateLoc(),
3055                 TemplateParams->getRAngleLoc());
3056       }
3057       return nullptr;
3058     }
3059 
3060     if (SS.isSet() && !SS.isInvalid()) {
3061       // The user provided a superfluous scope specifier inside a class
3062       // definition:
3063       //
3064       // class X {
3065       //   int X::member;
3066       // };
3067       if (DeclContext *DC = computeDeclContext(SS, false))
3068         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3069                                      D.getName().getKind() ==
3070                                          UnqualifiedIdKind::IK_TemplateId);
3071       else
3072         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3073           << Name << SS.getRange();
3074 
3075       SS.clear();
3076     }
3077 
3078     if (MSPropertyAttr) {
3079       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3080                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3081       if (!Member)
3082         return nullptr;
3083       isInstField = false;
3084     } else {
3085       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3086                                 BitWidth, InitStyle, AS);
3087       if (!Member)
3088         return nullptr;
3089     }
3090 
3091     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3092   } else {
3093     Member = HandleDeclarator(S, D, TemplateParameterLists);
3094     if (!Member)
3095       return nullptr;
3096 
3097     // Non-instance-fields can't have a bitfield.
3098     if (BitWidth) {
3099       if (Member->isInvalidDecl()) {
3100         // don't emit another diagnostic.
3101       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3102         // C++ 9.6p3: A bit-field shall not be a static member.
3103         // "static member 'A' cannot be a bit-field"
3104         Diag(Loc, diag::err_static_not_bitfield)
3105           << Name << BitWidth->getSourceRange();
3106       } else if (isa<TypedefDecl>(Member)) {
3107         // "typedef member 'x' cannot be a bit-field"
3108         Diag(Loc, diag::err_typedef_not_bitfield)
3109           << Name << BitWidth->getSourceRange();
3110       } else {
3111         // A function typedef ("typedef int f(); f a;").
3112         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3113         Diag(Loc, diag::err_not_integral_type_bitfield)
3114           << Name << cast<ValueDecl>(Member)->getType()
3115           << BitWidth->getSourceRange();
3116       }
3117 
3118       BitWidth = nullptr;
3119       Member->setInvalidDecl();
3120     }
3121 
3122     NamedDecl *NonTemplateMember = Member;
3123     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3124       NonTemplateMember = FunTmpl->getTemplatedDecl();
3125     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3126       NonTemplateMember = VarTmpl->getTemplatedDecl();
3127 
3128     Member->setAccess(AS);
3129 
3130     // If we have declared a member function template or static data member
3131     // template, set the access of the templated declaration as well.
3132     if (NonTemplateMember != Member)
3133       NonTemplateMember->setAccess(AS);
3134 
3135     // C++ [temp.deduct.guide]p3:
3136     //   A deduction guide [...] for a member class template [shall be
3137     //   declared] with the same access [as the template].
3138     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3139       auto *TD = DG->getDeducedTemplate();
3140       if (AS != TD->getAccess()) {
3141         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3142         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3143             << TD->getAccess();
3144         const AccessSpecDecl *LastAccessSpec = nullptr;
3145         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3146           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3147             LastAccessSpec = AccessSpec;
3148         }
3149         assert(LastAccessSpec && "differing access with no access specifier");
3150         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3151             << AS;
3152       }
3153     }
3154   }
3155 
3156   if (VS.isOverrideSpecified())
3157     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3158   if (VS.isFinalSpecified())
3159     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3160                                             VS.isFinalSpelledSealed()));
3161 
3162   if (VS.getLastLocation().isValid()) {
3163     // Update the end location of a method that has a virt-specifiers.
3164     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3165       MD->setRangeEnd(VS.getLastLocation());
3166   }
3167 
3168   CheckOverrideControl(Member);
3169 
3170   assert((Name || isInstField) && "No identifier for non-field ?");
3171 
3172   if (isInstField) {
3173     FieldDecl *FD = cast<FieldDecl>(Member);
3174     FieldCollector->Add(FD);
3175 
3176     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3177       // Remember all explicit private FieldDecls that have a name, no side
3178       // effects and are not part of a dependent type declaration.
3179       if (!FD->isImplicit() && FD->getDeclName() &&
3180           FD->getAccess() == AS_private &&
3181           !FD->hasAttr<UnusedAttr>() &&
3182           !FD->getParent()->isDependentContext() &&
3183           !InitializationHasSideEffects(*FD))
3184         UnusedPrivateFields.insert(FD);
3185     }
3186   }
3187 
3188   return Member;
3189 }
3190 
3191 namespace {
3192   class UninitializedFieldVisitor
3193       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3194     Sema &S;
3195     // List of Decls to generate a warning on.  Also remove Decls that become
3196     // initialized.
3197     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3198     // List of base classes of the record.  Classes are removed after their
3199     // initializers.
3200     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3201     // Vector of decls to be removed from the Decl set prior to visiting the
3202     // nodes.  These Decls may have been initialized in the prior initializer.
3203     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3204     // If non-null, add a note to the warning pointing back to the constructor.
3205     const CXXConstructorDecl *Constructor;
3206     // Variables to hold state when processing an initializer list.  When
3207     // InitList is true, special case initialization of FieldDecls matching
3208     // InitListFieldDecl.
3209     bool InitList;
3210     FieldDecl *InitListFieldDecl;
3211     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3212 
3213   public:
3214     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3215     UninitializedFieldVisitor(Sema &S,
3216                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3217                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3218       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3219         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3220 
3221     // Returns true if the use of ME is not an uninitialized use.
3222     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3223                                          bool CheckReferenceOnly) {
3224       llvm::SmallVector<FieldDecl*, 4> Fields;
3225       bool ReferenceField = false;
3226       while (ME) {
3227         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3228         if (!FD)
3229           return false;
3230         Fields.push_back(FD);
3231         if (FD->getType()->isReferenceType())
3232           ReferenceField = true;
3233         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3234       }
3235 
3236       // Binding a reference to an unintialized field is not an
3237       // uninitialized use.
3238       if (CheckReferenceOnly && !ReferenceField)
3239         return true;
3240 
3241       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3242       // Discard the first field since it is the field decl that is being
3243       // initialized.
3244       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3245         UsedFieldIndex.push_back((*I)->getFieldIndex());
3246       }
3247 
3248       for (auto UsedIter = UsedFieldIndex.begin(),
3249                 UsedEnd = UsedFieldIndex.end(),
3250                 OrigIter = InitFieldIndex.begin(),
3251                 OrigEnd = InitFieldIndex.end();
3252            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3253         if (*UsedIter < *OrigIter)
3254           return true;
3255         if (*UsedIter > *OrigIter)
3256           break;
3257       }
3258 
3259       return false;
3260     }
3261 
3262     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3263                           bool AddressOf) {
3264       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3265         return;
3266 
3267       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3268       // or union.
3269       MemberExpr *FieldME = ME;
3270 
3271       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3272 
3273       Expr *Base = ME;
3274       while (MemberExpr *SubME =
3275                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3276 
3277         if (isa<VarDecl>(SubME->getMemberDecl()))
3278           return;
3279 
3280         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3281           if (!FD->isAnonymousStructOrUnion())
3282             FieldME = SubME;
3283 
3284         if (!FieldME->getType().isPODType(S.Context))
3285           AllPODFields = false;
3286 
3287         Base = SubME->getBase();
3288       }
3289 
3290       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3291         return;
3292 
3293       if (AddressOf && AllPODFields)
3294         return;
3295 
3296       ValueDecl* FoundVD = FieldME->getMemberDecl();
3297 
3298       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3299         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3300           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3301         }
3302 
3303         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3304           QualType T = BaseCast->getType();
3305           if (T->isPointerType() &&
3306               BaseClasses.count(T->getPointeeType())) {
3307             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3308                 << T->getPointeeType() << FoundVD;
3309           }
3310         }
3311       }
3312 
3313       if (!Decls.count(FoundVD))
3314         return;
3315 
3316       const bool IsReference = FoundVD->getType()->isReferenceType();
3317 
3318       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3319         // Special checking for initializer lists.
3320         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3321           return;
3322         }
3323       } else {
3324         // Prevent double warnings on use of unbounded references.
3325         if (CheckReferenceOnly && !IsReference)
3326           return;
3327       }
3328 
3329       unsigned diag = IsReference
3330           ? diag::warn_reference_field_is_uninit
3331           : diag::warn_field_is_uninit;
3332       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3333       if (Constructor)
3334         S.Diag(Constructor->getLocation(),
3335                diag::note_uninit_in_this_constructor)
3336           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3337 
3338     }
3339 
3340     void HandleValue(Expr *E, bool AddressOf) {
3341       E = E->IgnoreParens();
3342 
3343       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3344         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3345                          AddressOf /*AddressOf*/);
3346         return;
3347       }
3348 
3349       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3350         Visit(CO->getCond());
3351         HandleValue(CO->getTrueExpr(), AddressOf);
3352         HandleValue(CO->getFalseExpr(), AddressOf);
3353         return;
3354       }
3355 
3356       if (BinaryConditionalOperator *BCO =
3357               dyn_cast<BinaryConditionalOperator>(E)) {
3358         Visit(BCO->getCond());
3359         HandleValue(BCO->getFalseExpr(), AddressOf);
3360         return;
3361       }
3362 
3363       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3364         HandleValue(OVE->getSourceExpr(), AddressOf);
3365         return;
3366       }
3367 
3368       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3369         switch (BO->getOpcode()) {
3370         default:
3371           break;
3372         case(BO_PtrMemD):
3373         case(BO_PtrMemI):
3374           HandleValue(BO->getLHS(), AddressOf);
3375           Visit(BO->getRHS());
3376           return;
3377         case(BO_Comma):
3378           Visit(BO->getLHS());
3379           HandleValue(BO->getRHS(), AddressOf);
3380           return;
3381         }
3382       }
3383 
3384       Visit(E);
3385     }
3386 
3387     void CheckInitListExpr(InitListExpr *ILE) {
3388       InitFieldIndex.push_back(0);
3389       for (auto Child : ILE->children()) {
3390         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3391           CheckInitListExpr(SubList);
3392         } else {
3393           Visit(Child);
3394         }
3395         ++InitFieldIndex.back();
3396       }
3397       InitFieldIndex.pop_back();
3398     }
3399 
3400     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3401                           FieldDecl *Field, const Type *BaseClass) {
3402       // Remove Decls that may have been initialized in the previous
3403       // initializer.
3404       for (ValueDecl* VD : DeclsToRemove)
3405         Decls.erase(VD);
3406       DeclsToRemove.clear();
3407 
3408       Constructor = FieldConstructor;
3409       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3410 
3411       if (ILE && Field) {
3412         InitList = true;
3413         InitListFieldDecl = Field;
3414         InitFieldIndex.clear();
3415         CheckInitListExpr(ILE);
3416       } else {
3417         InitList = false;
3418         Visit(E);
3419       }
3420 
3421       if (Field)
3422         Decls.erase(Field);
3423       if (BaseClass)
3424         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3425     }
3426 
3427     void VisitMemberExpr(MemberExpr *ME) {
3428       // All uses of unbounded reference fields will warn.
3429       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3430     }
3431 
3432     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3433       if (E->getCastKind() == CK_LValueToRValue) {
3434         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3435         return;
3436       }
3437 
3438       Inherited::VisitImplicitCastExpr(E);
3439     }
3440 
3441     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3442       if (E->getConstructor()->isCopyConstructor()) {
3443         Expr *ArgExpr = E->getArg(0);
3444         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3445           if (ILE->getNumInits() == 1)
3446             ArgExpr = ILE->getInit(0);
3447         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3448           if (ICE->getCastKind() == CK_NoOp)
3449             ArgExpr = ICE->getSubExpr();
3450         HandleValue(ArgExpr, false /*AddressOf*/);
3451         return;
3452       }
3453       Inherited::VisitCXXConstructExpr(E);
3454     }
3455 
3456     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3457       Expr *Callee = E->getCallee();
3458       if (isa<MemberExpr>(Callee)) {
3459         HandleValue(Callee, false /*AddressOf*/);
3460         for (auto Arg : E->arguments())
3461           Visit(Arg);
3462         return;
3463       }
3464 
3465       Inherited::VisitCXXMemberCallExpr(E);
3466     }
3467 
3468     void VisitCallExpr(CallExpr *E) {
3469       // Treat std::move as a use.
3470       if (E->isCallToStdMove()) {
3471         HandleValue(E->getArg(0), /*AddressOf=*/false);
3472         return;
3473       }
3474 
3475       Inherited::VisitCallExpr(E);
3476     }
3477 
3478     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3479       Expr *Callee = E->getCallee();
3480 
3481       if (isa<UnresolvedLookupExpr>(Callee))
3482         return Inherited::VisitCXXOperatorCallExpr(E);
3483 
3484       Visit(Callee);
3485       for (auto Arg : E->arguments())
3486         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3487     }
3488 
3489     void VisitBinaryOperator(BinaryOperator *E) {
3490       // If a field assignment is detected, remove the field from the
3491       // uninitiailized field set.
3492       if (E->getOpcode() == BO_Assign)
3493         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3494           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3495             if (!FD->getType()->isReferenceType())
3496               DeclsToRemove.push_back(FD);
3497 
3498       if (E->isCompoundAssignmentOp()) {
3499         HandleValue(E->getLHS(), false /*AddressOf*/);
3500         Visit(E->getRHS());
3501         return;
3502       }
3503 
3504       Inherited::VisitBinaryOperator(E);
3505     }
3506 
3507     void VisitUnaryOperator(UnaryOperator *E) {
3508       if (E->isIncrementDecrementOp()) {
3509         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3510         return;
3511       }
3512       if (E->getOpcode() == UO_AddrOf) {
3513         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3514           HandleValue(ME->getBase(), true /*AddressOf*/);
3515           return;
3516         }
3517       }
3518 
3519       Inherited::VisitUnaryOperator(E);
3520     }
3521   };
3522 
3523   // Diagnose value-uses of fields to initialize themselves, e.g.
3524   //   foo(foo)
3525   // where foo is not also a parameter to the constructor.
3526   // Also diagnose across field uninitialized use such as
3527   //   x(y), y(x)
3528   // TODO: implement -Wuninitialized and fold this into that framework.
3529   static void DiagnoseUninitializedFields(
3530       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3531 
3532     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3533                                            Constructor->getLocation())) {
3534       return;
3535     }
3536 
3537     if (Constructor->isInvalidDecl())
3538       return;
3539 
3540     const CXXRecordDecl *RD = Constructor->getParent();
3541 
3542     if (RD->getDescribedClassTemplate())
3543       return;
3544 
3545     // Holds fields that are uninitialized.
3546     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3547 
3548     // At the beginning, all fields are uninitialized.
3549     for (auto *I : RD->decls()) {
3550       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3551         UninitializedFields.insert(FD);
3552       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3553         UninitializedFields.insert(IFD->getAnonField());
3554       }
3555     }
3556 
3557     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3558     for (auto I : RD->bases())
3559       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3560 
3561     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3562       return;
3563 
3564     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3565                                                    UninitializedFields,
3566                                                    UninitializedBaseClasses);
3567 
3568     for (const auto *FieldInit : Constructor->inits()) {
3569       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3570         break;
3571 
3572       Expr *InitExpr = FieldInit->getInit();
3573       if (!InitExpr)
3574         continue;
3575 
3576       if (CXXDefaultInitExpr *Default =
3577               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3578         InitExpr = Default->getExpr();
3579         if (!InitExpr)
3580           continue;
3581         // In class initializers will point to the constructor.
3582         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3583                                               FieldInit->getAnyMember(),
3584                                               FieldInit->getBaseClass());
3585       } else {
3586         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3587                                               FieldInit->getAnyMember(),
3588                                               FieldInit->getBaseClass());
3589       }
3590     }
3591   }
3592 } // namespace
3593 
3594 /// Enter a new C++ default initializer scope. After calling this, the
3595 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3596 /// parsing or instantiating the initializer failed.
3597 void Sema::ActOnStartCXXInClassMemberInitializer() {
3598   // Create a synthetic function scope to represent the call to the constructor
3599   // that notionally surrounds a use of this initializer.
3600   PushFunctionScope();
3601 }
3602 
3603 /// This is invoked after parsing an in-class initializer for a
3604 /// non-static C++ class member, and after instantiating an in-class initializer
3605 /// in a class template. Such actions are deferred until the class is complete.
3606 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3607                                                   SourceLocation InitLoc,
3608                                                   Expr *InitExpr) {
3609   // Pop the notional constructor scope we created earlier.
3610   PopFunctionScopeInfo(nullptr, D);
3611 
3612   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3613   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3614          "must set init style when field is created");
3615 
3616   if (!InitExpr) {
3617     D->setInvalidDecl();
3618     if (FD)
3619       FD->removeInClassInitializer();
3620     return;
3621   }
3622 
3623   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3624     FD->setInvalidDecl();
3625     FD->removeInClassInitializer();
3626     return;
3627   }
3628 
3629   ExprResult Init = InitExpr;
3630   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3631     InitializedEntity Entity =
3632         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3633     InitializationKind Kind =
3634         FD->getInClassInitStyle() == ICIS_ListInit
3635             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3636                                                    InitExpr->getBeginLoc(),
3637                                                    InitExpr->getEndLoc())
3638             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3639     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3640     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3641     if (Init.isInvalid()) {
3642       FD->setInvalidDecl();
3643       return;
3644     }
3645   }
3646 
3647   // C++11 [class.base.init]p7:
3648   //   The initialization of each base and member constitutes a
3649   //   full-expression.
3650   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3651   if (Init.isInvalid()) {
3652     FD->setInvalidDecl();
3653     return;
3654   }
3655 
3656   InitExpr = Init.get();
3657 
3658   FD->setInClassInitializer(InitExpr);
3659 }
3660 
3661 /// Find the direct and/or virtual base specifiers that
3662 /// correspond to the given base type, for use in base initialization
3663 /// within a constructor.
3664 static bool FindBaseInitializer(Sema &SemaRef,
3665                                 CXXRecordDecl *ClassDecl,
3666                                 QualType BaseType,
3667                                 const CXXBaseSpecifier *&DirectBaseSpec,
3668                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3669   // First, check for a direct base class.
3670   DirectBaseSpec = nullptr;
3671   for (const auto &Base : ClassDecl->bases()) {
3672     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3673       // We found a direct base of this type. That's what we're
3674       // initializing.
3675       DirectBaseSpec = &Base;
3676       break;
3677     }
3678   }
3679 
3680   // Check for a virtual base class.
3681   // FIXME: We might be able to short-circuit this if we know in advance that
3682   // there are no virtual bases.
3683   VirtualBaseSpec = nullptr;
3684   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3685     // We haven't found a base yet; search the class hierarchy for a
3686     // virtual base class.
3687     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3688                        /*DetectVirtual=*/false);
3689     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3690                               SemaRef.Context.getTypeDeclType(ClassDecl),
3691                               BaseType, Paths)) {
3692       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3693            Path != Paths.end(); ++Path) {
3694         if (Path->back().Base->isVirtual()) {
3695           VirtualBaseSpec = Path->back().Base;
3696           break;
3697         }
3698       }
3699     }
3700   }
3701 
3702   return DirectBaseSpec || VirtualBaseSpec;
3703 }
3704 
3705 /// Handle a C++ member initializer using braced-init-list syntax.
3706 MemInitResult
3707 Sema::ActOnMemInitializer(Decl *ConstructorD,
3708                           Scope *S,
3709                           CXXScopeSpec &SS,
3710                           IdentifierInfo *MemberOrBase,
3711                           ParsedType TemplateTypeTy,
3712                           const DeclSpec &DS,
3713                           SourceLocation IdLoc,
3714                           Expr *InitList,
3715                           SourceLocation EllipsisLoc) {
3716   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3717                              DS, IdLoc, InitList,
3718                              EllipsisLoc);
3719 }
3720 
3721 /// Handle a C++ member initializer using parentheses syntax.
3722 MemInitResult
3723 Sema::ActOnMemInitializer(Decl *ConstructorD,
3724                           Scope *S,
3725                           CXXScopeSpec &SS,
3726                           IdentifierInfo *MemberOrBase,
3727                           ParsedType TemplateTypeTy,
3728                           const DeclSpec &DS,
3729                           SourceLocation IdLoc,
3730                           SourceLocation LParenLoc,
3731                           ArrayRef<Expr *> Args,
3732                           SourceLocation RParenLoc,
3733                           SourceLocation EllipsisLoc) {
3734   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3735                                            Args, RParenLoc);
3736   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3737                              DS, IdLoc, List, EllipsisLoc);
3738 }
3739 
3740 namespace {
3741 
3742 // Callback to only accept typo corrections that can be a valid C++ member
3743 // intializer: either a non-static field member or a base class.
3744 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3745 public:
3746   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3747       : ClassDecl(ClassDecl) {}
3748 
3749   bool ValidateCandidate(const TypoCorrection &candidate) override {
3750     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3751       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3752         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3753       return isa<TypeDecl>(ND);
3754     }
3755     return false;
3756   }
3757 
3758 private:
3759   CXXRecordDecl *ClassDecl;
3760 };
3761 
3762 }
3763 
3764 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3765                                              CXXScopeSpec &SS,
3766                                              ParsedType TemplateTypeTy,
3767                                              IdentifierInfo *MemberOrBase) {
3768   if (SS.getScopeRep() || TemplateTypeTy)
3769     return nullptr;
3770   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3771   if (Result.empty())
3772     return nullptr;
3773   ValueDecl *Member;
3774   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3775       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3776     return Member;
3777   return nullptr;
3778 }
3779 
3780 /// Handle a C++ member initializer.
3781 MemInitResult
3782 Sema::BuildMemInitializer(Decl *ConstructorD,
3783                           Scope *S,
3784                           CXXScopeSpec &SS,
3785                           IdentifierInfo *MemberOrBase,
3786                           ParsedType TemplateTypeTy,
3787                           const DeclSpec &DS,
3788                           SourceLocation IdLoc,
3789                           Expr *Init,
3790                           SourceLocation EllipsisLoc) {
3791   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3792   if (!Res.isUsable())
3793     return true;
3794   Init = Res.get();
3795 
3796   if (!ConstructorD)
3797     return true;
3798 
3799   AdjustDeclIfTemplate(ConstructorD);
3800 
3801   CXXConstructorDecl *Constructor
3802     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3803   if (!Constructor) {
3804     // The user wrote a constructor initializer on a function that is
3805     // not a C++ constructor. Ignore the error for now, because we may
3806     // have more member initializers coming; we'll diagnose it just
3807     // once in ActOnMemInitializers.
3808     return true;
3809   }
3810 
3811   CXXRecordDecl *ClassDecl = Constructor->getParent();
3812 
3813   // C++ [class.base.init]p2:
3814   //   Names in a mem-initializer-id are looked up in the scope of the
3815   //   constructor's class and, if not found in that scope, are looked
3816   //   up in the scope containing the constructor's definition.
3817   //   [Note: if the constructor's class contains a member with the
3818   //   same name as a direct or virtual base class of the class, a
3819   //   mem-initializer-id naming the member or base class and composed
3820   //   of a single identifier refers to the class member. A
3821   //   mem-initializer-id for the hidden base class may be specified
3822   //   using a qualified name. ]
3823 
3824   // Look for a member, first.
3825   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3826           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3827     if (EllipsisLoc.isValid())
3828       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3829           << MemberOrBase
3830           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3831 
3832     return BuildMemberInitializer(Member, Init, IdLoc);
3833   }
3834   // It didn't name a member, so see if it names a class.
3835   QualType BaseType;
3836   TypeSourceInfo *TInfo = nullptr;
3837 
3838   if (TemplateTypeTy) {
3839     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3840   } else if (DS.getTypeSpecType() == TST_decltype) {
3841     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3842   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3843     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3844     return true;
3845   } else {
3846     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3847     LookupParsedName(R, S, &SS);
3848 
3849     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3850     if (!TyD) {
3851       if (R.isAmbiguous()) return true;
3852 
3853       // We don't want access-control diagnostics here.
3854       R.suppressDiagnostics();
3855 
3856       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3857         bool NotUnknownSpecialization = false;
3858         DeclContext *DC = computeDeclContext(SS, false);
3859         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3860           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3861 
3862         if (!NotUnknownSpecialization) {
3863           // When the scope specifier can refer to a member of an unknown
3864           // specialization, we take it as a type name.
3865           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3866                                        SS.getWithLocInContext(Context),
3867                                        *MemberOrBase, IdLoc);
3868           if (BaseType.isNull())
3869             return true;
3870 
3871           TInfo = Context.CreateTypeSourceInfo(BaseType);
3872           DependentNameTypeLoc TL =
3873               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3874           if (!TL.isNull()) {
3875             TL.setNameLoc(IdLoc);
3876             TL.setElaboratedKeywordLoc(SourceLocation());
3877             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3878           }
3879 
3880           R.clear();
3881           R.setLookupName(MemberOrBase);
3882         }
3883       }
3884 
3885       // If no results were found, try to correct typos.
3886       TypoCorrection Corr;
3887       if (R.empty() && BaseType.isNull() &&
3888           (Corr = CorrectTypo(
3889                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3890                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3891                CTK_ErrorRecovery, ClassDecl))) {
3892         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3893           // We have found a non-static data member with a similar
3894           // name to what was typed; complain and initialize that
3895           // member.
3896           diagnoseTypo(Corr,
3897                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3898                          << MemberOrBase << true);
3899           return BuildMemberInitializer(Member, Init, IdLoc);
3900         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3901           const CXXBaseSpecifier *DirectBaseSpec;
3902           const CXXBaseSpecifier *VirtualBaseSpec;
3903           if (FindBaseInitializer(*this, ClassDecl,
3904                                   Context.getTypeDeclType(Type),
3905                                   DirectBaseSpec, VirtualBaseSpec)) {
3906             // We have found a direct or virtual base class with a
3907             // similar name to what was typed; complain and initialize
3908             // that base class.
3909             diagnoseTypo(Corr,
3910                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3911                            << MemberOrBase << false,
3912                          PDiag() /*Suppress note, we provide our own.*/);
3913 
3914             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3915                                                               : VirtualBaseSpec;
3916             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3917                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3918 
3919             TyD = Type;
3920           }
3921         }
3922       }
3923 
3924       if (!TyD && BaseType.isNull()) {
3925         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3926           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3927         return true;
3928       }
3929     }
3930 
3931     if (BaseType.isNull()) {
3932       BaseType = Context.getTypeDeclType(TyD);
3933       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3934       if (SS.isSet()) {
3935         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3936                                              BaseType);
3937         TInfo = Context.CreateTypeSourceInfo(BaseType);
3938         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3939         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3940         TL.setElaboratedKeywordLoc(SourceLocation());
3941         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3942       }
3943     }
3944   }
3945 
3946   if (!TInfo)
3947     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3948 
3949   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3950 }
3951 
3952 MemInitResult
3953 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3954                              SourceLocation IdLoc) {
3955   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3956   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3957   assert((DirectMember || IndirectMember) &&
3958          "Member must be a FieldDecl or IndirectFieldDecl");
3959 
3960   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3961     return true;
3962 
3963   if (Member->isInvalidDecl())
3964     return true;
3965 
3966   MultiExprArg Args;
3967   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3968     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3969   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3970     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3971   } else {
3972     // Template instantiation doesn't reconstruct ParenListExprs for us.
3973     Args = Init;
3974   }
3975 
3976   SourceRange InitRange = Init->getSourceRange();
3977 
3978   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3979     // Can't check initialization for a member of dependent type or when
3980     // any of the arguments are type-dependent expressions.
3981     DiscardCleanupsInEvaluationContext();
3982   } else {
3983     bool InitList = false;
3984     if (isa<InitListExpr>(Init)) {
3985       InitList = true;
3986       Args = Init;
3987     }
3988 
3989     // Initialize the member.
3990     InitializedEntity MemberEntity =
3991       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3992                    : InitializedEntity::InitializeMember(IndirectMember,
3993                                                          nullptr);
3994     InitializationKind Kind =
3995         InitList ? InitializationKind::CreateDirectList(
3996                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
3997                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3998                                                     InitRange.getEnd());
3999 
4000     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4001     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4002                                             nullptr);
4003     if (MemberInit.isInvalid())
4004       return true;
4005 
4006     // C++11 [class.base.init]p7:
4007     //   The initialization of each base and member constitutes a
4008     //   full-expression.
4009     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4010     if (MemberInit.isInvalid())
4011       return true;
4012 
4013     Init = MemberInit.get();
4014   }
4015 
4016   if (DirectMember) {
4017     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4018                                             InitRange.getBegin(), Init,
4019                                             InitRange.getEnd());
4020   } else {
4021     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4022                                             InitRange.getBegin(), Init,
4023                                             InitRange.getEnd());
4024   }
4025 }
4026 
4027 MemInitResult
4028 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4029                                  CXXRecordDecl *ClassDecl) {
4030   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4031   if (!LangOpts.CPlusPlus11)
4032     return Diag(NameLoc, diag::err_delegating_ctor)
4033       << TInfo->getTypeLoc().getLocalSourceRange();
4034   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4035 
4036   bool InitList = true;
4037   MultiExprArg Args = Init;
4038   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4039     InitList = false;
4040     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4041   }
4042 
4043   SourceRange InitRange = Init->getSourceRange();
4044   // Initialize the object.
4045   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4046                                      QualType(ClassDecl->getTypeForDecl(), 0));
4047   InitializationKind Kind =
4048       InitList ? InitializationKind::CreateDirectList(
4049                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4050                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4051                                                   InitRange.getEnd());
4052   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4053   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4054                                               Args, nullptr);
4055   if (DelegationInit.isInvalid())
4056     return true;
4057 
4058   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4059          "Delegating constructor with no target?");
4060 
4061   // C++11 [class.base.init]p7:
4062   //   The initialization of each base and member constitutes a
4063   //   full-expression.
4064   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4065                                        InitRange.getBegin());
4066   if (DelegationInit.isInvalid())
4067     return true;
4068 
4069   // If we are in a dependent context, template instantiation will
4070   // perform this type-checking again. Just save the arguments that we
4071   // received in a ParenListExpr.
4072   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4073   // of the information that we have about the base
4074   // initializer. However, deconstructing the ASTs is a dicey process,
4075   // and this approach is far more likely to get the corner cases right.
4076   if (CurContext->isDependentContext())
4077     DelegationInit = Init;
4078 
4079   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4080                                           DelegationInit.getAs<Expr>(),
4081                                           InitRange.getEnd());
4082 }
4083 
4084 MemInitResult
4085 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4086                            Expr *Init, CXXRecordDecl *ClassDecl,
4087                            SourceLocation EllipsisLoc) {
4088   SourceLocation BaseLoc
4089     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4090 
4091   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4092     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4093              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4094 
4095   // C++ [class.base.init]p2:
4096   //   [...] Unless the mem-initializer-id names a nonstatic data
4097   //   member of the constructor's class or a direct or virtual base
4098   //   of that class, the mem-initializer is ill-formed. A
4099   //   mem-initializer-list can initialize a base class using any
4100   //   name that denotes that base class type.
4101   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4102 
4103   SourceRange InitRange = Init->getSourceRange();
4104   if (EllipsisLoc.isValid()) {
4105     // This is a pack expansion.
4106     if (!BaseType->containsUnexpandedParameterPack())  {
4107       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4108         << SourceRange(BaseLoc, InitRange.getEnd());
4109 
4110       EllipsisLoc = SourceLocation();
4111     }
4112   } else {
4113     // Check for any unexpanded parameter packs.
4114     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4115       return true;
4116 
4117     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4118       return true;
4119   }
4120 
4121   // Check for direct and virtual base classes.
4122   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4123   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4124   if (!Dependent) {
4125     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4126                                        BaseType))
4127       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4128 
4129     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4130                         VirtualBaseSpec);
4131 
4132     // C++ [base.class.init]p2:
4133     // Unless the mem-initializer-id names a nonstatic data member of the
4134     // constructor's class or a direct or virtual base of that class, the
4135     // mem-initializer is ill-formed.
4136     if (!DirectBaseSpec && !VirtualBaseSpec) {
4137       // If the class has any dependent bases, then it's possible that
4138       // one of those types will resolve to the same type as
4139       // BaseType. Therefore, just treat this as a dependent base
4140       // class initialization.  FIXME: Should we try to check the
4141       // initialization anyway? It seems odd.
4142       if (ClassDecl->hasAnyDependentBases())
4143         Dependent = true;
4144       else
4145         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4146           << BaseType << Context.getTypeDeclType(ClassDecl)
4147           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4148     }
4149   }
4150 
4151   if (Dependent) {
4152     DiscardCleanupsInEvaluationContext();
4153 
4154     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4155                                             /*IsVirtual=*/false,
4156                                             InitRange.getBegin(), Init,
4157                                             InitRange.getEnd(), EllipsisLoc);
4158   }
4159 
4160   // C++ [base.class.init]p2:
4161   //   If a mem-initializer-id is ambiguous because it designates both
4162   //   a direct non-virtual base class and an inherited virtual base
4163   //   class, the mem-initializer is ill-formed.
4164   if (DirectBaseSpec && VirtualBaseSpec)
4165     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4166       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4167 
4168   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4169   if (!BaseSpec)
4170     BaseSpec = VirtualBaseSpec;
4171 
4172   // Initialize the base.
4173   bool InitList = true;
4174   MultiExprArg Args = Init;
4175   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4176     InitList = false;
4177     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4178   }
4179 
4180   InitializedEntity BaseEntity =
4181     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4182   InitializationKind Kind =
4183       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4184                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4185                                                   InitRange.getEnd());
4186   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4187   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4188   if (BaseInit.isInvalid())
4189     return true;
4190 
4191   // C++11 [class.base.init]p7:
4192   //   The initialization of each base and member constitutes a
4193   //   full-expression.
4194   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4195   if (BaseInit.isInvalid())
4196     return true;
4197 
4198   // If we are in a dependent context, template instantiation will
4199   // perform this type-checking again. Just save the arguments that we
4200   // received in a ParenListExpr.
4201   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4202   // of the information that we have about the base
4203   // initializer. However, deconstructing the ASTs is a dicey process,
4204   // and this approach is far more likely to get the corner cases right.
4205   if (CurContext->isDependentContext())
4206     BaseInit = Init;
4207 
4208   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4209                                           BaseSpec->isVirtual(),
4210                                           InitRange.getBegin(),
4211                                           BaseInit.getAs<Expr>(),
4212                                           InitRange.getEnd(), EllipsisLoc);
4213 }
4214 
4215 // Create a static_cast\<T&&>(expr).
4216 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4217   if (T.isNull()) T = E->getType();
4218   QualType TargetType = SemaRef.BuildReferenceType(
4219       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4220   SourceLocation ExprLoc = E->getBeginLoc();
4221   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4222       TargetType, ExprLoc);
4223 
4224   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4225                                    SourceRange(ExprLoc, ExprLoc),
4226                                    E->getSourceRange()).get();
4227 }
4228 
4229 /// ImplicitInitializerKind - How an implicit base or member initializer should
4230 /// initialize its base or member.
4231 enum ImplicitInitializerKind {
4232   IIK_Default,
4233   IIK_Copy,
4234   IIK_Move,
4235   IIK_Inherit
4236 };
4237 
4238 static bool
4239 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4240                              ImplicitInitializerKind ImplicitInitKind,
4241                              CXXBaseSpecifier *BaseSpec,
4242                              bool IsInheritedVirtualBase,
4243                              CXXCtorInitializer *&CXXBaseInit) {
4244   InitializedEntity InitEntity
4245     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4246                                         IsInheritedVirtualBase);
4247 
4248   ExprResult BaseInit;
4249 
4250   switch (ImplicitInitKind) {
4251   case IIK_Inherit:
4252   case IIK_Default: {
4253     InitializationKind InitKind
4254       = InitializationKind::CreateDefault(Constructor->getLocation());
4255     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4256     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4257     break;
4258   }
4259 
4260   case IIK_Move:
4261   case IIK_Copy: {
4262     bool Moving = ImplicitInitKind == IIK_Move;
4263     ParmVarDecl *Param = Constructor->getParamDecl(0);
4264     QualType ParamType = Param->getType().getNonReferenceType();
4265 
4266     Expr *CopyCtorArg =
4267       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4268                           SourceLocation(), Param, false,
4269                           Constructor->getLocation(), ParamType,
4270                           VK_LValue, nullptr);
4271 
4272     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4273 
4274     // Cast to the base class to avoid ambiguities.
4275     QualType ArgTy =
4276       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4277                                        ParamType.getQualifiers());
4278 
4279     if (Moving) {
4280       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4281     }
4282 
4283     CXXCastPath BasePath;
4284     BasePath.push_back(BaseSpec);
4285     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4286                                             CK_UncheckedDerivedToBase,
4287                                             Moving ? VK_XValue : VK_LValue,
4288                                             &BasePath).get();
4289 
4290     InitializationKind InitKind
4291       = InitializationKind::CreateDirect(Constructor->getLocation(),
4292                                          SourceLocation(), SourceLocation());
4293     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4294     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4295     break;
4296   }
4297   }
4298 
4299   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4300   if (BaseInit.isInvalid())
4301     return true;
4302 
4303   CXXBaseInit =
4304     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4305                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4306                                                         SourceLocation()),
4307                                              BaseSpec->isVirtual(),
4308                                              SourceLocation(),
4309                                              BaseInit.getAs<Expr>(),
4310                                              SourceLocation(),
4311                                              SourceLocation());
4312 
4313   return false;
4314 }
4315 
4316 static bool RefersToRValueRef(Expr *MemRef) {
4317   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4318   return Referenced->getType()->isRValueReferenceType();
4319 }
4320 
4321 static bool
4322 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4323                                ImplicitInitializerKind ImplicitInitKind,
4324                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4325                                CXXCtorInitializer *&CXXMemberInit) {
4326   if (Field->isInvalidDecl())
4327     return true;
4328 
4329   SourceLocation Loc = Constructor->getLocation();
4330 
4331   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4332     bool Moving = ImplicitInitKind == IIK_Move;
4333     ParmVarDecl *Param = Constructor->getParamDecl(0);
4334     QualType ParamType = Param->getType().getNonReferenceType();
4335 
4336     // Suppress copying zero-width bitfields.
4337     if (Field->isZeroLengthBitField(SemaRef.Context))
4338       return false;
4339 
4340     Expr *MemberExprBase =
4341       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4342                           SourceLocation(), Param, false,
4343                           Loc, ParamType, VK_LValue, nullptr);
4344 
4345     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4346 
4347     if (Moving) {
4348       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4349     }
4350 
4351     // Build a reference to this field within the parameter.
4352     CXXScopeSpec SS;
4353     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4354                               Sema::LookupMemberName);
4355     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4356                                   : cast<ValueDecl>(Field), AS_public);
4357     MemberLookup.resolveKind();
4358     ExprResult CtorArg
4359       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4360                                          ParamType, Loc,
4361                                          /*IsArrow=*/false,
4362                                          SS,
4363                                          /*TemplateKWLoc=*/SourceLocation(),
4364                                          /*FirstQualifierInScope=*/nullptr,
4365                                          MemberLookup,
4366                                          /*TemplateArgs=*/nullptr,
4367                                          /*S*/nullptr);
4368     if (CtorArg.isInvalid())
4369       return true;
4370 
4371     // C++11 [class.copy]p15:
4372     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4373     //     with static_cast<T&&>(x.m);
4374     if (RefersToRValueRef(CtorArg.get())) {
4375       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4376     }
4377 
4378     InitializedEntity Entity =
4379         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4380                                                        /*Implicit*/ true)
4381                  : InitializedEntity::InitializeMember(Field, nullptr,
4382                                                        /*Implicit*/ true);
4383 
4384     // Direct-initialize to use the copy constructor.
4385     InitializationKind InitKind =
4386       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4387 
4388     Expr *CtorArgE = CtorArg.getAs<Expr>();
4389     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4390     ExprResult MemberInit =
4391         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4392     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4393     if (MemberInit.isInvalid())
4394       return true;
4395 
4396     if (Indirect)
4397       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4398           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4399     else
4400       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4401           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4402     return false;
4403   }
4404 
4405   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4406          "Unhandled implicit init kind!");
4407 
4408   QualType FieldBaseElementType =
4409     SemaRef.Context.getBaseElementType(Field->getType());
4410 
4411   if (FieldBaseElementType->isRecordType()) {
4412     InitializedEntity InitEntity =
4413         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4414                                                        /*Implicit*/ true)
4415                  : InitializedEntity::InitializeMember(Field, nullptr,
4416                                                        /*Implicit*/ true);
4417     InitializationKind InitKind =
4418       InitializationKind::CreateDefault(Loc);
4419 
4420     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4421     ExprResult MemberInit =
4422       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4423 
4424     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4425     if (MemberInit.isInvalid())
4426       return true;
4427 
4428     if (Indirect)
4429       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4430                                                                Indirect, Loc,
4431                                                                Loc,
4432                                                                MemberInit.get(),
4433                                                                Loc);
4434     else
4435       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4436                                                                Field, Loc, Loc,
4437                                                                MemberInit.get(),
4438                                                                Loc);
4439     return false;
4440   }
4441 
4442   if (!Field->getParent()->isUnion()) {
4443     if (FieldBaseElementType->isReferenceType()) {
4444       SemaRef.Diag(Constructor->getLocation(),
4445                    diag::err_uninitialized_member_in_ctor)
4446       << (int)Constructor->isImplicit()
4447       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4448       << 0 << Field->getDeclName();
4449       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4450       return true;
4451     }
4452 
4453     if (FieldBaseElementType.isConstQualified()) {
4454       SemaRef.Diag(Constructor->getLocation(),
4455                    diag::err_uninitialized_member_in_ctor)
4456       << (int)Constructor->isImplicit()
4457       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4458       << 1 << Field->getDeclName();
4459       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4460       return true;
4461     }
4462   }
4463 
4464   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4465     // ARC and Weak:
4466     //   Default-initialize Objective-C pointers to NULL.
4467     CXXMemberInit
4468       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4469                                                  Loc, Loc,
4470                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4471                                                  Loc);
4472     return false;
4473   }
4474 
4475   // Nothing to initialize.
4476   CXXMemberInit = nullptr;
4477   return false;
4478 }
4479 
4480 namespace {
4481 struct BaseAndFieldInfo {
4482   Sema &S;
4483   CXXConstructorDecl *Ctor;
4484   bool AnyErrorsInInits;
4485   ImplicitInitializerKind IIK;
4486   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4487   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4488   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4489 
4490   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4491     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4492     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4493     if (Ctor->getInheritedConstructor())
4494       IIK = IIK_Inherit;
4495     else if (Generated && Ctor->isCopyConstructor())
4496       IIK = IIK_Copy;
4497     else if (Generated && Ctor->isMoveConstructor())
4498       IIK = IIK_Move;
4499     else
4500       IIK = IIK_Default;
4501   }
4502 
4503   bool isImplicitCopyOrMove() const {
4504     switch (IIK) {
4505     case IIK_Copy:
4506     case IIK_Move:
4507       return true;
4508 
4509     case IIK_Default:
4510     case IIK_Inherit:
4511       return false;
4512     }
4513 
4514     llvm_unreachable("Invalid ImplicitInitializerKind!");
4515   }
4516 
4517   bool addFieldInitializer(CXXCtorInitializer *Init) {
4518     AllToInit.push_back(Init);
4519 
4520     // Check whether this initializer makes the field "used".
4521     if (Init->getInit()->HasSideEffects(S.Context))
4522       S.UnusedPrivateFields.remove(Init->getAnyMember());
4523 
4524     return false;
4525   }
4526 
4527   bool isInactiveUnionMember(FieldDecl *Field) {
4528     RecordDecl *Record = Field->getParent();
4529     if (!Record->isUnion())
4530       return false;
4531 
4532     if (FieldDecl *Active =
4533             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4534       return Active != Field->getCanonicalDecl();
4535 
4536     // In an implicit copy or move constructor, ignore any in-class initializer.
4537     if (isImplicitCopyOrMove())
4538       return true;
4539 
4540     // If there's no explicit initialization, the field is active only if it
4541     // has an in-class initializer...
4542     if (Field->hasInClassInitializer())
4543       return false;
4544     // ... or it's an anonymous struct or union whose class has an in-class
4545     // initializer.
4546     if (!Field->isAnonymousStructOrUnion())
4547       return true;
4548     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4549     return !FieldRD->hasInClassInitializer();
4550   }
4551 
4552   /// Determine whether the given field is, or is within, a union member
4553   /// that is inactive (because there was an initializer given for a different
4554   /// member of the union, or because the union was not initialized at all).
4555   bool isWithinInactiveUnionMember(FieldDecl *Field,
4556                                    IndirectFieldDecl *Indirect) {
4557     if (!Indirect)
4558       return isInactiveUnionMember(Field);
4559 
4560     for (auto *C : Indirect->chain()) {
4561       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4562       if (Field && isInactiveUnionMember(Field))
4563         return true;
4564     }
4565     return false;
4566   }
4567 };
4568 }
4569 
4570 /// Determine whether the given type is an incomplete or zero-lenfgth
4571 /// array type.
4572 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4573   if (T->isIncompleteArrayType())
4574     return true;
4575 
4576   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4577     if (!ArrayT->getSize())
4578       return true;
4579 
4580     T = ArrayT->getElementType();
4581   }
4582 
4583   return false;
4584 }
4585 
4586 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4587                                     FieldDecl *Field,
4588                                     IndirectFieldDecl *Indirect = nullptr) {
4589   if (Field->isInvalidDecl())
4590     return false;
4591 
4592   // Overwhelmingly common case: we have a direct initializer for this field.
4593   if (CXXCtorInitializer *Init =
4594           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4595     return Info.addFieldInitializer(Init);
4596 
4597   // C++11 [class.base.init]p8:
4598   //   if the entity is a non-static data member that has a
4599   //   brace-or-equal-initializer and either
4600   //   -- the constructor's class is a union and no other variant member of that
4601   //      union is designated by a mem-initializer-id or
4602   //   -- the constructor's class is not a union, and, if the entity is a member
4603   //      of an anonymous union, no other member of that union is designated by
4604   //      a mem-initializer-id,
4605   //   the entity is initialized as specified in [dcl.init].
4606   //
4607   // We also apply the same rules to handle anonymous structs within anonymous
4608   // unions.
4609   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4610     return false;
4611 
4612   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4613     ExprResult DIE =
4614         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4615     if (DIE.isInvalid())
4616       return true;
4617 
4618     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4619     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4620 
4621     CXXCtorInitializer *Init;
4622     if (Indirect)
4623       Init = new (SemaRef.Context)
4624           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4625                              SourceLocation(), DIE.get(), SourceLocation());
4626     else
4627       Init = new (SemaRef.Context)
4628           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4629                              SourceLocation(), DIE.get(), SourceLocation());
4630     return Info.addFieldInitializer(Init);
4631   }
4632 
4633   // Don't initialize incomplete or zero-length arrays.
4634   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4635     return false;
4636 
4637   // Don't try to build an implicit initializer if there were semantic
4638   // errors in any of the initializers (and therefore we might be
4639   // missing some that the user actually wrote).
4640   if (Info.AnyErrorsInInits)
4641     return false;
4642 
4643   CXXCtorInitializer *Init = nullptr;
4644   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4645                                      Indirect, Init))
4646     return true;
4647 
4648   if (!Init)
4649     return false;
4650 
4651   return Info.addFieldInitializer(Init);
4652 }
4653 
4654 bool
4655 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4656                                CXXCtorInitializer *Initializer) {
4657   assert(Initializer->isDelegatingInitializer());
4658   Constructor->setNumCtorInitializers(1);
4659   CXXCtorInitializer **initializer =
4660     new (Context) CXXCtorInitializer*[1];
4661   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4662   Constructor->setCtorInitializers(initializer);
4663 
4664   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4665     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4666     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4667   }
4668 
4669   DelegatingCtorDecls.push_back(Constructor);
4670 
4671   DiagnoseUninitializedFields(*this, Constructor);
4672 
4673   return false;
4674 }
4675 
4676 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4677                                ArrayRef<CXXCtorInitializer *> Initializers) {
4678   if (Constructor->isDependentContext()) {
4679     // Just store the initializers as written, they will be checked during
4680     // instantiation.
4681     if (!Initializers.empty()) {
4682       Constructor->setNumCtorInitializers(Initializers.size());
4683       CXXCtorInitializer **baseOrMemberInitializers =
4684         new (Context) CXXCtorInitializer*[Initializers.size()];
4685       memcpy(baseOrMemberInitializers, Initializers.data(),
4686              Initializers.size() * sizeof(CXXCtorInitializer*));
4687       Constructor->setCtorInitializers(baseOrMemberInitializers);
4688     }
4689 
4690     // Let template instantiation know whether we had errors.
4691     if (AnyErrors)
4692       Constructor->setInvalidDecl();
4693 
4694     return false;
4695   }
4696 
4697   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4698 
4699   // We need to build the initializer AST according to order of construction
4700   // and not what user specified in the Initializers list.
4701   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4702   if (!ClassDecl)
4703     return true;
4704 
4705   bool HadError = false;
4706 
4707   for (unsigned i = 0; i < Initializers.size(); i++) {
4708     CXXCtorInitializer *Member = Initializers[i];
4709 
4710     if (Member->isBaseInitializer())
4711       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4712     else {
4713       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4714 
4715       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4716         for (auto *C : F->chain()) {
4717           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4718           if (FD && FD->getParent()->isUnion())
4719             Info.ActiveUnionMember.insert(std::make_pair(
4720                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4721         }
4722       } else if (FieldDecl *FD = Member->getMember()) {
4723         if (FD->getParent()->isUnion())
4724           Info.ActiveUnionMember.insert(std::make_pair(
4725               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4726       }
4727     }
4728   }
4729 
4730   // Keep track of the direct virtual bases.
4731   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4732   for (auto &I : ClassDecl->bases()) {
4733     if (I.isVirtual())
4734       DirectVBases.insert(&I);
4735   }
4736 
4737   // Push virtual bases before others.
4738   for (auto &VBase : ClassDecl->vbases()) {
4739     if (CXXCtorInitializer *Value
4740         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4741       // [class.base.init]p7, per DR257:
4742       //   A mem-initializer where the mem-initializer-id names a virtual base
4743       //   class is ignored during execution of a constructor of any class that
4744       //   is not the most derived class.
4745       if (ClassDecl->isAbstract()) {
4746         // FIXME: Provide a fixit to remove the base specifier. This requires
4747         // tracking the location of the associated comma for a base specifier.
4748         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4749           << VBase.getType() << ClassDecl;
4750         DiagnoseAbstractType(ClassDecl);
4751       }
4752 
4753       Info.AllToInit.push_back(Value);
4754     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4755       // [class.base.init]p8, per DR257:
4756       //   If a given [...] base class is not named by a mem-initializer-id
4757       //   [...] and the entity is not a virtual base class of an abstract
4758       //   class, then [...] the entity is default-initialized.
4759       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4760       CXXCtorInitializer *CXXBaseInit;
4761       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4762                                        &VBase, IsInheritedVirtualBase,
4763                                        CXXBaseInit)) {
4764         HadError = true;
4765         continue;
4766       }
4767 
4768       Info.AllToInit.push_back(CXXBaseInit);
4769     }
4770   }
4771 
4772   // Non-virtual bases.
4773   for (auto &Base : ClassDecl->bases()) {
4774     // Virtuals are in the virtual base list and already constructed.
4775     if (Base.isVirtual())
4776       continue;
4777 
4778     if (CXXCtorInitializer *Value
4779           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4780       Info.AllToInit.push_back(Value);
4781     } else if (!AnyErrors) {
4782       CXXCtorInitializer *CXXBaseInit;
4783       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4784                                        &Base, /*IsInheritedVirtualBase=*/false,
4785                                        CXXBaseInit)) {
4786         HadError = true;
4787         continue;
4788       }
4789 
4790       Info.AllToInit.push_back(CXXBaseInit);
4791     }
4792   }
4793 
4794   // Fields.
4795   for (auto *Mem : ClassDecl->decls()) {
4796     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4797       // C++ [class.bit]p2:
4798       //   A declaration for a bit-field that omits the identifier declares an
4799       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4800       //   initialized.
4801       if (F->isUnnamedBitfield())
4802         continue;
4803 
4804       // If we're not generating the implicit copy/move constructor, then we'll
4805       // handle anonymous struct/union fields based on their individual
4806       // indirect fields.
4807       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4808         continue;
4809 
4810       if (CollectFieldInitializer(*this, Info, F))
4811         HadError = true;
4812       continue;
4813     }
4814 
4815     // Beyond this point, we only consider default initialization.
4816     if (Info.isImplicitCopyOrMove())
4817       continue;
4818 
4819     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4820       if (F->getType()->isIncompleteArrayType()) {
4821         assert(ClassDecl->hasFlexibleArrayMember() &&
4822                "Incomplete array type is not valid");
4823         continue;
4824       }
4825 
4826       // Initialize each field of an anonymous struct individually.
4827       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4828         HadError = true;
4829 
4830       continue;
4831     }
4832   }
4833 
4834   unsigned NumInitializers = Info.AllToInit.size();
4835   if (NumInitializers > 0) {
4836     Constructor->setNumCtorInitializers(NumInitializers);
4837     CXXCtorInitializer **baseOrMemberInitializers =
4838       new (Context) CXXCtorInitializer*[NumInitializers];
4839     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4840            NumInitializers * sizeof(CXXCtorInitializer*));
4841     Constructor->setCtorInitializers(baseOrMemberInitializers);
4842 
4843     // Constructors implicitly reference the base and member
4844     // destructors.
4845     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4846                                            Constructor->getParent());
4847   }
4848 
4849   return HadError;
4850 }
4851 
4852 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4853   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4854     const RecordDecl *RD = RT->getDecl();
4855     if (RD->isAnonymousStructOrUnion()) {
4856       for (auto *Field : RD->fields())
4857         PopulateKeysForFields(Field, IdealInits);
4858       return;
4859     }
4860   }
4861   IdealInits.push_back(Field->getCanonicalDecl());
4862 }
4863 
4864 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4865   return Context.getCanonicalType(BaseType).getTypePtr();
4866 }
4867 
4868 static const void *GetKeyForMember(ASTContext &Context,
4869                                    CXXCtorInitializer *Member) {
4870   if (!Member->isAnyMemberInitializer())
4871     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4872 
4873   return Member->getAnyMember()->getCanonicalDecl();
4874 }
4875 
4876 static void DiagnoseBaseOrMemInitializerOrder(
4877     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4878     ArrayRef<CXXCtorInitializer *> Inits) {
4879   if (Constructor->getDeclContext()->isDependentContext())
4880     return;
4881 
4882   // Don't check initializers order unless the warning is enabled at the
4883   // location of at least one initializer.
4884   bool ShouldCheckOrder = false;
4885   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4886     CXXCtorInitializer *Init = Inits[InitIndex];
4887     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4888                                  Init->getSourceLocation())) {
4889       ShouldCheckOrder = true;
4890       break;
4891     }
4892   }
4893   if (!ShouldCheckOrder)
4894     return;
4895 
4896   // Build the list of bases and members in the order that they'll
4897   // actually be initialized.  The explicit initializers should be in
4898   // this same order but may be missing things.
4899   SmallVector<const void*, 32> IdealInitKeys;
4900 
4901   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4902 
4903   // 1. Virtual bases.
4904   for (const auto &VBase : ClassDecl->vbases())
4905     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4906 
4907   // 2. Non-virtual bases.
4908   for (const auto &Base : ClassDecl->bases()) {
4909     if (Base.isVirtual())
4910       continue;
4911     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4912   }
4913 
4914   // 3. Direct fields.
4915   for (auto *Field : ClassDecl->fields()) {
4916     if (Field->isUnnamedBitfield())
4917       continue;
4918 
4919     PopulateKeysForFields(Field, IdealInitKeys);
4920   }
4921 
4922   unsigned NumIdealInits = IdealInitKeys.size();
4923   unsigned IdealIndex = 0;
4924 
4925   CXXCtorInitializer *PrevInit = nullptr;
4926   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4927     CXXCtorInitializer *Init = Inits[InitIndex];
4928     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4929 
4930     // Scan forward to try to find this initializer in the idealized
4931     // initializers list.
4932     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4933       if (InitKey == IdealInitKeys[IdealIndex])
4934         break;
4935 
4936     // If we didn't find this initializer, it must be because we
4937     // scanned past it on a previous iteration.  That can only
4938     // happen if we're out of order;  emit a warning.
4939     if (IdealIndex == NumIdealInits && PrevInit) {
4940       Sema::SemaDiagnosticBuilder D =
4941         SemaRef.Diag(PrevInit->getSourceLocation(),
4942                      diag::warn_initializer_out_of_order);
4943 
4944       if (PrevInit->isAnyMemberInitializer())
4945         D << 0 << PrevInit->getAnyMember()->getDeclName();
4946       else
4947         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4948 
4949       if (Init->isAnyMemberInitializer())
4950         D << 0 << Init->getAnyMember()->getDeclName();
4951       else
4952         D << 1 << Init->getTypeSourceInfo()->getType();
4953 
4954       // Move back to the initializer's location in the ideal list.
4955       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4956         if (InitKey == IdealInitKeys[IdealIndex])
4957           break;
4958 
4959       assert(IdealIndex < NumIdealInits &&
4960              "initializer not found in initializer list");
4961     }
4962 
4963     PrevInit = Init;
4964   }
4965 }
4966 
4967 namespace {
4968 bool CheckRedundantInit(Sema &S,
4969                         CXXCtorInitializer *Init,
4970                         CXXCtorInitializer *&PrevInit) {
4971   if (!PrevInit) {
4972     PrevInit = Init;
4973     return false;
4974   }
4975 
4976   if (FieldDecl *Field = Init->getAnyMember())
4977     S.Diag(Init->getSourceLocation(),
4978            diag::err_multiple_mem_initialization)
4979       << Field->getDeclName()
4980       << Init->getSourceRange();
4981   else {
4982     const Type *BaseClass = Init->getBaseClass();
4983     assert(BaseClass && "neither field nor base");
4984     S.Diag(Init->getSourceLocation(),
4985            diag::err_multiple_base_initialization)
4986       << QualType(BaseClass, 0)
4987       << Init->getSourceRange();
4988   }
4989   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4990     << 0 << PrevInit->getSourceRange();
4991 
4992   return true;
4993 }
4994 
4995 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4996 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4997 
4998 bool CheckRedundantUnionInit(Sema &S,
4999                              CXXCtorInitializer *Init,
5000                              RedundantUnionMap &Unions) {
5001   FieldDecl *Field = Init->getAnyMember();
5002   RecordDecl *Parent = Field->getParent();
5003   NamedDecl *Child = Field;
5004 
5005   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5006     if (Parent->isUnion()) {
5007       UnionEntry &En = Unions[Parent];
5008       if (En.first && En.first != Child) {
5009         S.Diag(Init->getSourceLocation(),
5010                diag::err_multiple_mem_union_initialization)
5011           << Field->getDeclName()
5012           << Init->getSourceRange();
5013         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5014           << 0 << En.second->getSourceRange();
5015         return true;
5016       }
5017       if (!En.first) {
5018         En.first = Child;
5019         En.second = Init;
5020       }
5021       if (!Parent->isAnonymousStructOrUnion())
5022         return false;
5023     }
5024 
5025     Child = Parent;
5026     Parent = cast<RecordDecl>(Parent->getDeclContext());
5027   }
5028 
5029   return false;
5030 }
5031 }
5032 
5033 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5034 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5035                                 SourceLocation ColonLoc,
5036                                 ArrayRef<CXXCtorInitializer*> MemInits,
5037                                 bool AnyErrors) {
5038   if (!ConstructorDecl)
5039     return;
5040 
5041   AdjustDeclIfTemplate(ConstructorDecl);
5042 
5043   CXXConstructorDecl *Constructor
5044     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5045 
5046   if (!Constructor) {
5047     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5048     return;
5049   }
5050 
5051   // Mapping for the duplicate initializers check.
5052   // For member initializers, this is keyed with a FieldDecl*.
5053   // For base initializers, this is keyed with a Type*.
5054   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5055 
5056   // Mapping for the inconsistent anonymous-union initializers check.
5057   RedundantUnionMap MemberUnions;
5058 
5059   bool HadError = false;
5060   for (unsigned i = 0; i < MemInits.size(); i++) {
5061     CXXCtorInitializer *Init = MemInits[i];
5062 
5063     // Set the source order index.
5064     Init->setSourceOrder(i);
5065 
5066     if (Init->isAnyMemberInitializer()) {
5067       const void *Key = GetKeyForMember(Context, Init);
5068       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5069           CheckRedundantUnionInit(*this, Init, MemberUnions))
5070         HadError = true;
5071     } else if (Init->isBaseInitializer()) {
5072       const void *Key = GetKeyForMember(Context, Init);
5073       if (CheckRedundantInit(*this, Init, Members[Key]))
5074         HadError = true;
5075     } else {
5076       assert(Init->isDelegatingInitializer());
5077       // This must be the only initializer
5078       if (MemInits.size() != 1) {
5079         Diag(Init->getSourceLocation(),
5080              diag::err_delegating_initializer_alone)
5081           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5082         // We will treat this as being the only initializer.
5083       }
5084       SetDelegatingInitializer(Constructor, MemInits[i]);
5085       // Return immediately as the initializer is set.
5086       return;
5087     }
5088   }
5089 
5090   if (HadError)
5091     return;
5092 
5093   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5094 
5095   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5096 
5097   DiagnoseUninitializedFields(*this, Constructor);
5098 }
5099 
5100 void
5101 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5102                                              CXXRecordDecl *ClassDecl) {
5103   // Ignore dependent contexts. Also ignore unions, since their members never
5104   // have destructors implicitly called.
5105   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5106     return;
5107 
5108   // FIXME: all the access-control diagnostics are positioned on the
5109   // field/base declaration.  That's probably good; that said, the
5110   // user might reasonably want to know why the destructor is being
5111   // emitted, and we currently don't say.
5112 
5113   // Non-static data members.
5114   for (auto *Field : ClassDecl->fields()) {
5115     if (Field->isInvalidDecl())
5116       continue;
5117 
5118     // Don't destroy incomplete or zero-length arrays.
5119     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5120       continue;
5121 
5122     QualType FieldType = Context.getBaseElementType(Field->getType());
5123 
5124     const RecordType* RT = FieldType->getAs<RecordType>();
5125     if (!RT)
5126       continue;
5127 
5128     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5129     if (FieldClassDecl->isInvalidDecl())
5130       continue;
5131     if (FieldClassDecl->hasIrrelevantDestructor())
5132       continue;
5133     // The destructor for an implicit anonymous union member is never invoked.
5134     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5135       continue;
5136 
5137     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5138     assert(Dtor && "No dtor found for FieldClassDecl!");
5139     CheckDestructorAccess(Field->getLocation(), Dtor,
5140                           PDiag(diag::err_access_dtor_field)
5141                             << Field->getDeclName()
5142                             << FieldType);
5143 
5144     MarkFunctionReferenced(Location, Dtor);
5145     DiagnoseUseOfDecl(Dtor, Location);
5146   }
5147 
5148   // We only potentially invoke the destructors of potentially constructed
5149   // subobjects.
5150   bool VisitVirtualBases = !ClassDecl->isAbstract();
5151 
5152   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5153 
5154   // Bases.
5155   for (const auto &Base : ClassDecl->bases()) {
5156     // Bases are always records in a well-formed non-dependent class.
5157     const RecordType *RT = Base.getType()->getAs<RecordType>();
5158 
5159     // Remember direct virtual bases.
5160     if (Base.isVirtual()) {
5161       if (!VisitVirtualBases)
5162         continue;
5163       DirectVirtualBases.insert(RT);
5164     }
5165 
5166     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5167     // If our base class is invalid, we probably can't get its dtor anyway.
5168     if (BaseClassDecl->isInvalidDecl())
5169       continue;
5170     if (BaseClassDecl->hasIrrelevantDestructor())
5171       continue;
5172 
5173     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5174     assert(Dtor && "No dtor found for BaseClassDecl!");
5175 
5176     // FIXME: caret should be on the start of the class name
5177     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5178                           PDiag(diag::err_access_dtor_base)
5179                               << Base.getType() << Base.getSourceRange(),
5180                           Context.getTypeDeclType(ClassDecl));
5181 
5182     MarkFunctionReferenced(Location, Dtor);
5183     DiagnoseUseOfDecl(Dtor, Location);
5184   }
5185 
5186   if (!VisitVirtualBases)
5187     return;
5188 
5189   // Virtual bases.
5190   for (const auto &VBase : ClassDecl->vbases()) {
5191     // Bases are always records in a well-formed non-dependent class.
5192     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5193 
5194     // Ignore direct virtual bases.
5195     if (DirectVirtualBases.count(RT))
5196       continue;
5197 
5198     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5199     // If our base class is invalid, we probably can't get its dtor anyway.
5200     if (BaseClassDecl->isInvalidDecl())
5201       continue;
5202     if (BaseClassDecl->hasIrrelevantDestructor())
5203       continue;
5204 
5205     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5206     assert(Dtor && "No dtor found for BaseClassDecl!");
5207     if (CheckDestructorAccess(
5208             ClassDecl->getLocation(), Dtor,
5209             PDiag(diag::err_access_dtor_vbase)
5210                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5211             Context.getTypeDeclType(ClassDecl)) ==
5212         AR_accessible) {
5213       CheckDerivedToBaseConversion(
5214           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5215           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5216           SourceRange(), DeclarationName(), nullptr);
5217     }
5218 
5219     MarkFunctionReferenced(Location, Dtor);
5220     DiagnoseUseOfDecl(Dtor, Location);
5221   }
5222 }
5223 
5224 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5225   if (!CDtorDecl)
5226     return;
5227 
5228   if (CXXConstructorDecl *Constructor
5229       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5230     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5231     DiagnoseUninitializedFields(*this, Constructor);
5232   }
5233 }
5234 
5235 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5236   if (!getLangOpts().CPlusPlus)
5237     return false;
5238 
5239   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5240   if (!RD)
5241     return false;
5242 
5243   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5244   // class template specialization here, but doing so breaks a lot of code.
5245 
5246   // We can't answer whether something is abstract until it has a
5247   // definition. If it's currently being defined, we'll walk back
5248   // over all the declarations when we have a full definition.
5249   const CXXRecordDecl *Def = RD->getDefinition();
5250   if (!Def || Def->isBeingDefined())
5251     return false;
5252 
5253   return RD->isAbstract();
5254 }
5255 
5256 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5257                                   TypeDiagnoser &Diagnoser) {
5258   if (!isAbstractType(Loc, T))
5259     return false;
5260 
5261   T = Context.getBaseElementType(T);
5262   Diagnoser.diagnose(*this, Loc, T);
5263   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5264   return true;
5265 }
5266 
5267 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5268   // Check if we've already emitted the list of pure virtual functions
5269   // for this class.
5270   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5271     return;
5272 
5273   // If the diagnostic is suppressed, don't emit the notes. We're only
5274   // going to emit them once, so try to attach them to a diagnostic we're
5275   // actually going to show.
5276   if (Diags.isLastDiagnosticIgnored())
5277     return;
5278 
5279   CXXFinalOverriderMap FinalOverriders;
5280   RD->getFinalOverriders(FinalOverriders);
5281 
5282   // Keep a set of seen pure methods so we won't diagnose the same method
5283   // more than once.
5284   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5285 
5286   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5287                                    MEnd = FinalOverriders.end();
5288        M != MEnd;
5289        ++M) {
5290     for (OverridingMethods::iterator SO = M->second.begin(),
5291                                   SOEnd = M->second.end();
5292          SO != SOEnd; ++SO) {
5293       // C++ [class.abstract]p4:
5294       //   A class is abstract if it contains or inherits at least one
5295       //   pure virtual function for which the final overrider is pure
5296       //   virtual.
5297 
5298       //
5299       if (SO->second.size() != 1)
5300         continue;
5301 
5302       if (!SO->second.front().Method->isPure())
5303         continue;
5304 
5305       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5306         continue;
5307 
5308       Diag(SO->second.front().Method->getLocation(),
5309            diag::note_pure_virtual_function)
5310         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5311     }
5312   }
5313 
5314   if (!PureVirtualClassDiagSet)
5315     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5316   PureVirtualClassDiagSet->insert(RD);
5317 }
5318 
5319 namespace {
5320 struct AbstractUsageInfo {
5321   Sema &S;
5322   CXXRecordDecl *Record;
5323   CanQualType AbstractType;
5324   bool Invalid;
5325 
5326   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5327     : S(S), Record(Record),
5328       AbstractType(S.Context.getCanonicalType(
5329                    S.Context.getTypeDeclType(Record))),
5330       Invalid(false) {}
5331 
5332   void DiagnoseAbstractType() {
5333     if (Invalid) return;
5334     S.DiagnoseAbstractType(Record);
5335     Invalid = true;
5336   }
5337 
5338   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5339 };
5340 
5341 struct CheckAbstractUsage {
5342   AbstractUsageInfo &Info;
5343   const NamedDecl *Ctx;
5344 
5345   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5346     : Info(Info), Ctx(Ctx) {}
5347 
5348   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5349     switch (TL.getTypeLocClass()) {
5350 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5351 #define TYPELOC(CLASS, PARENT) \
5352     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5353 #include "clang/AST/TypeLocNodes.def"
5354     }
5355   }
5356 
5357   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5358     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5359     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5360       if (!TL.getParam(I))
5361         continue;
5362 
5363       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5364       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5365     }
5366   }
5367 
5368   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5369     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5370   }
5371 
5372   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5373     // Visit the type parameters from a permissive context.
5374     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5375       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5376       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5377         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5378           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5379       // TODO: other template argument types?
5380     }
5381   }
5382 
5383   // Visit pointee types from a permissive context.
5384 #define CheckPolymorphic(Type) \
5385   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5386     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5387   }
5388   CheckPolymorphic(PointerTypeLoc)
5389   CheckPolymorphic(ReferenceTypeLoc)
5390   CheckPolymorphic(MemberPointerTypeLoc)
5391   CheckPolymorphic(BlockPointerTypeLoc)
5392   CheckPolymorphic(AtomicTypeLoc)
5393 
5394   /// Handle all the types we haven't given a more specific
5395   /// implementation for above.
5396   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5397     // Every other kind of type that we haven't called out already
5398     // that has an inner type is either (1) sugar or (2) contains that
5399     // inner type in some way as a subobject.
5400     if (TypeLoc Next = TL.getNextTypeLoc())
5401       return Visit(Next, Sel);
5402 
5403     // If there's no inner type and we're in a permissive context,
5404     // don't diagnose.
5405     if (Sel == Sema::AbstractNone) return;
5406 
5407     // Check whether the type matches the abstract type.
5408     QualType T = TL.getType();
5409     if (T->isArrayType()) {
5410       Sel = Sema::AbstractArrayType;
5411       T = Info.S.Context.getBaseElementType(T);
5412     }
5413     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5414     if (CT != Info.AbstractType) return;
5415 
5416     // It matched; do some magic.
5417     if (Sel == Sema::AbstractArrayType) {
5418       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5419         << T << TL.getSourceRange();
5420     } else {
5421       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5422         << Sel << T << TL.getSourceRange();
5423     }
5424     Info.DiagnoseAbstractType();
5425   }
5426 };
5427 
5428 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5429                                   Sema::AbstractDiagSelID Sel) {
5430   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5431 }
5432 
5433 }
5434 
5435 /// Check for invalid uses of an abstract type in a method declaration.
5436 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5437                                     CXXMethodDecl *MD) {
5438   // No need to do the check on definitions, which require that
5439   // the return/param types be complete.
5440   if (MD->doesThisDeclarationHaveABody())
5441     return;
5442 
5443   // For safety's sake, just ignore it if we don't have type source
5444   // information.  This should never happen for non-implicit methods,
5445   // but...
5446   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5447     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5448 }
5449 
5450 /// Check for invalid uses of an abstract type within a class definition.
5451 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5452                                     CXXRecordDecl *RD) {
5453   for (auto *D : RD->decls()) {
5454     if (D->isImplicit()) continue;
5455 
5456     // Methods and method templates.
5457     if (isa<CXXMethodDecl>(D)) {
5458       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5459     } else if (isa<FunctionTemplateDecl>(D)) {
5460       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5461       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5462 
5463     // Fields and static variables.
5464     } else if (isa<FieldDecl>(D)) {
5465       FieldDecl *FD = cast<FieldDecl>(D);
5466       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5467         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5468     } else if (isa<VarDecl>(D)) {
5469       VarDecl *VD = cast<VarDecl>(D);
5470       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5471         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5472 
5473     // Nested classes and class templates.
5474     } else if (isa<CXXRecordDecl>(D)) {
5475       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5476     } else if (isa<ClassTemplateDecl>(D)) {
5477       CheckAbstractClassUsage(Info,
5478                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5479     }
5480   }
5481 }
5482 
5483 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5484   Attr *ClassAttr = getDLLAttr(Class);
5485   if (!ClassAttr)
5486     return;
5487 
5488   assert(ClassAttr->getKind() == attr::DLLExport);
5489 
5490   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5491 
5492   if (TSK == TSK_ExplicitInstantiationDeclaration)
5493     // Don't go any further if this is just an explicit instantiation
5494     // declaration.
5495     return;
5496 
5497   for (Decl *Member : Class->decls()) {
5498     // Defined static variables that are members of an exported base
5499     // class must be marked export too.
5500     auto *VD = dyn_cast<VarDecl>(Member);
5501     if (VD && Member->getAttr<DLLExportAttr>() &&
5502         VD->getStorageClass() == SC_Static &&
5503         TSK == TSK_ImplicitInstantiation)
5504       S.MarkVariableReferenced(VD->getLocation(), VD);
5505 
5506     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5507     if (!MD)
5508       continue;
5509 
5510     if (Member->getAttr<DLLExportAttr>()) {
5511       if (MD->isUserProvided()) {
5512         // Instantiate non-default class member functions ...
5513 
5514         // .. except for certain kinds of template specializations.
5515         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5516           continue;
5517 
5518         S.MarkFunctionReferenced(Class->getLocation(), MD);
5519 
5520         // The function will be passed to the consumer when its definition is
5521         // encountered.
5522       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5523                  MD->isCopyAssignmentOperator() ||
5524                  MD->isMoveAssignmentOperator()) {
5525         // Synthesize and instantiate non-trivial implicit methods, explicitly
5526         // defaulted methods, and the copy and move assignment operators. The
5527         // latter are exported even if they are trivial, because the address of
5528         // an operator can be taken and should compare equal across libraries.
5529         DiagnosticErrorTrap Trap(S.Diags);
5530         S.MarkFunctionReferenced(Class->getLocation(), MD);
5531         if (Trap.hasErrorOccurred()) {
5532           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5533               << Class << !S.getLangOpts().CPlusPlus11;
5534           break;
5535         }
5536 
5537         // There is no later point when we will see the definition of this
5538         // function, so pass it to the consumer now.
5539         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5540       }
5541     }
5542   }
5543 }
5544 
5545 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5546                                                         CXXRecordDecl *Class) {
5547   // Only the MS ABI has default constructor closures, so we don't need to do
5548   // this semantic checking anywhere else.
5549   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5550     return;
5551 
5552   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5553   for (Decl *Member : Class->decls()) {
5554     // Look for exported default constructors.
5555     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5556     if (!CD || !CD->isDefaultConstructor())
5557       continue;
5558     auto *Attr = CD->getAttr<DLLExportAttr>();
5559     if (!Attr)
5560       continue;
5561 
5562     // If the class is non-dependent, mark the default arguments as ODR-used so
5563     // that we can properly codegen the constructor closure.
5564     if (!Class->isDependentContext()) {
5565       for (ParmVarDecl *PD : CD->parameters()) {
5566         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5567         S.DiscardCleanupsInEvaluationContext();
5568       }
5569     }
5570 
5571     if (LastExportedDefaultCtor) {
5572       S.Diag(LastExportedDefaultCtor->getLocation(),
5573              diag::err_attribute_dll_ambiguous_default_ctor)
5574           << Class;
5575       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5576           << CD->getDeclName();
5577       return;
5578     }
5579     LastExportedDefaultCtor = CD;
5580   }
5581 }
5582 
5583 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5584   // Mark any compiler-generated routines with the implicit code_seg attribute.
5585   for (auto *Method : Class->methods()) {
5586     if (Method->isUserProvided())
5587       continue;
5588     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5589       Method->addAttr(A);
5590   }
5591 }
5592 
5593 /// Check class-level dllimport/dllexport attribute.
5594 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5595   Attr *ClassAttr = getDLLAttr(Class);
5596 
5597   // MSVC inherits DLL attributes to partial class template specializations.
5598   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5599     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5600       if (Attr *TemplateAttr =
5601               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5602         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5603         A->setInherited(true);
5604         ClassAttr = A;
5605       }
5606     }
5607   }
5608 
5609   if (!ClassAttr)
5610     return;
5611 
5612   if (!Class->isExternallyVisible()) {
5613     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5614         << Class << ClassAttr;
5615     return;
5616   }
5617 
5618   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5619       !ClassAttr->isInherited()) {
5620     // Diagnose dll attributes on members of class with dll attribute.
5621     for (Decl *Member : Class->decls()) {
5622       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5623         continue;
5624       InheritableAttr *MemberAttr = getDLLAttr(Member);
5625       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5626         continue;
5627 
5628       Diag(MemberAttr->getLocation(),
5629              diag::err_attribute_dll_member_of_dll_class)
5630           << MemberAttr << ClassAttr;
5631       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5632       Member->setInvalidDecl();
5633     }
5634   }
5635 
5636   if (Class->getDescribedClassTemplate())
5637     // Don't inherit dll attribute until the template is instantiated.
5638     return;
5639 
5640   // The class is either imported or exported.
5641   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5642 
5643   // Check if this was a dllimport attribute propagated from a derived class to
5644   // a base class template specialization. We don't apply these attributes to
5645   // static data members.
5646   const bool PropagatedImport =
5647       !ClassExported &&
5648       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5649 
5650   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5651 
5652   // Ignore explicit dllexport on explicit class template instantiation declarations.
5653   if (ClassExported && !ClassAttr->isInherited() &&
5654       TSK == TSK_ExplicitInstantiationDeclaration) {
5655     Class->dropAttr<DLLExportAttr>();
5656     return;
5657   }
5658 
5659   // Force declaration of implicit members so they can inherit the attribute.
5660   ForceDeclarationOfImplicitMembers(Class);
5661 
5662   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5663   // seem to be true in practice?
5664 
5665   for (Decl *Member : Class->decls()) {
5666     VarDecl *VD = dyn_cast<VarDecl>(Member);
5667     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5668 
5669     // Only methods and static fields inherit the attributes.
5670     if (!VD && !MD)
5671       continue;
5672 
5673     if (MD) {
5674       // Don't process deleted methods.
5675       if (MD->isDeleted())
5676         continue;
5677 
5678       if (MD->isInlined()) {
5679         // MinGW does not import or export inline methods.
5680         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5681             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5682           continue;
5683 
5684         // MSVC versions before 2015 don't export the move assignment operators
5685         // and move constructor, so don't attempt to import/export them if
5686         // we have a definition.
5687         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5688         if ((MD->isMoveAssignmentOperator() ||
5689              (Ctor && Ctor->isMoveConstructor())) &&
5690             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5691           continue;
5692 
5693         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5694         // operator is exported anyway.
5695         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5696             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5697           continue;
5698       }
5699     }
5700 
5701     // Don't apply dllimport attributes to static data members of class template
5702     // instantiations when the attribute is propagated from a derived class.
5703     if (VD && PropagatedImport)
5704       continue;
5705 
5706     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5707       continue;
5708 
5709     if (!getDLLAttr(Member)) {
5710       InheritableAttr *NewAttr = nullptr;
5711 
5712       // Do not export/import inline function when -fno-dllexport-inlines is
5713       // passed. But add attribute for later local static var check.
5714       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5715           TSK != TSK_ExplicitInstantiationDeclaration &&
5716           TSK != TSK_ExplicitInstantiationDefinition) {
5717         if (ClassExported) {
5718           NewAttr = ::new (getASTContext())
5719             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5720                                      getASTContext(),
5721                                      ClassAttr->getSpellingListIndex());
5722         } else {
5723           NewAttr = ::new (getASTContext())
5724             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5725                                      getASTContext(),
5726                                      ClassAttr->getSpellingListIndex());
5727         }
5728       } else {
5729         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5730       }
5731 
5732       NewAttr->setInherited(true);
5733       Member->addAttr(NewAttr);
5734 
5735       if (MD) {
5736         // Propagate DLLAttr to friend re-declarations of MD that have already
5737         // been constructed.
5738         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5739              FD = FD->getPreviousDecl()) {
5740           if (FD->getFriendObjectKind() == Decl::FOK_None)
5741             continue;
5742           assert(!getDLLAttr(FD) &&
5743                  "friend re-decl should not already have a DLLAttr");
5744           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5745           NewAttr->setInherited(true);
5746           FD->addAttr(NewAttr);
5747         }
5748       }
5749     }
5750   }
5751 
5752   if (ClassExported)
5753     DelayedDllExportClasses.push_back(Class);
5754 }
5755 
5756 /// Perform propagation of DLL attributes from a derived class to a
5757 /// templated base class for MS compatibility.
5758 void Sema::propagateDLLAttrToBaseClassTemplate(
5759     CXXRecordDecl *Class, Attr *ClassAttr,
5760     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5761   if (getDLLAttr(
5762           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5763     // If the base class template has a DLL attribute, don't try to change it.
5764     return;
5765   }
5766 
5767   auto TSK = BaseTemplateSpec->getSpecializationKind();
5768   if (!getDLLAttr(BaseTemplateSpec) &&
5769       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5770        TSK == TSK_ImplicitInstantiation)) {
5771     // The template hasn't been instantiated yet (or it has, but only as an
5772     // explicit instantiation declaration or implicit instantiation, which means
5773     // we haven't codegenned any members yet), so propagate the attribute.
5774     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5775     NewAttr->setInherited(true);
5776     BaseTemplateSpec->addAttr(NewAttr);
5777 
5778     // If this was an import, mark that we propagated it from a derived class to
5779     // a base class template specialization.
5780     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5781       ImportAttr->setPropagatedToBaseTemplate();
5782 
5783     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5784     // needs to be run again to work see the new attribute. Otherwise this will
5785     // get run whenever the template is instantiated.
5786     if (TSK != TSK_Undeclared)
5787       checkClassLevelDLLAttribute(BaseTemplateSpec);
5788 
5789     return;
5790   }
5791 
5792   if (getDLLAttr(BaseTemplateSpec)) {
5793     // The template has already been specialized or instantiated with an
5794     // attribute, explicitly or through propagation. We should not try to change
5795     // it.
5796     return;
5797   }
5798 
5799   // The template was previously instantiated or explicitly specialized without
5800   // a dll attribute, It's too late for us to add an attribute, so warn that
5801   // this is unsupported.
5802   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5803       << BaseTemplateSpec->isExplicitSpecialization();
5804   Diag(ClassAttr->getLocation(), diag::note_attribute);
5805   if (BaseTemplateSpec->isExplicitSpecialization()) {
5806     Diag(BaseTemplateSpec->getLocation(),
5807            diag::note_template_class_explicit_specialization_was_here)
5808         << BaseTemplateSpec;
5809   } else {
5810     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5811            diag::note_template_class_instantiation_was_here)
5812         << BaseTemplateSpec;
5813   }
5814 }
5815 
5816 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5817                                         SourceLocation DefaultLoc) {
5818   switch (S.getSpecialMember(MD)) {
5819   case Sema::CXXDefaultConstructor:
5820     S.DefineImplicitDefaultConstructor(DefaultLoc,
5821                                        cast<CXXConstructorDecl>(MD));
5822     break;
5823   case Sema::CXXCopyConstructor:
5824     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5825     break;
5826   case Sema::CXXCopyAssignment:
5827     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5828     break;
5829   case Sema::CXXDestructor:
5830     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5831     break;
5832   case Sema::CXXMoveConstructor:
5833     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5834     break;
5835   case Sema::CXXMoveAssignment:
5836     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5837     break;
5838   case Sema::CXXInvalid:
5839     llvm_unreachable("Invalid special member.");
5840   }
5841 }
5842 
5843 /// Determine whether a type is permitted to be passed or returned in
5844 /// registers, per C++ [class.temporary]p3.
5845 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5846                                TargetInfo::CallingConvKind CCK) {
5847   if (D->isDependentType() || D->isInvalidDecl())
5848     return false;
5849 
5850   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5851   // The PS4 platform ABI follows the behavior of Clang 3.2.
5852   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5853     return !D->hasNonTrivialDestructorForCall() &&
5854            !D->hasNonTrivialCopyConstructorForCall();
5855 
5856   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5857     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5858     bool DtorIsTrivialForCall = false;
5859 
5860     // If a class has at least one non-deleted, trivial copy constructor, it
5861     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5862     //
5863     // Note: This permits classes with non-trivial copy or move ctors to be
5864     // passed in registers, so long as they *also* have a trivial copy ctor,
5865     // which is non-conforming.
5866     if (D->needsImplicitCopyConstructor()) {
5867       if (!D->defaultedCopyConstructorIsDeleted()) {
5868         if (D->hasTrivialCopyConstructor())
5869           CopyCtorIsTrivial = true;
5870         if (D->hasTrivialCopyConstructorForCall())
5871           CopyCtorIsTrivialForCall = true;
5872       }
5873     } else {
5874       for (const CXXConstructorDecl *CD : D->ctors()) {
5875         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5876           if (CD->isTrivial())
5877             CopyCtorIsTrivial = true;
5878           if (CD->isTrivialForCall())
5879             CopyCtorIsTrivialForCall = true;
5880         }
5881       }
5882     }
5883 
5884     if (D->needsImplicitDestructor()) {
5885       if (!D->defaultedDestructorIsDeleted() &&
5886           D->hasTrivialDestructorForCall())
5887         DtorIsTrivialForCall = true;
5888     } else if (const auto *DD = D->getDestructor()) {
5889       if (!DD->isDeleted() && DD->isTrivialForCall())
5890         DtorIsTrivialForCall = true;
5891     }
5892 
5893     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5894     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5895       return true;
5896 
5897     // If a class has a destructor, we'd really like to pass it indirectly
5898     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5899     // impossible for small types, which it will pass in a single register or
5900     // stack slot. Most objects with dtors are large-ish, so handle that early.
5901     // We can't call out all large objects as being indirect because there are
5902     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5903     // how we pass large POD types.
5904 
5905     // Note: This permits small classes with nontrivial destructors to be
5906     // passed in registers, which is non-conforming.
5907     if (CopyCtorIsTrivial &&
5908         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5909       return true;
5910     return false;
5911   }
5912 
5913   // Per C++ [class.temporary]p3, the relevant condition is:
5914   //   each copy constructor, move constructor, and destructor of X is
5915   //   either trivial or deleted, and X has at least one non-deleted copy
5916   //   or move constructor
5917   bool HasNonDeletedCopyOrMove = false;
5918 
5919   if (D->needsImplicitCopyConstructor() &&
5920       !D->defaultedCopyConstructorIsDeleted()) {
5921     if (!D->hasTrivialCopyConstructorForCall())
5922       return false;
5923     HasNonDeletedCopyOrMove = true;
5924   }
5925 
5926   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5927       !D->defaultedMoveConstructorIsDeleted()) {
5928     if (!D->hasTrivialMoveConstructorForCall())
5929       return false;
5930     HasNonDeletedCopyOrMove = true;
5931   }
5932 
5933   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5934       !D->hasTrivialDestructorForCall())
5935     return false;
5936 
5937   for (const CXXMethodDecl *MD : D->methods()) {
5938     if (MD->isDeleted())
5939       continue;
5940 
5941     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5942     if (CD && CD->isCopyOrMoveConstructor())
5943       HasNonDeletedCopyOrMove = true;
5944     else if (!isa<CXXDestructorDecl>(MD))
5945       continue;
5946 
5947     if (!MD->isTrivialForCall())
5948       return false;
5949   }
5950 
5951   return HasNonDeletedCopyOrMove;
5952 }
5953 
5954 /// Perform semantic checks on a class definition that has been
5955 /// completing, introducing implicitly-declared members, checking for
5956 /// abstract types, etc.
5957 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5958   if (!Record)
5959     return;
5960 
5961   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5962     AbstractUsageInfo Info(*this, Record);
5963     CheckAbstractClassUsage(Info, Record);
5964   }
5965 
5966   // If this is not an aggregate type and has no user-declared constructor,
5967   // complain about any non-static data members of reference or const scalar
5968   // type, since they will never get initializers.
5969   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5970       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5971       !Record->isLambda()) {
5972     bool Complained = false;
5973     for (const auto *F : Record->fields()) {
5974       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5975         continue;
5976 
5977       if (F->getType()->isReferenceType() ||
5978           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5979         if (!Complained) {
5980           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5981             << Record->getTagKind() << Record;
5982           Complained = true;
5983         }
5984 
5985         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5986           << F->getType()->isReferenceType()
5987           << F->getDeclName();
5988       }
5989     }
5990   }
5991 
5992   if (Record->getIdentifier()) {
5993     // C++ [class.mem]p13:
5994     //   If T is the name of a class, then each of the following shall have a
5995     //   name different from T:
5996     //     - every member of every anonymous union that is a member of class T.
5997     //
5998     // C++ [class.mem]p14:
5999     //   In addition, if class T has a user-declared constructor (12.1), every
6000     //   non-static data member of class T shall have a name different from T.
6001     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6002     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6003          ++I) {
6004       NamedDecl *D = (*I)->getUnderlyingDecl();
6005       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6006            Record->hasUserDeclaredConstructor()) ||
6007           isa<IndirectFieldDecl>(D)) {
6008         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6009           << D->getDeclName();
6010         break;
6011       }
6012     }
6013   }
6014 
6015   // Warn if the class has virtual methods but non-virtual public destructor.
6016   if (Record->isPolymorphic() && !Record->isDependentType()) {
6017     CXXDestructorDecl *dtor = Record->getDestructor();
6018     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6019         !Record->hasAttr<FinalAttr>())
6020       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6021            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6022   }
6023 
6024   if (Record->isAbstract()) {
6025     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6026       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6027         << FA->isSpelledAsSealed();
6028       DiagnoseAbstractType(Record);
6029     }
6030   }
6031 
6032   // See if trivial_abi has to be dropped.
6033   if (Record->hasAttr<TrivialABIAttr>())
6034     checkIllFormedTrivialABIStruct(*Record);
6035 
6036   // Set HasTrivialSpecialMemberForCall if the record has attribute
6037   // "trivial_abi".
6038   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6039 
6040   if (HasTrivialABI)
6041     Record->setHasTrivialSpecialMemberForCall();
6042 
6043   bool HasMethodWithOverrideControl = false,
6044        HasOverridingMethodWithoutOverrideControl = false;
6045   if (!Record->isDependentType()) {
6046     for (auto *M : Record->methods()) {
6047       // See if a method overloads virtual methods in a base
6048       // class without overriding any.
6049       if (!M->isStatic())
6050         DiagnoseHiddenVirtualMethods(M);
6051       if (M->hasAttr<OverrideAttr>())
6052         HasMethodWithOverrideControl = true;
6053       else if (M->size_overridden_methods() > 0)
6054         HasOverridingMethodWithoutOverrideControl = true;
6055       // Check whether the explicitly-defaulted special members are valid.
6056       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6057         CheckExplicitlyDefaultedSpecialMember(M);
6058 
6059       // For an explicitly defaulted or deleted special member, we defer
6060       // determining triviality until the class is complete. That time is now!
6061       CXXSpecialMember CSM = getSpecialMember(M);
6062       if (!M->isImplicit() && !M->isUserProvided()) {
6063         if (CSM != CXXInvalid) {
6064           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6065           // Inform the class that we've finished declaring this member.
6066           Record->finishedDefaultedOrDeletedMember(M);
6067           M->setTrivialForCall(
6068               HasTrivialABI ||
6069               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6070           Record->setTrivialForCallFlags(M);
6071         }
6072       }
6073 
6074       // Set triviality for the purpose of calls if this is a user-provided
6075       // copy/move constructor or destructor.
6076       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6077            CSM == CXXDestructor) && M->isUserProvided()) {
6078         M->setTrivialForCall(HasTrivialABI);
6079         Record->setTrivialForCallFlags(M);
6080       }
6081 
6082       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6083           M->hasAttr<DLLExportAttr>()) {
6084         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6085             M->isTrivial() &&
6086             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6087              CSM == CXXDestructor))
6088           M->dropAttr<DLLExportAttr>();
6089 
6090         if (M->hasAttr<DLLExportAttr>()) {
6091           DefineImplicitSpecialMember(*this, M, M->getLocation());
6092           ActOnFinishInlineFunctionDef(M);
6093         }
6094       }
6095     }
6096   }
6097 
6098   if (HasMethodWithOverrideControl &&
6099       HasOverridingMethodWithoutOverrideControl) {
6100     // At least one method has the 'override' control declared.
6101     // Diagnose all other overridden methods which do not have 'override' specified on them.
6102     for (auto *M : Record->methods())
6103       DiagnoseAbsenceOfOverrideControl(M);
6104   }
6105 
6106   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6107   // whether this class uses any C++ features that are implemented
6108   // completely differently in MSVC, and if so, emit a diagnostic.
6109   // That diagnostic defaults to an error, but we allow projects to
6110   // map it down to a warning (or ignore it).  It's a fairly common
6111   // practice among users of the ms_struct pragma to mass-annotate
6112   // headers, sweeping up a bunch of types that the project doesn't
6113   // really rely on MSVC-compatible layout for.  We must therefore
6114   // support "ms_struct except for C++ stuff" as a secondary ABI.
6115   if (Record->isMsStruct(Context) &&
6116       (Record->isPolymorphic() || Record->getNumBases())) {
6117     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6118   }
6119 
6120   checkClassLevelDLLAttribute(Record);
6121   checkClassLevelCodeSegAttribute(Record);
6122 
6123   bool ClangABICompat4 =
6124       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6125   TargetInfo::CallingConvKind CCK =
6126       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6127   bool CanPass = canPassInRegisters(*this, Record, CCK);
6128 
6129   // Do not change ArgPassingRestrictions if it has already been set to
6130   // APK_CanNeverPassInRegs.
6131   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6132     Record->setArgPassingRestrictions(CanPass
6133                                           ? RecordDecl::APK_CanPassInRegs
6134                                           : RecordDecl::APK_CannotPassInRegs);
6135 
6136   // If canPassInRegisters returns true despite the record having a non-trivial
6137   // destructor, the record is destructed in the callee. This happens only when
6138   // the record or one of its subobjects has a field annotated with trivial_abi
6139   // or a field qualified with ObjC __strong/__weak.
6140   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6141     Record->setParamDestroyedInCallee(true);
6142   else if (Record->hasNonTrivialDestructor())
6143     Record->setParamDestroyedInCallee(CanPass);
6144 
6145   if (getLangOpts().ForceEmitVTables) {
6146     // If we want to emit all the vtables, we need to mark it as used.  This
6147     // is especially required for cases like vtable assumption loads.
6148     MarkVTableUsed(Record->getInnerLocStart(), Record);
6149   }
6150 }
6151 
6152 /// Look up the special member function that would be called by a special
6153 /// member function for a subobject of class type.
6154 ///
6155 /// \param Class The class type of the subobject.
6156 /// \param CSM The kind of special member function.
6157 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6158 /// \param ConstRHS True if this is a copy operation with a const object
6159 ///        on its RHS, that is, if the argument to the outer special member
6160 ///        function is 'const' and this is not a field marked 'mutable'.
6161 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6162     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6163     unsigned FieldQuals, bool ConstRHS) {
6164   unsigned LHSQuals = 0;
6165   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6166     LHSQuals = FieldQuals;
6167 
6168   unsigned RHSQuals = FieldQuals;
6169   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6170     RHSQuals = 0;
6171   else if (ConstRHS)
6172     RHSQuals |= Qualifiers::Const;
6173 
6174   return S.LookupSpecialMember(Class, CSM,
6175                                RHSQuals & Qualifiers::Const,
6176                                RHSQuals & Qualifiers::Volatile,
6177                                false,
6178                                LHSQuals & Qualifiers::Const,
6179                                LHSQuals & Qualifiers::Volatile);
6180 }
6181 
6182 class Sema::InheritedConstructorInfo {
6183   Sema &S;
6184   SourceLocation UseLoc;
6185 
6186   /// A mapping from the base classes through which the constructor was
6187   /// inherited to the using shadow declaration in that base class (or a null
6188   /// pointer if the constructor was declared in that base class).
6189   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6190       InheritedFromBases;
6191 
6192 public:
6193   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6194                            ConstructorUsingShadowDecl *Shadow)
6195       : S(S), UseLoc(UseLoc) {
6196     bool DiagnosedMultipleConstructedBases = false;
6197     CXXRecordDecl *ConstructedBase = nullptr;
6198     UsingDecl *ConstructedBaseUsing = nullptr;
6199 
6200     // Find the set of such base class subobjects and check that there's a
6201     // unique constructed subobject.
6202     for (auto *D : Shadow->redecls()) {
6203       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6204       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6205       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6206 
6207       InheritedFromBases.insert(
6208           std::make_pair(DNominatedBase->getCanonicalDecl(),
6209                          DShadow->getNominatedBaseClassShadowDecl()));
6210       if (DShadow->constructsVirtualBase())
6211         InheritedFromBases.insert(
6212             std::make_pair(DConstructedBase->getCanonicalDecl(),
6213                            DShadow->getConstructedBaseClassShadowDecl()));
6214       else
6215         assert(DNominatedBase == DConstructedBase);
6216 
6217       // [class.inhctor.init]p2:
6218       //   If the constructor was inherited from multiple base class subobjects
6219       //   of type B, the program is ill-formed.
6220       if (!ConstructedBase) {
6221         ConstructedBase = DConstructedBase;
6222         ConstructedBaseUsing = D->getUsingDecl();
6223       } else if (ConstructedBase != DConstructedBase &&
6224                  !Shadow->isInvalidDecl()) {
6225         if (!DiagnosedMultipleConstructedBases) {
6226           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6227               << Shadow->getTargetDecl();
6228           S.Diag(ConstructedBaseUsing->getLocation(),
6229                diag::note_ambiguous_inherited_constructor_using)
6230               << ConstructedBase;
6231           DiagnosedMultipleConstructedBases = true;
6232         }
6233         S.Diag(D->getUsingDecl()->getLocation(),
6234                diag::note_ambiguous_inherited_constructor_using)
6235             << DConstructedBase;
6236       }
6237     }
6238 
6239     if (DiagnosedMultipleConstructedBases)
6240       Shadow->setInvalidDecl();
6241   }
6242 
6243   /// Find the constructor to use for inherited construction of a base class,
6244   /// and whether that base class constructor inherits the constructor from a
6245   /// virtual base class (in which case it won't actually invoke it).
6246   std::pair<CXXConstructorDecl *, bool>
6247   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6248     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6249     if (It == InheritedFromBases.end())
6250       return std::make_pair(nullptr, false);
6251 
6252     // This is an intermediary class.
6253     if (It->second)
6254       return std::make_pair(
6255           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6256           It->second->constructsVirtualBase());
6257 
6258     // This is the base class from which the constructor was inherited.
6259     return std::make_pair(Ctor, false);
6260   }
6261 };
6262 
6263 /// Is the special member function which would be selected to perform the
6264 /// specified operation on the specified class type a constexpr constructor?
6265 static bool
6266 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6267                          Sema::CXXSpecialMember CSM, unsigned Quals,
6268                          bool ConstRHS,
6269                          CXXConstructorDecl *InheritedCtor = nullptr,
6270                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6271   // If we're inheriting a constructor, see if we need to call it for this base
6272   // class.
6273   if (InheritedCtor) {
6274     assert(CSM == Sema::CXXDefaultConstructor);
6275     auto BaseCtor =
6276         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6277     if (BaseCtor)
6278       return BaseCtor->isConstexpr();
6279   }
6280 
6281   if (CSM == Sema::CXXDefaultConstructor)
6282     return ClassDecl->hasConstexprDefaultConstructor();
6283 
6284   Sema::SpecialMemberOverloadResult SMOR =
6285       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6286   if (!SMOR.getMethod())
6287     // A constructor we wouldn't select can't be "involved in initializing"
6288     // anything.
6289     return true;
6290   return SMOR.getMethod()->isConstexpr();
6291 }
6292 
6293 /// Determine whether the specified special member function would be constexpr
6294 /// if it were implicitly defined.
6295 static bool defaultedSpecialMemberIsConstexpr(
6296     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6297     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6298     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6299   if (!S.getLangOpts().CPlusPlus11)
6300     return false;
6301 
6302   // C++11 [dcl.constexpr]p4:
6303   // In the definition of a constexpr constructor [...]
6304   bool Ctor = true;
6305   switch (CSM) {
6306   case Sema::CXXDefaultConstructor:
6307     if (Inherited)
6308       break;
6309     // Since default constructor lookup is essentially trivial (and cannot
6310     // involve, for instance, template instantiation), we compute whether a
6311     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6312     //
6313     // This is important for performance; we need to know whether the default
6314     // constructor is constexpr to determine whether the type is a literal type.
6315     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6316 
6317   case Sema::CXXCopyConstructor:
6318   case Sema::CXXMoveConstructor:
6319     // For copy or move constructors, we need to perform overload resolution.
6320     break;
6321 
6322   case Sema::CXXCopyAssignment:
6323   case Sema::CXXMoveAssignment:
6324     if (!S.getLangOpts().CPlusPlus14)
6325       return false;
6326     // In C++1y, we need to perform overload resolution.
6327     Ctor = false;
6328     break;
6329 
6330   case Sema::CXXDestructor:
6331   case Sema::CXXInvalid:
6332     return false;
6333   }
6334 
6335   //   -- if the class is a non-empty union, or for each non-empty anonymous
6336   //      union member of a non-union class, exactly one non-static data member
6337   //      shall be initialized; [DR1359]
6338   //
6339   // If we squint, this is guaranteed, since exactly one non-static data member
6340   // will be initialized (if the constructor isn't deleted), we just don't know
6341   // which one.
6342   if (Ctor && ClassDecl->isUnion())
6343     return CSM == Sema::CXXDefaultConstructor
6344                ? ClassDecl->hasInClassInitializer() ||
6345                      !ClassDecl->hasVariantMembers()
6346                : true;
6347 
6348   //   -- the class shall not have any virtual base classes;
6349   if (Ctor && ClassDecl->getNumVBases())
6350     return false;
6351 
6352   // C++1y [class.copy]p26:
6353   //   -- [the class] is a literal type, and
6354   if (!Ctor && !ClassDecl->isLiteral())
6355     return false;
6356 
6357   //   -- every constructor involved in initializing [...] base class
6358   //      sub-objects shall be a constexpr constructor;
6359   //   -- the assignment operator selected to copy/move each direct base
6360   //      class is a constexpr function, and
6361   for (const auto &B : ClassDecl->bases()) {
6362     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6363     if (!BaseType) continue;
6364 
6365     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6366     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6367                                   InheritedCtor, Inherited))
6368       return false;
6369   }
6370 
6371   //   -- every constructor involved in initializing non-static data members
6372   //      [...] shall be a constexpr constructor;
6373   //   -- every non-static data member and base class sub-object shall be
6374   //      initialized
6375   //   -- for each non-static data member of X that is of class type (or array
6376   //      thereof), the assignment operator selected to copy/move that member is
6377   //      a constexpr function
6378   for (const auto *F : ClassDecl->fields()) {
6379     if (F->isInvalidDecl())
6380       continue;
6381     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6382       continue;
6383     QualType BaseType = S.Context.getBaseElementType(F->getType());
6384     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6385       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6386       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6387                                     BaseType.getCVRQualifiers(),
6388                                     ConstArg && !F->isMutable()))
6389         return false;
6390     } else if (CSM == Sema::CXXDefaultConstructor) {
6391       return false;
6392     }
6393   }
6394 
6395   // All OK, it's constexpr!
6396   return true;
6397 }
6398 
6399 static Sema::ImplicitExceptionSpecification
6400 ComputeDefaultedSpecialMemberExceptionSpec(
6401     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6402     Sema::InheritedConstructorInfo *ICI);
6403 
6404 static Sema::ImplicitExceptionSpecification
6405 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6406   auto CSM = S.getSpecialMember(MD);
6407   if (CSM != Sema::CXXInvalid)
6408     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6409 
6410   auto *CD = cast<CXXConstructorDecl>(MD);
6411   assert(CD->getInheritedConstructor() &&
6412          "only special members have implicit exception specs");
6413   Sema::InheritedConstructorInfo ICI(
6414       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6415   return ComputeDefaultedSpecialMemberExceptionSpec(
6416       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6417 }
6418 
6419 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6420                                                             CXXMethodDecl *MD) {
6421   FunctionProtoType::ExtProtoInfo EPI;
6422 
6423   // Build an exception specification pointing back at this member.
6424   EPI.ExceptionSpec.Type = EST_Unevaluated;
6425   EPI.ExceptionSpec.SourceDecl = MD;
6426 
6427   // Set the calling convention to the default for C++ instance methods.
6428   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6429       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6430                                             /*IsCXXMethod=*/true));
6431   return EPI;
6432 }
6433 
6434 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6435   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6436   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6437     return;
6438 
6439   // Evaluate the exception specification.
6440   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6441   auto ESI = IES.getExceptionSpec();
6442 
6443   // Update the type of the special member to use it.
6444   UpdateExceptionSpec(MD, ESI);
6445 
6446   // A user-provided destructor can be defined outside the class. When that
6447   // happens, be sure to update the exception specification on both
6448   // declarations.
6449   const FunctionProtoType *CanonicalFPT =
6450     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6451   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6452     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6453 }
6454 
6455 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6456   CXXRecordDecl *RD = MD->getParent();
6457   CXXSpecialMember CSM = getSpecialMember(MD);
6458 
6459   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6460          "not an explicitly-defaulted special member");
6461 
6462   // Whether this was the first-declared instance of the constructor.
6463   // This affects whether we implicitly add an exception spec and constexpr.
6464   bool First = MD == MD->getCanonicalDecl();
6465 
6466   bool HadError = false;
6467 
6468   // C++11 [dcl.fct.def.default]p1:
6469   //   A function that is explicitly defaulted shall
6470   //     -- be a special member function (checked elsewhere),
6471   //     -- have the same type (except for ref-qualifiers, and except that a
6472   //        copy operation can take a non-const reference) as an implicit
6473   //        declaration, and
6474   //     -- not have default arguments.
6475   // C++2a changes the second bullet to instead delete the function if it's
6476   // defaulted on its first declaration, unless it's "an assignment operator,
6477   // and its return type differs or its parameter type is not a reference".
6478   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6479   bool ShouldDeleteForTypeMismatch = false;
6480   unsigned ExpectedParams = 1;
6481   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6482     ExpectedParams = 0;
6483   if (MD->getNumParams() != ExpectedParams) {
6484     // This checks for default arguments: a copy or move constructor with a
6485     // default argument is classified as a default constructor, and assignment
6486     // operations and destructors can't have default arguments.
6487     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6488       << CSM << MD->getSourceRange();
6489     HadError = true;
6490   } else if (MD->isVariadic()) {
6491     if (DeleteOnTypeMismatch)
6492       ShouldDeleteForTypeMismatch = true;
6493     else {
6494       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6495         << CSM << MD->getSourceRange();
6496       HadError = true;
6497     }
6498   }
6499 
6500   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6501 
6502   bool CanHaveConstParam = false;
6503   if (CSM == CXXCopyConstructor)
6504     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6505   else if (CSM == CXXCopyAssignment)
6506     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6507 
6508   QualType ReturnType = Context.VoidTy;
6509   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6510     // Check for return type matching.
6511     ReturnType = Type->getReturnType();
6512     QualType ExpectedReturnType =
6513         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6514     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6515       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6516         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6517       HadError = true;
6518     }
6519 
6520     // A defaulted special member cannot have cv-qualifiers.
6521     if (Type->getTypeQuals()) {
6522       if (DeleteOnTypeMismatch)
6523         ShouldDeleteForTypeMismatch = true;
6524       else {
6525         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6526           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6527         HadError = true;
6528       }
6529     }
6530   }
6531 
6532   // Check for parameter type matching.
6533   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6534   bool HasConstParam = false;
6535   if (ExpectedParams && ArgType->isReferenceType()) {
6536     // Argument must be reference to possibly-const T.
6537     QualType ReferentType = ArgType->getPointeeType();
6538     HasConstParam = ReferentType.isConstQualified();
6539 
6540     if (ReferentType.isVolatileQualified()) {
6541       if (DeleteOnTypeMismatch)
6542         ShouldDeleteForTypeMismatch = true;
6543       else {
6544         Diag(MD->getLocation(),
6545              diag::err_defaulted_special_member_volatile_param) << CSM;
6546         HadError = true;
6547       }
6548     }
6549 
6550     if (HasConstParam && !CanHaveConstParam) {
6551       if (DeleteOnTypeMismatch)
6552         ShouldDeleteForTypeMismatch = true;
6553       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6554         Diag(MD->getLocation(),
6555              diag::err_defaulted_special_member_copy_const_param)
6556           << (CSM == CXXCopyAssignment);
6557         // FIXME: Explain why this special member can't be const.
6558         HadError = true;
6559       } else {
6560         Diag(MD->getLocation(),
6561              diag::err_defaulted_special_member_move_const_param)
6562           << (CSM == CXXMoveAssignment);
6563         HadError = true;
6564       }
6565     }
6566   } else if (ExpectedParams) {
6567     // A copy assignment operator can take its argument by value, but a
6568     // defaulted one cannot.
6569     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6570     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6571     HadError = true;
6572   }
6573 
6574   // C++11 [dcl.fct.def.default]p2:
6575   //   An explicitly-defaulted function may be declared constexpr only if it
6576   //   would have been implicitly declared as constexpr,
6577   // Do not apply this rule to members of class templates, since core issue 1358
6578   // makes such functions always instantiate to constexpr functions. For
6579   // functions which cannot be constexpr (for non-constructors in C++11 and for
6580   // destructors in C++1y), this is checked elsewhere.
6581   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6582                                                      HasConstParam);
6583   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6584                                  : isa<CXXConstructorDecl>(MD)) &&
6585       MD->isConstexpr() && !Constexpr &&
6586       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6587     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6588     // FIXME: Explain why the special member can't be constexpr.
6589     HadError = true;
6590   }
6591 
6592   //   and may have an explicit exception-specification only if it is compatible
6593   //   with the exception-specification on the implicit declaration.
6594   if (Type->hasExceptionSpec()) {
6595     // Delay the check if this is the first declaration of the special member,
6596     // since we may not have parsed some necessary in-class initializers yet.
6597     if (First) {
6598       // If the exception specification needs to be instantiated, do so now,
6599       // before we clobber it with an EST_Unevaluated specification below.
6600       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6601         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6602         Type = MD->getType()->getAs<FunctionProtoType>();
6603       }
6604       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6605     } else
6606       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6607   }
6608 
6609   //   If a function is explicitly defaulted on its first declaration,
6610   if (First) {
6611     //  -- it is implicitly considered to be constexpr if the implicit
6612     //     definition would be,
6613     MD->setConstexpr(Constexpr);
6614 
6615     //  -- it is implicitly considered to have the same exception-specification
6616     //     as if it had been implicitly declared,
6617     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6618     EPI.ExceptionSpec.Type = EST_Unevaluated;
6619     EPI.ExceptionSpec.SourceDecl = MD;
6620     MD->setType(Context.getFunctionType(ReturnType,
6621                                         llvm::makeArrayRef(&ArgType,
6622                                                            ExpectedParams),
6623                                         EPI));
6624   }
6625 
6626   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6627     if (First) {
6628       SetDeclDeleted(MD, MD->getLocation());
6629       if (!inTemplateInstantiation() && !HadError) {
6630         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6631         if (ShouldDeleteForTypeMismatch) {
6632           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6633         } else {
6634           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6635         }
6636       }
6637       if (ShouldDeleteForTypeMismatch && !HadError) {
6638         Diag(MD->getLocation(),
6639              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6640       }
6641     } else {
6642       // C++11 [dcl.fct.def.default]p4:
6643       //   [For a] user-provided explicitly-defaulted function [...] if such a
6644       //   function is implicitly defined as deleted, the program is ill-formed.
6645       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6646       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6647       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6648       HadError = true;
6649     }
6650   }
6651 
6652   if (HadError)
6653     MD->setInvalidDecl();
6654 }
6655 
6656 /// Check whether the exception specification provided for an
6657 /// explicitly-defaulted special member matches the exception specification
6658 /// that would have been generated for an implicit special member, per
6659 /// C++11 [dcl.fct.def.default]p2.
6660 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6661     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6662   // If the exception specification was explicitly specified but hadn't been
6663   // parsed when the method was defaulted, grab it now.
6664   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6665     SpecifiedType =
6666         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6667 
6668   // Compute the implicit exception specification.
6669   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6670                                                        /*IsCXXMethod=*/true);
6671   FunctionProtoType::ExtProtoInfo EPI(CC);
6672   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6673   EPI.ExceptionSpec = IES.getExceptionSpec();
6674   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6675     Context.getFunctionType(Context.VoidTy, None, EPI));
6676 
6677   // Ensure that it matches.
6678   CheckEquivalentExceptionSpec(
6679     PDiag(diag::err_incorrect_defaulted_exception_spec)
6680       << getSpecialMember(MD), PDiag(),
6681     ImplicitType, SourceLocation(),
6682     SpecifiedType, MD->getLocation());
6683 }
6684 
6685 void Sema::CheckDelayedMemberExceptionSpecs() {
6686   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6687   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6688   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6689 
6690   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6691   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6692   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6693 
6694   // Perform any deferred checking of exception specifications for virtual
6695   // destructors.
6696   for (auto &Check : Overriding)
6697     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6698 
6699   // Perform any deferred checking of exception specifications for befriended
6700   // special members.
6701   for (auto &Check : Equivalent)
6702     CheckEquivalentExceptionSpec(Check.second, Check.first);
6703 
6704   // Check that any explicitly-defaulted methods have exception specifications
6705   // compatible with their implicit exception specifications.
6706   for (auto &Spec : Defaulted)
6707     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6708 }
6709 
6710 namespace {
6711 /// CRTP base class for visiting operations performed by a special member
6712 /// function (or inherited constructor).
6713 template<typename Derived>
6714 struct SpecialMemberVisitor {
6715   Sema &S;
6716   CXXMethodDecl *MD;
6717   Sema::CXXSpecialMember CSM;
6718   Sema::InheritedConstructorInfo *ICI;
6719 
6720   // Properties of the special member, computed for convenience.
6721   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6722 
6723   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6724                        Sema::InheritedConstructorInfo *ICI)
6725       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6726     switch (CSM) {
6727     case Sema::CXXDefaultConstructor:
6728     case Sema::CXXCopyConstructor:
6729     case Sema::CXXMoveConstructor:
6730       IsConstructor = true;
6731       break;
6732     case Sema::CXXCopyAssignment:
6733     case Sema::CXXMoveAssignment:
6734       IsAssignment = true;
6735       break;
6736     case Sema::CXXDestructor:
6737       break;
6738     case Sema::CXXInvalid:
6739       llvm_unreachable("invalid special member kind");
6740     }
6741 
6742     if (MD->getNumParams()) {
6743       if (const ReferenceType *RT =
6744               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6745         ConstArg = RT->getPointeeType().isConstQualified();
6746     }
6747   }
6748 
6749   Derived &getDerived() { return static_cast<Derived&>(*this); }
6750 
6751   /// Is this a "move" special member?
6752   bool isMove() const {
6753     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6754   }
6755 
6756   /// Look up the corresponding special member in the given class.
6757   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6758                                              unsigned Quals, bool IsMutable) {
6759     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6760                                        ConstArg && !IsMutable);
6761   }
6762 
6763   /// Look up the constructor for the specified base class to see if it's
6764   /// overridden due to this being an inherited constructor.
6765   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6766     if (!ICI)
6767       return {};
6768     assert(CSM == Sema::CXXDefaultConstructor);
6769     auto *BaseCtor =
6770       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6771     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6772       return MD;
6773     return {};
6774   }
6775 
6776   /// A base or member subobject.
6777   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6778 
6779   /// Get the location to use for a subobject in diagnostics.
6780   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6781     // FIXME: For an indirect virtual base, the direct base leading to
6782     // the indirect virtual base would be a more useful choice.
6783     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6784       return B->getBaseTypeLoc();
6785     else
6786       return Subobj.get<FieldDecl*>()->getLocation();
6787   }
6788 
6789   enum BasesToVisit {
6790     /// Visit all non-virtual (direct) bases.
6791     VisitNonVirtualBases,
6792     /// Visit all direct bases, virtual or not.
6793     VisitDirectBases,
6794     /// Visit all non-virtual bases, and all virtual bases if the class
6795     /// is not abstract.
6796     VisitPotentiallyConstructedBases,
6797     /// Visit all direct or virtual bases.
6798     VisitAllBases
6799   };
6800 
6801   // Visit the bases and members of the class.
6802   bool visit(BasesToVisit Bases) {
6803     CXXRecordDecl *RD = MD->getParent();
6804 
6805     if (Bases == VisitPotentiallyConstructedBases)
6806       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6807 
6808     for (auto &B : RD->bases())
6809       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6810           getDerived().visitBase(&B))
6811         return true;
6812 
6813     if (Bases == VisitAllBases)
6814       for (auto &B : RD->vbases())
6815         if (getDerived().visitBase(&B))
6816           return true;
6817 
6818     for (auto *F : RD->fields())
6819       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6820           getDerived().visitField(F))
6821         return true;
6822 
6823     return false;
6824   }
6825 };
6826 }
6827 
6828 namespace {
6829 struct SpecialMemberDeletionInfo
6830     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6831   bool Diagnose;
6832 
6833   SourceLocation Loc;
6834 
6835   bool AllFieldsAreConst;
6836 
6837   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6838                             Sema::CXXSpecialMember CSM,
6839                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6840       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6841         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6842 
6843   bool inUnion() const { return MD->getParent()->isUnion(); }
6844 
6845   Sema::CXXSpecialMember getEffectiveCSM() {
6846     return ICI ? Sema::CXXInvalid : CSM;
6847   }
6848 
6849   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6850   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6851 
6852   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6853   bool shouldDeleteForField(FieldDecl *FD);
6854   bool shouldDeleteForAllConstMembers();
6855 
6856   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6857                                      unsigned Quals);
6858   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6859                                     Sema::SpecialMemberOverloadResult SMOR,
6860                                     bool IsDtorCallInCtor);
6861 
6862   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6863 };
6864 }
6865 
6866 /// Is the given special member inaccessible when used on the given
6867 /// sub-object.
6868 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6869                                              CXXMethodDecl *target) {
6870   /// If we're operating on a base class, the object type is the
6871   /// type of this special member.
6872   QualType objectTy;
6873   AccessSpecifier access = target->getAccess();
6874   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6875     objectTy = S.Context.getTypeDeclType(MD->getParent());
6876     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6877 
6878   // If we're operating on a field, the object type is the type of the field.
6879   } else {
6880     objectTy = S.Context.getTypeDeclType(target->getParent());
6881   }
6882 
6883   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6884 }
6885 
6886 /// Check whether we should delete a special member due to the implicit
6887 /// definition containing a call to a special member of a subobject.
6888 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6889     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6890     bool IsDtorCallInCtor) {
6891   CXXMethodDecl *Decl = SMOR.getMethod();
6892   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6893 
6894   int DiagKind = -1;
6895 
6896   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6897     DiagKind = !Decl ? 0 : 1;
6898   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6899     DiagKind = 2;
6900   else if (!isAccessible(Subobj, Decl))
6901     DiagKind = 3;
6902   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6903            !Decl->isTrivial()) {
6904     // A member of a union must have a trivial corresponding special member.
6905     // As a weird special case, a destructor call from a union's constructor
6906     // must be accessible and non-deleted, but need not be trivial. Such a
6907     // destructor is never actually called, but is semantically checked as
6908     // if it were.
6909     DiagKind = 4;
6910   }
6911 
6912   if (DiagKind == -1)
6913     return false;
6914 
6915   if (Diagnose) {
6916     if (Field) {
6917       S.Diag(Field->getLocation(),
6918              diag::note_deleted_special_member_class_subobject)
6919         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6920         << Field << DiagKind << IsDtorCallInCtor;
6921     } else {
6922       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6923       S.Diag(Base->getBeginLoc(),
6924              diag::note_deleted_special_member_class_subobject)
6925           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6926           << Base->getType() << DiagKind << IsDtorCallInCtor;
6927     }
6928 
6929     if (DiagKind == 1)
6930       S.NoteDeletedFunction(Decl);
6931     // FIXME: Explain inaccessibility if DiagKind == 3.
6932   }
6933 
6934   return true;
6935 }
6936 
6937 /// Check whether we should delete a special member function due to having a
6938 /// direct or virtual base class or non-static data member of class type M.
6939 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6940     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6941   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6942   bool IsMutable = Field && Field->isMutable();
6943 
6944   // C++11 [class.ctor]p5:
6945   // -- any direct or virtual base class, or non-static data member with no
6946   //    brace-or-equal-initializer, has class type M (or array thereof) and
6947   //    either M has no default constructor or overload resolution as applied
6948   //    to M's default constructor results in an ambiguity or in a function
6949   //    that is deleted or inaccessible
6950   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6951   // -- a direct or virtual base class B that cannot be copied/moved because
6952   //    overload resolution, as applied to B's corresponding special member,
6953   //    results in an ambiguity or a function that is deleted or inaccessible
6954   //    from the defaulted special member
6955   // C++11 [class.dtor]p5:
6956   // -- any direct or virtual base class [...] has a type with a destructor
6957   //    that is deleted or inaccessible
6958   if (!(CSM == Sema::CXXDefaultConstructor &&
6959         Field && Field->hasInClassInitializer()) &&
6960       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6961                                    false))
6962     return true;
6963 
6964   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6965   // -- any direct or virtual base class or non-static data member has a
6966   //    type with a destructor that is deleted or inaccessible
6967   if (IsConstructor) {
6968     Sema::SpecialMemberOverloadResult SMOR =
6969         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6970                               false, false, false, false, false);
6971     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6972       return true;
6973   }
6974 
6975   return false;
6976 }
6977 
6978 /// Check whether we should delete a special member function due to the class
6979 /// having a particular direct or virtual base class.
6980 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6981   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6982   // If program is correct, BaseClass cannot be null, but if it is, the error
6983   // must be reported elsewhere.
6984   if (!BaseClass)
6985     return false;
6986   // If we have an inheriting constructor, check whether we're calling an
6987   // inherited constructor instead of a default constructor.
6988   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6989   if (auto *BaseCtor = SMOR.getMethod()) {
6990     // Note that we do not check access along this path; other than that,
6991     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6992     // FIXME: Check that the base has a usable destructor! Sink this into
6993     // shouldDeleteForClassSubobject.
6994     if (BaseCtor->isDeleted() && Diagnose) {
6995       S.Diag(Base->getBeginLoc(),
6996              diag::note_deleted_special_member_class_subobject)
6997           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6998           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
6999       S.NoteDeletedFunction(BaseCtor);
7000     }
7001     return BaseCtor->isDeleted();
7002   }
7003   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7004 }
7005 
7006 /// Check whether we should delete a special member function due to the class
7007 /// having a particular non-static data member.
7008 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7009   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7010   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7011 
7012   if (CSM == Sema::CXXDefaultConstructor) {
7013     // For a default constructor, all references must be initialized in-class
7014     // and, if a union, it must have a non-const member.
7015     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7016       if (Diagnose)
7017         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7018           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7019       return true;
7020     }
7021     // C++11 [class.ctor]p5: any non-variant non-static data member of
7022     // const-qualified type (or array thereof) with no
7023     // brace-or-equal-initializer does not have a user-provided default
7024     // constructor.
7025     if (!inUnion() && FieldType.isConstQualified() &&
7026         !FD->hasInClassInitializer() &&
7027         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7028       if (Diagnose)
7029         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7030           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7031       return true;
7032     }
7033 
7034     if (inUnion() && !FieldType.isConstQualified())
7035       AllFieldsAreConst = false;
7036   } else if (CSM == Sema::CXXCopyConstructor) {
7037     // For a copy constructor, data members must not be of rvalue reference
7038     // type.
7039     if (FieldType->isRValueReferenceType()) {
7040       if (Diagnose)
7041         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7042           << MD->getParent() << FD << FieldType;
7043       return true;
7044     }
7045   } else if (IsAssignment) {
7046     // For an assignment operator, data members must not be of reference type.
7047     if (FieldType->isReferenceType()) {
7048       if (Diagnose)
7049         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7050           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7051       return true;
7052     }
7053     if (!FieldRecord && FieldType.isConstQualified()) {
7054       // C++11 [class.copy]p23:
7055       // -- a non-static data member of const non-class type (or array thereof)
7056       if (Diagnose)
7057         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7058           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7059       return true;
7060     }
7061   }
7062 
7063   if (FieldRecord) {
7064     // Some additional restrictions exist on the variant members.
7065     if (!inUnion() && FieldRecord->isUnion() &&
7066         FieldRecord->isAnonymousStructOrUnion()) {
7067       bool AllVariantFieldsAreConst = true;
7068 
7069       // FIXME: Handle anonymous unions declared within anonymous unions.
7070       for (auto *UI : FieldRecord->fields()) {
7071         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7072 
7073         if (!UnionFieldType.isConstQualified())
7074           AllVariantFieldsAreConst = false;
7075 
7076         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7077         if (UnionFieldRecord &&
7078             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7079                                           UnionFieldType.getCVRQualifiers()))
7080           return true;
7081       }
7082 
7083       // At least one member in each anonymous union must be non-const
7084       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7085           !FieldRecord->field_empty()) {
7086         if (Diagnose)
7087           S.Diag(FieldRecord->getLocation(),
7088                  diag::note_deleted_default_ctor_all_const)
7089             << !!ICI << MD->getParent() << /*anonymous union*/1;
7090         return true;
7091       }
7092 
7093       // Don't check the implicit member of the anonymous union type.
7094       // This is technically non-conformant, but sanity demands it.
7095       return false;
7096     }
7097 
7098     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7099                                       FieldType.getCVRQualifiers()))
7100       return true;
7101   }
7102 
7103   return false;
7104 }
7105 
7106 /// C++11 [class.ctor] p5:
7107 ///   A defaulted default constructor for a class X is defined as deleted if
7108 /// X is a union and all of its variant members are of const-qualified type.
7109 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7110   // This is a silly definition, because it gives an empty union a deleted
7111   // default constructor. Don't do that.
7112   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7113     bool AnyFields = false;
7114     for (auto *F : MD->getParent()->fields())
7115       if ((AnyFields = !F->isUnnamedBitfield()))
7116         break;
7117     if (!AnyFields)
7118       return false;
7119     if (Diagnose)
7120       S.Diag(MD->getParent()->getLocation(),
7121              diag::note_deleted_default_ctor_all_const)
7122         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7123     return true;
7124   }
7125   return false;
7126 }
7127 
7128 /// Determine whether a defaulted special member function should be defined as
7129 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7130 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7131 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7132                                      InheritedConstructorInfo *ICI,
7133                                      bool Diagnose) {
7134   if (MD->isInvalidDecl())
7135     return false;
7136   CXXRecordDecl *RD = MD->getParent();
7137   assert(!RD->isDependentType() && "do deletion after instantiation");
7138   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7139     return false;
7140 
7141   // C++11 [expr.lambda.prim]p19:
7142   //   The closure type associated with a lambda-expression has a
7143   //   deleted (8.4.3) default constructor and a deleted copy
7144   //   assignment operator.
7145   // C++2a adds back these operators if the lambda has no capture-default.
7146   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7147       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7148     if (Diagnose)
7149       Diag(RD->getLocation(), diag::note_lambda_decl);
7150     return true;
7151   }
7152 
7153   // For an anonymous struct or union, the copy and assignment special members
7154   // will never be used, so skip the check. For an anonymous union declared at
7155   // namespace scope, the constructor and destructor are used.
7156   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7157       RD->isAnonymousStructOrUnion())
7158     return false;
7159 
7160   // C++11 [class.copy]p7, p18:
7161   //   If the class definition declares a move constructor or move assignment
7162   //   operator, an implicitly declared copy constructor or copy assignment
7163   //   operator is defined as deleted.
7164   if (MD->isImplicit() &&
7165       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7166     CXXMethodDecl *UserDeclaredMove = nullptr;
7167 
7168     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7169     // deletion of the corresponding copy operation, not both copy operations.
7170     // MSVC 2015 has adopted the standards conforming behavior.
7171     bool DeletesOnlyMatchingCopy =
7172         getLangOpts().MSVCCompat &&
7173         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7174 
7175     if (RD->hasUserDeclaredMoveConstructor() &&
7176         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7177       if (!Diagnose) return true;
7178 
7179       // Find any user-declared move constructor.
7180       for (auto *I : RD->ctors()) {
7181         if (I->isMoveConstructor()) {
7182           UserDeclaredMove = I;
7183           break;
7184         }
7185       }
7186       assert(UserDeclaredMove);
7187     } else if (RD->hasUserDeclaredMoveAssignment() &&
7188                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7189       if (!Diagnose) return true;
7190 
7191       // Find any user-declared move assignment operator.
7192       for (auto *I : RD->methods()) {
7193         if (I->isMoveAssignmentOperator()) {
7194           UserDeclaredMove = I;
7195           break;
7196         }
7197       }
7198       assert(UserDeclaredMove);
7199     }
7200 
7201     if (UserDeclaredMove) {
7202       Diag(UserDeclaredMove->getLocation(),
7203            diag::note_deleted_copy_user_declared_move)
7204         << (CSM == CXXCopyAssignment) << RD
7205         << UserDeclaredMove->isMoveAssignmentOperator();
7206       return true;
7207     }
7208   }
7209 
7210   // Do access control from the special member function
7211   ContextRAII MethodContext(*this, MD);
7212 
7213   // C++11 [class.dtor]p5:
7214   // -- for a virtual destructor, lookup of the non-array deallocation function
7215   //    results in an ambiguity or in a function that is deleted or inaccessible
7216   if (CSM == CXXDestructor && MD->isVirtual()) {
7217     FunctionDecl *OperatorDelete = nullptr;
7218     DeclarationName Name =
7219       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7220     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7221                                  OperatorDelete, /*Diagnose*/false)) {
7222       if (Diagnose)
7223         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7224       return true;
7225     }
7226   }
7227 
7228   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7229 
7230   // Per DR1611, do not consider virtual bases of constructors of abstract
7231   // classes, since we are not going to construct them.
7232   // Per DR1658, do not consider virtual bases of destructors of abstract
7233   // classes either.
7234   // Per DR2180, for assignment operators we only assign (and thus only
7235   // consider) direct bases.
7236   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7237                                  : SMI.VisitPotentiallyConstructedBases))
7238     return true;
7239 
7240   if (SMI.shouldDeleteForAllConstMembers())
7241     return true;
7242 
7243   if (getLangOpts().CUDA) {
7244     // We should delete the special member in CUDA mode if target inference
7245     // failed.
7246     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7247     // is treated as certain special member, which may not reflect what special
7248     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7249     // expects CSM to match MD, therefore recalculate CSM.
7250     assert(ICI || CSM == getSpecialMember(MD));
7251     auto RealCSM = CSM;
7252     if (ICI)
7253       RealCSM = getSpecialMember(MD);
7254 
7255     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7256                                                    SMI.ConstArg, Diagnose);
7257   }
7258 
7259   return false;
7260 }
7261 
7262 /// Perform lookup for a special member of the specified kind, and determine
7263 /// whether it is trivial. If the triviality can be determined without the
7264 /// lookup, skip it. This is intended for use when determining whether a
7265 /// special member of a containing object is trivial, and thus does not ever
7266 /// perform overload resolution for default constructors.
7267 ///
7268 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7269 /// member that was most likely to be intended to be trivial, if any.
7270 ///
7271 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7272 /// determine whether the special member is trivial.
7273 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7274                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7275                                      bool ConstRHS,
7276                                      Sema::TrivialABIHandling TAH,
7277                                      CXXMethodDecl **Selected) {
7278   if (Selected)
7279     *Selected = nullptr;
7280 
7281   switch (CSM) {
7282   case Sema::CXXInvalid:
7283     llvm_unreachable("not a special member");
7284 
7285   case Sema::CXXDefaultConstructor:
7286     // C++11 [class.ctor]p5:
7287     //   A default constructor is trivial if:
7288     //    - all the [direct subobjects] have trivial default constructors
7289     //
7290     // Note, no overload resolution is performed in this case.
7291     if (RD->hasTrivialDefaultConstructor())
7292       return true;
7293 
7294     if (Selected) {
7295       // If there's a default constructor which could have been trivial, dig it
7296       // out. Otherwise, if there's any user-provided default constructor, point
7297       // to that as an example of why there's not a trivial one.
7298       CXXConstructorDecl *DefCtor = nullptr;
7299       if (RD->needsImplicitDefaultConstructor())
7300         S.DeclareImplicitDefaultConstructor(RD);
7301       for (auto *CI : RD->ctors()) {
7302         if (!CI->isDefaultConstructor())
7303           continue;
7304         DefCtor = CI;
7305         if (!DefCtor->isUserProvided())
7306           break;
7307       }
7308 
7309       *Selected = DefCtor;
7310     }
7311 
7312     return false;
7313 
7314   case Sema::CXXDestructor:
7315     // C++11 [class.dtor]p5:
7316     //   A destructor is trivial if:
7317     //    - all the direct [subobjects] have trivial destructors
7318     if (RD->hasTrivialDestructor() ||
7319         (TAH == Sema::TAH_ConsiderTrivialABI &&
7320          RD->hasTrivialDestructorForCall()))
7321       return true;
7322 
7323     if (Selected) {
7324       if (RD->needsImplicitDestructor())
7325         S.DeclareImplicitDestructor(RD);
7326       *Selected = RD->getDestructor();
7327     }
7328 
7329     return false;
7330 
7331   case Sema::CXXCopyConstructor:
7332     // C++11 [class.copy]p12:
7333     //   A copy constructor is trivial if:
7334     //    - the constructor selected to copy each direct [subobject] is trivial
7335     if (RD->hasTrivialCopyConstructor() ||
7336         (TAH == Sema::TAH_ConsiderTrivialABI &&
7337          RD->hasTrivialCopyConstructorForCall())) {
7338       if (Quals == Qualifiers::Const)
7339         // We must either select the trivial copy constructor or reach an
7340         // ambiguity; no need to actually perform overload resolution.
7341         return true;
7342     } else if (!Selected) {
7343       return false;
7344     }
7345     // In C++98, we are not supposed to perform overload resolution here, but we
7346     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7347     // cases like B as having a non-trivial copy constructor:
7348     //   struct A { template<typename T> A(T&); };
7349     //   struct B { mutable A a; };
7350     goto NeedOverloadResolution;
7351 
7352   case Sema::CXXCopyAssignment:
7353     // C++11 [class.copy]p25:
7354     //   A copy assignment operator is trivial if:
7355     //    - the assignment operator selected to copy each direct [subobject] is
7356     //      trivial
7357     if (RD->hasTrivialCopyAssignment()) {
7358       if (Quals == Qualifiers::Const)
7359         return true;
7360     } else if (!Selected) {
7361       return false;
7362     }
7363     // In C++98, we are not supposed to perform overload resolution here, but we
7364     // treat that as a language defect.
7365     goto NeedOverloadResolution;
7366 
7367   case Sema::CXXMoveConstructor:
7368   case Sema::CXXMoveAssignment:
7369   NeedOverloadResolution:
7370     Sema::SpecialMemberOverloadResult SMOR =
7371         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7372 
7373     // The standard doesn't describe how to behave if the lookup is ambiguous.
7374     // We treat it as not making the member non-trivial, just like the standard
7375     // mandates for the default constructor. This should rarely matter, because
7376     // the member will also be deleted.
7377     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7378       return true;
7379 
7380     if (!SMOR.getMethod()) {
7381       assert(SMOR.getKind() ==
7382              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7383       return false;
7384     }
7385 
7386     // We deliberately don't check if we found a deleted special member. We're
7387     // not supposed to!
7388     if (Selected)
7389       *Selected = SMOR.getMethod();
7390 
7391     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7392         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7393       return SMOR.getMethod()->isTrivialForCall();
7394     return SMOR.getMethod()->isTrivial();
7395   }
7396 
7397   llvm_unreachable("unknown special method kind");
7398 }
7399 
7400 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7401   for (auto *CI : RD->ctors())
7402     if (!CI->isImplicit())
7403       return CI;
7404 
7405   // Look for constructor templates.
7406   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7407   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7408     if (CXXConstructorDecl *CD =
7409           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7410       return CD;
7411   }
7412 
7413   return nullptr;
7414 }
7415 
7416 /// The kind of subobject we are checking for triviality. The values of this
7417 /// enumeration are used in diagnostics.
7418 enum TrivialSubobjectKind {
7419   /// The subobject is a base class.
7420   TSK_BaseClass,
7421   /// The subobject is a non-static data member.
7422   TSK_Field,
7423   /// The object is actually the complete object.
7424   TSK_CompleteObject
7425 };
7426 
7427 /// Check whether the special member selected for a given type would be trivial.
7428 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7429                                       QualType SubType, bool ConstRHS,
7430                                       Sema::CXXSpecialMember CSM,
7431                                       TrivialSubobjectKind Kind,
7432                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7433   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7434   if (!SubRD)
7435     return true;
7436 
7437   CXXMethodDecl *Selected;
7438   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7439                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7440     return true;
7441 
7442   if (Diagnose) {
7443     if (ConstRHS)
7444       SubType.addConst();
7445 
7446     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7447       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7448         << Kind << SubType.getUnqualifiedType();
7449       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7450         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7451     } else if (!Selected)
7452       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7453         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7454     else if (Selected->isUserProvided()) {
7455       if (Kind == TSK_CompleteObject)
7456         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7457           << Kind << SubType.getUnqualifiedType() << CSM;
7458       else {
7459         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7460           << Kind << SubType.getUnqualifiedType() << CSM;
7461         S.Diag(Selected->getLocation(), diag::note_declared_at);
7462       }
7463     } else {
7464       if (Kind != TSK_CompleteObject)
7465         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7466           << Kind << SubType.getUnqualifiedType() << CSM;
7467 
7468       // Explain why the defaulted or deleted special member isn't trivial.
7469       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7470                                Diagnose);
7471     }
7472   }
7473 
7474   return false;
7475 }
7476 
7477 /// Check whether the members of a class type allow a special member to be
7478 /// trivial.
7479 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7480                                      Sema::CXXSpecialMember CSM,
7481                                      bool ConstArg,
7482                                      Sema::TrivialABIHandling TAH,
7483                                      bool Diagnose) {
7484   for (const auto *FI : RD->fields()) {
7485     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7486       continue;
7487 
7488     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7489 
7490     // Pretend anonymous struct or union members are members of this class.
7491     if (FI->isAnonymousStructOrUnion()) {
7492       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7493                                     CSM, ConstArg, TAH, Diagnose))
7494         return false;
7495       continue;
7496     }
7497 
7498     // C++11 [class.ctor]p5:
7499     //   A default constructor is trivial if [...]
7500     //    -- no non-static data member of its class has a
7501     //       brace-or-equal-initializer
7502     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7503       if (Diagnose)
7504         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7505       return false;
7506     }
7507 
7508     // Objective C ARC 4.3.5:
7509     //   [...] nontrivally ownership-qualified types are [...] not trivially
7510     //   default constructible, copy constructible, move constructible, copy
7511     //   assignable, move assignable, or destructible [...]
7512     if (FieldType.hasNonTrivialObjCLifetime()) {
7513       if (Diagnose)
7514         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7515           << RD << FieldType.getObjCLifetime();
7516       return false;
7517     }
7518 
7519     bool ConstRHS = ConstArg && !FI->isMutable();
7520     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7521                                    CSM, TSK_Field, TAH, Diagnose))
7522       return false;
7523   }
7524 
7525   return true;
7526 }
7527 
7528 /// Diagnose why the specified class does not have a trivial special member of
7529 /// the given kind.
7530 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7531   QualType Ty = Context.getRecordType(RD);
7532 
7533   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7534   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7535                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7536                             /*Diagnose*/true);
7537 }
7538 
7539 /// Determine whether a defaulted or deleted special member function is trivial,
7540 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7541 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7542 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7543                                   TrivialABIHandling TAH, bool Diagnose) {
7544   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7545 
7546   CXXRecordDecl *RD = MD->getParent();
7547 
7548   bool ConstArg = false;
7549 
7550   // C++11 [class.copy]p12, p25: [DR1593]
7551   //   A [special member] is trivial if [...] its parameter-type-list is
7552   //   equivalent to the parameter-type-list of an implicit declaration [...]
7553   switch (CSM) {
7554   case CXXDefaultConstructor:
7555   case CXXDestructor:
7556     // Trivial default constructors and destructors cannot have parameters.
7557     break;
7558 
7559   case CXXCopyConstructor:
7560   case CXXCopyAssignment: {
7561     // Trivial copy operations always have const, non-volatile parameter types.
7562     ConstArg = true;
7563     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7564     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7565     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7566       if (Diagnose)
7567         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7568           << Param0->getSourceRange() << Param0->getType()
7569           << Context.getLValueReferenceType(
7570                Context.getRecordType(RD).withConst());
7571       return false;
7572     }
7573     break;
7574   }
7575 
7576   case CXXMoveConstructor:
7577   case CXXMoveAssignment: {
7578     // Trivial move operations always have non-cv-qualified parameters.
7579     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7580     const RValueReferenceType *RT =
7581       Param0->getType()->getAs<RValueReferenceType>();
7582     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7583       if (Diagnose)
7584         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7585           << Param0->getSourceRange() << Param0->getType()
7586           << Context.getRValueReferenceType(Context.getRecordType(RD));
7587       return false;
7588     }
7589     break;
7590   }
7591 
7592   case CXXInvalid:
7593     llvm_unreachable("not a special member");
7594   }
7595 
7596   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7597     if (Diagnose)
7598       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7599            diag::note_nontrivial_default_arg)
7600         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7601     return false;
7602   }
7603   if (MD->isVariadic()) {
7604     if (Diagnose)
7605       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7606     return false;
7607   }
7608 
7609   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7610   //   A copy/move [constructor or assignment operator] is trivial if
7611   //    -- the [member] selected to copy/move each direct base class subobject
7612   //       is trivial
7613   //
7614   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7615   //   A [default constructor or destructor] is trivial if
7616   //    -- all the direct base classes have trivial [default constructors or
7617   //       destructors]
7618   for (const auto &BI : RD->bases())
7619     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7620                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7621       return false;
7622 
7623   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7624   //   A copy/move [constructor or assignment operator] for a class X is
7625   //   trivial if
7626   //    -- for each non-static data member of X that is of class type (or array
7627   //       thereof), the constructor selected to copy/move that member is
7628   //       trivial
7629   //
7630   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7631   //   A [default constructor or destructor] is trivial if
7632   //    -- for all of the non-static data members of its class that are of class
7633   //       type (or array thereof), each such class has a trivial [default
7634   //       constructor or destructor]
7635   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7636     return false;
7637 
7638   // C++11 [class.dtor]p5:
7639   //   A destructor is trivial if [...]
7640   //    -- the destructor is not virtual
7641   if (CSM == CXXDestructor && MD->isVirtual()) {
7642     if (Diagnose)
7643       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7644     return false;
7645   }
7646 
7647   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7648   //   A [special member] for class X is trivial if [...]
7649   //    -- class X has no virtual functions and no virtual base classes
7650   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7651     if (!Diagnose)
7652       return false;
7653 
7654     if (RD->getNumVBases()) {
7655       // Check for virtual bases. We already know that the corresponding
7656       // member in all bases is trivial, so vbases must all be direct.
7657       CXXBaseSpecifier &BS = *RD->vbases_begin();
7658       assert(BS.isVirtual());
7659       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7660       return false;
7661     }
7662 
7663     // Must have a virtual method.
7664     for (const auto *MI : RD->methods()) {
7665       if (MI->isVirtual()) {
7666         SourceLocation MLoc = MI->getBeginLoc();
7667         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7668         return false;
7669       }
7670     }
7671 
7672     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7673   }
7674 
7675   // Looks like it's trivial!
7676   return true;
7677 }
7678 
7679 namespace {
7680 struct FindHiddenVirtualMethod {
7681   Sema *S;
7682   CXXMethodDecl *Method;
7683   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7684   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7685 
7686 private:
7687   /// Check whether any most overriden method from MD in Methods
7688   static bool CheckMostOverridenMethods(
7689       const CXXMethodDecl *MD,
7690       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7691     if (MD->size_overridden_methods() == 0)
7692       return Methods.count(MD->getCanonicalDecl());
7693     for (const CXXMethodDecl *O : MD->overridden_methods())
7694       if (CheckMostOverridenMethods(O, Methods))
7695         return true;
7696     return false;
7697   }
7698 
7699 public:
7700   /// Member lookup function that determines whether a given C++
7701   /// method overloads virtual methods in a base class without overriding any,
7702   /// to be used with CXXRecordDecl::lookupInBases().
7703   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7704     RecordDecl *BaseRecord =
7705         Specifier->getType()->getAs<RecordType>()->getDecl();
7706 
7707     DeclarationName Name = Method->getDeclName();
7708     assert(Name.getNameKind() == DeclarationName::Identifier);
7709 
7710     bool foundSameNameMethod = false;
7711     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7712     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7713          Path.Decls = Path.Decls.slice(1)) {
7714       NamedDecl *D = Path.Decls.front();
7715       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7716         MD = MD->getCanonicalDecl();
7717         foundSameNameMethod = true;
7718         // Interested only in hidden virtual methods.
7719         if (!MD->isVirtual())
7720           continue;
7721         // If the method we are checking overrides a method from its base
7722         // don't warn about the other overloaded methods. Clang deviates from
7723         // GCC by only diagnosing overloads of inherited virtual functions that
7724         // do not override any other virtual functions in the base. GCC's
7725         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7726         // function from a base class. These cases may be better served by a
7727         // warning (not specific to virtual functions) on call sites when the
7728         // call would select a different function from the base class, were it
7729         // visible.
7730         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7731         if (!S->IsOverload(Method, MD, false))
7732           return true;
7733         // Collect the overload only if its hidden.
7734         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7735           overloadedMethods.push_back(MD);
7736       }
7737     }
7738 
7739     if (foundSameNameMethod)
7740       OverloadedMethods.append(overloadedMethods.begin(),
7741                                overloadedMethods.end());
7742     return foundSameNameMethod;
7743   }
7744 };
7745 } // end anonymous namespace
7746 
7747 /// Add the most overriden methods from MD to Methods
7748 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7749                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7750   if (MD->size_overridden_methods() == 0)
7751     Methods.insert(MD->getCanonicalDecl());
7752   else
7753     for (const CXXMethodDecl *O : MD->overridden_methods())
7754       AddMostOverridenMethods(O, Methods);
7755 }
7756 
7757 /// Check if a method overloads virtual methods in a base class without
7758 /// overriding any.
7759 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7760                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7761   if (!MD->getDeclName().isIdentifier())
7762     return;
7763 
7764   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7765                      /*bool RecordPaths=*/false,
7766                      /*bool DetectVirtual=*/false);
7767   FindHiddenVirtualMethod FHVM;
7768   FHVM.Method = MD;
7769   FHVM.S = this;
7770 
7771   // Keep the base methods that were overriden or introduced in the subclass
7772   // by 'using' in a set. A base method not in this set is hidden.
7773   CXXRecordDecl *DC = MD->getParent();
7774   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7775   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7776     NamedDecl *ND = *I;
7777     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7778       ND = shad->getTargetDecl();
7779     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7780       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7781   }
7782 
7783   if (DC->lookupInBases(FHVM, Paths))
7784     OverloadedMethods = FHVM.OverloadedMethods;
7785 }
7786 
7787 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7788                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7789   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7790     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7791     PartialDiagnostic PD = PDiag(
7792          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7793     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7794     Diag(overloadedMD->getLocation(), PD);
7795   }
7796 }
7797 
7798 /// Diagnose methods which overload virtual methods in a base class
7799 /// without overriding any.
7800 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7801   if (MD->isInvalidDecl())
7802     return;
7803 
7804   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7805     return;
7806 
7807   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7808   FindHiddenVirtualMethods(MD, OverloadedMethods);
7809   if (!OverloadedMethods.empty()) {
7810     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7811       << MD << (OverloadedMethods.size() > 1);
7812 
7813     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7814   }
7815 }
7816 
7817 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7818   auto PrintDiagAndRemoveAttr = [&]() {
7819     // No diagnostics if this is a template instantiation.
7820     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7821       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7822            diag::ext_cannot_use_trivial_abi) << &RD;
7823     RD.dropAttr<TrivialABIAttr>();
7824   };
7825 
7826   // Ill-formed if the struct has virtual functions.
7827   if (RD.isPolymorphic()) {
7828     PrintDiagAndRemoveAttr();
7829     return;
7830   }
7831 
7832   for (const auto &B : RD.bases()) {
7833     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7834     // virtual base.
7835     if ((!B.getType()->isDependentType() &&
7836          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7837         B.isVirtual()) {
7838       PrintDiagAndRemoveAttr();
7839       return;
7840     }
7841   }
7842 
7843   for (const auto *FD : RD.fields()) {
7844     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7845     // non-trivial for the purpose of calls.
7846     QualType FT = FD->getType();
7847     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7848       PrintDiagAndRemoveAttr();
7849       return;
7850     }
7851 
7852     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7853       if (!RT->isDependentType() &&
7854           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7855         PrintDiagAndRemoveAttr();
7856         return;
7857       }
7858   }
7859 }
7860 
7861 void Sema::ActOnFinishCXXMemberSpecification(
7862     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7863     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7864   if (!TagDecl)
7865     return;
7866 
7867   AdjustDeclIfTemplate(TagDecl);
7868 
7869   for (const ParsedAttr &AL : AttrList) {
7870     if (AL.getKind() != ParsedAttr::AT_Visibility)
7871       continue;
7872     AL.setInvalid();
7873     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7874         << AL.getName();
7875   }
7876 
7877   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7878               // strict aliasing violation!
7879               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7880               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7881 
7882   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7883 }
7884 
7885 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7886 /// special functions, such as the default constructor, copy
7887 /// constructor, or destructor, to the given C++ class (C++
7888 /// [special]p1).  This routine can only be executed just before the
7889 /// definition of the class is complete.
7890 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7891   if (ClassDecl->needsImplicitDefaultConstructor()) {
7892     ++ASTContext::NumImplicitDefaultConstructors;
7893 
7894     if (ClassDecl->hasInheritedConstructor())
7895       DeclareImplicitDefaultConstructor(ClassDecl);
7896   }
7897 
7898   if (ClassDecl->needsImplicitCopyConstructor()) {
7899     ++ASTContext::NumImplicitCopyConstructors;
7900 
7901     // If the properties or semantics of the copy constructor couldn't be
7902     // determined while the class was being declared, force a declaration
7903     // of it now.
7904     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7905         ClassDecl->hasInheritedConstructor())
7906       DeclareImplicitCopyConstructor(ClassDecl);
7907     // For the MS ABI we need to know whether the copy ctor is deleted. A
7908     // prerequisite for deleting the implicit copy ctor is that the class has a
7909     // move ctor or move assignment that is either user-declared or whose
7910     // semantics are inherited from a subobject. FIXME: We should provide a more
7911     // direct way for CodeGen to ask whether the constructor was deleted.
7912     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7913              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7914               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7915               ClassDecl->hasUserDeclaredMoveAssignment() ||
7916               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7917       DeclareImplicitCopyConstructor(ClassDecl);
7918   }
7919 
7920   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7921     ++ASTContext::NumImplicitMoveConstructors;
7922 
7923     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7924         ClassDecl->hasInheritedConstructor())
7925       DeclareImplicitMoveConstructor(ClassDecl);
7926   }
7927 
7928   if (ClassDecl->needsImplicitCopyAssignment()) {
7929     ++ASTContext::NumImplicitCopyAssignmentOperators;
7930 
7931     // If we have a dynamic class, then the copy assignment operator may be
7932     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7933     // it shows up in the right place in the vtable and that we diagnose
7934     // problems with the implicit exception specification.
7935     if (ClassDecl->isDynamicClass() ||
7936         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7937         ClassDecl->hasInheritedAssignment())
7938       DeclareImplicitCopyAssignment(ClassDecl);
7939   }
7940 
7941   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7942     ++ASTContext::NumImplicitMoveAssignmentOperators;
7943 
7944     // Likewise for the move assignment operator.
7945     if (ClassDecl->isDynamicClass() ||
7946         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7947         ClassDecl->hasInheritedAssignment())
7948       DeclareImplicitMoveAssignment(ClassDecl);
7949   }
7950 
7951   if (ClassDecl->needsImplicitDestructor()) {
7952     ++ASTContext::NumImplicitDestructors;
7953 
7954     // If we have a dynamic class, then the destructor may be virtual, so we
7955     // have to declare the destructor immediately. This ensures that, e.g., it
7956     // shows up in the right place in the vtable and that we diagnose problems
7957     // with the implicit exception specification.
7958     if (ClassDecl->isDynamicClass() ||
7959         ClassDecl->needsOverloadResolutionForDestructor())
7960       DeclareImplicitDestructor(ClassDecl);
7961   }
7962 }
7963 
7964 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7965   if (!D)
7966     return 0;
7967 
7968   // The order of template parameters is not important here. All names
7969   // get added to the same scope.
7970   SmallVector<TemplateParameterList *, 4> ParameterLists;
7971 
7972   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7973     D = TD->getTemplatedDecl();
7974 
7975   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7976     ParameterLists.push_back(PSD->getTemplateParameters());
7977 
7978   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7979     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7980       ParameterLists.push_back(DD->getTemplateParameterList(i));
7981 
7982     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7983       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7984         ParameterLists.push_back(FTD->getTemplateParameters());
7985     }
7986   }
7987 
7988   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7989     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7990       ParameterLists.push_back(TD->getTemplateParameterList(i));
7991 
7992     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7993       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7994         ParameterLists.push_back(CTD->getTemplateParameters());
7995     }
7996   }
7997 
7998   unsigned Count = 0;
7999   for (TemplateParameterList *Params : ParameterLists) {
8000     if (Params->size() > 0)
8001       // Ignore explicit specializations; they don't contribute to the template
8002       // depth.
8003       ++Count;
8004     for (NamedDecl *Param : *Params) {
8005       if (Param->getDeclName()) {
8006         S->AddDecl(Param);
8007         IdResolver.AddDecl(Param);
8008       }
8009     }
8010   }
8011 
8012   return Count;
8013 }
8014 
8015 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8016   if (!RecordD) return;
8017   AdjustDeclIfTemplate(RecordD);
8018   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8019   PushDeclContext(S, Record);
8020 }
8021 
8022 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8023   if (!RecordD) return;
8024   PopDeclContext();
8025 }
8026 
8027 /// This is used to implement the constant expression evaluation part of the
8028 /// attribute enable_if extension. There is nothing in standard C++ which would
8029 /// require reentering parameters.
8030 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8031   if (!Param)
8032     return;
8033 
8034   S->AddDecl(Param);
8035   if (Param->getDeclName())
8036     IdResolver.AddDecl(Param);
8037 }
8038 
8039 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8040 /// parsing a top-level (non-nested) C++ class, and we are now
8041 /// parsing those parts of the given Method declaration that could
8042 /// not be parsed earlier (C++ [class.mem]p2), such as default
8043 /// arguments. This action should enter the scope of the given
8044 /// Method declaration as if we had just parsed the qualified method
8045 /// name. However, it should not bring the parameters into scope;
8046 /// that will be performed by ActOnDelayedCXXMethodParameter.
8047 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8048 }
8049 
8050 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8051 /// C++ method declaration. We're (re-)introducing the given
8052 /// function parameter into scope for use in parsing later parts of
8053 /// the method declaration. For example, we could see an
8054 /// ActOnParamDefaultArgument event for this parameter.
8055 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8056   if (!ParamD)
8057     return;
8058 
8059   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8060 
8061   // If this parameter has an unparsed default argument, clear it out
8062   // to make way for the parsed default argument.
8063   if (Param->hasUnparsedDefaultArg())
8064     Param->setDefaultArg(nullptr);
8065 
8066   S->AddDecl(Param);
8067   if (Param->getDeclName())
8068     IdResolver.AddDecl(Param);
8069 }
8070 
8071 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8072 /// processing the delayed method declaration for Method. The method
8073 /// declaration is now considered finished. There may be a separate
8074 /// ActOnStartOfFunctionDef action later (not necessarily
8075 /// immediately!) for this method, if it was also defined inside the
8076 /// class body.
8077 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8078   if (!MethodD)
8079     return;
8080 
8081   AdjustDeclIfTemplate(MethodD);
8082 
8083   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8084 
8085   // Now that we have our default arguments, check the constructor
8086   // again. It could produce additional diagnostics or affect whether
8087   // the class has implicitly-declared destructors, among other
8088   // things.
8089   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8090     CheckConstructor(Constructor);
8091 
8092   // Check the default arguments, which we may have added.
8093   if (!Method->isInvalidDecl())
8094     CheckCXXDefaultArguments(Method);
8095 }
8096 
8097 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8098 /// the well-formedness of the constructor declarator @p D with type @p
8099 /// R. If there are any errors in the declarator, this routine will
8100 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8101 /// will be updated to reflect a well-formed type for the constructor and
8102 /// returned.
8103 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8104                                           StorageClass &SC) {
8105   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8106 
8107   // C++ [class.ctor]p3:
8108   //   A constructor shall not be virtual (10.3) or static (9.4). A
8109   //   constructor can be invoked for a const, volatile or const
8110   //   volatile object. A constructor shall not be declared const,
8111   //   volatile, or const volatile (9.3.2).
8112   if (isVirtual) {
8113     if (!D.isInvalidType())
8114       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8115         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8116         << SourceRange(D.getIdentifierLoc());
8117     D.setInvalidType();
8118   }
8119   if (SC == SC_Static) {
8120     if (!D.isInvalidType())
8121       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8122         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8123         << SourceRange(D.getIdentifierLoc());
8124     D.setInvalidType();
8125     SC = SC_None;
8126   }
8127 
8128   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8129     diagnoseIgnoredQualifiers(
8130         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8131         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8132         D.getDeclSpec().getRestrictSpecLoc(),
8133         D.getDeclSpec().getAtomicSpecLoc());
8134     D.setInvalidType();
8135   }
8136 
8137   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8138   if (FTI.TypeQuals != 0) {
8139     if (FTI.TypeQuals & Qualifiers::Const)
8140       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8141         << "const" << SourceRange(D.getIdentifierLoc());
8142     if (FTI.TypeQuals & Qualifiers::Volatile)
8143       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8144         << "volatile" << SourceRange(D.getIdentifierLoc());
8145     if (FTI.TypeQuals & Qualifiers::Restrict)
8146       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8147         << "restrict" << SourceRange(D.getIdentifierLoc());
8148     D.setInvalidType();
8149   }
8150 
8151   // C++0x [class.ctor]p4:
8152   //   A constructor shall not be declared with a ref-qualifier.
8153   if (FTI.hasRefQualifier()) {
8154     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8155       << FTI.RefQualifierIsLValueRef
8156       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8157     D.setInvalidType();
8158   }
8159 
8160   // Rebuild the function type "R" without any type qualifiers (in
8161   // case any of the errors above fired) and with "void" as the
8162   // return type, since constructors don't have return types.
8163   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8164   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8165     return R;
8166 
8167   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8168   EPI.TypeQuals = 0;
8169   EPI.RefQualifier = RQ_None;
8170 
8171   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8172 }
8173 
8174 /// CheckConstructor - Checks a fully-formed constructor for
8175 /// well-formedness, issuing any diagnostics required. Returns true if
8176 /// the constructor declarator is invalid.
8177 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8178   CXXRecordDecl *ClassDecl
8179     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8180   if (!ClassDecl)
8181     return Constructor->setInvalidDecl();
8182 
8183   // C++ [class.copy]p3:
8184   //   A declaration of a constructor for a class X is ill-formed if
8185   //   its first parameter is of type (optionally cv-qualified) X and
8186   //   either there are no other parameters or else all other
8187   //   parameters have default arguments.
8188   if (!Constructor->isInvalidDecl() &&
8189       ((Constructor->getNumParams() == 1) ||
8190        (Constructor->getNumParams() > 1 &&
8191         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8192       Constructor->getTemplateSpecializationKind()
8193                                               != TSK_ImplicitInstantiation) {
8194     QualType ParamType = Constructor->getParamDecl(0)->getType();
8195     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8196     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8197       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8198       const char *ConstRef
8199         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8200                                                         : " const &";
8201       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8202         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8203 
8204       // FIXME: Rather that making the constructor invalid, we should endeavor
8205       // to fix the type.
8206       Constructor->setInvalidDecl();
8207     }
8208   }
8209 }
8210 
8211 /// CheckDestructor - Checks a fully-formed destructor definition for
8212 /// well-formedness, issuing any diagnostics required.  Returns true
8213 /// on error.
8214 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8215   CXXRecordDecl *RD = Destructor->getParent();
8216 
8217   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8218     SourceLocation Loc;
8219 
8220     if (!Destructor->isImplicit())
8221       Loc = Destructor->getLocation();
8222     else
8223       Loc = RD->getLocation();
8224 
8225     // If we have a virtual destructor, look up the deallocation function
8226     if (FunctionDecl *OperatorDelete =
8227             FindDeallocationFunctionForDestructor(Loc, RD)) {
8228       Expr *ThisArg = nullptr;
8229 
8230       // If the notional 'delete this' expression requires a non-trivial
8231       // conversion from 'this' to the type of a destroying operator delete's
8232       // first parameter, perform that conversion now.
8233       if (OperatorDelete->isDestroyingOperatorDelete()) {
8234         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8235         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8236           // C++ [class.dtor]p13:
8237           //   ... as if for the expression 'delete this' appearing in a
8238           //   non-virtual destructor of the destructor's class.
8239           ContextRAII SwitchContext(*this, Destructor);
8240           ExprResult This =
8241               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8242           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8243           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8244           if (This.isInvalid()) {
8245             // FIXME: Register this as a context note so that it comes out
8246             // in the right order.
8247             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8248             return true;
8249           }
8250           ThisArg = This.get();
8251         }
8252       }
8253 
8254       MarkFunctionReferenced(Loc, OperatorDelete);
8255       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8256     }
8257   }
8258 
8259   return false;
8260 }
8261 
8262 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8263 /// the well-formednes of the destructor declarator @p D with type @p
8264 /// R. If there are any errors in the declarator, this routine will
8265 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8266 /// will be updated to reflect a well-formed type for the destructor and
8267 /// returned.
8268 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8269                                          StorageClass& SC) {
8270   // C++ [class.dtor]p1:
8271   //   [...] A typedef-name that names a class is a class-name
8272   //   (7.1.3); however, a typedef-name that names a class shall not
8273   //   be used as the identifier in the declarator for a destructor
8274   //   declaration.
8275   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8276   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8277     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8278       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8279   else if (const TemplateSpecializationType *TST =
8280              DeclaratorType->getAs<TemplateSpecializationType>())
8281     if (TST->isTypeAlias())
8282       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8283         << DeclaratorType << 1;
8284 
8285   // C++ [class.dtor]p2:
8286   //   A destructor is used to destroy objects of its class type. A
8287   //   destructor takes no parameters, and no return type can be
8288   //   specified for it (not even void). The address of a destructor
8289   //   shall not be taken. A destructor shall not be static. A
8290   //   destructor can be invoked for a const, volatile or const
8291   //   volatile object. A destructor shall not be declared const,
8292   //   volatile or const volatile (9.3.2).
8293   if (SC == SC_Static) {
8294     if (!D.isInvalidType())
8295       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8296         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8297         << SourceRange(D.getIdentifierLoc())
8298         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8299 
8300     SC = SC_None;
8301   }
8302   if (!D.isInvalidType()) {
8303     // Destructors don't have return types, but the parser will
8304     // happily parse something like:
8305     //
8306     //   class X {
8307     //     float ~X();
8308     //   };
8309     //
8310     // The return type will be eliminated later.
8311     if (D.getDeclSpec().hasTypeSpecifier())
8312       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8313         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8314         << SourceRange(D.getIdentifierLoc());
8315     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8316       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8317                                 SourceLocation(),
8318                                 D.getDeclSpec().getConstSpecLoc(),
8319                                 D.getDeclSpec().getVolatileSpecLoc(),
8320                                 D.getDeclSpec().getRestrictSpecLoc(),
8321                                 D.getDeclSpec().getAtomicSpecLoc());
8322       D.setInvalidType();
8323     }
8324   }
8325 
8326   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8327   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8328     if (FTI.TypeQuals & Qualifiers::Const)
8329       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8330         << "const" << SourceRange(D.getIdentifierLoc());
8331     if (FTI.TypeQuals & Qualifiers::Volatile)
8332       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8333         << "volatile" << SourceRange(D.getIdentifierLoc());
8334     if (FTI.TypeQuals & Qualifiers::Restrict)
8335       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8336         << "restrict" << SourceRange(D.getIdentifierLoc());
8337     D.setInvalidType();
8338   }
8339 
8340   // C++0x [class.dtor]p2:
8341   //   A destructor shall not be declared with a ref-qualifier.
8342   if (FTI.hasRefQualifier()) {
8343     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8344       << FTI.RefQualifierIsLValueRef
8345       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8346     D.setInvalidType();
8347   }
8348 
8349   // Make sure we don't have any parameters.
8350   if (FTIHasNonVoidParameters(FTI)) {
8351     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8352 
8353     // Delete the parameters.
8354     FTI.freeParams();
8355     D.setInvalidType();
8356   }
8357 
8358   // Make sure the destructor isn't variadic.
8359   if (FTI.isVariadic) {
8360     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8361     D.setInvalidType();
8362   }
8363 
8364   // Rebuild the function type "R" without any type qualifiers or
8365   // parameters (in case any of the errors above fired) and with
8366   // "void" as the return type, since destructors don't have return
8367   // types.
8368   if (!D.isInvalidType())
8369     return R;
8370 
8371   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8372   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8373   EPI.Variadic = false;
8374   EPI.TypeQuals = 0;
8375   EPI.RefQualifier = RQ_None;
8376   return Context.getFunctionType(Context.VoidTy, None, EPI);
8377 }
8378 
8379 static void extendLeft(SourceRange &R, SourceRange Before) {
8380   if (Before.isInvalid())
8381     return;
8382   R.setBegin(Before.getBegin());
8383   if (R.getEnd().isInvalid())
8384     R.setEnd(Before.getEnd());
8385 }
8386 
8387 static void extendRight(SourceRange &R, SourceRange After) {
8388   if (After.isInvalid())
8389     return;
8390   if (R.getBegin().isInvalid())
8391     R.setBegin(After.getBegin());
8392   R.setEnd(After.getEnd());
8393 }
8394 
8395 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8396 /// well-formednes of the conversion function declarator @p D with
8397 /// type @p R. If there are any errors in the declarator, this routine
8398 /// will emit diagnostics and return true. Otherwise, it will return
8399 /// false. Either way, the type @p R will be updated to reflect a
8400 /// well-formed type for the conversion operator.
8401 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8402                                      StorageClass& SC) {
8403   // C++ [class.conv.fct]p1:
8404   //   Neither parameter types nor return type can be specified. The
8405   //   type of a conversion function (8.3.5) is "function taking no
8406   //   parameter returning conversion-type-id."
8407   if (SC == SC_Static) {
8408     if (!D.isInvalidType())
8409       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8410         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8411         << D.getName().getSourceRange();
8412     D.setInvalidType();
8413     SC = SC_None;
8414   }
8415 
8416   TypeSourceInfo *ConvTSI = nullptr;
8417   QualType ConvType =
8418       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8419 
8420   const DeclSpec &DS = D.getDeclSpec();
8421   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8422     // Conversion functions don't have return types, but the parser will
8423     // happily parse something like:
8424     //
8425     //   class X {
8426     //     float operator bool();
8427     //   };
8428     //
8429     // The return type will be changed later anyway.
8430     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8431       << SourceRange(DS.getTypeSpecTypeLoc())
8432       << SourceRange(D.getIdentifierLoc());
8433     D.setInvalidType();
8434   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8435     // It's also plausible that the user writes type qualifiers in the wrong
8436     // place, such as:
8437     //   struct S { const operator int(); };
8438     // FIXME: we could provide a fixit to move the qualifiers onto the
8439     // conversion type.
8440     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8441         << SourceRange(D.getIdentifierLoc()) << 0;
8442     D.setInvalidType();
8443   }
8444 
8445   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8446 
8447   // Make sure we don't have any parameters.
8448   if (Proto->getNumParams() > 0) {
8449     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8450 
8451     // Delete the parameters.
8452     D.getFunctionTypeInfo().freeParams();
8453     D.setInvalidType();
8454   } else if (Proto->isVariadic()) {
8455     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8456     D.setInvalidType();
8457   }
8458 
8459   // Diagnose "&operator bool()" and other such nonsense.  This
8460   // is actually a gcc extension which we don't support.
8461   if (Proto->getReturnType() != ConvType) {
8462     bool NeedsTypedef = false;
8463     SourceRange Before, After;
8464 
8465     // Walk the chunks and extract information on them for our diagnostic.
8466     bool PastFunctionChunk = false;
8467     for (auto &Chunk : D.type_objects()) {
8468       switch (Chunk.Kind) {
8469       case DeclaratorChunk::Function:
8470         if (!PastFunctionChunk) {
8471           if (Chunk.Fun.HasTrailingReturnType) {
8472             TypeSourceInfo *TRT = nullptr;
8473             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8474             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8475           }
8476           PastFunctionChunk = true;
8477           break;
8478         }
8479         LLVM_FALLTHROUGH;
8480       case DeclaratorChunk::Array:
8481         NeedsTypedef = true;
8482         extendRight(After, Chunk.getSourceRange());
8483         break;
8484 
8485       case DeclaratorChunk::Pointer:
8486       case DeclaratorChunk::BlockPointer:
8487       case DeclaratorChunk::Reference:
8488       case DeclaratorChunk::MemberPointer:
8489       case DeclaratorChunk::Pipe:
8490         extendLeft(Before, Chunk.getSourceRange());
8491         break;
8492 
8493       case DeclaratorChunk::Paren:
8494         extendLeft(Before, Chunk.Loc);
8495         extendRight(After, Chunk.EndLoc);
8496         break;
8497       }
8498     }
8499 
8500     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8501                          After.isValid()  ? After.getBegin() :
8502                                             D.getIdentifierLoc();
8503     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8504     DB << Before << After;
8505 
8506     if (!NeedsTypedef) {
8507       DB << /*don't need a typedef*/0;
8508 
8509       // If we can provide a correct fix-it hint, do so.
8510       if (After.isInvalid() && ConvTSI) {
8511         SourceLocation InsertLoc =
8512             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8513         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8514            << FixItHint::CreateInsertionFromRange(
8515                   InsertLoc, CharSourceRange::getTokenRange(Before))
8516            << FixItHint::CreateRemoval(Before);
8517       }
8518     } else if (!Proto->getReturnType()->isDependentType()) {
8519       DB << /*typedef*/1 << Proto->getReturnType();
8520     } else if (getLangOpts().CPlusPlus11) {
8521       DB << /*alias template*/2 << Proto->getReturnType();
8522     } else {
8523       DB << /*might not be fixable*/3;
8524     }
8525 
8526     // Recover by incorporating the other type chunks into the result type.
8527     // Note, this does *not* change the name of the function. This is compatible
8528     // with the GCC extension:
8529     //   struct S { &operator int(); } s;
8530     //   int &r = s.operator int(); // ok in GCC
8531     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8532     ConvType = Proto->getReturnType();
8533   }
8534 
8535   // C++ [class.conv.fct]p4:
8536   //   The conversion-type-id shall not represent a function type nor
8537   //   an array type.
8538   if (ConvType->isArrayType()) {
8539     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8540     ConvType = Context.getPointerType(ConvType);
8541     D.setInvalidType();
8542   } else if (ConvType->isFunctionType()) {
8543     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8544     ConvType = Context.getPointerType(ConvType);
8545     D.setInvalidType();
8546   }
8547 
8548   // Rebuild the function type "R" without any parameters (in case any
8549   // of the errors above fired) and with the conversion type as the
8550   // return type.
8551   if (D.isInvalidType())
8552     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8553 
8554   // C++0x explicit conversion operators.
8555   if (DS.isExplicitSpecified())
8556     Diag(DS.getExplicitSpecLoc(),
8557          getLangOpts().CPlusPlus11
8558              ? diag::warn_cxx98_compat_explicit_conversion_functions
8559              : diag::ext_explicit_conversion_functions)
8560         << SourceRange(DS.getExplicitSpecLoc());
8561 }
8562 
8563 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8564 /// the declaration of the given C++ conversion function. This routine
8565 /// is responsible for recording the conversion function in the C++
8566 /// class, if possible.
8567 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8568   assert(Conversion && "Expected to receive a conversion function declaration");
8569 
8570   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8571 
8572   // Make sure we aren't redeclaring the conversion function.
8573   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8574 
8575   // C++ [class.conv.fct]p1:
8576   //   [...] A conversion function is never used to convert a
8577   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8578   //   same object type (or a reference to it), to a (possibly
8579   //   cv-qualified) base class of that type (or a reference to it),
8580   //   or to (possibly cv-qualified) void.
8581   // FIXME: Suppress this warning if the conversion function ends up being a
8582   // virtual function that overrides a virtual function in a base class.
8583   QualType ClassType
8584     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8585   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8586     ConvType = ConvTypeRef->getPointeeType();
8587   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8588       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8589     /* Suppress diagnostics for instantiations. */;
8590   else if (ConvType->isRecordType()) {
8591     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8592     if (ConvType == ClassType)
8593       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8594         << ClassType;
8595     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8596       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8597         <<  ClassType << ConvType;
8598   } else if (ConvType->isVoidType()) {
8599     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8600       << ClassType << ConvType;
8601   }
8602 
8603   if (FunctionTemplateDecl *ConversionTemplate
8604                                 = Conversion->getDescribedFunctionTemplate())
8605     return ConversionTemplate;
8606 
8607   return Conversion;
8608 }
8609 
8610 namespace {
8611 /// Utility class to accumulate and print a diagnostic listing the invalid
8612 /// specifier(s) on a declaration.
8613 struct BadSpecifierDiagnoser {
8614   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8615       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8616   ~BadSpecifierDiagnoser() {
8617     Diagnostic << Specifiers;
8618   }
8619 
8620   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8621     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8622   }
8623   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8624     return check(SpecLoc,
8625                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8626   }
8627   void check(SourceLocation SpecLoc, const char *Spec) {
8628     if (SpecLoc.isInvalid()) return;
8629     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8630     if (!Specifiers.empty()) Specifiers += " ";
8631     Specifiers += Spec;
8632   }
8633 
8634   Sema &S;
8635   Sema::SemaDiagnosticBuilder Diagnostic;
8636   std::string Specifiers;
8637 };
8638 }
8639 
8640 /// Check the validity of a declarator that we parsed for a deduction-guide.
8641 /// These aren't actually declarators in the grammar, so we need to check that
8642 /// the user didn't specify any pieces that are not part of the deduction-guide
8643 /// grammar.
8644 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8645                                          StorageClass &SC) {
8646   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8647   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8648   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8649 
8650   // C++ [temp.deduct.guide]p3:
8651   //   A deduction-gide shall be declared in the same scope as the
8652   //   corresponding class template.
8653   if (!CurContext->getRedeclContext()->Equals(
8654           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8655     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8656       << GuidedTemplateDecl;
8657     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8658   }
8659 
8660   auto &DS = D.getMutableDeclSpec();
8661   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8662   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8663       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8664       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8665     BadSpecifierDiagnoser Diagnoser(
8666         *this, D.getIdentifierLoc(),
8667         diag::err_deduction_guide_invalid_specifier);
8668 
8669     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8670     DS.ClearStorageClassSpecs();
8671     SC = SC_None;
8672 
8673     // 'explicit' is permitted.
8674     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8675     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8676     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8677     DS.ClearConstexprSpec();
8678 
8679     Diagnoser.check(DS.getConstSpecLoc(), "const");
8680     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8681     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8682     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8683     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8684     DS.ClearTypeQualifiers();
8685 
8686     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8687     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8688     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8689     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8690     DS.ClearTypeSpecType();
8691   }
8692 
8693   if (D.isInvalidType())
8694     return;
8695 
8696   // Check the declarator is simple enough.
8697   bool FoundFunction = false;
8698   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8699     if (Chunk.Kind == DeclaratorChunk::Paren)
8700       continue;
8701     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8702       Diag(D.getDeclSpec().getBeginLoc(),
8703            diag::err_deduction_guide_with_complex_decl)
8704           << D.getSourceRange();
8705       break;
8706     }
8707     if (!Chunk.Fun.hasTrailingReturnType()) {
8708       Diag(D.getName().getBeginLoc(),
8709            diag::err_deduction_guide_no_trailing_return_type);
8710       break;
8711     }
8712 
8713     // Check that the return type is written as a specialization of
8714     // the template specified as the deduction-guide's name.
8715     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8716     TypeSourceInfo *TSI = nullptr;
8717     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8718     assert(TSI && "deduction guide has valid type but invalid return type?");
8719     bool AcceptableReturnType = false;
8720     bool MightInstantiateToSpecialization = false;
8721     if (auto RetTST =
8722             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8723       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8724       bool TemplateMatches =
8725           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8726       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8727         AcceptableReturnType = true;
8728       else {
8729         // This could still instantiate to the right type, unless we know it
8730         // names the wrong class template.
8731         auto *TD = SpecifiedName.getAsTemplateDecl();
8732         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8733                                              !TemplateMatches);
8734       }
8735     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8736       MightInstantiateToSpecialization = true;
8737     }
8738 
8739     if (!AcceptableReturnType) {
8740       Diag(TSI->getTypeLoc().getBeginLoc(),
8741            diag::err_deduction_guide_bad_trailing_return_type)
8742           << GuidedTemplate << TSI->getType()
8743           << MightInstantiateToSpecialization
8744           << TSI->getTypeLoc().getSourceRange();
8745     }
8746 
8747     // Keep going to check that we don't have any inner declarator pieces (we
8748     // could still have a function returning a pointer to a function).
8749     FoundFunction = true;
8750   }
8751 
8752   if (D.isFunctionDefinition())
8753     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8754 }
8755 
8756 //===----------------------------------------------------------------------===//
8757 // Namespace Handling
8758 //===----------------------------------------------------------------------===//
8759 
8760 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8761 /// reopened.
8762 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8763                                             SourceLocation Loc,
8764                                             IdentifierInfo *II, bool *IsInline,
8765                                             NamespaceDecl *PrevNS) {
8766   assert(*IsInline != PrevNS->isInline());
8767 
8768   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8769   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8770   // inline namespaces, with the intention of bringing names into namespace std.
8771   //
8772   // We support this just well enough to get that case working; this is not
8773   // sufficient to support reopening namespaces as inline in general.
8774   if (*IsInline && II && II->getName().startswith("__atomic") &&
8775       S.getSourceManager().isInSystemHeader(Loc)) {
8776     // Mark all prior declarations of the namespace as inline.
8777     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8778          NS = NS->getPreviousDecl())
8779       NS->setInline(*IsInline);
8780     // Patch up the lookup table for the containing namespace. This isn't really
8781     // correct, but it's good enough for this particular case.
8782     for (auto *I : PrevNS->decls())
8783       if (auto *ND = dyn_cast<NamedDecl>(I))
8784         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8785     return;
8786   }
8787 
8788   if (PrevNS->isInline())
8789     // The user probably just forgot the 'inline', so suggest that it
8790     // be added back.
8791     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8792       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8793   else
8794     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8795 
8796   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8797   *IsInline = PrevNS->isInline();
8798 }
8799 
8800 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8801 /// definition.
8802 Decl *Sema::ActOnStartNamespaceDef(
8803     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8804     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8805     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8806   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8807   // For anonymous namespace, take the location of the left brace.
8808   SourceLocation Loc = II ? IdentLoc : LBrace;
8809   bool IsInline = InlineLoc.isValid();
8810   bool IsInvalid = false;
8811   bool IsStd = false;
8812   bool AddToKnown = false;
8813   Scope *DeclRegionScope = NamespcScope->getParent();
8814 
8815   NamespaceDecl *PrevNS = nullptr;
8816   if (II) {
8817     // C++ [namespace.def]p2:
8818     //   The identifier in an original-namespace-definition shall not
8819     //   have been previously defined in the declarative region in
8820     //   which the original-namespace-definition appears. The
8821     //   identifier in an original-namespace-definition is the name of
8822     //   the namespace. Subsequently in that declarative region, it is
8823     //   treated as an original-namespace-name.
8824     //
8825     // Since namespace names are unique in their scope, and we don't
8826     // look through using directives, just look for any ordinary names
8827     // as if by qualified name lookup.
8828     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8829                    ForExternalRedeclaration);
8830     LookupQualifiedName(R, CurContext->getRedeclContext());
8831     NamedDecl *PrevDecl =
8832         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8833     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8834 
8835     if (PrevNS) {
8836       // This is an extended namespace definition.
8837       if (IsInline != PrevNS->isInline())
8838         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8839                                         &IsInline, PrevNS);
8840     } else if (PrevDecl) {
8841       // This is an invalid name redefinition.
8842       Diag(Loc, diag::err_redefinition_different_kind)
8843         << II;
8844       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8845       IsInvalid = true;
8846       // Continue on to push Namespc as current DeclContext and return it.
8847     } else if (II->isStr("std") &&
8848                CurContext->getRedeclContext()->isTranslationUnit()) {
8849       // This is the first "real" definition of the namespace "std", so update
8850       // our cache of the "std" namespace to point at this definition.
8851       PrevNS = getStdNamespace();
8852       IsStd = true;
8853       AddToKnown = !IsInline;
8854     } else {
8855       // We've seen this namespace for the first time.
8856       AddToKnown = !IsInline;
8857     }
8858   } else {
8859     // Anonymous namespaces.
8860 
8861     // Determine whether the parent already has an anonymous namespace.
8862     DeclContext *Parent = CurContext->getRedeclContext();
8863     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8864       PrevNS = TU->getAnonymousNamespace();
8865     } else {
8866       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8867       PrevNS = ND->getAnonymousNamespace();
8868     }
8869 
8870     if (PrevNS && IsInline != PrevNS->isInline())
8871       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8872                                       &IsInline, PrevNS);
8873   }
8874 
8875   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8876                                                  StartLoc, Loc, II, PrevNS);
8877   if (IsInvalid)
8878     Namespc->setInvalidDecl();
8879 
8880   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8881   AddPragmaAttributes(DeclRegionScope, Namespc);
8882 
8883   // FIXME: Should we be merging attributes?
8884   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8885     PushNamespaceVisibilityAttr(Attr, Loc);
8886 
8887   if (IsStd)
8888     StdNamespace = Namespc;
8889   if (AddToKnown)
8890     KnownNamespaces[Namespc] = false;
8891 
8892   if (II) {
8893     PushOnScopeChains(Namespc, DeclRegionScope);
8894   } else {
8895     // Link the anonymous namespace into its parent.
8896     DeclContext *Parent = CurContext->getRedeclContext();
8897     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8898       TU->setAnonymousNamespace(Namespc);
8899     } else {
8900       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8901     }
8902 
8903     CurContext->addDecl(Namespc);
8904 
8905     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8906     //   behaves as if it were replaced by
8907     //     namespace unique { /* empty body */ }
8908     //     using namespace unique;
8909     //     namespace unique { namespace-body }
8910     //   where all occurrences of 'unique' in a translation unit are
8911     //   replaced by the same identifier and this identifier differs
8912     //   from all other identifiers in the entire program.
8913 
8914     // We just create the namespace with an empty name and then add an
8915     // implicit using declaration, just like the standard suggests.
8916     //
8917     // CodeGen enforces the "universally unique" aspect by giving all
8918     // declarations semantically contained within an anonymous
8919     // namespace internal linkage.
8920 
8921     if (!PrevNS) {
8922       UD = UsingDirectiveDecl::Create(Context, Parent,
8923                                       /* 'using' */ LBrace,
8924                                       /* 'namespace' */ SourceLocation(),
8925                                       /* qualifier */ NestedNameSpecifierLoc(),
8926                                       /* identifier */ SourceLocation(),
8927                                       Namespc,
8928                                       /* Ancestor */ Parent);
8929       UD->setImplicit();
8930       Parent->addDecl(UD);
8931     }
8932   }
8933 
8934   ActOnDocumentableDecl(Namespc);
8935 
8936   // Although we could have an invalid decl (i.e. the namespace name is a
8937   // redefinition), push it as current DeclContext and try to continue parsing.
8938   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8939   // for the namespace has the declarations that showed up in that particular
8940   // namespace definition.
8941   PushDeclContext(NamespcScope, Namespc);
8942   return Namespc;
8943 }
8944 
8945 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8946 /// is a namespace alias, returns the namespace it points to.
8947 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8948   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8949     return AD->getNamespace();
8950   return dyn_cast_or_null<NamespaceDecl>(D);
8951 }
8952 
8953 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8954 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8955 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8956   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8957   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8958   Namespc->setRBraceLoc(RBrace);
8959   PopDeclContext();
8960   if (Namespc->hasAttr<VisibilityAttr>())
8961     PopPragmaVisibility(true, RBrace);
8962 }
8963 
8964 CXXRecordDecl *Sema::getStdBadAlloc() const {
8965   return cast_or_null<CXXRecordDecl>(
8966                                   StdBadAlloc.get(Context.getExternalSource()));
8967 }
8968 
8969 EnumDecl *Sema::getStdAlignValT() const {
8970   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8971 }
8972 
8973 NamespaceDecl *Sema::getStdNamespace() const {
8974   return cast_or_null<NamespaceDecl>(
8975                                  StdNamespace.get(Context.getExternalSource()));
8976 }
8977 
8978 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8979   if (!StdExperimentalNamespaceCache) {
8980     if (auto Std = getStdNamespace()) {
8981       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8982                           SourceLocation(), LookupNamespaceName);
8983       if (!LookupQualifiedName(Result, Std) ||
8984           !(StdExperimentalNamespaceCache =
8985                 Result.getAsSingle<NamespaceDecl>()))
8986         Result.suppressDiagnostics();
8987     }
8988   }
8989   return StdExperimentalNamespaceCache;
8990 }
8991 
8992 namespace {
8993 
8994 enum UnsupportedSTLSelect {
8995   USS_InvalidMember,
8996   USS_MissingMember,
8997   USS_NonTrivial,
8998   USS_Other
8999 };
9000 
9001 struct InvalidSTLDiagnoser {
9002   Sema &S;
9003   SourceLocation Loc;
9004   QualType TyForDiags;
9005 
9006   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9007                       const VarDecl *VD = nullptr) {
9008     {
9009       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9010                << TyForDiags << ((int)Sel);
9011       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9012         assert(!Name.empty());
9013         D << Name;
9014       }
9015     }
9016     if (Sel == USS_InvalidMember) {
9017       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9018           << VD << VD->getSourceRange();
9019     }
9020     return QualType();
9021   }
9022 };
9023 } // namespace
9024 
9025 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9026                                            SourceLocation Loc) {
9027   assert(getLangOpts().CPlusPlus &&
9028          "Looking for comparison category type outside of C++.");
9029 
9030   // Check if we've already successfully checked the comparison category type
9031   // before. If so, skip checking it again.
9032   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9033   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9034     return Info->getType();
9035 
9036   // If lookup failed
9037   if (!Info) {
9038     std::string NameForDiags = "std::";
9039     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9040     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9041         << NameForDiags;
9042     return QualType();
9043   }
9044 
9045   assert(Info->Kind == Kind);
9046   assert(Info->Record);
9047 
9048   // Update the Record decl in case we encountered a forward declaration on our
9049   // first pass. FIXME: This is a bit of a hack.
9050   if (Info->Record->hasDefinition())
9051     Info->Record = Info->Record->getDefinition();
9052 
9053   // Use an elaborated type for diagnostics which has a name containing the
9054   // prepended 'std' namespace but not any inline namespace names.
9055   QualType TyForDiags = [&]() {
9056     auto *NNS =
9057         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9058     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9059   }();
9060 
9061   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9062     return QualType();
9063 
9064   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9065 
9066   if (!Info->Record->isTriviallyCopyable())
9067     return UnsupportedSTLError(USS_NonTrivial);
9068 
9069   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9070     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9071     // Tolerate empty base classes.
9072     if (Base->isEmpty())
9073       continue;
9074     // Reject STL implementations which have at least one non-empty base.
9075     return UnsupportedSTLError();
9076   }
9077 
9078   // Check that the STL has implemented the types using a single integer field.
9079   // This expectation allows better codegen for builtin operators. We require:
9080   //   (1) The class has exactly one field.
9081   //   (2) The field is an integral or enumeration type.
9082   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9083   if (std::distance(FIt, FEnd) != 1 ||
9084       !FIt->getType()->isIntegralOrEnumerationType()) {
9085     return UnsupportedSTLError();
9086   }
9087 
9088   // Build each of the require values and store them in Info.
9089   for (ComparisonCategoryResult CCR :
9090        ComparisonCategories::getPossibleResultsForType(Kind)) {
9091     StringRef MemName = ComparisonCategories::getResultString(CCR);
9092     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9093 
9094     if (!ValInfo)
9095       return UnsupportedSTLError(USS_MissingMember, MemName);
9096 
9097     VarDecl *VD = ValInfo->VD;
9098     assert(VD && "should not be null!");
9099 
9100     // Attempt to diagnose reasons why the STL definition of this type
9101     // might be foobar, including it failing to be a constant expression.
9102     // TODO Handle more ways the lookup or result can be invalid.
9103     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9104         !VD->checkInitIsICE())
9105       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9106 
9107     // Attempt to evaluate the var decl as a constant expression and extract
9108     // the value of its first field as a ICE. If this fails, the STL
9109     // implementation is not supported.
9110     if (!ValInfo->hasValidIntValue())
9111       return UnsupportedSTLError();
9112 
9113     MarkVariableReferenced(Loc, VD);
9114   }
9115 
9116   // We've successfully built the required types and expressions. Update
9117   // the cache and return the newly cached value.
9118   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9119   return Info->getType();
9120 }
9121 
9122 /// Retrieve the special "std" namespace, which may require us to
9123 /// implicitly define the namespace.
9124 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9125   if (!StdNamespace) {
9126     // The "std" namespace has not yet been defined, so build one implicitly.
9127     StdNamespace = NamespaceDecl::Create(Context,
9128                                          Context.getTranslationUnitDecl(),
9129                                          /*Inline=*/false,
9130                                          SourceLocation(), SourceLocation(),
9131                                          &PP.getIdentifierTable().get("std"),
9132                                          /*PrevDecl=*/nullptr);
9133     getStdNamespace()->setImplicit(true);
9134   }
9135 
9136   return getStdNamespace();
9137 }
9138 
9139 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9140   assert(getLangOpts().CPlusPlus &&
9141          "Looking for std::initializer_list outside of C++.");
9142 
9143   // We're looking for implicit instantiations of
9144   // template <typename E> class std::initializer_list.
9145 
9146   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9147     return false;
9148 
9149   ClassTemplateDecl *Template = nullptr;
9150   const TemplateArgument *Arguments = nullptr;
9151 
9152   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9153 
9154     ClassTemplateSpecializationDecl *Specialization =
9155         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9156     if (!Specialization)
9157       return false;
9158 
9159     Template = Specialization->getSpecializedTemplate();
9160     Arguments = Specialization->getTemplateArgs().data();
9161   } else if (const TemplateSpecializationType *TST =
9162                  Ty->getAs<TemplateSpecializationType>()) {
9163     Template = dyn_cast_or_null<ClassTemplateDecl>(
9164         TST->getTemplateName().getAsTemplateDecl());
9165     Arguments = TST->getArgs();
9166   }
9167   if (!Template)
9168     return false;
9169 
9170   if (!StdInitializerList) {
9171     // Haven't recognized std::initializer_list yet, maybe this is it.
9172     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9173     if (TemplateClass->getIdentifier() !=
9174             &PP.getIdentifierTable().get("initializer_list") ||
9175         !getStdNamespace()->InEnclosingNamespaceSetOf(
9176             TemplateClass->getDeclContext()))
9177       return false;
9178     // This is a template called std::initializer_list, but is it the right
9179     // template?
9180     TemplateParameterList *Params = Template->getTemplateParameters();
9181     if (Params->getMinRequiredArguments() != 1)
9182       return false;
9183     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9184       return false;
9185 
9186     // It's the right template.
9187     StdInitializerList = Template;
9188   }
9189 
9190   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9191     return false;
9192 
9193   // This is an instance of std::initializer_list. Find the argument type.
9194   if (Element)
9195     *Element = Arguments[0].getAsType();
9196   return true;
9197 }
9198 
9199 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9200   NamespaceDecl *Std = S.getStdNamespace();
9201   if (!Std) {
9202     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9203     return nullptr;
9204   }
9205 
9206   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9207                       Loc, Sema::LookupOrdinaryName);
9208   if (!S.LookupQualifiedName(Result, Std)) {
9209     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9210     return nullptr;
9211   }
9212   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9213   if (!Template) {
9214     Result.suppressDiagnostics();
9215     // We found something weird. Complain about the first thing we found.
9216     NamedDecl *Found = *Result.begin();
9217     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9218     return nullptr;
9219   }
9220 
9221   // We found some template called std::initializer_list. Now verify that it's
9222   // correct.
9223   TemplateParameterList *Params = Template->getTemplateParameters();
9224   if (Params->getMinRequiredArguments() != 1 ||
9225       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9226     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9227     return nullptr;
9228   }
9229 
9230   return Template;
9231 }
9232 
9233 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9234   if (!StdInitializerList) {
9235     StdInitializerList = LookupStdInitializerList(*this, Loc);
9236     if (!StdInitializerList)
9237       return QualType();
9238   }
9239 
9240   TemplateArgumentListInfo Args(Loc, Loc);
9241   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9242                                        Context.getTrivialTypeSourceInfo(Element,
9243                                                                         Loc)));
9244   return Context.getCanonicalType(
9245       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9246 }
9247 
9248 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9249   // C++ [dcl.init.list]p2:
9250   //   A constructor is an initializer-list constructor if its first parameter
9251   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9252   //   std::initializer_list<E> for some type E, and either there are no other
9253   //   parameters or else all other parameters have default arguments.
9254   if (Ctor->getNumParams() < 1 ||
9255       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9256     return false;
9257 
9258   QualType ArgType = Ctor->getParamDecl(0)->getType();
9259   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9260     ArgType = RT->getPointeeType().getUnqualifiedType();
9261 
9262   return isStdInitializerList(ArgType, nullptr);
9263 }
9264 
9265 /// Determine whether a using statement is in a context where it will be
9266 /// apply in all contexts.
9267 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9268   switch (CurContext->getDeclKind()) {
9269     case Decl::TranslationUnit:
9270       return true;
9271     case Decl::LinkageSpec:
9272       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9273     default:
9274       return false;
9275   }
9276 }
9277 
9278 namespace {
9279 
9280 // Callback to only accept typo corrections that are namespaces.
9281 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9282 public:
9283   bool ValidateCandidate(const TypoCorrection &candidate) override {
9284     if (NamedDecl *ND = candidate.getCorrectionDecl())
9285       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9286     return false;
9287   }
9288 };
9289 
9290 }
9291 
9292 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9293                                        CXXScopeSpec &SS,
9294                                        SourceLocation IdentLoc,
9295                                        IdentifierInfo *Ident) {
9296   R.clear();
9297   if (TypoCorrection Corrected =
9298           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9299                         llvm::make_unique<NamespaceValidatorCCC>(),
9300                         Sema::CTK_ErrorRecovery)) {
9301     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9302       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9303       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9304                               Ident->getName().equals(CorrectedStr);
9305       S.diagnoseTypo(Corrected,
9306                      S.PDiag(diag::err_using_directive_member_suggest)
9307                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9308                      S.PDiag(diag::note_namespace_defined_here));
9309     } else {
9310       S.diagnoseTypo(Corrected,
9311                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9312                      S.PDiag(diag::note_namespace_defined_here));
9313     }
9314     R.addDecl(Corrected.getFoundDecl());
9315     return true;
9316   }
9317   return false;
9318 }
9319 
9320 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9321                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9322                                 SourceLocation IdentLoc,
9323                                 IdentifierInfo *NamespcName,
9324                                 const ParsedAttributesView &AttrList) {
9325   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9326   assert(NamespcName && "Invalid NamespcName.");
9327   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9328 
9329   // This can only happen along a recovery path.
9330   while (S->isTemplateParamScope())
9331     S = S->getParent();
9332   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9333 
9334   UsingDirectiveDecl *UDir = nullptr;
9335   NestedNameSpecifier *Qualifier = nullptr;
9336   if (SS.isSet())
9337     Qualifier = SS.getScopeRep();
9338 
9339   // Lookup namespace name.
9340   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9341   LookupParsedName(R, S, &SS);
9342   if (R.isAmbiguous())
9343     return nullptr;
9344 
9345   if (R.empty()) {
9346     R.clear();
9347     // Allow "using namespace std;" or "using namespace ::std;" even if
9348     // "std" hasn't been defined yet, for GCC compatibility.
9349     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9350         NamespcName->isStr("std")) {
9351       Diag(IdentLoc, diag::ext_using_undefined_std);
9352       R.addDecl(getOrCreateStdNamespace());
9353       R.resolveKind();
9354     }
9355     // Otherwise, attempt typo correction.
9356     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9357   }
9358 
9359   if (!R.empty()) {
9360     NamedDecl *Named = R.getRepresentativeDecl();
9361     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9362     assert(NS && "expected namespace decl");
9363 
9364     // The use of a nested name specifier may trigger deprecation warnings.
9365     DiagnoseUseOfDecl(Named, IdentLoc);
9366 
9367     // C++ [namespace.udir]p1:
9368     //   A using-directive specifies that the names in the nominated
9369     //   namespace can be used in the scope in which the
9370     //   using-directive appears after the using-directive. During
9371     //   unqualified name lookup (3.4.1), the names appear as if they
9372     //   were declared in the nearest enclosing namespace which
9373     //   contains both the using-directive and the nominated
9374     //   namespace. [Note: in this context, "contains" means "contains
9375     //   directly or indirectly". ]
9376 
9377     // Find enclosing context containing both using-directive and
9378     // nominated namespace.
9379     DeclContext *CommonAncestor = NS;
9380     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9381       CommonAncestor = CommonAncestor->getParent();
9382 
9383     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9384                                       SS.getWithLocInContext(Context),
9385                                       IdentLoc, Named, CommonAncestor);
9386 
9387     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9388         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9389       Diag(IdentLoc, diag::warn_using_directive_in_header);
9390     }
9391 
9392     PushUsingDirective(S, UDir);
9393   } else {
9394     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9395   }
9396 
9397   if (UDir)
9398     ProcessDeclAttributeList(S, UDir, AttrList);
9399 
9400   return UDir;
9401 }
9402 
9403 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9404   // If the scope has an associated entity and the using directive is at
9405   // namespace or translation unit scope, add the UsingDirectiveDecl into
9406   // its lookup structure so qualified name lookup can find it.
9407   DeclContext *Ctx = S->getEntity();
9408   if (Ctx && !Ctx->isFunctionOrMethod())
9409     Ctx->addDecl(UDir);
9410   else
9411     // Otherwise, it is at block scope. The using-directives will affect lookup
9412     // only to the end of the scope.
9413     S->PushUsingDirective(UDir);
9414 }
9415 
9416 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9417                                   SourceLocation UsingLoc,
9418                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9419                                   UnqualifiedId &Name,
9420                                   SourceLocation EllipsisLoc,
9421                                   const ParsedAttributesView &AttrList) {
9422   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9423 
9424   if (SS.isEmpty()) {
9425     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9426     return nullptr;
9427   }
9428 
9429   switch (Name.getKind()) {
9430   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9431   case UnqualifiedIdKind::IK_Identifier:
9432   case UnqualifiedIdKind::IK_OperatorFunctionId:
9433   case UnqualifiedIdKind::IK_LiteralOperatorId:
9434   case UnqualifiedIdKind::IK_ConversionFunctionId:
9435     break;
9436 
9437   case UnqualifiedIdKind::IK_ConstructorName:
9438   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9439     // C++11 inheriting constructors.
9440     Diag(Name.getBeginLoc(),
9441          getLangOpts().CPlusPlus11
9442              ? diag::warn_cxx98_compat_using_decl_constructor
9443              : diag::err_using_decl_constructor)
9444         << SS.getRange();
9445 
9446     if (getLangOpts().CPlusPlus11) break;
9447 
9448     return nullptr;
9449 
9450   case UnqualifiedIdKind::IK_DestructorName:
9451     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9452     return nullptr;
9453 
9454   case UnqualifiedIdKind::IK_TemplateId:
9455     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9456         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9457     return nullptr;
9458 
9459   case UnqualifiedIdKind::IK_DeductionGuideName:
9460     llvm_unreachable("cannot parse qualified deduction guide name");
9461   }
9462 
9463   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9464   DeclarationName TargetName = TargetNameInfo.getName();
9465   if (!TargetName)
9466     return nullptr;
9467 
9468   // Warn about access declarations.
9469   if (UsingLoc.isInvalid()) {
9470     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9471                                  ? diag::err_access_decl
9472                                  : diag::warn_access_decl_deprecated)
9473         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9474   }
9475 
9476   if (EllipsisLoc.isInvalid()) {
9477     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9478         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9479       return nullptr;
9480   } else {
9481     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9482         !TargetNameInfo.containsUnexpandedParameterPack()) {
9483       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9484         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9485       EllipsisLoc = SourceLocation();
9486     }
9487   }
9488 
9489   NamedDecl *UD =
9490       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9491                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9492                             /*IsInstantiation*/false);
9493   if (UD)
9494     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9495 
9496   return UD;
9497 }
9498 
9499 /// Determine whether a using declaration considers the given
9500 /// declarations as "equivalent", e.g., if they are redeclarations of
9501 /// the same entity or are both typedefs of the same type.
9502 static bool
9503 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9504   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9505     return true;
9506 
9507   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9508     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9509       return Context.hasSameType(TD1->getUnderlyingType(),
9510                                  TD2->getUnderlyingType());
9511 
9512   return false;
9513 }
9514 
9515 
9516 /// Determines whether to create a using shadow decl for a particular
9517 /// decl, given the set of decls existing prior to this using lookup.
9518 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9519                                 const LookupResult &Previous,
9520                                 UsingShadowDecl *&PrevShadow) {
9521   // Diagnose finding a decl which is not from a base class of the
9522   // current class.  We do this now because there are cases where this
9523   // function will silently decide not to build a shadow decl, which
9524   // will pre-empt further diagnostics.
9525   //
9526   // We don't need to do this in C++11 because we do the check once on
9527   // the qualifier.
9528   //
9529   // FIXME: diagnose the following if we care enough:
9530   //   struct A { int foo; };
9531   //   struct B : A { using A::foo; };
9532   //   template <class T> struct C : A {};
9533   //   template <class T> struct D : C<T> { using B::foo; } // <---
9534   // This is invalid (during instantiation) in C++03 because B::foo
9535   // resolves to the using decl in B, which is not a base class of D<T>.
9536   // We can't diagnose it immediately because C<T> is an unknown
9537   // specialization.  The UsingShadowDecl in D<T> then points directly
9538   // to A::foo, which will look well-formed when we instantiate.
9539   // The right solution is to not collapse the shadow-decl chain.
9540   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9541     DeclContext *OrigDC = Orig->getDeclContext();
9542 
9543     // Handle enums and anonymous structs.
9544     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9545     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9546     while (OrigRec->isAnonymousStructOrUnion())
9547       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9548 
9549     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9550       if (OrigDC == CurContext) {
9551         Diag(Using->getLocation(),
9552              diag::err_using_decl_nested_name_specifier_is_current_class)
9553           << Using->getQualifierLoc().getSourceRange();
9554         Diag(Orig->getLocation(), diag::note_using_decl_target);
9555         Using->setInvalidDecl();
9556         return true;
9557       }
9558 
9559       Diag(Using->getQualifierLoc().getBeginLoc(),
9560            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9561         << Using->getQualifier()
9562         << cast<CXXRecordDecl>(CurContext)
9563         << Using->getQualifierLoc().getSourceRange();
9564       Diag(Orig->getLocation(), diag::note_using_decl_target);
9565       Using->setInvalidDecl();
9566       return true;
9567     }
9568   }
9569 
9570   if (Previous.empty()) return false;
9571 
9572   NamedDecl *Target = Orig;
9573   if (isa<UsingShadowDecl>(Target))
9574     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9575 
9576   // If the target happens to be one of the previous declarations, we
9577   // don't have a conflict.
9578   //
9579   // FIXME: but we might be increasing its access, in which case we
9580   // should redeclare it.
9581   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9582   bool FoundEquivalentDecl = false;
9583   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9584          I != E; ++I) {
9585     NamedDecl *D = (*I)->getUnderlyingDecl();
9586     // We can have UsingDecls in our Previous results because we use the same
9587     // LookupResult for checking whether the UsingDecl itself is a valid
9588     // redeclaration.
9589     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9590       continue;
9591 
9592     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9593       // C++ [class.mem]p19:
9594       //   If T is the name of a class, then [every named member other than
9595       //   a non-static data member] shall have a name different from T
9596       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9597           !isa<IndirectFieldDecl>(Target) &&
9598           !isa<UnresolvedUsingValueDecl>(Target) &&
9599           DiagnoseClassNameShadow(
9600               CurContext,
9601               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9602         return true;
9603     }
9604 
9605     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9606       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9607         PrevShadow = Shadow;
9608       FoundEquivalentDecl = true;
9609     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9610       // We don't conflict with an existing using shadow decl of an equivalent
9611       // declaration, but we're not a redeclaration of it.
9612       FoundEquivalentDecl = true;
9613     }
9614 
9615     if (isVisible(D))
9616       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9617   }
9618 
9619   if (FoundEquivalentDecl)
9620     return false;
9621 
9622   if (FunctionDecl *FD = Target->getAsFunction()) {
9623     NamedDecl *OldDecl = nullptr;
9624     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9625                           /*IsForUsingDecl*/ true)) {
9626     case Ovl_Overload:
9627       return false;
9628 
9629     case Ovl_NonFunction:
9630       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9631       break;
9632 
9633     // We found a decl with the exact signature.
9634     case Ovl_Match:
9635       // If we're in a record, we want to hide the target, so we
9636       // return true (without a diagnostic) to tell the caller not to
9637       // build a shadow decl.
9638       if (CurContext->isRecord())
9639         return true;
9640 
9641       // If we're not in a record, this is an error.
9642       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9643       break;
9644     }
9645 
9646     Diag(Target->getLocation(), diag::note_using_decl_target);
9647     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9648     Using->setInvalidDecl();
9649     return true;
9650   }
9651 
9652   // Target is not a function.
9653 
9654   if (isa<TagDecl>(Target)) {
9655     // No conflict between a tag and a non-tag.
9656     if (!Tag) return false;
9657 
9658     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9659     Diag(Target->getLocation(), diag::note_using_decl_target);
9660     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9661     Using->setInvalidDecl();
9662     return true;
9663   }
9664 
9665   // No conflict between a tag and a non-tag.
9666   if (!NonTag) return false;
9667 
9668   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9669   Diag(Target->getLocation(), diag::note_using_decl_target);
9670   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9671   Using->setInvalidDecl();
9672   return true;
9673 }
9674 
9675 /// Determine whether a direct base class is a virtual base class.
9676 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9677   if (!Derived->getNumVBases())
9678     return false;
9679   for (auto &B : Derived->bases())
9680     if (B.getType()->getAsCXXRecordDecl() == Base)
9681       return B.isVirtual();
9682   llvm_unreachable("not a direct base class");
9683 }
9684 
9685 /// Builds a shadow declaration corresponding to a 'using' declaration.
9686 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9687                                             UsingDecl *UD,
9688                                             NamedDecl *Orig,
9689                                             UsingShadowDecl *PrevDecl) {
9690   // If we resolved to another shadow declaration, just coalesce them.
9691   NamedDecl *Target = Orig;
9692   if (isa<UsingShadowDecl>(Target)) {
9693     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9694     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9695   }
9696 
9697   NamedDecl *NonTemplateTarget = Target;
9698   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9699     NonTemplateTarget = TargetTD->getTemplatedDecl();
9700 
9701   UsingShadowDecl *Shadow;
9702   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9703     bool IsVirtualBase =
9704         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9705                             UD->getQualifier()->getAsRecordDecl());
9706     Shadow = ConstructorUsingShadowDecl::Create(
9707         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9708   } else {
9709     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9710                                      Target);
9711   }
9712   UD->addShadowDecl(Shadow);
9713 
9714   Shadow->setAccess(UD->getAccess());
9715   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9716     Shadow->setInvalidDecl();
9717 
9718   Shadow->setPreviousDecl(PrevDecl);
9719 
9720   if (S)
9721     PushOnScopeChains(Shadow, S);
9722   else
9723     CurContext->addDecl(Shadow);
9724 
9725 
9726   return Shadow;
9727 }
9728 
9729 /// Hides a using shadow declaration.  This is required by the current
9730 /// using-decl implementation when a resolvable using declaration in a
9731 /// class is followed by a declaration which would hide or override
9732 /// one or more of the using decl's targets; for example:
9733 ///
9734 ///   struct Base { void foo(int); };
9735 ///   struct Derived : Base {
9736 ///     using Base::foo;
9737 ///     void foo(int);
9738 ///   };
9739 ///
9740 /// The governing language is C++03 [namespace.udecl]p12:
9741 ///
9742 ///   When a using-declaration brings names from a base class into a
9743 ///   derived class scope, member functions in the derived class
9744 ///   override and/or hide member functions with the same name and
9745 ///   parameter types in a base class (rather than conflicting).
9746 ///
9747 /// There are two ways to implement this:
9748 ///   (1) optimistically create shadow decls when they're not hidden
9749 ///       by existing declarations, or
9750 ///   (2) don't create any shadow decls (or at least don't make them
9751 ///       visible) until we've fully parsed/instantiated the class.
9752 /// The problem with (1) is that we might have to retroactively remove
9753 /// a shadow decl, which requires several O(n) operations because the
9754 /// decl structures are (very reasonably) not designed for removal.
9755 /// (2) avoids this but is very fiddly and phase-dependent.
9756 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9757   if (Shadow->getDeclName().getNameKind() ==
9758         DeclarationName::CXXConversionFunctionName)
9759     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9760 
9761   // Remove it from the DeclContext...
9762   Shadow->getDeclContext()->removeDecl(Shadow);
9763 
9764   // ...and the scope, if applicable...
9765   if (S) {
9766     S->RemoveDecl(Shadow);
9767     IdResolver.RemoveDecl(Shadow);
9768   }
9769 
9770   // ...and the using decl.
9771   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9772 
9773   // TODO: complain somehow if Shadow was used.  It shouldn't
9774   // be possible for this to happen, because...?
9775 }
9776 
9777 /// Find the base specifier for a base class with the given type.
9778 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9779                                                 QualType DesiredBase,
9780                                                 bool &AnyDependentBases) {
9781   // Check whether the named type is a direct base class.
9782   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9783   for (auto &Base : Derived->bases()) {
9784     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9785     if (CanonicalDesiredBase == BaseType)
9786       return &Base;
9787     if (BaseType->isDependentType())
9788       AnyDependentBases = true;
9789   }
9790   return nullptr;
9791 }
9792 
9793 namespace {
9794 class UsingValidatorCCC : public CorrectionCandidateCallback {
9795 public:
9796   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9797                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9798       : HasTypenameKeyword(HasTypenameKeyword),
9799         IsInstantiation(IsInstantiation), OldNNS(NNS),
9800         RequireMemberOf(RequireMemberOf) {}
9801 
9802   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9803     NamedDecl *ND = Candidate.getCorrectionDecl();
9804 
9805     // Keywords are not valid here.
9806     if (!ND || isa<NamespaceDecl>(ND))
9807       return false;
9808 
9809     // Completely unqualified names are invalid for a 'using' declaration.
9810     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9811       return false;
9812 
9813     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9814     // reject.
9815 
9816     if (RequireMemberOf) {
9817       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9818       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9819         // No-one ever wants a using-declaration to name an injected-class-name
9820         // of a base class, unless they're declaring an inheriting constructor.
9821         ASTContext &Ctx = ND->getASTContext();
9822         if (!Ctx.getLangOpts().CPlusPlus11)
9823           return false;
9824         QualType FoundType = Ctx.getRecordType(FoundRecord);
9825 
9826         // Check that the injected-class-name is named as a member of its own
9827         // type; we don't want to suggest 'using Derived::Base;', since that
9828         // means something else.
9829         NestedNameSpecifier *Specifier =
9830             Candidate.WillReplaceSpecifier()
9831                 ? Candidate.getCorrectionSpecifier()
9832                 : OldNNS;
9833         if (!Specifier->getAsType() ||
9834             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9835           return false;
9836 
9837         // Check that this inheriting constructor declaration actually names a
9838         // direct base class of the current class.
9839         bool AnyDependentBases = false;
9840         if (!findDirectBaseWithType(RequireMemberOf,
9841                                     Ctx.getRecordType(FoundRecord),
9842                                     AnyDependentBases) &&
9843             !AnyDependentBases)
9844           return false;
9845       } else {
9846         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9847         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9848           return false;
9849 
9850         // FIXME: Check that the base class member is accessible?
9851       }
9852     } else {
9853       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9854       if (FoundRecord && FoundRecord->isInjectedClassName())
9855         return false;
9856     }
9857 
9858     if (isa<TypeDecl>(ND))
9859       return HasTypenameKeyword || !IsInstantiation;
9860 
9861     return !HasTypenameKeyword;
9862   }
9863 
9864 private:
9865   bool HasTypenameKeyword;
9866   bool IsInstantiation;
9867   NestedNameSpecifier *OldNNS;
9868   CXXRecordDecl *RequireMemberOf;
9869 };
9870 } // end anonymous namespace
9871 
9872 /// Builds a using declaration.
9873 ///
9874 /// \param IsInstantiation - Whether this call arises from an
9875 ///   instantiation of an unresolved using declaration.  We treat
9876 ///   the lookup differently for these declarations.
9877 NamedDecl *Sema::BuildUsingDeclaration(
9878     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9879     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9880     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9881     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9882   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9883   SourceLocation IdentLoc = NameInfo.getLoc();
9884   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9885 
9886   // FIXME: We ignore attributes for now.
9887 
9888   // For an inheriting constructor declaration, the name of the using
9889   // declaration is the name of a constructor in this class, not in the
9890   // base class.
9891   DeclarationNameInfo UsingName = NameInfo;
9892   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9893     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9894       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9895           Context.getCanonicalType(Context.getRecordType(RD))));
9896 
9897   // Do the redeclaration lookup in the current scope.
9898   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9899                         ForVisibleRedeclaration);
9900   Previous.setHideTags(false);
9901   if (S) {
9902     LookupName(Previous, S);
9903 
9904     // It is really dumb that we have to do this.
9905     LookupResult::Filter F = Previous.makeFilter();
9906     while (F.hasNext()) {
9907       NamedDecl *D = F.next();
9908       if (!isDeclInScope(D, CurContext, S))
9909         F.erase();
9910       // If we found a local extern declaration that's not ordinarily visible,
9911       // and this declaration is being added to a non-block scope, ignore it.
9912       // We're only checking for scope conflicts here, not also for violations
9913       // of the linkage rules.
9914       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9915                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9916         F.erase();
9917     }
9918     F.done();
9919   } else {
9920     assert(IsInstantiation && "no scope in non-instantiation");
9921     if (CurContext->isRecord())
9922       LookupQualifiedName(Previous, CurContext);
9923     else {
9924       // No redeclaration check is needed here; in non-member contexts we
9925       // diagnosed all possible conflicts with other using-declarations when
9926       // building the template:
9927       //
9928       // For a dependent non-type using declaration, the only valid case is
9929       // if we instantiate to a single enumerator. We check for conflicts
9930       // between shadow declarations we introduce, and we check in the template
9931       // definition for conflicts between a non-type using declaration and any
9932       // other declaration, which together covers all cases.
9933       //
9934       // A dependent typename using declaration will never successfully
9935       // instantiate, since it will always name a class member, so we reject
9936       // that in the template definition.
9937     }
9938   }
9939 
9940   // Check for invalid redeclarations.
9941   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9942                                   SS, IdentLoc, Previous))
9943     return nullptr;
9944 
9945   // Check for bad qualifiers.
9946   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9947                               IdentLoc))
9948     return nullptr;
9949 
9950   DeclContext *LookupContext = computeDeclContext(SS);
9951   NamedDecl *D;
9952   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9953   if (!LookupContext || EllipsisLoc.isValid()) {
9954     if (HasTypenameKeyword) {
9955       // FIXME: not all declaration name kinds are legal here
9956       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9957                                               UsingLoc, TypenameLoc,
9958                                               QualifierLoc,
9959                                               IdentLoc, NameInfo.getName(),
9960                                               EllipsisLoc);
9961     } else {
9962       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9963                                            QualifierLoc, NameInfo, EllipsisLoc);
9964     }
9965     D->setAccess(AS);
9966     CurContext->addDecl(D);
9967     return D;
9968   }
9969 
9970   auto Build = [&](bool Invalid) {
9971     UsingDecl *UD =
9972         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9973                           UsingName, HasTypenameKeyword);
9974     UD->setAccess(AS);
9975     CurContext->addDecl(UD);
9976     UD->setInvalidDecl(Invalid);
9977     return UD;
9978   };
9979   auto BuildInvalid = [&]{ return Build(true); };
9980   auto BuildValid = [&]{ return Build(false); };
9981 
9982   if (RequireCompleteDeclContext(SS, LookupContext))
9983     return BuildInvalid();
9984 
9985   // Look up the target name.
9986   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9987 
9988   // Unlike most lookups, we don't always want to hide tag
9989   // declarations: tag names are visible through the using declaration
9990   // even if hidden by ordinary names, *except* in a dependent context
9991   // where it's important for the sanity of two-phase lookup.
9992   if (!IsInstantiation)
9993     R.setHideTags(false);
9994 
9995   // For the purposes of this lookup, we have a base object type
9996   // equal to that of the current context.
9997   if (CurContext->isRecord()) {
9998     R.setBaseObjectType(
9999                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10000   }
10001 
10002   LookupQualifiedName(R, LookupContext);
10003 
10004   // Try to correct typos if possible. If constructor name lookup finds no
10005   // results, that means the named class has no explicit constructors, and we
10006   // suppressed declaring implicit ones (probably because it's dependent or
10007   // invalid).
10008   if (R.empty() &&
10009       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10010     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10011     // it will believe that glibc provides a ::gets in cases where it does not,
10012     // and will try to pull it into namespace std with a using-declaration.
10013     // Just ignore the using-declaration in that case.
10014     auto *II = NameInfo.getName().getAsIdentifierInfo();
10015     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10016         CurContext->isStdNamespace() &&
10017         isa<TranslationUnitDecl>(LookupContext) &&
10018         getSourceManager().isInSystemHeader(UsingLoc))
10019       return nullptr;
10020     if (TypoCorrection Corrected = CorrectTypo(
10021             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10022             llvm::make_unique<UsingValidatorCCC>(
10023                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10024                 dyn_cast<CXXRecordDecl>(CurContext)),
10025             CTK_ErrorRecovery)) {
10026       // We reject candidates where DroppedSpecifier == true, hence the
10027       // literal '0' below.
10028       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10029                                 << NameInfo.getName() << LookupContext << 0
10030                                 << SS.getRange());
10031 
10032       // If we picked a correction with no attached Decl we can't do anything
10033       // useful with it, bail out.
10034       NamedDecl *ND = Corrected.getCorrectionDecl();
10035       if (!ND)
10036         return BuildInvalid();
10037 
10038       // If we corrected to an inheriting constructor, handle it as one.
10039       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10040       if (RD && RD->isInjectedClassName()) {
10041         // The parent of the injected class name is the class itself.
10042         RD = cast<CXXRecordDecl>(RD->getParent());
10043 
10044         // Fix up the information we'll use to build the using declaration.
10045         if (Corrected.WillReplaceSpecifier()) {
10046           NestedNameSpecifierLocBuilder Builder;
10047           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10048                               QualifierLoc.getSourceRange());
10049           QualifierLoc = Builder.getWithLocInContext(Context);
10050         }
10051 
10052         // In this case, the name we introduce is the name of a derived class
10053         // constructor.
10054         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10055         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10056             Context.getCanonicalType(Context.getRecordType(CurClass))));
10057         UsingName.setNamedTypeInfo(nullptr);
10058         for (auto *Ctor : LookupConstructors(RD))
10059           R.addDecl(Ctor);
10060         R.resolveKind();
10061       } else {
10062         // FIXME: Pick up all the declarations if we found an overloaded
10063         // function.
10064         UsingName.setName(ND->getDeclName());
10065         R.addDecl(ND);
10066       }
10067     } else {
10068       Diag(IdentLoc, diag::err_no_member)
10069         << NameInfo.getName() << LookupContext << SS.getRange();
10070       return BuildInvalid();
10071     }
10072   }
10073 
10074   if (R.isAmbiguous())
10075     return BuildInvalid();
10076 
10077   if (HasTypenameKeyword) {
10078     // If we asked for a typename and got a non-type decl, error out.
10079     if (!R.getAsSingle<TypeDecl>()) {
10080       Diag(IdentLoc, diag::err_using_typename_non_type);
10081       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10082         Diag((*I)->getUnderlyingDecl()->getLocation(),
10083              diag::note_using_decl_target);
10084       return BuildInvalid();
10085     }
10086   } else {
10087     // If we asked for a non-typename and we got a type, error out,
10088     // but only if this is an instantiation of an unresolved using
10089     // decl.  Otherwise just silently find the type name.
10090     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10091       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10092       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10093       return BuildInvalid();
10094     }
10095   }
10096 
10097   // C++14 [namespace.udecl]p6:
10098   // A using-declaration shall not name a namespace.
10099   if (R.getAsSingle<NamespaceDecl>()) {
10100     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10101       << SS.getRange();
10102     return BuildInvalid();
10103   }
10104 
10105   // C++14 [namespace.udecl]p7:
10106   // A using-declaration shall not name a scoped enumerator.
10107   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10108     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10109       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10110         << SS.getRange();
10111       return BuildInvalid();
10112     }
10113   }
10114 
10115   UsingDecl *UD = BuildValid();
10116 
10117   // Some additional rules apply to inheriting constructors.
10118   if (UsingName.getName().getNameKind() ==
10119         DeclarationName::CXXConstructorName) {
10120     // Suppress access diagnostics; the access check is instead performed at the
10121     // point of use for an inheriting constructor.
10122     R.suppressDiagnostics();
10123     if (CheckInheritingConstructorUsingDecl(UD))
10124       return UD;
10125   }
10126 
10127   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10128     UsingShadowDecl *PrevDecl = nullptr;
10129     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10130       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10131   }
10132 
10133   return UD;
10134 }
10135 
10136 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10137                                     ArrayRef<NamedDecl *> Expansions) {
10138   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10139          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10140          isa<UsingPackDecl>(InstantiatedFrom));
10141 
10142   auto *UPD =
10143       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10144   UPD->setAccess(InstantiatedFrom->getAccess());
10145   CurContext->addDecl(UPD);
10146   return UPD;
10147 }
10148 
10149 /// Additional checks for a using declaration referring to a constructor name.
10150 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10151   assert(!UD->hasTypename() && "expecting a constructor name");
10152 
10153   const Type *SourceType = UD->getQualifier()->getAsType();
10154   assert(SourceType &&
10155          "Using decl naming constructor doesn't have type in scope spec.");
10156   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10157 
10158   // Check whether the named type is a direct base class.
10159   bool AnyDependentBases = false;
10160   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10161                                       AnyDependentBases);
10162   if (!Base && !AnyDependentBases) {
10163     Diag(UD->getUsingLoc(),
10164          diag::err_using_decl_constructor_not_in_direct_base)
10165       << UD->getNameInfo().getSourceRange()
10166       << QualType(SourceType, 0) << TargetClass;
10167     UD->setInvalidDecl();
10168     return true;
10169   }
10170 
10171   if (Base)
10172     Base->setInheritConstructors();
10173 
10174   return false;
10175 }
10176 
10177 /// Checks that the given using declaration is not an invalid
10178 /// redeclaration.  Note that this is checking only for the using decl
10179 /// itself, not for any ill-formedness among the UsingShadowDecls.
10180 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10181                                        bool HasTypenameKeyword,
10182                                        const CXXScopeSpec &SS,
10183                                        SourceLocation NameLoc,
10184                                        const LookupResult &Prev) {
10185   NestedNameSpecifier *Qual = SS.getScopeRep();
10186 
10187   // C++03 [namespace.udecl]p8:
10188   // C++0x [namespace.udecl]p10:
10189   //   A using-declaration is a declaration and can therefore be used
10190   //   repeatedly where (and only where) multiple declarations are
10191   //   allowed.
10192   //
10193   // That's in non-member contexts.
10194   if (!CurContext->getRedeclContext()->isRecord()) {
10195     // A dependent qualifier outside a class can only ever resolve to an
10196     // enumeration type. Therefore it conflicts with any other non-type
10197     // declaration in the same scope.
10198     // FIXME: How should we check for dependent type-type conflicts at block
10199     // scope?
10200     if (Qual->isDependent() && !HasTypenameKeyword) {
10201       for (auto *D : Prev) {
10202         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10203           bool OldCouldBeEnumerator =
10204               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10205           Diag(NameLoc,
10206                OldCouldBeEnumerator ? diag::err_redefinition
10207                                     : diag::err_redefinition_different_kind)
10208               << Prev.getLookupName();
10209           Diag(D->getLocation(), diag::note_previous_definition);
10210           return true;
10211         }
10212       }
10213     }
10214     return false;
10215   }
10216 
10217   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10218     NamedDecl *D = *I;
10219 
10220     bool DTypename;
10221     NestedNameSpecifier *DQual;
10222     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10223       DTypename = UD->hasTypename();
10224       DQual = UD->getQualifier();
10225     } else if (UnresolvedUsingValueDecl *UD
10226                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10227       DTypename = false;
10228       DQual = UD->getQualifier();
10229     } else if (UnresolvedUsingTypenameDecl *UD
10230                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10231       DTypename = true;
10232       DQual = UD->getQualifier();
10233     } else continue;
10234 
10235     // using decls differ if one says 'typename' and the other doesn't.
10236     // FIXME: non-dependent using decls?
10237     if (HasTypenameKeyword != DTypename) continue;
10238 
10239     // using decls differ if they name different scopes (but note that
10240     // template instantiation can cause this check to trigger when it
10241     // didn't before instantiation).
10242     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10243         Context.getCanonicalNestedNameSpecifier(DQual))
10244       continue;
10245 
10246     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10247     Diag(D->getLocation(), diag::note_using_decl) << 1;
10248     return true;
10249   }
10250 
10251   return false;
10252 }
10253 
10254 
10255 /// Checks that the given nested-name qualifier used in a using decl
10256 /// in the current context is appropriately related to the current
10257 /// scope.  If an error is found, diagnoses it and returns true.
10258 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10259                                    bool HasTypename,
10260                                    const CXXScopeSpec &SS,
10261                                    const DeclarationNameInfo &NameInfo,
10262                                    SourceLocation NameLoc) {
10263   DeclContext *NamedContext = computeDeclContext(SS);
10264 
10265   if (!CurContext->isRecord()) {
10266     // C++03 [namespace.udecl]p3:
10267     // C++0x [namespace.udecl]p8:
10268     //   A using-declaration for a class member shall be a member-declaration.
10269 
10270     // If we weren't able to compute a valid scope, it might validly be a
10271     // dependent class scope or a dependent enumeration unscoped scope. If
10272     // we have a 'typename' keyword, the scope must resolve to a class type.
10273     if ((HasTypename && !NamedContext) ||
10274         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10275       auto *RD = NamedContext
10276                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10277                      : nullptr;
10278       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10279         RD = nullptr;
10280 
10281       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10282         << SS.getRange();
10283 
10284       // If we have a complete, non-dependent source type, try to suggest a
10285       // way to get the same effect.
10286       if (!RD)
10287         return true;
10288 
10289       // Find what this using-declaration was referring to.
10290       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10291       R.setHideTags(false);
10292       R.suppressDiagnostics();
10293       LookupQualifiedName(R, RD);
10294 
10295       if (R.getAsSingle<TypeDecl>()) {
10296         if (getLangOpts().CPlusPlus11) {
10297           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10298           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10299             << 0 // alias declaration
10300             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10301                                           NameInfo.getName().getAsString() +
10302                                               " = ");
10303         } else {
10304           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10305           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10306           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10307             << 1 // typedef declaration
10308             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10309             << FixItHint::CreateInsertion(
10310                    InsertLoc, " " + NameInfo.getName().getAsString());
10311         }
10312       } else if (R.getAsSingle<VarDecl>()) {
10313         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10314         // repeating the type of the static data member here.
10315         FixItHint FixIt;
10316         if (getLangOpts().CPlusPlus11) {
10317           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10318           FixIt = FixItHint::CreateReplacement(
10319               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10320         }
10321 
10322         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10323           << 2 // reference declaration
10324           << FixIt;
10325       } else if (R.getAsSingle<EnumConstantDecl>()) {
10326         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10327         // repeating the type of the enumeration here, and we can't do so if
10328         // the type is anonymous.
10329         FixItHint FixIt;
10330         if (getLangOpts().CPlusPlus11) {
10331           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10332           FixIt = FixItHint::CreateReplacement(
10333               UsingLoc,
10334               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10335         }
10336 
10337         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10338           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10339           << FixIt;
10340       }
10341       return true;
10342     }
10343 
10344     // Otherwise, this might be valid.
10345     return false;
10346   }
10347 
10348   // The current scope is a record.
10349 
10350   // If the named context is dependent, we can't decide much.
10351   if (!NamedContext) {
10352     // FIXME: in C++0x, we can diagnose if we can prove that the
10353     // nested-name-specifier does not refer to a base class, which is
10354     // still possible in some cases.
10355 
10356     // Otherwise we have to conservatively report that things might be
10357     // okay.
10358     return false;
10359   }
10360 
10361   if (!NamedContext->isRecord()) {
10362     // Ideally this would point at the last name in the specifier,
10363     // but we don't have that level of source info.
10364     Diag(SS.getRange().getBegin(),
10365          diag::err_using_decl_nested_name_specifier_is_not_class)
10366       << SS.getScopeRep() << SS.getRange();
10367     return true;
10368   }
10369 
10370   if (!NamedContext->isDependentContext() &&
10371       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10372     return true;
10373 
10374   if (getLangOpts().CPlusPlus11) {
10375     // C++11 [namespace.udecl]p3:
10376     //   In a using-declaration used as a member-declaration, the
10377     //   nested-name-specifier shall name a base class of the class
10378     //   being defined.
10379 
10380     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10381                                  cast<CXXRecordDecl>(NamedContext))) {
10382       if (CurContext == NamedContext) {
10383         Diag(NameLoc,
10384              diag::err_using_decl_nested_name_specifier_is_current_class)
10385           << SS.getRange();
10386         return true;
10387       }
10388 
10389       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10390         Diag(SS.getRange().getBegin(),
10391              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10392           << SS.getScopeRep()
10393           << cast<CXXRecordDecl>(CurContext)
10394           << SS.getRange();
10395       }
10396       return true;
10397     }
10398 
10399     return false;
10400   }
10401 
10402   // C++03 [namespace.udecl]p4:
10403   //   A using-declaration used as a member-declaration shall refer
10404   //   to a member of a base class of the class being defined [etc.].
10405 
10406   // Salient point: SS doesn't have to name a base class as long as
10407   // lookup only finds members from base classes.  Therefore we can
10408   // diagnose here only if we can prove that that can't happen,
10409   // i.e. if the class hierarchies provably don't intersect.
10410 
10411   // TODO: it would be nice if "definitely valid" results were cached
10412   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10413   // need to be repeated.
10414 
10415   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10416   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10417     Bases.insert(Base);
10418     return true;
10419   };
10420 
10421   // Collect all bases. Return false if we find a dependent base.
10422   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10423     return false;
10424 
10425   // Returns true if the base is dependent or is one of the accumulated base
10426   // classes.
10427   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10428     return !Bases.count(Base);
10429   };
10430 
10431   // Return false if the class has a dependent base or if it or one
10432   // of its bases is present in the base set of the current context.
10433   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10434       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10435     return false;
10436 
10437   Diag(SS.getRange().getBegin(),
10438        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10439     << SS.getScopeRep()
10440     << cast<CXXRecordDecl>(CurContext)
10441     << SS.getRange();
10442 
10443   return true;
10444 }
10445 
10446 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10447                                   MultiTemplateParamsArg TemplateParamLists,
10448                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10449                                   const ParsedAttributesView &AttrList,
10450                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10451   // Skip up to the relevant declaration scope.
10452   while (S->isTemplateParamScope())
10453     S = S->getParent();
10454   assert((S->getFlags() & Scope::DeclScope) &&
10455          "got alias-declaration outside of declaration scope");
10456 
10457   if (Type.isInvalid())
10458     return nullptr;
10459 
10460   bool Invalid = false;
10461   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10462   TypeSourceInfo *TInfo = nullptr;
10463   GetTypeFromParser(Type.get(), &TInfo);
10464 
10465   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10466     return nullptr;
10467 
10468   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10469                                       UPPC_DeclarationType)) {
10470     Invalid = true;
10471     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10472                                              TInfo->getTypeLoc().getBeginLoc());
10473   }
10474 
10475   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10476                         TemplateParamLists.size()
10477                             ? forRedeclarationInCurContext()
10478                             : ForVisibleRedeclaration);
10479   LookupName(Previous, S);
10480 
10481   // Warn about shadowing the name of a template parameter.
10482   if (Previous.isSingleResult() &&
10483       Previous.getFoundDecl()->isTemplateParameter()) {
10484     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10485     Previous.clear();
10486   }
10487 
10488   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10489          "name in alias declaration must be an identifier");
10490   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10491                                                Name.StartLocation,
10492                                                Name.Identifier, TInfo);
10493 
10494   NewTD->setAccess(AS);
10495 
10496   if (Invalid)
10497     NewTD->setInvalidDecl();
10498 
10499   ProcessDeclAttributeList(S, NewTD, AttrList);
10500   AddPragmaAttributes(S, NewTD);
10501 
10502   CheckTypedefForVariablyModifiedType(S, NewTD);
10503   Invalid |= NewTD->isInvalidDecl();
10504 
10505   bool Redeclaration = false;
10506 
10507   NamedDecl *NewND;
10508   if (TemplateParamLists.size()) {
10509     TypeAliasTemplateDecl *OldDecl = nullptr;
10510     TemplateParameterList *OldTemplateParams = nullptr;
10511 
10512     if (TemplateParamLists.size() != 1) {
10513       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10514         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10515          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10516     }
10517     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10518 
10519     // Check that we can declare a template here.
10520     if (CheckTemplateDeclScope(S, TemplateParams))
10521       return nullptr;
10522 
10523     // Only consider previous declarations in the same scope.
10524     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10525                          /*ExplicitInstantiationOrSpecialization*/false);
10526     if (!Previous.empty()) {
10527       Redeclaration = true;
10528 
10529       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10530       if (!OldDecl && !Invalid) {
10531         Diag(UsingLoc, diag::err_redefinition_different_kind)
10532           << Name.Identifier;
10533 
10534         NamedDecl *OldD = Previous.getRepresentativeDecl();
10535         if (OldD->getLocation().isValid())
10536           Diag(OldD->getLocation(), diag::note_previous_definition);
10537 
10538         Invalid = true;
10539       }
10540 
10541       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10542         if (TemplateParameterListsAreEqual(TemplateParams,
10543                                            OldDecl->getTemplateParameters(),
10544                                            /*Complain=*/true,
10545                                            TPL_TemplateMatch))
10546           OldTemplateParams =
10547               OldDecl->getMostRecentDecl()->getTemplateParameters();
10548         else
10549           Invalid = true;
10550 
10551         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10552         if (!Invalid &&
10553             !Context.hasSameType(OldTD->getUnderlyingType(),
10554                                  NewTD->getUnderlyingType())) {
10555           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10556           // but we can't reasonably accept it.
10557           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10558             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10559           if (OldTD->getLocation().isValid())
10560             Diag(OldTD->getLocation(), diag::note_previous_definition);
10561           Invalid = true;
10562         }
10563       }
10564     }
10565 
10566     // Merge any previous default template arguments into our parameters,
10567     // and check the parameter list.
10568     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10569                                    TPC_TypeAliasTemplate))
10570       return nullptr;
10571 
10572     TypeAliasTemplateDecl *NewDecl =
10573       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10574                                     Name.Identifier, TemplateParams,
10575                                     NewTD);
10576     NewTD->setDescribedAliasTemplate(NewDecl);
10577 
10578     NewDecl->setAccess(AS);
10579 
10580     if (Invalid)
10581       NewDecl->setInvalidDecl();
10582     else if (OldDecl) {
10583       NewDecl->setPreviousDecl(OldDecl);
10584       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10585     }
10586 
10587     NewND = NewDecl;
10588   } else {
10589     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10590       setTagNameForLinkagePurposes(TD, NewTD);
10591       handleTagNumbering(TD, S);
10592     }
10593     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10594     NewND = NewTD;
10595   }
10596 
10597   PushOnScopeChains(NewND, S);
10598   ActOnDocumentableDecl(NewND);
10599   return NewND;
10600 }
10601 
10602 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10603                                    SourceLocation AliasLoc,
10604                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10605                                    SourceLocation IdentLoc,
10606                                    IdentifierInfo *Ident) {
10607 
10608   // Lookup the namespace name.
10609   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10610   LookupParsedName(R, S, &SS);
10611 
10612   if (R.isAmbiguous())
10613     return nullptr;
10614 
10615   if (R.empty()) {
10616     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10617       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10618       return nullptr;
10619     }
10620   }
10621   assert(!R.isAmbiguous() && !R.empty());
10622   NamedDecl *ND = R.getRepresentativeDecl();
10623 
10624   // Check if we have a previous declaration with the same name.
10625   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10626                      ForVisibleRedeclaration);
10627   LookupName(PrevR, S);
10628 
10629   // Check we're not shadowing a template parameter.
10630   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10631     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10632     PrevR.clear();
10633   }
10634 
10635   // Filter out any other lookup result from an enclosing scope.
10636   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10637                        /*AllowInlineNamespace*/false);
10638 
10639   // Find the previous declaration and check that we can redeclare it.
10640   NamespaceAliasDecl *Prev = nullptr;
10641   if (PrevR.isSingleResult()) {
10642     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10643     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10644       // We already have an alias with the same name that points to the same
10645       // namespace; check that it matches.
10646       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10647         Prev = AD;
10648       } else if (isVisible(PrevDecl)) {
10649         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10650           << Alias;
10651         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10652           << AD->getNamespace();
10653         return nullptr;
10654       }
10655     } else if (isVisible(PrevDecl)) {
10656       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10657                             ? diag::err_redefinition
10658                             : diag::err_redefinition_different_kind;
10659       Diag(AliasLoc, DiagID) << Alias;
10660       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10661       return nullptr;
10662     }
10663   }
10664 
10665   // The use of a nested name specifier may trigger deprecation warnings.
10666   DiagnoseUseOfDecl(ND, IdentLoc);
10667 
10668   NamespaceAliasDecl *AliasDecl =
10669     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10670                                Alias, SS.getWithLocInContext(Context),
10671                                IdentLoc, ND);
10672   if (Prev)
10673     AliasDecl->setPreviousDecl(Prev);
10674 
10675   PushOnScopeChains(AliasDecl, S);
10676   return AliasDecl;
10677 }
10678 
10679 namespace {
10680 struct SpecialMemberExceptionSpecInfo
10681     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10682   SourceLocation Loc;
10683   Sema::ImplicitExceptionSpecification ExceptSpec;
10684 
10685   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10686                                  Sema::CXXSpecialMember CSM,
10687                                  Sema::InheritedConstructorInfo *ICI,
10688                                  SourceLocation Loc)
10689       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10690 
10691   bool visitBase(CXXBaseSpecifier *Base);
10692   bool visitField(FieldDecl *FD);
10693 
10694   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10695                            unsigned Quals);
10696 
10697   void visitSubobjectCall(Subobject Subobj,
10698                           Sema::SpecialMemberOverloadResult SMOR);
10699 };
10700 }
10701 
10702 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10703   auto *RT = Base->getType()->getAs<RecordType>();
10704   if (!RT)
10705     return false;
10706 
10707   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10708   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10709   if (auto *BaseCtor = SMOR.getMethod()) {
10710     visitSubobjectCall(Base, BaseCtor);
10711     return false;
10712   }
10713 
10714   visitClassSubobject(BaseClass, Base, 0);
10715   return false;
10716 }
10717 
10718 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10719   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10720     Expr *E = FD->getInClassInitializer();
10721     if (!E)
10722       // FIXME: It's a little wasteful to build and throw away a
10723       // CXXDefaultInitExpr here.
10724       // FIXME: We should have a single context note pointing at Loc, and
10725       // this location should be MD->getLocation() instead, since that's
10726       // the location where we actually use the default init expression.
10727       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10728     if (E)
10729       ExceptSpec.CalledExpr(E);
10730   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10731                             ->getAs<RecordType>()) {
10732     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10733                         FD->getType().getCVRQualifiers());
10734   }
10735   return false;
10736 }
10737 
10738 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10739                                                          Subobject Subobj,
10740                                                          unsigned Quals) {
10741   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10742   bool IsMutable = Field && Field->isMutable();
10743   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10744 }
10745 
10746 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10747     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10748   // Note, if lookup fails, it doesn't matter what exception specification we
10749   // choose because the special member will be deleted.
10750   if (CXXMethodDecl *MD = SMOR.getMethod())
10751     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10752 }
10753 
10754 namespace {
10755 /// RAII object to register a special member as being currently declared.
10756 struct ComputingExceptionSpec {
10757   Sema &S;
10758 
10759   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10760       : S(S) {
10761     Sema::CodeSynthesisContext Ctx;
10762     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10763     Ctx.PointOfInstantiation = Loc;
10764     Ctx.Entity = MD;
10765     S.pushCodeSynthesisContext(Ctx);
10766   }
10767   ~ComputingExceptionSpec() {
10768     S.popCodeSynthesisContext();
10769   }
10770 };
10771 }
10772 
10773 static Sema::ImplicitExceptionSpecification
10774 ComputeDefaultedSpecialMemberExceptionSpec(
10775     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10776     Sema::InheritedConstructorInfo *ICI) {
10777   ComputingExceptionSpec CES(S, MD, Loc);
10778 
10779   CXXRecordDecl *ClassDecl = MD->getParent();
10780 
10781   // C++ [except.spec]p14:
10782   //   An implicitly declared special member function (Clause 12) shall have an
10783   //   exception-specification. [...]
10784   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10785   if (ClassDecl->isInvalidDecl())
10786     return Info.ExceptSpec;
10787 
10788   // FIXME: If this diagnostic fires, we're probably missing a check for
10789   // attempting to resolve an exception specification before it's known
10790   // at a higher level.
10791   if (S.RequireCompleteType(MD->getLocation(),
10792                             S.Context.getRecordType(ClassDecl),
10793                             diag::err_exception_spec_incomplete_type))
10794     return Info.ExceptSpec;
10795 
10796   // C++1z [except.spec]p7:
10797   //   [Look for exceptions thrown by] a constructor selected [...] to
10798   //   initialize a potentially constructed subobject,
10799   // C++1z [except.spec]p8:
10800   //   The exception specification for an implicitly-declared destructor, or a
10801   //   destructor without a noexcept-specifier, is potentially-throwing if and
10802   //   only if any of the destructors for any of its potentially constructed
10803   //   subojects is potentially throwing.
10804   // FIXME: We respect the first rule but ignore the "potentially constructed"
10805   // in the second rule to resolve a core issue (no number yet) that would have
10806   // us reject:
10807   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10808   //   struct B : A {};
10809   //   struct C : B { void f(); };
10810   // ... due to giving B::~B() a non-throwing exception specification.
10811   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10812                                 : Info.VisitAllBases);
10813 
10814   return Info.ExceptSpec;
10815 }
10816 
10817 namespace {
10818 /// RAII object to register a special member as being currently declared.
10819 struct DeclaringSpecialMember {
10820   Sema &S;
10821   Sema::SpecialMemberDecl D;
10822   Sema::ContextRAII SavedContext;
10823   bool WasAlreadyBeingDeclared;
10824 
10825   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10826       : S(S), D(RD, CSM), SavedContext(S, RD) {
10827     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10828     if (WasAlreadyBeingDeclared)
10829       // This almost never happens, but if it does, ensure that our cache
10830       // doesn't contain a stale result.
10831       S.SpecialMemberCache.clear();
10832     else {
10833       // Register a note to be produced if we encounter an error while
10834       // declaring the special member.
10835       Sema::CodeSynthesisContext Ctx;
10836       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10837       // FIXME: We don't have a location to use here. Using the class's
10838       // location maintains the fiction that we declare all special members
10839       // with the class, but (1) it's not clear that lying about that helps our
10840       // users understand what's going on, and (2) there may be outer contexts
10841       // on the stack (some of which are relevant) and printing them exposes
10842       // our lies.
10843       Ctx.PointOfInstantiation = RD->getLocation();
10844       Ctx.Entity = RD;
10845       Ctx.SpecialMember = CSM;
10846       S.pushCodeSynthesisContext(Ctx);
10847     }
10848   }
10849   ~DeclaringSpecialMember() {
10850     if (!WasAlreadyBeingDeclared) {
10851       S.SpecialMembersBeingDeclared.erase(D);
10852       S.popCodeSynthesisContext();
10853     }
10854   }
10855 
10856   /// Are we already trying to declare this special member?
10857   bool isAlreadyBeingDeclared() const {
10858     return WasAlreadyBeingDeclared;
10859   }
10860 };
10861 }
10862 
10863 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10864   // Look up any existing declarations, but don't trigger declaration of all
10865   // implicit special members with this name.
10866   DeclarationName Name = FD->getDeclName();
10867   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10868                  ForExternalRedeclaration);
10869   for (auto *D : FD->getParent()->lookup(Name))
10870     if (auto *Acceptable = R.getAcceptableDecl(D))
10871       R.addDecl(Acceptable);
10872   R.resolveKind();
10873   R.suppressDiagnostics();
10874 
10875   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10876 }
10877 
10878 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10879                                                      CXXRecordDecl *ClassDecl) {
10880   // C++ [class.ctor]p5:
10881   //   A default constructor for a class X is a constructor of class X
10882   //   that can be called without an argument. If there is no
10883   //   user-declared constructor for class X, a default constructor is
10884   //   implicitly declared. An implicitly-declared default constructor
10885   //   is an inline public member of its class.
10886   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10887          "Should not build implicit default constructor!");
10888 
10889   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10890   if (DSM.isAlreadyBeingDeclared())
10891     return nullptr;
10892 
10893   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10894                                                      CXXDefaultConstructor,
10895                                                      false);
10896 
10897   // Create the actual constructor declaration.
10898   CanQualType ClassType
10899     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10900   SourceLocation ClassLoc = ClassDecl->getLocation();
10901   DeclarationName Name
10902     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10903   DeclarationNameInfo NameInfo(Name, ClassLoc);
10904   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10905       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10906       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10907       /*isImplicitlyDeclared=*/true, Constexpr);
10908   DefaultCon->setAccess(AS_public);
10909   DefaultCon->setDefaulted();
10910 
10911   if (getLangOpts().CUDA) {
10912     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10913                                             DefaultCon,
10914                                             /* ConstRHS */ false,
10915                                             /* Diagnose */ false);
10916   }
10917 
10918   // Build an exception specification pointing back at this constructor.
10919   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10920   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10921 
10922   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10923   // constructors is easy to compute.
10924   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10925 
10926   // Note that we have declared this constructor.
10927   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10928 
10929   Scope *S = getScopeForContext(ClassDecl);
10930   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10931 
10932   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10933     SetDeclDeleted(DefaultCon, ClassLoc);
10934 
10935   if (S)
10936     PushOnScopeChains(DefaultCon, S, false);
10937   ClassDecl->addDecl(DefaultCon);
10938 
10939   return DefaultCon;
10940 }
10941 
10942 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10943                                             CXXConstructorDecl *Constructor) {
10944   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10945           !Constructor->doesThisDeclarationHaveABody() &&
10946           !Constructor->isDeleted()) &&
10947     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10948   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10949     return;
10950 
10951   CXXRecordDecl *ClassDecl = Constructor->getParent();
10952   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10953 
10954   SynthesizedFunctionScope Scope(*this, Constructor);
10955 
10956   // The exception specification is needed because we are defining the
10957   // function.
10958   ResolveExceptionSpec(CurrentLocation,
10959                        Constructor->getType()->castAs<FunctionProtoType>());
10960   MarkVTableUsed(CurrentLocation, ClassDecl);
10961 
10962   // Add a context note for diagnostics produced after this point.
10963   Scope.addContextNote(CurrentLocation);
10964 
10965   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10966     Constructor->setInvalidDecl();
10967     return;
10968   }
10969 
10970   SourceLocation Loc = Constructor->getEndLoc().isValid()
10971                            ? Constructor->getEndLoc()
10972                            : Constructor->getLocation();
10973   Constructor->setBody(new (Context) CompoundStmt(Loc));
10974   Constructor->markUsed(Context);
10975 
10976   if (ASTMutationListener *L = getASTMutationListener()) {
10977     L->CompletedImplicitDefinition(Constructor);
10978   }
10979 
10980   DiagnoseUninitializedFields(*this, Constructor);
10981 }
10982 
10983 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10984   // Perform any delayed checks on exception specifications.
10985   CheckDelayedMemberExceptionSpecs();
10986 }
10987 
10988 /// Find or create the fake constructor we synthesize to model constructing an
10989 /// object of a derived class via a constructor of a base class.
10990 CXXConstructorDecl *
10991 Sema::findInheritingConstructor(SourceLocation Loc,
10992                                 CXXConstructorDecl *BaseCtor,
10993                                 ConstructorUsingShadowDecl *Shadow) {
10994   CXXRecordDecl *Derived = Shadow->getParent();
10995   SourceLocation UsingLoc = Shadow->getLocation();
10996 
10997   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10998   // For now we use the name of the base class constructor as a member of the
10999   // derived class to indicate a (fake) inherited constructor name.
11000   DeclarationName Name = BaseCtor->getDeclName();
11001 
11002   // Check to see if we already have a fake constructor for this inherited
11003   // constructor call.
11004   for (NamedDecl *Ctor : Derived->lookup(Name))
11005     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11006                                ->getInheritedConstructor()
11007                                .getConstructor(),
11008                            BaseCtor))
11009       return cast<CXXConstructorDecl>(Ctor);
11010 
11011   DeclarationNameInfo NameInfo(Name, UsingLoc);
11012   TypeSourceInfo *TInfo =
11013       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11014   FunctionProtoTypeLoc ProtoLoc =
11015       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11016 
11017   // Check the inherited constructor is valid and find the list of base classes
11018   // from which it was inherited.
11019   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11020 
11021   bool Constexpr =
11022       BaseCtor->isConstexpr() &&
11023       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11024                                         false, BaseCtor, &ICI);
11025 
11026   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11027       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11028       BaseCtor->isExplicit(), /*Inline=*/true,
11029       /*ImplicitlyDeclared=*/true, Constexpr,
11030       InheritedConstructor(Shadow, BaseCtor));
11031   if (Shadow->isInvalidDecl())
11032     DerivedCtor->setInvalidDecl();
11033 
11034   // Build an unevaluated exception specification for this fake constructor.
11035   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11036   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11037   EPI.ExceptionSpec.Type = EST_Unevaluated;
11038   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11039   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11040                                                FPT->getParamTypes(), EPI));
11041 
11042   // Build the parameter declarations.
11043   SmallVector<ParmVarDecl *, 16> ParamDecls;
11044   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11045     TypeSourceInfo *TInfo =
11046         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11047     ParmVarDecl *PD = ParmVarDecl::Create(
11048         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11049         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11050     PD->setScopeInfo(0, I);
11051     PD->setImplicit();
11052     // Ensure attributes are propagated onto parameters (this matters for
11053     // format, pass_object_size, ...).
11054     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11055     ParamDecls.push_back(PD);
11056     ProtoLoc.setParam(I, PD);
11057   }
11058 
11059   // Set up the new constructor.
11060   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11061   DerivedCtor->setAccess(BaseCtor->getAccess());
11062   DerivedCtor->setParams(ParamDecls);
11063   Derived->addDecl(DerivedCtor);
11064 
11065   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11066     SetDeclDeleted(DerivedCtor, UsingLoc);
11067 
11068   return DerivedCtor;
11069 }
11070 
11071 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11072   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11073                                Ctor->getInheritedConstructor().getShadowDecl());
11074   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11075                             /*Diagnose*/true);
11076 }
11077 
11078 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11079                                        CXXConstructorDecl *Constructor) {
11080   CXXRecordDecl *ClassDecl = Constructor->getParent();
11081   assert(Constructor->getInheritedConstructor() &&
11082          !Constructor->doesThisDeclarationHaveABody() &&
11083          !Constructor->isDeleted());
11084   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11085     return;
11086 
11087   // Initializations are performed "as if by a defaulted default constructor",
11088   // so enter the appropriate scope.
11089   SynthesizedFunctionScope Scope(*this, Constructor);
11090 
11091   // The exception specification is needed because we are defining the
11092   // function.
11093   ResolveExceptionSpec(CurrentLocation,
11094                        Constructor->getType()->castAs<FunctionProtoType>());
11095   MarkVTableUsed(CurrentLocation, ClassDecl);
11096 
11097   // Add a context note for diagnostics produced after this point.
11098   Scope.addContextNote(CurrentLocation);
11099 
11100   ConstructorUsingShadowDecl *Shadow =
11101       Constructor->getInheritedConstructor().getShadowDecl();
11102   CXXConstructorDecl *InheritedCtor =
11103       Constructor->getInheritedConstructor().getConstructor();
11104 
11105   // [class.inhctor.init]p1:
11106   //   initialization proceeds as if a defaulted default constructor is used to
11107   //   initialize the D object and each base class subobject from which the
11108   //   constructor was inherited
11109 
11110   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11111   CXXRecordDecl *RD = Shadow->getParent();
11112   SourceLocation InitLoc = Shadow->getLocation();
11113 
11114   // Build explicit initializers for all base classes from which the
11115   // constructor was inherited.
11116   SmallVector<CXXCtorInitializer*, 8> Inits;
11117   for (bool VBase : {false, true}) {
11118     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11119       if (B.isVirtual() != VBase)
11120         continue;
11121 
11122       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11123       if (!BaseRD)
11124         continue;
11125 
11126       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11127       if (!BaseCtor.first)
11128         continue;
11129 
11130       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11131       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11132           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11133 
11134       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11135       Inits.push_back(new (Context) CXXCtorInitializer(
11136           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11137           SourceLocation()));
11138     }
11139   }
11140 
11141   // We now proceed as if for a defaulted default constructor, with the relevant
11142   // initializers replaced.
11143 
11144   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11145     Constructor->setInvalidDecl();
11146     return;
11147   }
11148 
11149   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11150   Constructor->markUsed(Context);
11151 
11152   if (ASTMutationListener *L = getASTMutationListener()) {
11153     L->CompletedImplicitDefinition(Constructor);
11154   }
11155 
11156   DiagnoseUninitializedFields(*this, Constructor);
11157 }
11158 
11159 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11160   // C++ [class.dtor]p2:
11161   //   If a class has no user-declared destructor, a destructor is
11162   //   declared implicitly. An implicitly-declared destructor is an
11163   //   inline public member of its class.
11164   assert(ClassDecl->needsImplicitDestructor());
11165 
11166   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11167   if (DSM.isAlreadyBeingDeclared())
11168     return nullptr;
11169 
11170   // Create the actual destructor declaration.
11171   CanQualType ClassType
11172     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11173   SourceLocation ClassLoc = ClassDecl->getLocation();
11174   DeclarationName Name
11175     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11176   DeclarationNameInfo NameInfo(Name, ClassLoc);
11177   CXXDestructorDecl *Destructor
11178       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11179                                   QualType(), nullptr, /*isInline=*/true,
11180                                   /*isImplicitlyDeclared=*/true);
11181   Destructor->setAccess(AS_public);
11182   Destructor->setDefaulted();
11183 
11184   if (getLangOpts().CUDA) {
11185     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11186                                             Destructor,
11187                                             /* ConstRHS */ false,
11188                                             /* Diagnose */ false);
11189   }
11190 
11191   // Build an exception specification pointing back at this destructor.
11192   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11193   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11194 
11195   // We don't need to use SpecialMemberIsTrivial here; triviality for
11196   // destructors is easy to compute.
11197   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11198   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11199                                 ClassDecl->hasTrivialDestructorForCall());
11200 
11201   // Note that we have declared this destructor.
11202   ++ASTContext::NumImplicitDestructorsDeclared;
11203 
11204   Scope *S = getScopeForContext(ClassDecl);
11205   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11206 
11207   // We can't check whether an implicit destructor is deleted before we complete
11208   // the definition of the class, because its validity depends on the alignment
11209   // of the class. We'll check this from ActOnFields once the class is complete.
11210   if (ClassDecl->isCompleteDefinition() &&
11211       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11212     SetDeclDeleted(Destructor, ClassLoc);
11213 
11214   // Introduce this destructor into its scope.
11215   if (S)
11216     PushOnScopeChains(Destructor, S, false);
11217   ClassDecl->addDecl(Destructor);
11218 
11219   return Destructor;
11220 }
11221 
11222 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11223                                     CXXDestructorDecl *Destructor) {
11224   assert((Destructor->isDefaulted() &&
11225           !Destructor->doesThisDeclarationHaveABody() &&
11226           !Destructor->isDeleted()) &&
11227          "DefineImplicitDestructor - call it for implicit default dtor");
11228   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11229     return;
11230 
11231   CXXRecordDecl *ClassDecl = Destructor->getParent();
11232   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11233 
11234   SynthesizedFunctionScope Scope(*this, Destructor);
11235 
11236   // The exception specification is needed because we are defining the
11237   // function.
11238   ResolveExceptionSpec(CurrentLocation,
11239                        Destructor->getType()->castAs<FunctionProtoType>());
11240   MarkVTableUsed(CurrentLocation, ClassDecl);
11241 
11242   // Add a context note for diagnostics produced after this point.
11243   Scope.addContextNote(CurrentLocation);
11244 
11245   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11246                                          Destructor->getParent());
11247 
11248   if (CheckDestructor(Destructor)) {
11249     Destructor->setInvalidDecl();
11250     return;
11251   }
11252 
11253   SourceLocation Loc = Destructor->getEndLoc().isValid()
11254                            ? Destructor->getEndLoc()
11255                            : Destructor->getLocation();
11256   Destructor->setBody(new (Context) CompoundStmt(Loc));
11257   Destructor->markUsed(Context);
11258 
11259   if (ASTMutationListener *L = getASTMutationListener()) {
11260     L->CompletedImplicitDefinition(Destructor);
11261   }
11262 }
11263 
11264 /// Perform any semantic analysis which needs to be delayed until all
11265 /// pending class member declarations have been parsed.
11266 void Sema::ActOnFinishCXXMemberDecls() {
11267   // If the context is an invalid C++ class, just suppress these checks.
11268   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11269     if (Record->isInvalidDecl()) {
11270       DelayedOverridingExceptionSpecChecks.clear();
11271       DelayedEquivalentExceptionSpecChecks.clear();
11272       DelayedDefaultedMemberExceptionSpecs.clear();
11273       return;
11274     }
11275     checkForMultipleExportedDefaultConstructors(*this, Record);
11276   }
11277 }
11278 
11279 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11280   referenceDLLExportedClassMethods();
11281 }
11282 
11283 void Sema::referenceDLLExportedClassMethods() {
11284   if (!DelayedDllExportClasses.empty()) {
11285     // Calling ReferenceDllExportedMembers might cause the current function to
11286     // be called again, so use a local copy of DelayedDllExportClasses.
11287     SmallVector<CXXRecordDecl *, 4> WorkList;
11288     std::swap(DelayedDllExportClasses, WorkList);
11289     for (CXXRecordDecl *Class : WorkList)
11290       ReferenceDllExportedMembers(*this, Class);
11291   }
11292 }
11293 
11294 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11295   assert(getLangOpts().CPlusPlus11 &&
11296          "adjusting dtor exception specs was introduced in c++11");
11297 
11298   if (Destructor->isDependentContext())
11299     return;
11300 
11301   // C++11 [class.dtor]p3:
11302   //   A declaration of a destructor that does not have an exception-
11303   //   specification is implicitly considered to have the same exception-
11304   //   specification as an implicit declaration.
11305   const FunctionProtoType *DtorType = Destructor->getType()->
11306                                         getAs<FunctionProtoType>();
11307   if (DtorType->hasExceptionSpec())
11308     return;
11309 
11310   // Replace the destructor's type, building off the existing one. Fortunately,
11311   // the only thing of interest in the destructor type is its extended info.
11312   // The return and arguments are fixed.
11313   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11314   EPI.ExceptionSpec.Type = EST_Unevaluated;
11315   EPI.ExceptionSpec.SourceDecl = Destructor;
11316   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11317 
11318   // FIXME: If the destructor has a body that could throw, and the newly created
11319   // spec doesn't allow exceptions, we should emit a warning, because this
11320   // change in behavior can break conforming C++03 programs at runtime.
11321   // However, we don't have a body or an exception specification yet, so it
11322   // needs to be done somewhere else.
11323 }
11324 
11325 namespace {
11326 /// An abstract base class for all helper classes used in building the
11327 //  copy/move operators. These classes serve as factory functions and help us
11328 //  avoid using the same Expr* in the AST twice.
11329 class ExprBuilder {
11330   ExprBuilder(const ExprBuilder&) = delete;
11331   ExprBuilder &operator=(const ExprBuilder&) = delete;
11332 
11333 protected:
11334   static Expr *assertNotNull(Expr *E) {
11335     assert(E && "Expression construction must not fail.");
11336     return E;
11337   }
11338 
11339 public:
11340   ExprBuilder() {}
11341   virtual ~ExprBuilder() {}
11342 
11343   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11344 };
11345 
11346 class RefBuilder: public ExprBuilder {
11347   VarDecl *Var;
11348   QualType VarType;
11349 
11350 public:
11351   Expr *build(Sema &S, SourceLocation Loc) const override {
11352     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11353   }
11354 
11355   RefBuilder(VarDecl *Var, QualType VarType)
11356       : Var(Var), VarType(VarType) {}
11357 };
11358 
11359 class ThisBuilder: public ExprBuilder {
11360 public:
11361   Expr *build(Sema &S, SourceLocation Loc) const override {
11362     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11363   }
11364 };
11365 
11366 class CastBuilder: public ExprBuilder {
11367   const ExprBuilder &Builder;
11368   QualType Type;
11369   ExprValueKind Kind;
11370   const CXXCastPath &Path;
11371 
11372 public:
11373   Expr *build(Sema &S, SourceLocation Loc) const override {
11374     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11375                                              CK_UncheckedDerivedToBase, Kind,
11376                                              &Path).get());
11377   }
11378 
11379   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11380               const CXXCastPath &Path)
11381       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11382 };
11383 
11384 class DerefBuilder: public ExprBuilder {
11385   const ExprBuilder &Builder;
11386 
11387 public:
11388   Expr *build(Sema &S, SourceLocation Loc) const override {
11389     return assertNotNull(
11390         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11391   }
11392 
11393   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11394 };
11395 
11396 class MemberBuilder: public ExprBuilder {
11397   const ExprBuilder &Builder;
11398   QualType Type;
11399   CXXScopeSpec SS;
11400   bool IsArrow;
11401   LookupResult &MemberLookup;
11402 
11403 public:
11404   Expr *build(Sema &S, SourceLocation Loc) const override {
11405     return assertNotNull(S.BuildMemberReferenceExpr(
11406         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11407         nullptr, MemberLookup, nullptr, nullptr).get());
11408   }
11409 
11410   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11411                 LookupResult &MemberLookup)
11412       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11413         MemberLookup(MemberLookup) {}
11414 };
11415 
11416 class MoveCastBuilder: public ExprBuilder {
11417   const ExprBuilder &Builder;
11418 
11419 public:
11420   Expr *build(Sema &S, SourceLocation Loc) const override {
11421     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11422   }
11423 
11424   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11425 };
11426 
11427 class LvalueConvBuilder: public ExprBuilder {
11428   const ExprBuilder &Builder;
11429 
11430 public:
11431   Expr *build(Sema &S, SourceLocation Loc) const override {
11432     return assertNotNull(
11433         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11434   }
11435 
11436   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11437 };
11438 
11439 class SubscriptBuilder: public ExprBuilder {
11440   const ExprBuilder &Base;
11441   const ExprBuilder &Index;
11442 
11443 public:
11444   Expr *build(Sema &S, SourceLocation Loc) const override {
11445     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11446         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11447   }
11448 
11449   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11450       : Base(Base), Index(Index) {}
11451 };
11452 
11453 } // end anonymous namespace
11454 
11455 /// When generating a defaulted copy or move assignment operator, if a field
11456 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11457 /// do so. This optimization only applies for arrays of scalars, and for arrays
11458 /// of class type where the selected copy/move-assignment operator is trivial.
11459 static StmtResult
11460 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11461                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11462   // Compute the size of the memory buffer to be copied.
11463   QualType SizeType = S.Context.getSizeType();
11464   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11465                    S.Context.getTypeSizeInChars(T).getQuantity());
11466 
11467   // Take the address of the field references for "from" and "to". We
11468   // directly construct UnaryOperators here because semantic analysis
11469   // does not permit us to take the address of an xvalue.
11470   Expr *From = FromB.build(S, Loc);
11471   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11472                          S.Context.getPointerType(From->getType()),
11473                          VK_RValue, OK_Ordinary, Loc, false);
11474   Expr *To = ToB.build(S, Loc);
11475   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11476                        S.Context.getPointerType(To->getType()),
11477                        VK_RValue, OK_Ordinary, Loc, false);
11478 
11479   const Type *E = T->getBaseElementTypeUnsafe();
11480   bool NeedsCollectableMemCpy =
11481     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11482 
11483   // Create a reference to the __builtin_objc_memmove_collectable function
11484   StringRef MemCpyName = NeedsCollectableMemCpy ?
11485     "__builtin_objc_memmove_collectable" :
11486     "__builtin_memcpy";
11487   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11488                  Sema::LookupOrdinaryName);
11489   S.LookupName(R, S.TUScope, true);
11490 
11491   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11492   if (!MemCpy)
11493     // Something went horribly wrong earlier, and we will have complained
11494     // about it.
11495     return StmtError();
11496 
11497   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11498                                             VK_RValue, Loc, nullptr);
11499   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11500 
11501   Expr *CallArgs[] = {
11502     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11503   };
11504   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11505                                     Loc, CallArgs, Loc);
11506 
11507   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11508   return Call.getAs<Stmt>();
11509 }
11510 
11511 /// Builds a statement that copies/moves the given entity from \p From to
11512 /// \c To.
11513 ///
11514 /// This routine is used to copy/move the members of a class with an
11515 /// implicitly-declared copy/move assignment operator. When the entities being
11516 /// copied are arrays, this routine builds for loops to copy them.
11517 ///
11518 /// \param S The Sema object used for type-checking.
11519 ///
11520 /// \param Loc The location where the implicit copy/move is being generated.
11521 ///
11522 /// \param T The type of the expressions being copied/moved. Both expressions
11523 /// must have this type.
11524 ///
11525 /// \param To The expression we are copying/moving to.
11526 ///
11527 /// \param From The expression we are copying/moving from.
11528 ///
11529 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11530 /// Otherwise, it's a non-static member subobject.
11531 ///
11532 /// \param Copying Whether we're copying or moving.
11533 ///
11534 /// \param Depth Internal parameter recording the depth of the recursion.
11535 ///
11536 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11537 /// if a memcpy should be used instead.
11538 static StmtResult
11539 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11540                                  const ExprBuilder &To, const ExprBuilder &From,
11541                                  bool CopyingBaseSubobject, bool Copying,
11542                                  unsigned Depth = 0) {
11543   // C++11 [class.copy]p28:
11544   //   Each subobject is assigned in the manner appropriate to its type:
11545   //
11546   //     - if the subobject is of class type, as if by a call to operator= with
11547   //       the subobject as the object expression and the corresponding
11548   //       subobject of x as a single function argument (as if by explicit
11549   //       qualification; that is, ignoring any possible virtual overriding
11550   //       functions in more derived classes);
11551   //
11552   // C++03 [class.copy]p13:
11553   //     - if the subobject is of class type, the copy assignment operator for
11554   //       the class is used (as if by explicit qualification; that is,
11555   //       ignoring any possible virtual overriding functions in more derived
11556   //       classes);
11557   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11558     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11559 
11560     // Look for operator=.
11561     DeclarationName Name
11562       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11563     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11564     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11565 
11566     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11567     // operator.
11568     if (!S.getLangOpts().CPlusPlus11) {
11569       LookupResult::Filter F = OpLookup.makeFilter();
11570       while (F.hasNext()) {
11571         NamedDecl *D = F.next();
11572         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11573           if (Method->isCopyAssignmentOperator() ||
11574               (!Copying && Method->isMoveAssignmentOperator()))
11575             continue;
11576 
11577         F.erase();
11578       }
11579       F.done();
11580     }
11581 
11582     // Suppress the protected check (C++ [class.protected]) for each of the
11583     // assignment operators we found. This strange dance is required when
11584     // we're assigning via a base classes's copy-assignment operator. To
11585     // ensure that we're getting the right base class subobject (without
11586     // ambiguities), we need to cast "this" to that subobject type; to
11587     // ensure that we don't go through the virtual call mechanism, we need
11588     // to qualify the operator= name with the base class (see below). However,
11589     // this means that if the base class has a protected copy assignment
11590     // operator, the protected member access check will fail. So, we
11591     // rewrite "protected" access to "public" access in this case, since we
11592     // know by construction that we're calling from a derived class.
11593     if (CopyingBaseSubobject) {
11594       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11595            L != LEnd; ++L) {
11596         if (L.getAccess() == AS_protected)
11597           L.setAccess(AS_public);
11598       }
11599     }
11600 
11601     // Create the nested-name-specifier that will be used to qualify the
11602     // reference to operator=; this is required to suppress the virtual
11603     // call mechanism.
11604     CXXScopeSpec SS;
11605     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11606     SS.MakeTrivial(S.Context,
11607                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11608                                                CanonicalT),
11609                    Loc);
11610 
11611     // Create the reference to operator=.
11612     ExprResult OpEqualRef
11613       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11614                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11615                                    /*FirstQualifierInScope=*/nullptr,
11616                                    OpLookup,
11617                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11618                                    /*SuppressQualifierCheck=*/true);
11619     if (OpEqualRef.isInvalid())
11620       return StmtError();
11621 
11622     // Build the call to the assignment operator.
11623 
11624     Expr *FromInst = From.build(S, Loc);
11625     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11626                                                   OpEqualRef.getAs<Expr>(),
11627                                                   Loc, FromInst, Loc);
11628     if (Call.isInvalid())
11629       return StmtError();
11630 
11631     // If we built a call to a trivial 'operator=' while copying an array,
11632     // bail out. We'll replace the whole shebang with a memcpy.
11633     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11634     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11635       return StmtResult((Stmt*)nullptr);
11636 
11637     // Convert to an expression-statement, and clean up any produced
11638     // temporaries.
11639     return S.ActOnExprStmt(Call);
11640   }
11641 
11642   //     - if the subobject is of scalar type, the built-in assignment
11643   //       operator is used.
11644   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11645   if (!ArrayTy) {
11646     ExprResult Assignment = S.CreateBuiltinBinOp(
11647         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11648     if (Assignment.isInvalid())
11649       return StmtError();
11650     return S.ActOnExprStmt(Assignment);
11651   }
11652 
11653   //     - if the subobject is an array, each element is assigned, in the
11654   //       manner appropriate to the element type;
11655 
11656   // Construct a loop over the array bounds, e.g.,
11657   //
11658   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11659   //
11660   // that will copy each of the array elements.
11661   QualType SizeType = S.Context.getSizeType();
11662 
11663   // Create the iteration variable.
11664   IdentifierInfo *IterationVarName = nullptr;
11665   {
11666     SmallString<8> Str;
11667     llvm::raw_svector_ostream OS(Str);
11668     OS << "__i" << Depth;
11669     IterationVarName = &S.Context.Idents.get(OS.str());
11670   }
11671   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11672                                           IterationVarName, SizeType,
11673                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11674                                           SC_None);
11675 
11676   // Initialize the iteration variable to zero.
11677   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11678   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11679 
11680   // Creates a reference to the iteration variable.
11681   RefBuilder IterationVarRef(IterationVar, SizeType);
11682   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11683 
11684   // Create the DeclStmt that holds the iteration variable.
11685   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11686 
11687   // Subscript the "from" and "to" expressions with the iteration variable.
11688   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11689   MoveCastBuilder FromIndexMove(FromIndexCopy);
11690   const ExprBuilder *FromIndex;
11691   if (Copying)
11692     FromIndex = &FromIndexCopy;
11693   else
11694     FromIndex = &FromIndexMove;
11695 
11696   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11697 
11698   // Build the copy/move for an individual element of the array.
11699   StmtResult Copy =
11700     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11701                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11702                                      Copying, Depth + 1);
11703   // Bail out if copying fails or if we determined that we should use memcpy.
11704   if (Copy.isInvalid() || !Copy.get())
11705     return Copy;
11706 
11707   // Create the comparison against the array bound.
11708   llvm::APInt Upper
11709     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11710   Expr *Comparison
11711     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11712                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11713                                      BO_NE, S.Context.BoolTy,
11714                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11715 
11716   // Create the pre-increment of the iteration variable. We can determine
11717   // whether the increment will overflow based on the value of the array
11718   // bound.
11719   Expr *Increment = new (S.Context)
11720       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11721                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11722 
11723   // Construct the loop that copies all elements of this array.
11724   return S.ActOnForStmt(
11725       Loc, Loc, InitStmt,
11726       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11727       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11728 }
11729 
11730 static StmtResult
11731 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11732                       const ExprBuilder &To, const ExprBuilder &From,
11733                       bool CopyingBaseSubobject, bool Copying) {
11734   // Maybe we should use a memcpy?
11735   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11736       T.isTriviallyCopyableType(S.Context))
11737     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11738 
11739   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11740                                                      CopyingBaseSubobject,
11741                                                      Copying, 0));
11742 
11743   // If we ended up picking a trivial assignment operator for an array of a
11744   // non-trivially-copyable class type, just emit a memcpy.
11745   if (!Result.isInvalid() && !Result.get())
11746     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11747 
11748   return Result;
11749 }
11750 
11751 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11752   // Note: The following rules are largely analoguous to the copy
11753   // constructor rules. Note that virtual bases are not taken into account
11754   // for determining the argument type of the operator. Note also that
11755   // operators taking an object instead of a reference are allowed.
11756   assert(ClassDecl->needsImplicitCopyAssignment());
11757 
11758   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11759   if (DSM.isAlreadyBeingDeclared())
11760     return nullptr;
11761 
11762   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11763   QualType RetType = Context.getLValueReferenceType(ArgType);
11764   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11765   if (Const)
11766     ArgType = ArgType.withConst();
11767   ArgType = Context.getLValueReferenceType(ArgType);
11768 
11769   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11770                                                      CXXCopyAssignment,
11771                                                      Const);
11772 
11773   //   An implicitly-declared copy assignment operator is an inline public
11774   //   member of its class.
11775   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11776   SourceLocation ClassLoc = ClassDecl->getLocation();
11777   DeclarationNameInfo NameInfo(Name, ClassLoc);
11778   CXXMethodDecl *CopyAssignment =
11779       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11780                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11781                             /*isInline=*/true, Constexpr, SourceLocation());
11782   CopyAssignment->setAccess(AS_public);
11783   CopyAssignment->setDefaulted();
11784   CopyAssignment->setImplicit();
11785 
11786   if (getLangOpts().CUDA) {
11787     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11788                                             CopyAssignment,
11789                                             /* ConstRHS */ Const,
11790                                             /* Diagnose */ false);
11791   }
11792 
11793   // Build an exception specification pointing back at this member.
11794   FunctionProtoType::ExtProtoInfo EPI =
11795       getImplicitMethodEPI(*this, CopyAssignment);
11796   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11797 
11798   // Add the parameter to the operator.
11799   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11800                                                ClassLoc, ClassLoc,
11801                                                /*Id=*/nullptr, ArgType,
11802                                                /*TInfo=*/nullptr, SC_None,
11803                                                nullptr);
11804   CopyAssignment->setParams(FromParam);
11805 
11806   CopyAssignment->setTrivial(
11807     ClassDecl->needsOverloadResolutionForCopyAssignment()
11808       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11809       : ClassDecl->hasTrivialCopyAssignment());
11810 
11811   // Note that we have added this copy-assignment operator.
11812   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11813 
11814   Scope *S = getScopeForContext(ClassDecl);
11815   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11816 
11817   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11818     SetDeclDeleted(CopyAssignment, ClassLoc);
11819 
11820   if (S)
11821     PushOnScopeChains(CopyAssignment, S, false);
11822   ClassDecl->addDecl(CopyAssignment);
11823 
11824   return CopyAssignment;
11825 }
11826 
11827 /// Diagnose an implicit copy operation for a class which is odr-used, but
11828 /// which is deprecated because the class has a user-declared copy constructor,
11829 /// copy assignment operator, or destructor.
11830 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11831   assert(CopyOp->isImplicit());
11832 
11833   CXXRecordDecl *RD = CopyOp->getParent();
11834   CXXMethodDecl *UserDeclaredOperation = nullptr;
11835 
11836   // In Microsoft mode, assignment operations don't affect constructors and
11837   // vice versa.
11838   if (RD->hasUserDeclaredDestructor()) {
11839     UserDeclaredOperation = RD->getDestructor();
11840   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11841              RD->hasUserDeclaredCopyConstructor() &&
11842              !S.getLangOpts().MSVCCompat) {
11843     // Find any user-declared copy constructor.
11844     for (auto *I : RD->ctors()) {
11845       if (I->isCopyConstructor()) {
11846         UserDeclaredOperation = I;
11847         break;
11848       }
11849     }
11850     assert(UserDeclaredOperation);
11851   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11852              RD->hasUserDeclaredCopyAssignment() &&
11853              !S.getLangOpts().MSVCCompat) {
11854     // Find any user-declared move assignment operator.
11855     for (auto *I : RD->methods()) {
11856       if (I->isCopyAssignmentOperator()) {
11857         UserDeclaredOperation = I;
11858         break;
11859       }
11860     }
11861     assert(UserDeclaredOperation);
11862   }
11863 
11864   if (UserDeclaredOperation) {
11865     S.Diag(UserDeclaredOperation->getLocation(),
11866          diag::warn_deprecated_copy_operation)
11867       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11868       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11869   }
11870 }
11871 
11872 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11873                                         CXXMethodDecl *CopyAssignOperator) {
11874   assert((CopyAssignOperator->isDefaulted() &&
11875           CopyAssignOperator->isOverloadedOperator() &&
11876           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11877           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11878           !CopyAssignOperator->isDeleted()) &&
11879          "DefineImplicitCopyAssignment called for wrong function");
11880   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11881     return;
11882 
11883   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11884   if (ClassDecl->isInvalidDecl()) {
11885     CopyAssignOperator->setInvalidDecl();
11886     return;
11887   }
11888 
11889   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11890 
11891   // The exception specification is needed because we are defining the
11892   // function.
11893   ResolveExceptionSpec(CurrentLocation,
11894                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11895 
11896   // Add a context note for diagnostics produced after this point.
11897   Scope.addContextNote(CurrentLocation);
11898 
11899   // C++11 [class.copy]p18:
11900   //   The [definition of an implicitly declared copy assignment operator] is
11901   //   deprecated if the class has a user-declared copy constructor or a
11902   //   user-declared destructor.
11903   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11904     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11905 
11906   // C++0x [class.copy]p30:
11907   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11908   //   for a non-union class X performs memberwise copy assignment of its
11909   //   subobjects. The direct base classes of X are assigned first, in the
11910   //   order of their declaration in the base-specifier-list, and then the
11911   //   immediate non-static data members of X are assigned, in the order in
11912   //   which they were declared in the class definition.
11913 
11914   // The statements that form the synthesized function body.
11915   SmallVector<Stmt*, 8> Statements;
11916 
11917   // The parameter for the "other" object, which we are copying from.
11918   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11919   Qualifiers OtherQuals = Other->getType().getQualifiers();
11920   QualType OtherRefType = Other->getType();
11921   if (const LValueReferenceType *OtherRef
11922                                 = OtherRefType->getAs<LValueReferenceType>()) {
11923     OtherRefType = OtherRef->getPointeeType();
11924     OtherQuals = OtherRefType.getQualifiers();
11925   }
11926 
11927   // Our location for everything implicitly-generated.
11928   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11929                            ? CopyAssignOperator->getEndLoc()
11930                            : CopyAssignOperator->getLocation();
11931 
11932   // Builds a DeclRefExpr for the "other" object.
11933   RefBuilder OtherRef(Other, OtherRefType);
11934 
11935   // Builds the "this" pointer.
11936   ThisBuilder This;
11937 
11938   // Assign base classes.
11939   bool Invalid = false;
11940   for (auto &Base : ClassDecl->bases()) {
11941     // Form the assignment:
11942     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11943     QualType BaseType = Base.getType().getUnqualifiedType();
11944     if (!BaseType->isRecordType()) {
11945       Invalid = true;
11946       continue;
11947     }
11948 
11949     CXXCastPath BasePath;
11950     BasePath.push_back(&Base);
11951 
11952     // Construct the "from" expression, which is an implicit cast to the
11953     // appropriately-qualified base type.
11954     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11955                      VK_LValue, BasePath);
11956 
11957     // Dereference "this".
11958     DerefBuilder DerefThis(This);
11959     CastBuilder To(DerefThis,
11960                    Context.getCVRQualifiedType(
11961                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11962                    VK_LValue, BasePath);
11963 
11964     // Build the copy.
11965     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11966                                             To, From,
11967                                             /*CopyingBaseSubobject=*/true,
11968                                             /*Copying=*/true);
11969     if (Copy.isInvalid()) {
11970       CopyAssignOperator->setInvalidDecl();
11971       return;
11972     }
11973 
11974     // Success! Record the copy.
11975     Statements.push_back(Copy.getAs<Expr>());
11976   }
11977 
11978   // Assign non-static members.
11979   for (auto *Field : ClassDecl->fields()) {
11980     // FIXME: We should form some kind of AST representation for the implied
11981     // memcpy in a union copy operation.
11982     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11983       continue;
11984 
11985     if (Field->isInvalidDecl()) {
11986       Invalid = true;
11987       continue;
11988     }
11989 
11990     // Check for members of reference type; we can't copy those.
11991     if (Field->getType()->isReferenceType()) {
11992       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11993         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11994       Diag(Field->getLocation(), diag::note_declared_at);
11995       Invalid = true;
11996       continue;
11997     }
11998 
11999     // Check for members of const-qualified, non-class type.
12000     QualType BaseType = Context.getBaseElementType(Field->getType());
12001     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12002       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12003         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12004       Diag(Field->getLocation(), diag::note_declared_at);
12005       Invalid = true;
12006       continue;
12007     }
12008 
12009     // Suppress assigning zero-width bitfields.
12010     if (Field->isZeroLengthBitField(Context))
12011       continue;
12012 
12013     QualType FieldType = Field->getType().getNonReferenceType();
12014     if (FieldType->isIncompleteArrayType()) {
12015       assert(ClassDecl->hasFlexibleArrayMember() &&
12016              "Incomplete array type is not valid");
12017       continue;
12018     }
12019 
12020     // Build references to the field in the object we're copying from and to.
12021     CXXScopeSpec SS; // Intentionally empty
12022     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12023                               LookupMemberName);
12024     MemberLookup.addDecl(Field);
12025     MemberLookup.resolveKind();
12026 
12027     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12028 
12029     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12030 
12031     // Build the copy of this field.
12032     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12033                                             To, From,
12034                                             /*CopyingBaseSubobject=*/false,
12035                                             /*Copying=*/true);
12036     if (Copy.isInvalid()) {
12037       CopyAssignOperator->setInvalidDecl();
12038       return;
12039     }
12040 
12041     // Success! Record the copy.
12042     Statements.push_back(Copy.getAs<Stmt>());
12043   }
12044 
12045   if (!Invalid) {
12046     // Add a "return *this;"
12047     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12048 
12049     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12050     if (Return.isInvalid())
12051       Invalid = true;
12052     else
12053       Statements.push_back(Return.getAs<Stmt>());
12054   }
12055 
12056   if (Invalid) {
12057     CopyAssignOperator->setInvalidDecl();
12058     return;
12059   }
12060 
12061   StmtResult Body;
12062   {
12063     CompoundScopeRAII CompoundScope(*this);
12064     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12065                              /*isStmtExpr=*/false);
12066     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12067   }
12068   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12069   CopyAssignOperator->markUsed(Context);
12070 
12071   if (ASTMutationListener *L = getASTMutationListener()) {
12072     L->CompletedImplicitDefinition(CopyAssignOperator);
12073   }
12074 }
12075 
12076 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12077   assert(ClassDecl->needsImplicitMoveAssignment());
12078 
12079   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12080   if (DSM.isAlreadyBeingDeclared())
12081     return nullptr;
12082 
12083   // Note: The following rules are largely analoguous to the move
12084   // constructor rules.
12085 
12086   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12087   QualType RetType = Context.getLValueReferenceType(ArgType);
12088   ArgType = Context.getRValueReferenceType(ArgType);
12089 
12090   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12091                                                      CXXMoveAssignment,
12092                                                      false);
12093 
12094   //   An implicitly-declared move assignment operator is an inline public
12095   //   member of its class.
12096   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12097   SourceLocation ClassLoc = ClassDecl->getLocation();
12098   DeclarationNameInfo NameInfo(Name, ClassLoc);
12099   CXXMethodDecl *MoveAssignment =
12100       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12101                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12102                             /*isInline=*/true, Constexpr, SourceLocation());
12103   MoveAssignment->setAccess(AS_public);
12104   MoveAssignment->setDefaulted();
12105   MoveAssignment->setImplicit();
12106 
12107   if (getLangOpts().CUDA) {
12108     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12109                                             MoveAssignment,
12110                                             /* ConstRHS */ false,
12111                                             /* Diagnose */ false);
12112   }
12113 
12114   // Build an exception specification pointing back at this member.
12115   FunctionProtoType::ExtProtoInfo EPI =
12116       getImplicitMethodEPI(*this, MoveAssignment);
12117   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12118 
12119   // Add the parameter to the operator.
12120   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12121                                                ClassLoc, ClassLoc,
12122                                                /*Id=*/nullptr, ArgType,
12123                                                /*TInfo=*/nullptr, SC_None,
12124                                                nullptr);
12125   MoveAssignment->setParams(FromParam);
12126 
12127   MoveAssignment->setTrivial(
12128     ClassDecl->needsOverloadResolutionForMoveAssignment()
12129       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12130       : ClassDecl->hasTrivialMoveAssignment());
12131 
12132   // Note that we have added this copy-assignment operator.
12133   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12134 
12135   Scope *S = getScopeForContext(ClassDecl);
12136   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12137 
12138   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12139     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12140     SetDeclDeleted(MoveAssignment, ClassLoc);
12141   }
12142 
12143   if (S)
12144     PushOnScopeChains(MoveAssignment, S, false);
12145   ClassDecl->addDecl(MoveAssignment);
12146 
12147   return MoveAssignment;
12148 }
12149 
12150 /// Check if we're implicitly defining a move assignment operator for a class
12151 /// with virtual bases. Such a move assignment might move-assign the virtual
12152 /// base multiple times.
12153 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12154                                                SourceLocation CurrentLocation) {
12155   assert(!Class->isDependentContext() && "should not define dependent move");
12156 
12157   // Only a virtual base could get implicitly move-assigned multiple times.
12158   // Only a non-trivial move assignment can observe this. We only want to
12159   // diagnose if we implicitly define an assignment operator that assigns
12160   // two base classes, both of which move-assign the same virtual base.
12161   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12162       Class->getNumBases() < 2)
12163     return;
12164 
12165   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12166   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12167   VBaseMap VBases;
12168 
12169   for (auto &BI : Class->bases()) {
12170     Worklist.push_back(&BI);
12171     while (!Worklist.empty()) {
12172       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12173       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12174 
12175       // If the base has no non-trivial move assignment operators,
12176       // we don't care about moves from it.
12177       if (!Base->hasNonTrivialMoveAssignment())
12178         continue;
12179 
12180       // If there's nothing virtual here, skip it.
12181       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12182         continue;
12183 
12184       // If we're not actually going to call a move assignment for this base,
12185       // or the selected move assignment is trivial, skip it.
12186       Sema::SpecialMemberOverloadResult SMOR =
12187         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12188                               /*ConstArg*/false, /*VolatileArg*/false,
12189                               /*RValueThis*/true, /*ConstThis*/false,
12190                               /*VolatileThis*/false);
12191       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12192           !SMOR.getMethod()->isMoveAssignmentOperator())
12193         continue;
12194 
12195       if (BaseSpec->isVirtual()) {
12196         // We're going to move-assign this virtual base, and its move
12197         // assignment operator is not trivial. If this can happen for
12198         // multiple distinct direct bases of Class, diagnose it. (If it
12199         // only happens in one base, we'll diagnose it when synthesizing
12200         // that base class's move assignment operator.)
12201         CXXBaseSpecifier *&Existing =
12202             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12203                 .first->second;
12204         if (Existing && Existing != &BI) {
12205           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12206             << Class << Base;
12207           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12208               << (Base->getCanonicalDecl() ==
12209                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12210               << Base << Existing->getType() << Existing->getSourceRange();
12211           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12212               << (Base->getCanonicalDecl() ==
12213                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12214               << Base << BI.getType() << BaseSpec->getSourceRange();
12215 
12216           // Only diagnose each vbase once.
12217           Existing = nullptr;
12218         }
12219       } else {
12220         // Only walk over bases that have defaulted move assignment operators.
12221         // We assume that any user-provided move assignment operator handles
12222         // the multiple-moves-of-vbase case itself somehow.
12223         if (!SMOR.getMethod()->isDefaulted())
12224           continue;
12225 
12226         // We're going to move the base classes of Base. Add them to the list.
12227         for (auto &BI : Base->bases())
12228           Worklist.push_back(&BI);
12229       }
12230     }
12231   }
12232 }
12233 
12234 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12235                                         CXXMethodDecl *MoveAssignOperator) {
12236   assert((MoveAssignOperator->isDefaulted() &&
12237           MoveAssignOperator->isOverloadedOperator() &&
12238           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12239           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12240           !MoveAssignOperator->isDeleted()) &&
12241          "DefineImplicitMoveAssignment called for wrong function");
12242   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12243     return;
12244 
12245   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12246   if (ClassDecl->isInvalidDecl()) {
12247     MoveAssignOperator->setInvalidDecl();
12248     return;
12249   }
12250 
12251   // C++0x [class.copy]p28:
12252   //   The implicitly-defined or move assignment operator for a non-union class
12253   //   X performs memberwise move assignment of its subobjects. The direct base
12254   //   classes of X are assigned first, in the order of their declaration in the
12255   //   base-specifier-list, and then the immediate non-static data members of X
12256   //   are assigned, in the order in which they were declared in the class
12257   //   definition.
12258 
12259   // Issue a warning if our implicit move assignment operator will move
12260   // from a virtual base more than once.
12261   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12262 
12263   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12264 
12265   // The exception specification is needed because we are defining the
12266   // function.
12267   ResolveExceptionSpec(CurrentLocation,
12268                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12269 
12270   // Add a context note for diagnostics produced after this point.
12271   Scope.addContextNote(CurrentLocation);
12272 
12273   // The statements that form the synthesized function body.
12274   SmallVector<Stmt*, 8> Statements;
12275 
12276   // The parameter for the "other" object, which we are move from.
12277   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12278   QualType OtherRefType = Other->getType()->
12279       getAs<RValueReferenceType>()->getPointeeType();
12280   assert(!OtherRefType.getQualifiers() &&
12281          "Bad argument type of defaulted move assignment");
12282 
12283   // Our location for everything implicitly-generated.
12284   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12285                            ? MoveAssignOperator->getEndLoc()
12286                            : MoveAssignOperator->getLocation();
12287 
12288   // Builds a reference to the "other" object.
12289   RefBuilder OtherRef(Other, OtherRefType);
12290   // Cast to rvalue.
12291   MoveCastBuilder MoveOther(OtherRef);
12292 
12293   // Builds the "this" pointer.
12294   ThisBuilder This;
12295 
12296   // Assign base classes.
12297   bool Invalid = false;
12298   for (auto &Base : ClassDecl->bases()) {
12299     // C++11 [class.copy]p28:
12300     //   It is unspecified whether subobjects representing virtual base classes
12301     //   are assigned more than once by the implicitly-defined copy assignment
12302     //   operator.
12303     // FIXME: Do not assign to a vbase that will be assigned by some other base
12304     // class. For a move-assignment, this can result in the vbase being moved
12305     // multiple times.
12306 
12307     // Form the assignment:
12308     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12309     QualType BaseType = Base.getType().getUnqualifiedType();
12310     if (!BaseType->isRecordType()) {
12311       Invalid = true;
12312       continue;
12313     }
12314 
12315     CXXCastPath BasePath;
12316     BasePath.push_back(&Base);
12317 
12318     // Construct the "from" expression, which is an implicit cast to the
12319     // appropriately-qualified base type.
12320     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12321 
12322     // Dereference "this".
12323     DerefBuilder DerefThis(This);
12324 
12325     // Implicitly cast "this" to the appropriately-qualified base type.
12326     CastBuilder To(DerefThis,
12327                    Context.getCVRQualifiedType(
12328                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12329                    VK_LValue, BasePath);
12330 
12331     // Build the move.
12332     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12333                                             To, From,
12334                                             /*CopyingBaseSubobject=*/true,
12335                                             /*Copying=*/false);
12336     if (Move.isInvalid()) {
12337       MoveAssignOperator->setInvalidDecl();
12338       return;
12339     }
12340 
12341     // Success! Record the move.
12342     Statements.push_back(Move.getAs<Expr>());
12343   }
12344 
12345   // Assign non-static members.
12346   for (auto *Field : ClassDecl->fields()) {
12347     // FIXME: We should form some kind of AST representation for the implied
12348     // memcpy in a union copy operation.
12349     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12350       continue;
12351 
12352     if (Field->isInvalidDecl()) {
12353       Invalid = true;
12354       continue;
12355     }
12356 
12357     // Check for members of reference type; we can't move those.
12358     if (Field->getType()->isReferenceType()) {
12359       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12360         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12361       Diag(Field->getLocation(), diag::note_declared_at);
12362       Invalid = true;
12363       continue;
12364     }
12365 
12366     // Check for members of const-qualified, non-class type.
12367     QualType BaseType = Context.getBaseElementType(Field->getType());
12368     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12369       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12370         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12371       Diag(Field->getLocation(), diag::note_declared_at);
12372       Invalid = true;
12373       continue;
12374     }
12375 
12376     // Suppress assigning zero-width bitfields.
12377     if (Field->isZeroLengthBitField(Context))
12378       continue;
12379 
12380     QualType FieldType = Field->getType().getNonReferenceType();
12381     if (FieldType->isIncompleteArrayType()) {
12382       assert(ClassDecl->hasFlexibleArrayMember() &&
12383              "Incomplete array type is not valid");
12384       continue;
12385     }
12386 
12387     // Build references to the field in the object we're copying from and to.
12388     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12389                               LookupMemberName);
12390     MemberLookup.addDecl(Field);
12391     MemberLookup.resolveKind();
12392     MemberBuilder From(MoveOther, OtherRefType,
12393                        /*IsArrow=*/false, MemberLookup);
12394     MemberBuilder To(This, getCurrentThisType(),
12395                      /*IsArrow=*/true, MemberLookup);
12396 
12397     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12398         "Member reference with rvalue base must be rvalue except for reference "
12399         "members, which aren't allowed for move assignment.");
12400 
12401     // Build the move of this field.
12402     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12403                                             To, From,
12404                                             /*CopyingBaseSubobject=*/false,
12405                                             /*Copying=*/false);
12406     if (Move.isInvalid()) {
12407       MoveAssignOperator->setInvalidDecl();
12408       return;
12409     }
12410 
12411     // Success! Record the copy.
12412     Statements.push_back(Move.getAs<Stmt>());
12413   }
12414 
12415   if (!Invalid) {
12416     // Add a "return *this;"
12417     ExprResult ThisObj =
12418         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12419 
12420     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12421     if (Return.isInvalid())
12422       Invalid = true;
12423     else
12424       Statements.push_back(Return.getAs<Stmt>());
12425   }
12426 
12427   if (Invalid) {
12428     MoveAssignOperator->setInvalidDecl();
12429     return;
12430   }
12431 
12432   StmtResult Body;
12433   {
12434     CompoundScopeRAII CompoundScope(*this);
12435     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12436                              /*isStmtExpr=*/false);
12437     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12438   }
12439   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12440   MoveAssignOperator->markUsed(Context);
12441 
12442   if (ASTMutationListener *L = getASTMutationListener()) {
12443     L->CompletedImplicitDefinition(MoveAssignOperator);
12444   }
12445 }
12446 
12447 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12448                                                     CXXRecordDecl *ClassDecl) {
12449   // C++ [class.copy]p4:
12450   //   If the class definition does not explicitly declare a copy
12451   //   constructor, one is declared implicitly.
12452   assert(ClassDecl->needsImplicitCopyConstructor());
12453 
12454   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12455   if (DSM.isAlreadyBeingDeclared())
12456     return nullptr;
12457 
12458   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12459   QualType ArgType = ClassType;
12460   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12461   if (Const)
12462     ArgType = ArgType.withConst();
12463   ArgType = Context.getLValueReferenceType(ArgType);
12464 
12465   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12466                                                      CXXCopyConstructor,
12467                                                      Const);
12468 
12469   DeclarationName Name
12470     = Context.DeclarationNames.getCXXConstructorName(
12471                                            Context.getCanonicalType(ClassType));
12472   SourceLocation ClassLoc = ClassDecl->getLocation();
12473   DeclarationNameInfo NameInfo(Name, ClassLoc);
12474 
12475   //   An implicitly-declared copy constructor is an inline public
12476   //   member of its class.
12477   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12478       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12479       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12480       Constexpr);
12481   CopyConstructor->setAccess(AS_public);
12482   CopyConstructor->setDefaulted();
12483 
12484   if (getLangOpts().CUDA) {
12485     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12486                                             CopyConstructor,
12487                                             /* ConstRHS */ Const,
12488                                             /* Diagnose */ false);
12489   }
12490 
12491   // Build an exception specification pointing back at this member.
12492   FunctionProtoType::ExtProtoInfo EPI =
12493       getImplicitMethodEPI(*this, CopyConstructor);
12494   CopyConstructor->setType(
12495       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12496 
12497   // Add the parameter to the constructor.
12498   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12499                                                ClassLoc, ClassLoc,
12500                                                /*IdentifierInfo=*/nullptr,
12501                                                ArgType, /*TInfo=*/nullptr,
12502                                                SC_None, nullptr);
12503   CopyConstructor->setParams(FromParam);
12504 
12505   CopyConstructor->setTrivial(
12506       ClassDecl->needsOverloadResolutionForCopyConstructor()
12507           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12508           : ClassDecl->hasTrivialCopyConstructor());
12509 
12510   CopyConstructor->setTrivialForCall(
12511       ClassDecl->hasAttr<TrivialABIAttr>() ||
12512       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12513            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12514              TAH_ConsiderTrivialABI)
12515            : ClassDecl->hasTrivialCopyConstructorForCall()));
12516 
12517   // Note that we have declared this constructor.
12518   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12519 
12520   Scope *S = getScopeForContext(ClassDecl);
12521   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12522 
12523   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12524     ClassDecl->setImplicitCopyConstructorIsDeleted();
12525     SetDeclDeleted(CopyConstructor, ClassLoc);
12526   }
12527 
12528   if (S)
12529     PushOnScopeChains(CopyConstructor, S, false);
12530   ClassDecl->addDecl(CopyConstructor);
12531 
12532   return CopyConstructor;
12533 }
12534 
12535 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12536                                          CXXConstructorDecl *CopyConstructor) {
12537   assert((CopyConstructor->isDefaulted() &&
12538           CopyConstructor->isCopyConstructor() &&
12539           !CopyConstructor->doesThisDeclarationHaveABody() &&
12540           !CopyConstructor->isDeleted()) &&
12541          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12542   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12543     return;
12544 
12545   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12546   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12547 
12548   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12549 
12550   // The exception specification is needed because we are defining the
12551   // function.
12552   ResolveExceptionSpec(CurrentLocation,
12553                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12554   MarkVTableUsed(CurrentLocation, ClassDecl);
12555 
12556   // Add a context note for diagnostics produced after this point.
12557   Scope.addContextNote(CurrentLocation);
12558 
12559   // C++11 [class.copy]p7:
12560   //   The [definition of an implicitly declared copy constructor] is
12561   //   deprecated if the class has a user-declared copy assignment operator
12562   //   or a user-declared destructor.
12563   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12564     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12565 
12566   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12567     CopyConstructor->setInvalidDecl();
12568   }  else {
12569     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12570                              ? CopyConstructor->getEndLoc()
12571                              : CopyConstructor->getLocation();
12572     Sema::CompoundScopeRAII CompoundScope(*this);
12573     CopyConstructor->setBody(
12574         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12575     CopyConstructor->markUsed(Context);
12576   }
12577 
12578   if (ASTMutationListener *L = getASTMutationListener()) {
12579     L->CompletedImplicitDefinition(CopyConstructor);
12580   }
12581 }
12582 
12583 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12584                                                     CXXRecordDecl *ClassDecl) {
12585   assert(ClassDecl->needsImplicitMoveConstructor());
12586 
12587   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12588   if (DSM.isAlreadyBeingDeclared())
12589     return nullptr;
12590 
12591   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12592   QualType ArgType = Context.getRValueReferenceType(ClassType);
12593 
12594   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12595                                                      CXXMoveConstructor,
12596                                                      false);
12597 
12598   DeclarationName Name
12599     = Context.DeclarationNames.getCXXConstructorName(
12600                                            Context.getCanonicalType(ClassType));
12601   SourceLocation ClassLoc = ClassDecl->getLocation();
12602   DeclarationNameInfo NameInfo(Name, ClassLoc);
12603 
12604   // C++11 [class.copy]p11:
12605   //   An implicitly-declared copy/move constructor is an inline public
12606   //   member of its class.
12607   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12608       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12609       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12610       Constexpr);
12611   MoveConstructor->setAccess(AS_public);
12612   MoveConstructor->setDefaulted();
12613 
12614   if (getLangOpts().CUDA) {
12615     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12616                                             MoveConstructor,
12617                                             /* ConstRHS */ false,
12618                                             /* Diagnose */ false);
12619   }
12620 
12621   // Build an exception specification pointing back at this member.
12622   FunctionProtoType::ExtProtoInfo EPI =
12623       getImplicitMethodEPI(*this, MoveConstructor);
12624   MoveConstructor->setType(
12625       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12626 
12627   // Add the parameter to the constructor.
12628   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12629                                                ClassLoc, ClassLoc,
12630                                                /*IdentifierInfo=*/nullptr,
12631                                                ArgType, /*TInfo=*/nullptr,
12632                                                SC_None, nullptr);
12633   MoveConstructor->setParams(FromParam);
12634 
12635   MoveConstructor->setTrivial(
12636       ClassDecl->needsOverloadResolutionForMoveConstructor()
12637           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12638           : ClassDecl->hasTrivialMoveConstructor());
12639 
12640   MoveConstructor->setTrivialForCall(
12641       ClassDecl->hasAttr<TrivialABIAttr>() ||
12642       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12643            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12644                                     TAH_ConsiderTrivialABI)
12645            : ClassDecl->hasTrivialMoveConstructorForCall()));
12646 
12647   // Note that we have declared this constructor.
12648   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12649 
12650   Scope *S = getScopeForContext(ClassDecl);
12651   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12652 
12653   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12654     ClassDecl->setImplicitMoveConstructorIsDeleted();
12655     SetDeclDeleted(MoveConstructor, ClassLoc);
12656   }
12657 
12658   if (S)
12659     PushOnScopeChains(MoveConstructor, S, false);
12660   ClassDecl->addDecl(MoveConstructor);
12661 
12662   return MoveConstructor;
12663 }
12664 
12665 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12666                                          CXXConstructorDecl *MoveConstructor) {
12667   assert((MoveConstructor->isDefaulted() &&
12668           MoveConstructor->isMoveConstructor() &&
12669           !MoveConstructor->doesThisDeclarationHaveABody() &&
12670           !MoveConstructor->isDeleted()) &&
12671          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12672   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12673     return;
12674 
12675   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12676   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12677 
12678   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12679 
12680   // The exception specification is needed because we are defining the
12681   // function.
12682   ResolveExceptionSpec(CurrentLocation,
12683                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12684   MarkVTableUsed(CurrentLocation, ClassDecl);
12685 
12686   // Add a context note for diagnostics produced after this point.
12687   Scope.addContextNote(CurrentLocation);
12688 
12689   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12690     MoveConstructor->setInvalidDecl();
12691   } else {
12692     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12693                              ? MoveConstructor->getEndLoc()
12694                              : MoveConstructor->getLocation();
12695     Sema::CompoundScopeRAII CompoundScope(*this);
12696     MoveConstructor->setBody(ActOnCompoundStmt(
12697         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12698     MoveConstructor->markUsed(Context);
12699   }
12700 
12701   if (ASTMutationListener *L = getASTMutationListener()) {
12702     L->CompletedImplicitDefinition(MoveConstructor);
12703   }
12704 }
12705 
12706 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12707   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12708 }
12709 
12710 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12711                             SourceLocation CurrentLocation,
12712                             CXXConversionDecl *Conv) {
12713   SynthesizedFunctionScope Scope(*this, Conv);
12714   assert(!Conv->getReturnType()->isUndeducedType());
12715 
12716   CXXRecordDecl *Lambda = Conv->getParent();
12717   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12718   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12719 
12720   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12721     CallOp = InstantiateFunctionDeclaration(
12722         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12723     if (!CallOp)
12724       return;
12725 
12726     Invoker = InstantiateFunctionDeclaration(
12727         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12728     if (!Invoker)
12729       return;
12730   }
12731 
12732   if (CallOp->isInvalidDecl())
12733     return;
12734 
12735   // Mark the call operator referenced (and add to pending instantiations
12736   // if necessary).
12737   // For both the conversion and static-invoker template specializations
12738   // we construct their body's in this function, so no need to add them
12739   // to the PendingInstantiations.
12740   MarkFunctionReferenced(CurrentLocation, CallOp);
12741 
12742   // Fill in the __invoke function with a dummy implementation. IR generation
12743   // will fill in the actual details. Update its type in case it contained
12744   // an 'auto'.
12745   Invoker->markUsed(Context);
12746   Invoker->setReferenced();
12747   Invoker->setType(Conv->getReturnType()->getPointeeType());
12748   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12749 
12750   // Construct the body of the conversion function { return __invoke; }.
12751   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12752                                        VK_LValue, Conv->getLocation()).get();
12753   assert(FunctionRef && "Can't refer to __invoke function?");
12754   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12755   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12756                                      Conv->getLocation()));
12757   Conv->markUsed(Context);
12758   Conv->setReferenced();
12759 
12760   if (ASTMutationListener *L = getASTMutationListener()) {
12761     L->CompletedImplicitDefinition(Conv);
12762     L->CompletedImplicitDefinition(Invoker);
12763   }
12764 }
12765 
12766 
12767 
12768 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12769        SourceLocation CurrentLocation,
12770        CXXConversionDecl *Conv)
12771 {
12772   assert(!Conv->getParent()->isGenericLambda());
12773 
12774   SynthesizedFunctionScope Scope(*this, Conv);
12775 
12776   // Copy-initialize the lambda object as needed to capture it.
12777   Expr *This = ActOnCXXThis(CurrentLocation).get();
12778   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12779 
12780   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12781                                                         Conv->getLocation(),
12782                                                         Conv, DerefThis);
12783 
12784   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12785   // behavior.  Note that only the general conversion function does this
12786   // (since it's unusable otherwise); in the case where we inline the
12787   // block literal, it has block literal lifetime semantics.
12788   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12789     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12790                                           CK_CopyAndAutoreleaseBlockObject,
12791                                           BuildBlock.get(), nullptr, VK_RValue);
12792 
12793   if (BuildBlock.isInvalid()) {
12794     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12795     Conv->setInvalidDecl();
12796     return;
12797   }
12798 
12799   // Create the return statement that returns the block from the conversion
12800   // function.
12801   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12802   if (Return.isInvalid()) {
12803     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12804     Conv->setInvalidDecl();
12805     return;
12806   }
12807 
12808   // Set the body of the conversion function.
12809   Stmt *ReturnS = Return.get();
12810   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12811                                      Conv->getLocation()));
12812   Conv->markUsed(Context);
12813 
12814   // We're done; notify the mutation listener, if any.
12815   if (ASTMutationListener *L = getASTMutationListener()) {
12816     L->CompletedImplicitDefinition(Conv);
12817   }
12818 }
12819 
12820 /// Determine whether the given list arguments contains exactly one
12821 /// "real" (non-default) argument.
12822 static bool hasOneRealArgument(MultiExprArg Args) {
12823   switch (Args.size()) {
12824   case 0:
12825     return false;
12826 
12827   default:
12828     if (!Args[1]->isDefaultArgument())
12829       return false;
12830 
12831     LLVM_FALLTHROUGH;
12832   case 1:
12833     return !Args[0]->isDefaultArgument();
12834   }
12835 
12836   return false;
12837 }
12838 
12839 ExprResult
12840 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12841                             NamedDecl *FoundDecl,
12842                             CXXConstructorDecl *Constructor,
12843                             MultiExprArg ExprArgs,
12844                             bool HadMultipleCandidates,
12845                             bool IsListInitialization,
12846                             bool IsStdInitListInitialization,
12847                             bool RequiresZeroInit,
12848                             unsigned ConstructKind,
12849                             SourceRange ParenRange) {
12850   bool Elidable = false;
12851 
12852   // C++0x [class.copy]p34:
12853   //   When certain criteria are met, an implementation is allowed to
12854   //   omit the copy/move construction of a class object, even if the
12855   //   copy/move constructor and/or destructor for the object have
12856   //   side effects. [...]
12857   //     - when a temporary class object that has not been bound to a
12858   //       reference (12.2) would be copied/moved to a class object
12859   //       with the same cv-unqualified type, the copy/move operation
12860   //       can be omitted by constructing the temporary object
12861   //       directly into the target of the omitted copy/move
12862   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12863       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12864     Expr *SubExpr = ExprArgs[0];
12865     Elidable = SubExpr->isTemporaryObject(
12866         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12867   }
12868 
12869   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12870                                FoundDecl, Constructor,
12871                                Elidable, ExprArgs, HadMultipleCandidates,
12872                                IsListInitialization,
12873                                IsStdInitListInitialization, RequiresZeroInit,
12874                                ConstructKind, ParenRange);
12875 }
12876 
12877 ExprResult
12878 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12879                             NamedDecl *FoundDecl,
12880                             CXXConstructorDecl *Constructor,
12881                             bool Elidable,
12882                             MultiExprArg ExprArgs,
12883                             bool HadMultipleCandidates,
12884                             bool IsListInitialization,
12885                             bool IsStdInitListInitialization,
12886                             bool RequiresZeroInit,
12887                             unsigned ConstructKind,
12888                             SourceRange ParenRange) {
12889   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12890     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12891     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12892       return ExprError();
12893   }
12894 
12895   return BuildCXXConstructExpr(
12896       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12897       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12898       RequiresZeroInit, ConstructKind, ParenRange);
12899 }
12900 
12901 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12902 /// including handling of its default argument expressions.
12903 ExprResult
12904 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12905                             CXXConstructorDecl *Constructor,
12906                             bool Elidable,
12907                             MultiExprArg ExprArgs,
12908                             bool HadMultipleCandidates,
12909                             bool IsListInitialization,
12910                             bool IsStdInitListInitialization,
12911                             bool RequiresZeroInit,
12912                             unsigned ConstructKind,
12913                             SourceRange ParenRange) {
12914   assert(declaresSameEntity(
12915              Constructor->getParent(),
12916              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12917          "given constructor for wrong type");
12918   MarkFunctionReferenced(ConstructLoc, Constructor);
12919   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12920     return ExprError();
12921 
12922   return CXXConstructExpr::Create(
12923       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12924       ExprArgs, HadMultipleCandidates, IsListInitialization,
12925       IsStdInitListInitialization, RequiresZeroInit,
12926       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12927       ParenRange);
12928 }
12929 
12930 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12931   assert(Field->hasInClassInitializer());
12932 
12933   // If we already have the in-class initializer nothing needs to be done.
12934   if (Field->getInClassInitializer())
12935     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12936 
12937   // If we might have already tried and failed to instantiate, don't try again.
12938   if (Field->isInvalidDecl())
12939     return ExprError();
12940 
12941   // Maybe we haven't instantiated the in-class initializer. Go check the
12942   // pattern FieldDecl to see if it has one.
12943   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12944 
12945   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12946     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12947     DeclContext::lookup_result Lookup =
12948         ClassPattern->lookup(Field->getDeclName());
12949 
12950     // Lookup can return at most two results: the pattern for the field, or the
12951     // injected class name of the parent record. No other member can have the
12952     // same name as the field.
12953     // In modules mode, lookup can return multiple results (coming from
12954     // different modules).
12955     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12956            "more than two lookup results for field name");
12957     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12958     if (!Pattern) {
12959       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12960              "cannot have other non-field member with same name");
12961       for (auto L : Lookup)
12962         if (isa<FieldDecl>(L)) {
12963           Pattern = cast<FieldDecl>(L);
12964           break;
12965         }
12966       assert(Pattern && "We must have set the Pattern!");
12967     }
12968 
12969     if (!Pattern->hasInClassInitializer() ||
12970         InstantiateInClassInitializer(Loc, Field, Pattern,
12971                                       getTemplateInstantiationArgs(Field))) {
12972       // Don't diagnose this again.
12973       Field->setInvalidDecl();
12974       return ExprError();
12975     }
12976     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12977   }
12978 
12979   // DR1351:
12980   //   If the brace-or-equal-initializer of a non-static data member
12981   //   invokes a defaulted default constructor of its class or of an
12982   //   enclosing class in a potentially evaluated subexpression, the
12983   //   program is ill-formed.
12984   //
12985   // This resolution is unworkable: the exception specification of the
12986   // default constructor can be needed in an unevaluated context, in
12987   // particular, in the operand of a noexcept-expression, and we can be
12988   // unable to compute an exception specification for an enclosed class.
12989   //
12990   // Any attempt to resolve the exception specification of a defaulted default
12991   // constructor before the initializer is lexically complete will ultimately
12992   // come here at which point we can diagnose it.
12993   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12994   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12995       << OutermostClass << Field;
12996   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
12997   // Recover by marking the field invalid, unless we're in a SFINAE context.
12998   if (!isSFINAEContext())
12999     Field->setInvalidDecl();
13000   return ExprError();
13001 }
13002 
13003 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13004   if (VD->isInvalidDecl()) return;
13005 
13006   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13007   if (ClassDecl->isInvalidDecl()) return;
13008   if (ClassDecl->hasIrrelevantDestructor()) return;
13009   if (ClassDecl->isDependentContext()) return;
13010 
13011   if (VD->isNoDestroy(getASTContext()))
13012     return;
13013 
13014   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13015   MarkFunctionReferenced(VD->getLocation(), Destructor);
13016   CheckDestructorAccess(VD->getLocation(), Destructor,
13017                         PDiag(diag::err_access_dtor_var)
13018                         << VD->getDeclName()
13019                         << VD->getType());
13020   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13021 
13022   if (Destructor->isTrivial()) return;
13023   if (!VD->hasGlobalStorage()) return;
13024 
13025   // Emit warning for non-trivial dtor in global scope (a real global,
13026   // class-static, function-static).
13027   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13028 
13029   // TODO: this should be re-enabled for static locals by !CXAAtExit
13030   if (!VD->isStaticLocal())
13031     Diag(VD->getLocation(), diag::warn_global_destructor);
13032 }
13033 
13034 /// Given a constructor and the set of arguments provided for the
13035 /// constructor, convert the arguments and add any required default arguments
13036 /// to form a proper call to this constructor.
13037 ///
13038 /// \returns true if an error occurred, false otherwise.
13039 bool
13040 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13041                               MultiExprArg ArgsPtr,
13042                               SourceLocation Loc,
13043                               SmallVectorImpl<Expr*> &ConvertedArgs,
13044                               bool AllowExplicit,
13045                               bool IsListInitialization) {
13046   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13047   unsigned NumArgs = ArgsPtr.size();
13048   Expr **Args = ArgsPtr.data();
13049 
13050   const FunctionProtoType *Proto
13051     = Constructor->getType()->getAs<FunctionProtoType>();
13052   assert(Proto && "Constructor without a prototype?");
13053   unsigned NumParams = Proto->getNumParams();
13054 
13055   // If too few arguments are available, we'll fill in the rest with defaults.
13056   if (NumArgs < NumParams)
13057     ConvertedArgs.reserve(NumParams);
13058   else
13059     ConvertedArgs.reserve(NumArgs);
13060 
13061   VariadicCallType CallType =
13062     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13063   SmallVector<Expr *, 8> AllArgs;
13064   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13065                                         Proto, 0,
13066                                         llvm::makeArrayRef(Args, NumArgs),
13067                                         AllArgs,
13068                                         CallType, AllowExplicit,
13069                                         IsListInitialization);
13070   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13071 
13072   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13073 
13074   CheckConstructorCall(Constructor,
13075                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13076                        Proto, Loc);
13077 
13078   return Invalid;
13079 }
13080 
13081 static inline bool
13082 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13083                                        const FunctionDecl *FnDecl) {
13084   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13085   if (isa<NamespaceDecl>(DC)) {
13086     return SemaRef.Diag(FnDecl->getLocation(),
13087                         diag::err_operator_new_delete_declared_in_namespace)
13088       << FnDecl->getDeclName();
13089   }
13090 
13091   if (isa<TranslationUnitDecl>(DC) &&
13092       FnDecl->getStorageClass() == SC_Static) {
13093     return SemaRef.Diag(FnDecl->getLocation(),
13094                         diag::err_operator_new_delete_declared_static)
13095       << FnDecl->getDeclName();
13096   }
13097 
13098   return false;
13099 }
13100 
13101 static QualType
13102 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13103   QualType QTy = PtrTy->getPointeeType();
13104   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13105   return SemaRef.Context.getPointerType(QTy);
13106 }
13107 
13108 static inline bool
13109 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13110                             CanQualType ExpectedResultType,
13111                             CanQualType ExpectedFirstParamType,
13112                             unsigned DependentParamTypeDiag,
13113                             unsigned InvalidParamTypeDiag) {
13114   QualType ResultType =
13115       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13116 
13117   // Check that the result type is not dependent.
13118   if (ResultType->isDependentType())
13119     return SemaRef.Diag(FnDecl->getLocation(),
13120                         diag::err_operator_new_delete_dependent_result_type)
13121     << FnDecl->getDeclName() << ExpectedResultType;
13122 
13123   // OpenCL C++: the operator is valid on any address space.
13124   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13125     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13126       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13127     }
13128   }
13129 
13130   // Check that the result type is what we expect.
13131   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13132     return SemaRef.Diag(FnDecl->getLocation(),
13133                         diag::err_operator_new_delete_invalid_result_type)
13134     << FnDecl->getDeclName() << ExpectedResultType;
13135 
13136   // A function template must have at least 2 parameters.
13137   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13138     return SemaRef.Diag(FnDecl->getLocation(),
13139                       diag::err_operator_new_delete_template_too_few_parameters)
13140         << FnDecl->getDeclName();
13141 
13142   // The function decl must have at least 1 parameter.
13143   if (FnDecl->getNumParams() == 0)
13144     return SemaRef.Diag(FnDecl->getLocation(),
13145                         diag::err_operator_new_delete_too_few_parameters)
13146       << FnDecl->getDeclName();
13147 
13148   // Check the first parameter type is not dependent.
13149   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13150   if (FirstParamType->isDependentType())
13151     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13152       << FnDecl->getDeclName() << ExpectedFirstParamType;
13153 
13154   // Check that the first parameter type is what we expect.
13155   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13156     // OpenCL C++: the operator is valid on any address space.
13157     if (auto *PtrTy =
13158             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13159       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13160     }
13161   }
13162   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13163       ExpectedFirstParamType)
13164     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13165     << FnDecl->getDeclName() << ExpectedFirstParamType;
13166 
13167   return false;
13168 }
13169 
13170 static bool
13171 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13172   // C++ [basic.stc.dynamic.allocation]p1:
13173   //   A program is ill-formed if an allocation function is declared in a
13174   //   namespace scope other than global scope or declared static in global
13175   //   scope.
13176   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13177     return true;
13178 
13179   CanQualType SizeTy =
13180     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13181 
13182   // C++ [basic.stc.dynamic.allocation]p1:
13183   //  The return type shall be void*. The first parameter shall have type
13184   //  std::size_t.
13185   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13186                                   SizeTy,
13187                                   diag::err_operator_new_dependent_param_type,
13188                                   diag::err_operator_new_param_type))
13189     return true;
13190 
13191   // C++ [basic.stc.dynamic.allocation]p1:
13192   //  The first parameter shall not have an associated default argument.
13193   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13194     return SemaRef.Diag(FnDecl->getLocation(),
13195                         diag::err_operator_new_default_arg)
13196       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13197 
13198   return false;
13199 }
13200 
13201 static bool
13202 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13203   // C++ [basic.stc.dynamic.deallocation]p1:
13204   //   A program is ill-formed if deallocation functions are declared in a
13205   //   namespace scope other than global scope or declared static in global
13206   //   scope.
13207   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13208     return true;
13209 
13210   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13211 
13212   // C++ P0722:
13213   //   Within a class C, the first parameter of a destroying operator delete
13214   //   shall be of type C *. The first parameter of any other deallocation
13215   //   function shall be of type void *.
13216   CanQualType ExpectedFirstParamType =
13217       MD && MD->isDestroyingOperatorDelete()
13218           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13219                 SemaRef.Context.getRecordType(MD->getParent())))
13220           : SemaRef.Context.VoidPtrTy;
13221 
13222   // C++ [basic.stc.dynamic.deallocation]p2:
13223   //   Each deallocation function shall return void
13224   if (CheckOperatorNewDeleteTypes(
13225           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13226           diag::err_operator_delete_dependent_param_type,
13227           diag::err_operator_delete_param_type))
13228     return true;
13229 
13230   // C++ P0722:
13231   //   A destroying operator delete shall be a usual deallocation function.
13232   if (MD && !MD->getParent()->isDependentContext() &&
13233       MD->isDestroyingOperatorDelete() &&
13234       !SemaRef.isUsualDeallocationFunction(MD)) {
13235     SemaRef.Diag(MD->getLocation(),
13236                  diag::err_destroying_operator_delete_not_usual);
13237     return true;
13238   }
13239 
13240   return false;
13241 }
13242 
13243 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13244 /// of this overloaded operator is well-formed. If so, returns false;
13245 /// otherwise, emits appropriate diagnostics and returns true.
13246 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13247   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13248          "Expected an overloaded operator declaration");
13249 
13250   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13251 
13252   // C++ [over.oper]p5:
13253   //   The allocation and deallocation functions, operator new,
13254   //   operator new[], operator delete and operator delete[], are
13255   //   described completely in 3.7.3. The attributes and restrictions
13256   //   found in the rest of this subclause do not apply to them unless
13257   //   explicitly stated in 3.7.3.
13258   if (Op == OO_Delete || Op == OO_Array_Delete)
13259     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13260 
13261   if (Op == OO_New || Op == OO_Array_New)
13262     return CheckOperatorNewDeclaration(*this, FnDecl);
13263 
13264   // C++ [over.oper]p6:
13265   //   An operator function shall either be a non-static member
13266   //   function or be a non-member function and have at least one
13267   //   parameter whose type is a class, a reference to a class, an
13268   //   enumeration, or a reference to an enumeration.
13269   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13270     if (MethodDecl->isStatic())
13271       return Diag(FnDecl->getLocation(),
13272                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13273   } else {
13274     bool ClassOrEnumParam = false;
13275     for (auto Param : FnDecl->parameters()) {
13276       QualType ParamType = Param->getType().getNonReferenceType();
13277       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13278           ParamType->isEnumeralType()) {
13279         ClassOrEnumParam = true;
13280         break;
13281       }
13282     }
13283 
13284     if (!ClassOrEnumParam)
13285       return Diag(FnDecl->getLocation(),
13286                   diag::err_operator_overload_needs_class_or_enum)
13287         << FnDecl->getDeclName();
13288   }
13289 
13290   // C++ [over.oper]p8:
13291   //   An operator function cannot have default arguments (8.3.6),
13292   //   except where explicitly stated below.
13293   //
13294   // Only the function-call operator allows default arguments
13295   // (C++ [over.call]p1).
13296   if (Op != OO_Call) {
13297     for (auto Param : FnDecl->parameters()) {
13298       if (Param->hasDefaultArg())
13299         return Diag(Param->getLocation(),
13300                     diag::err_operator_overload_default_arg)
13301           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13302     }
13303   }
13304 
13305   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13306     { false, false, false }
13307 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13308     , { Unary, Binary, MemberOnly }
13309 #include "clang/Basic/OperatorKinds.def"
13310   };
13311 
13312   bool CanBeUnaryOperator = OperatorUses[Op][0];
13313   bool CanBeBinaryOperator = OperatorUses[Op][1];
13314   bool MustBeMemberOperator = OperatorUses[Op][2];
13315 
13316   // C++ [over.oper]p8:
13317   //   [...] Operator functions cannot have more or fewer parameters
13318   //   than the number required for the corresponding operator, as
13319   //   described in the rest of this subclause.
13320   unsigned NumParams = FnDecl->getNumParams()
13321                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13322   if (Op != OO_Call &&
13323       ((NumParams == 1 && !CanBeUnaryOperator) ||
13324        (NumParams == 2 && !CanBeBinaryOperator) ||
13325        (NumParams < 1) || (NumParams > 2))) {
13326     // We have the wrong number of parameters.
13327     unsigned ErrorKind;
13328     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13329       ErrorKind = 2;  // 2 -> unary or binary.
13330     } else if (CanBeUnaryOperator) {
13331       ErrorKind = 0;  // 0 -> unary
13332     } else {
13333       assert(CanBeBinaryOperator &&
13334              "All non-call overloaded operators are unary or binary!");
13335       ErrorKind = 1;  // 1 -> binary
13336     }
13337 
13338     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13339       << FnDecl->getDeclName() << NumParams << ErrorKind;
13340   }
13341 
13342   // Overloaded operators other than operator() cannot be variadic.
13343   if (Op != OO_Call &&
13344       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13345     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13346       << FnDecl->getDeclName();
13347   }
13348 
13349   // Some operators must be non-static member functions.
13350   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13351     return Diag(FnDecl->getLocation(),
13352                 diag::err_operator_overload_must_be_member)
13353       << FnDecl->getDeclName();
13354   }
13355 
13356   // C++ [over.inc]p1:
13357   //   The user-defined function called operator++ implements the
13358   //   prefix and postfix ++ operator. If this function is a member
13359   //   function with no parameters, or a non-member function with one
13360   //   parameter of class or enumeration type, it defines the prefix
13361   //   increment operator ++ for objects of that type. If the function
13362   //   is a member function with one parameter (which shall be of type
13363   //   int) or a non-member function with two parameters (the second
13364   //   of which shall be of type int), it defines the postfix
13365   //   increment operator ++ for objects of that type.
13366   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13367     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13368     QualType ParamType = LastParam->getType();
13369 
13370     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13371         !ParamType->isDependentType())
13372       return Diag(LastParam->getLocation(),
13373                   diag::err_operator_overload_post_incdec_must_be_int)
13374         << LastParam->getType() << (Op == OO_MinusMinus);
13375   }
13376 
13377   return false;
13378 }
13379 
13380 static bool
13381 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13382                                           FunctionTemplateDecl *TpDecl) {
13383   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13384 
13385   // Must have one or two template parameters.
13386   if (TemplateParams->size() == 1) {
13387     NonTypeTemplateParmDecl *PmDecl =
13388         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13389 
13390     // The template parameter must be a char parameter pack.
13391     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13392         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13393       return false;
13394 
13395   } else if (TemplateParams->size() == 2) {
13396     TemplateTypeParmDecl *PmType =
13397         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13398     NonTypeTemplateParmDecl *PmArgs =
13399         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13400 
13401     // The second template parameter must be a parameter pack with the
13402     // first template parameter as its type.
13403     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13404         PmArgs->isTemplateParameterPack()) {
13405       const TemplateTypeParmType *TArgs =
13406           PmArgs->getType()->getAs<TemplateTypeParmType>();
13407       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13408           TArgs->getIndex() == PmType->getIndex()) {
13409         if (!SemaRef.inTemplateInstantiation())
13410           SemaRef.Diag(TpDecl->getLocation(),
13411                        diag::ext_string_literal_operator_template);
13412         return false;
13413       }
13414     }
13415   }
13416 
13417   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13418                diag::err_literal_operator_template)
13419       << TpDecl->getTemplateParameters()->getSourceRange();
13420   return true;
13421 }
13422 
13423 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13424 /// of this literal operator function is well-formed. If so, returns
13425 /// false; otherwise, emits appropriate diagnostics and returns true.
13426 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13427   if (isa<CXXMethodDecl>(FnDecl)) {
13428     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13429       << FnDecl->getDeclName();
13430     return true;
13431   }
13432 
13433   if (FnDecl->isExternC()) {
13434     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13435     if (const LinkageSpecDecl *LSD =
13436             FnDecl->getDeclContext()->getExternCContext())
13437       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13438     return true;
13439   }
13440 
13441   // This might be the definition of a literal operator template.
13442   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13443 
13444   // This might be a specialization of a literal operator template.
13445   if (!TpDecl)
13446     TpDecl = FnDecl->getPrimaryTemplate();
13447 
13448   // template <char...> type operator "" name() and
13449   // template <class T, T...> type operator "" name() are the only valid
13450   // template signatures, and the only valid signatures with no parameters.
13451   if (TpDecl) {
13452     if (FnDecl->param_size() != 0) {
13453       Diag(FnDecl->getLocation(),
13454            diag::err_literal_operator_template_with_params);
13455       return true;
13456     }
13457 
13458     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13459       return true;
13460 
13461   } else if (FnDecl->param_size() == 1) {
13462     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13463 
13464     QualType ParamType = Param->getType().getUnqualifiedType();
13465 
13466     // Only unsigned long long int, long double, any character type, and const
13467     // char * are allowed as the only parameters.
13468     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13469         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13470         Context.hasSameType(ParamType, Context.CharTy) ||
13471         Context.hasSameType(ParamType, Context.WideCharTy) ||
13472         Context.hasSameType(ParamType, Context.Char8Ty) ||
13473         Context.hasSameType(ParamType, Context.Char16Ty) ||
13474         Context.hasSameType(ParamType, Context.Char32Ty)) {
13475     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13476       QualType InnerType = Ptr->getPointeeType();
13477 
13478       // Pointer parameter must be a const char *.
13479       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13480                                 Context.CharTy) &&
13481             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13482         Diag(Param->getSourceRange().getBegin(),
13483              diag::err_literal_operator_param)
13484             << ParamType << "'const char *'" << Param->getSourceRange();
13485         return true;
13486       }
13487 
13488     } else if (ParamType->isRealFloatingType()) {
13489       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13490           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13491       return true;
13492 
13493     } else if (ParamType->isIntegerType()) {
13494       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13495           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13496       return true;
13497 
13498     } else {
13499       Diag(Param->getSourceRange().getBegin(),
13500            diag::err_literal_operator_invalid_param)
13501           << ParamType << Param->getSourceRange();
13502       return true;
13503     }
13504 
13505   } else if (FnDecl->param_size() == 2) {
13506     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13507 
13508     // First, verify that the first parameter is correct.
13509 
13510     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13511 
13512     // Two parameter function must have a pointer to const as a
13513     // first parameter; let's strip those qualifiers.
13514     const PointerType *PT = FirstParamType->getAs<PointerType>();
13515 
13516     if (!PT) {
13517       Diag((*Param)->getSourceRange().getBegin(),
13518            diag::err_literal_operator_param)
13519           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13520       return true;
13521     }
13522 
13523     QualType PointeeType = PT->getPointeeType();
13524     // First parameter must be const
13525     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13526       Diag((*Param)->getSourceRange().getBegin(),
13527            diag::err_literal_operator_param)
13528           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13529       return true;
13530     }
13531 
13532     QualType InnerType = PointeeType.getUnqualifiedType();
13533     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13534     // const char32_t* are allowed as the first parameter to a two-parameter
13535     // function
13536     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13537           Context.hasSameType(InnerType, Context.WideCharTy) ||
13538           Context.hasSameType(InnerType, Context.Char8Ty) ||
13539           Context.hasSameType(InnerType, Context.Char16Ty) ||
13540           Context.hasSameType(InnerType, Context.Char32Ty))) {
13541       Diag((*Param)->getSourceRange().getBegin(),
13542            diag::err_literal_operator_param)
13543           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13544       return true;
13545     }
13546 
13547     // Move on to the second and final parameter.
13548     ++Param;
13549 
13550     // The second parameter must be a std::size_t.
13551     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13552     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13553       Diag((*Param)->getSourceRange().getBegin(),
13554            diag::err_literal_operator_param)
13555           << SecondParamType << Context.getSizeType()
13556           << (*Param)->getSourceRange();
13557       return true;
13558     }
13559   } else {
13560     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13561     return true;
13562   }
13563 
13564   // Parameters are good.
13565 
13566   // A parameter-declaration-clause containing a default argument is not
13567   // equivalent to any of the permitted forms.
13568   for (auto Param : FnDecl->parameters()) {
13569     if (Param->hasDefaultArg()) {
13570       Diag(Param->getDefaultArgRange().getBegin(),
13571            diag::err_literal_operator_default_argument)
13572         << Param->getDefaultArgRange();
13573       break;
13574     }
13575   }
13576 
13577   StringRef LiteralName
13578     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13579   if (LiteralName[0] != '_' &&
13580       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13581     // C++11 [usrlit.suffix]p1:
13582     //   Literal suffix identifiers that do not start with an underscore
13583     //   are reserved for future standardization.
13584     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13585       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13586   }
13587 
13588   return false;
13589 }
13590 
13591 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13592 /// linkage specification, including the language and (if present)
13593 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13594 /// language string literal. LBraceLoc, if valid, provides the location of
13595 /// the '{' brace. Otherwise, this linkage specification does not
13596 /// have any braces.
13597 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13598                                            Expr *LangStr,
13599                                            SourceLocation LBraceLoc) {
13600   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13601   if (!Lit->isAscii()) {
13602     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13603       << LangStr->getSourceRange();
13604     return nullptr;
13605   }
13606 
13607   StringRef Lang = Lit->getString();
13608   LinkageSpecDecl::LanguageIDs Language;
13609   if (Lang == "C")
13610     Language = LinkageSpecDecl::lang_c;
13611   else if (Lang == "C++")
13612     Language = LinkageSpecDecl::lang_cxx;
13613   else {
13614     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13615       << LangStr->getSourceRange();
13616     return nullptr;
13617   }
13618 
13619   // FIXME: Add all the various semantics of linkage specifications
13620 
13621   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13622                                                LangStr->getExprLoc(), Language,
13623                                                LBraceLoc.isValid());
13624   CurContext->addDecl(D);
13625   PushDeclContext(S, D);
13626   return D;
13627 }
13628 
13629 /// ActOnFinishLinkageSpecification - Complete the definition of
13630 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13631 /// valid, it's the position of the closing '}' brace in a linkage
13632 /// specification that uses braces.
13633 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13634                                             Decl *LinkageSpec,
13635                                             SourceLocation RBraceLoc) {
13636   if (RBraceLoc.isValid()) {
13637     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13638     LSDecl->setRBraceLoc(RBraceLoc);
13639   }
13640   PopDeclContext();
13641   return LinkageSpec;
13642 }
13643 
13644 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13645                                   const ParsedAttributesView &AttrList,
13646                                   SourceLocation SemiLoc) {
13647   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13648   // Attribute declarations appertain to empty declaration so we handle
13649   // them here.
13650   ProcessDeclAttributeList(S, ED, AttrList);
13651 
13652   CurContext->addDecl(ED);
13653   return ED;
13654 }
13655 
13656 /// Perform semantic analysis for the variable declaration that
13657 /// occurs within a C++ catch clause, returning the newly-created
13658 /// variable.
13659 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13660                                          TypeSourceInfo *TInfo,
13661                                          SourceLocation StartLoc,
13662                                          SourceLocation Loc,
13663                                          IdentifierInfo *Name) {
13664   bool Invalid = false;
13665   QualType ExDeclType = TInfo->getType();
13666 
13667   // Arrays and functions decay.
13668   if (ExDeclType->isArrayType())
13669     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13670   else if (ExDeclType->isFunctionType())
13671     ExDeclType = Context.getPointerType(ExDeclType);
13672 
13673   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13674   // The exception-declaration shall not denote a pointer or reference to an
13675   // incomplete type, other than [cv] void*.
13676   // N2844 forbids rvalue references.
13677   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13678     Diag(Loc, diag::err_catch_rvalue_ref);
13679     Invalid = true;
13680   }
13681 
13682   if (ExDeclType->isVariablyModifiedType()) {
13683     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13684     Invalid = true;
13685   }
13686 
13687   QualType BaseType = ExDeclType;
13688   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13689   unsigned DK = diag::err_catch_incomplete;
13690   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13691     BaseType = Ptr->getPointeeType();
13692     Mode = 1;
13693     DK = diag::err_catch_incomplete_ptr;
13694   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13695     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13696     BaseType = Ref->getPointeeType();
13697     Mode = 2;
13698     DK = diag::err_catch_incomplete_ref;
13699   }
13700   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13701       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13702     Invalid = true;
13703 
13704   if (!Invalid && !ExDeclType->isDependentType() &&
13705       RequireNonAbstractType(Loc, ExDeclType,
13706                              diag::err_abstract_type_in_decl,
13707                              AbstractVariableType))
13708     Invalid = true;
13709 
13710   // Only the non-fragile NeXT runtime currently supports C++ catches
13711   // of ObjC types, and no runtime supports catching ObjC types by value.
13712   if (!Invalid && getLangOpts().ObjC) {
13713     QualType T = ExDeclType;
13714     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13715       T = RT->getPointeeType();
13716 
13717     if (T->isObjCObjectType()) {
13718       Diag(Loc, diag::err_objc_object_catch);
13719       Invalid = true;
13720     } else if (T->isObjCObjectPointerType()) {
13721       // FIXME: should this be a test for macosx-fragile specifically?
13722       if (getLangOpts().ObjCRuntime.isFragile())
13723         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13724     }
13725   }
13726 
13727   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13728                                     ExDeclType, TInfo, SC_None);
13729   ExDecl->setExceptionVariable(true);
13730 
13731   // In ARC, infer 'retaining' for variables of retainable type.
13732   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13733     Invalid = true;
13734 
13735   if (!Invalid && !ExDeclType->isDependentType()) {
13736     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13737       // Insulate this from anything else we might currently be parsing.
13738       EnterExpressionEvaluationContext scope(
13739           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13740 
13741       // C++ [except.handle]p16:
13742       //   The object declared in an exception-declaration or, if the
13743       //   exception-declaration does not specify a name, a temporary (12.2) is
13744       //   copy-initialized (8.5) from the exception object. [...]
13745       //   The object is destroyed when the handler exits, after the destruction
13746       //   of any automatic objects initialized within the handler.
13747       //
13748       // We just pretend to initialize the object with itself, then make sure
13749       // it can be destroyed later.
13750       QualType initType = Context.getExceptionObjectType(ExDeclType);
13751 
13752       InitializedEntity entity =
13753         InitializedEntity::InitializeVariable(ExDecl);
13754       InitializationKind initKind =
13755         InitializationKind::CreateCopy(Loc, SourceLocation());
13756 
13757       Expr *opaqueValue =
13758         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13759       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13760       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13761       if (result.isInvalid())
13762         Invalid = true;
13763       else {
13764         // If the constructor used was non-trivial, set this as the
13765         // "initializer".
13766         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13767         if (!construct->getConstructor()->isTrivial()) {
13768           Expr *init = MaybeCreateExprWithCleanups(construct);
13769           ExDecl->setInit(init);
13770         }
13771 
13772         // And make sure it's destructable.
13773         FinalizeVarWithDestructor(ExDecl, recordType);
13774       }
13775     }
13776   }
13777 
13778   if (Invalid)
13779     ExDecl->setInvalidDecl();
13780 
13781   return ExDecl;
13782 }
13783 
13784 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13785 /// handler.
13786 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13787   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13788   bool Invalid = D.isInvalidType();
13789 
13790   // Check for unexpanded parameter packs.
13791   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13792                                       UPPC_ExceptionType)) {
13793     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13794                                              D.getIdentifierLoc());
13795     Invalid = true;
13796   }
13797 
13798   IdentifierInfo *II = D.getIdentifier();
13799   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13800                                              LookupOrdinaryName,
13801                                              ForVisibleRedeclaration)) {
13802     // The scope should be freshly made just for us. There is just no way
13803     // it contains any previous declaration, except for function parameters in
13804     // a function-try-block's catch statement.
13805     assert(!S->isDeclScope(PrevDecl));
13806     if (isDeclInScope(PrevDecl, CurContext, S)) {
13807       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13808         << D.getIdentifier();
13809       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13810       Invalid = true;
13811     } else if (PrevDecl->isTemplateParameter())
13812       // Maybe we will complain about the shadowed template parameter.
13813       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13814   }
13815 
13816   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13817     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13818       << D.getCXXScopeSpec().getRange();
13819     Invalid = true;
13820   }
13821 
13822   VarDecl *ExDecl = BuildExceptionDeclaration(
13823       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13824   if (Invalid)
13825     ExDecl->setInvalidDecl();
13826 
13827   // Add the exception declaration into this scope.
13828   if (II)
13829     PushOnScopeChains(ExDecl, S);
13830   else
13831     CurContext->addDecl(ExDecl);
13832 
13833   ProcessDeclAttributes(S, ExDecl, D);
13834   return ExDecl;
13835 }
13836 
13837 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13838                                          Expr *AssertExpr,
13839                                          Expr *AssertMessageExpr,
13840                                          SourceLocation RParenLoc) {
13841   StringLiteral *AssertMessage =
13842       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13843 
13844   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13845     return nullptr;
13846 
13847   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13848                                       AssertMessage, RParenLoc, false);
13849 }
13850 
13851 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13852                                          Expr *AssertExpr,
13853                                          StringLiteral *AssertMessage,
13854                                          SourceLocation RParenLoc,
13855                                          bool Failed) {
13856   assert(AssertExpr != nullptr && "Expected non-null condition");
13857   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13858       !Failed) {
13859     // In a static_assert-declaration, the constant-expression shall be a
13860     // constant expression that can be contextually converted to bool.
13861     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13862     if (Converted.isInvalid())
13863       Failed = true;
13864 
13865     llvm::APSInt Cond;
13866     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13867           diag::err_static_assert_expression_is_not_constant,
13868           /*AllowFold=*/false).isInvalid())
13869       Failed = true;
13870 
13871     if (!Failed && !Cond) {
13872       SmallString<256> MsgBuffer;
13873       llvm::raw_svector_ostream Msg(MsgBuffer);
13874       if (AssertMessage)
13875         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13876 
13877       Expr *InnerCond = nullptr;
13878       std::string InnerCondDescription;
13879       std::tie(InnerCond, InnerCondDescription) =
13880         findFailedBooleanCondition(Converted.get(),
13881                                    /*AllowTopLevelCond=*/false);
13882       if (InnerCond) {
13883         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13884           << InnerCondDescription << !AssertMessage
13885           << Msg.str() << InnerCond->getSourceRange();
13886       } else {
13887         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13888           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13889       }
13890       Failed = true;
13891     }
13892   }
13893 
13894   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13895                                                   /*DiscardedValue*/false,
13896                                                   /*IsConstexpr*/true);
13897   if (FullAssertExpr.isInvalid())
13898     Failed = true;
13899   else
13900     AssertExpr = FullAssertExpr.get();
13901 
13902   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13903                                         AssertExpr, AssertMessage, RParenLoc,
13904                                         Failed);
13905 
13906   CurContext->addDecl(Decl);
13907   return Decl;
13908 }
13909 
13910 /// Perform semantic analysis of the given friend type declaration.
13911 ///
13912 /// \returns A friend declaration that.
13913 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13914                                       SourceLocation FriendLoc,
13915                                       TypeSourceInfo *TSInfo) {
13916   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13917 
13918   QualType T = TSInfo->getType();
13919   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13920 
13921   // C++03 [class.friend]p2:
13922   //   An elaborated-type-specifier shall be used in a friend declaration
13923   //   for a class.*
13924   //
13925   //   * The class-key of the elaborated-type-specifier is required.
13926   if (!CodeSynthesisContexts.empty()) {
13927     // Do not complain about the form of friend template types during any kind
13928     // of code synthesis. For template instantiation, we will have complained
13929     // when the template was defined.
13930   } else {
13931     if (!T->isElaboratedTypeSpecifier()) {
13932       // If we evaluated the type to a record type, suggest putting
13933       // a tag in front.
13934       if (const RecordType *RT = T->getAs<RecordType>()) {
13935         RecordDecl *RD = RT->getDecl();
13936 
13937         SmallString<16> InsertionText(" ");
13938         InsertionText += RD->getKindName();
13939 
13940         Diag(TypeRange.getBegin(),
13941              getLangOpts().CPlusPlus11 ?
13942                diag::warn_cxx98_compat_unelaborated_friend_type :
13943                diag::ext_unelaborated_friend_type)
13944           << (unsigned) RD->getTagKind()
13945           << T
13946           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13947                                         InsertionText);
13948       } else {
13949         Diag(FriendLoc,
13950              getLangOpts().CPlusPlus11 ?
13951                diag::warn_cxx98_compat_nonclass_type_friend :
13952                diag::ext_nonclass_type_friend)
13953           << T
13954           << TypeRange;
13955       }
13956     } else if (T->getAs<EnumType>()) {
13957       Diag(FriendLoc,
13958            getLangOpts().CPlusPlus11 ?
13959              diag::warn_cxx98_compat_enum_friend :
13960              diag::ext_enum_friend)
13961         << T
13962         << TypeRange;
13963     }
13964 
13965     // C++11 [class.friend]p3:
13966     //   A friend declaration that does not declare a function shall have one
13967     //   of the following forms:
13968     //     friend elaborated-type-specifier ;
13969     //     friend simple-type-specifier ;
13970     //     friend typename-specifier ;
13971     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13972       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13973   }
13974 
13975   //   If the type specifier in a friend declaration designates a (possibly
13976   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13977   //   the friend declaration is ignored.
13978   return FriendDecl::Create(Context, CurContext,
13979                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
13980                             FriendLoc);
13981 }
13982 
13983 /// Handle a friend tag declaration where the scope specifier was
13984 /// templated.
13985 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13986                                     unsigned TagSpec, SourceLocation TagLoc,
13987                                     CXXScopeSpec &SS, IdentifierInfo *Name,
13988                                     SourceLocation NameLoc,
13989                                     const ParsedAttributesView &Attr,
13990                                     MultiTemplateParamsArg TempParamLists) {
13991   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13992 
13993   bool IsMemberSpecialization = false;
13994   bool Invalid = false;
13995 
13996   if (TemplateParameterList *TemplateParams =
13997           MatchTemplateParametersToScopeSpecifier(
13998               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13999               IsMemberSpecialization, Invalid)) {
14000     if (TemplateParams->size() > 0) {
14001       // This is a declaration of a class template.
14002       if (Invalid)
14003         return nullptr;
14004 
14005       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14006                                 NameLoc, Attr, TemplateParams, AS_public,
14007                                 /*ModulePrivateLoc=*/SourceLocation(),
14008                                 FriendLoc, TempParamLists.size() - 1,
14009                                 TempParamLists.data()).get();
14010     } else {
14011       // The "template<>" header is extraneous.
14012       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14013         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14014       IsMemberSpecialization = true;
14015     }
14016   }
14017 
14018   if (Invalid) return nullptr;
14019 
14020   bool isAllExplicitSpecializations = true;
14021   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14022     if (TempParamLists[I]->size()) {
14023       isAllExplicitSpecializations = false;
14024       break;
14025     }
14026   }
14027 
14028   // FIXME: don't ignore attributes.
14029 
14030   // If it's explicit specializations all the way down, just forget
14031   // about the template header and build an appropriate non-templated
14032   // friend.  TODO: for source fidelity, remember the headers.
14033   if (isAllExplicitSpecializations) {
14034     if (SS.isEmpty()) {
14035       bool Owned = false;
14036       bool IsDependent = false;
14037       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14038                       Attr, AS_public,
14039                       /*ModulePrivateLoc=*/SourceLocation(),
14040                       MultiTemplateParamsArg(), Owned, IsDependent,
14041                       /*ScopedEnumKWLoc=*/SourceLocation(),
14042                       /*ScopedEnumUsesClassTag=*/false,
14043                       /*UnderlyingType=*/TypeResult(),
14044                       /*IsTypeSpecifier=*/false,
14045                       /*IsTemplateParamOrArg=*/false);
14046     }
14047 
14048     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14049     ElaboratedTypeKeyword Keyword
14050       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14051     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14052                                    *Name, NameLoc);
14053     if (T.isNull())
14054       return nullptr;
14055 
14056     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14057     if (isa<DependentNameType>(T)) {
14058       DependentNameTypeLoc TL =
14059           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14060       TL.setElaboratedKeywordLoc(TagLoc);
14061       TL.setQualifierLoc(QualifierLoc);
14062       TL.setNameLoc(NameLoc);
14063     } else {
14064       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14065       TL.setElaboratedKeywordLoc(TagLoc);
14066       TL.setQualifierLoc(QualifierLoc);
14067       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14068     }
14069 
14070     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14071                                             TSI, FriendLoc, TempParamLists);
14072     Friend->setAccess(AS_public);
14073     CurContext->addDecl(Friend);
14074     return Friend;
14075   }
14076 
14077   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14078 
14079 
14080 
14081   // Handle the case of a templated-scope friend class.  e.g.
14082   //   template <class T> class A<T>::B;
14083   // FIXME: we don't support these right now.
14084   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14085     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14086   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14087   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14088   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14089   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14090   TL.setElaboratedKeywordLoc(TagLoc);
14091   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14092   TL.setNameLoc(NameLoc);
14093 
14094   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14095                                           TSI, FriendLoc, TempParamLists);
14096   Friend->setAccess(AS_public);
14097   Friend->setUnsupportedFriend(true);
14098   CurContext->addDecl(Friend);
14099   return Friend;
14100 }
14101 
14102 /// Handle a friend type declaration.  This works in tandem with
14103 /// ActOnTag.
14104 ///
14105 /// Notes on friend class templates:
14106 ///
14107 /// We generally treat friend class declarations as if they were
14108 /// declaring a class.  So, for example, the elaborated type specifier
14109 /// in a friend declaration is required to obey the restrictions of a
14110 /// class-head (i.e. no typedefs in the scope chain), template
14111 /// parameters are required to match up with simple template-ids, &c.
14112 /// However, unlike when declaring a template specialization, it's
14113 /// okay to refer to a template specialization without an empty
14114 /// template parameter declaration, e.g.
14115 ///   friend class A<T>::B<unsigned>;
14116 /// We permit this as a special case; if there are any template
14117 /// parameters present at all, require proper matching, i.e.
14118 ///   template <> template \<class T> friend class A<int>::B;
14119 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14120                                 MultiTemplateParamsArg TempParams) {
14121   SourceLocation Loc = DS.getBeginLoc();
14122 
14123   assert(DS.isFriendSpecified());
14124   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14125 
14126   // C++ [class.friend]p3:
14127   // A friend declaration that does not declare a function shall have one of
14128   // the following forms:
14129   //     friend elaborated-type-specifier ;
14130   //     friend simple-type-specifier ;
14131   //     friend typename-specifier ;
14132   //
14133   // Any declaration with a type qualifier does not have that form. (It's
14134   // legal to specify a qualified type as a friend, you just can't write the
14135   // keywords.)
14136   if (DS.getTypeQualifiers()) {
14137     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14138       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14139     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14140       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14141     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14142       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14143     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14144       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14145     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14146       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14147   }
14148 
14149   // Try to convert the decl specifier to a type.  This works for
14150   // friend templates because ActOnTag never produces a ClassTemplateDecl
14151   // for a TUK_Friend.
14152   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14153   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14154   QualType T = TSI->getType();
14155   if (TheDeclarator.isInvalidType())
14156     return nullptr;
14157 
14158   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14159     return nullptr;
14160 
14161   // This is definitely an error in C++98.  It's probably meant to
14162   // be forbidden in C++0x, too, but the specification is just
14163   // poorly written.
14164   //
14165   // The problem is with declarations like the following:
14166   //   template <T> friend A<T>::foo;
14167   // where deciding whether a class C is a friend or not now hinges
14168   // on whether there exists an instantiation of A that causes
14169   // 'foo' to equal C.  There are restrictions on class-heads
14170   // (which we declare (by fiat) elaborated friend declarations to
14171   // be) that makes this tractable.
14172   //
14173   // FIXME: handle "template <> friend class A<T>;", which
14174   // is possibly well-formed?  Who even knows?
14175   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14176     Diag(Loc, diag::err_tagless_friend_type_template)
14177       << DS.getSourceRange();
14178     return nullptr;
14179   }
14180 
14181   // C++98 [class.friend]p1: A friend of a class is a function
14182   //   or class that is not a member of the class . . .
14183   // This is fixed in DR77, which just barely didn't make the C++03
14184   // deadline.  It's also a very silly restriction that seriously
14185   // affects inner classes and which nobody else seems to implement;
14186   // thus we never diagnose it, not even in -pedantic.
14187   //
14188   // But note that we could warn about it: it's always useless to
14189   // friend one of your own members (it's not, however, worthless to
14190   // friend a member of an arbitrary specialization of your template).
14191 
14192   Decl *D;
14193   if (!TempParams.empty())
14194     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14195                                    TempParams,
14196                                    TSI,
14197                                    DS.getFriendSpecLoc());
14198   else
14199     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14200 
14201   if (!D)
14202     return nullptr;
14203 
14204   D->setAccess(AS_public);
14205   CurContext->addDecl(D);
14206 
14207   return D;
14208 }
14209 
14210 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14211                                         MultiTemplateParamsArg TemplateParams) {
14212   const DeclSpec &DS = D.getDeclSpec();
14213 
14214   assert(DS.isFriendSpecified());
14215   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14216 
14217   SourceLocation Loc = D.getIdentifierLoc();
14218   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14219 
14220   // C++ [class.friend]p1
14221   //   A friend of a class is a function or class....
14222   // Note that this sees through typedefs, which is intended.
14223   // It *doesn't* see through dependent types, which is correct
14224   // according to [temp.arg.type]p3:
14225   //   If a declaration acquires a function type through a
14226   //   type dependent on a template-parameter and this causes
14227   //   a declaration that does not use the syntactic form of a
14228   //   function declarator to have a function type, the program
14229   //   is ill-formed.
14230   if (!TInfo->getType()->isFunctionType()) {
14231     Diag(Loc, diag::err_unexpected_friend);
14232 
14233     // It might be worthwhile to try to recover by creating an
14234     // appropriate declaration.
14235     return nullptr;
14236   }
14237 
14238   // C++ [namespace.memdef]p3
14239   //  - If a friend declaration in a non-local class first declares a
14240   //    class or function, the friend class or function is a member
14241   //    of the innermost enclosing namespace.
14242   //  - The name of the friend is not found by simple name lookup
14243   //    until a matching declaration is provided in that namespace
14244   //    scope (either before or after the class declaration granting
14245   //    friendship).
14246   //  - If a friend function is called, its name may be found by the
14247   //    name lookup that considers functions from namespaces and
14248   //    classes associated with the types of the function arguments.
14249   //  - When looking for a prior declaration of a class or a function
14250   //    declared as a friend, scopes outside the innermost enclosing
14251   //    namespace scope are not considered.
14252 
14253   CXXScopeSpec &SS = D.getCXXScopeSpec();
14254   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14255   DeclarationName Name = NameInfo.getName();
14256   assert(Name);
14257 
14258   // Check for unexpanded parameter packs.
14259   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14260       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14261       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14262     return nullptr;
14263 
14264   // The context we found the declaration in, or in which we should
14265   // create the declaration.
14266   DeclContext *DC;
14267   Scope *DCScope = S;
14268   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14269                         ForExternalRedeclaration);
14270 
14271   // There are five cases here.
14272   //   - There's no scope specifier and we're in a local class. Only look
14273   //     for functions declared in the immediately-enclosing block scope.
14274   // We recover from invalid scope qualifiers as if they just weren't there.
14275   FunctionDecl *FunctionContainingLocalClass = nullptr;
14276   if ((SS.isInvalid() || !SS.isSet()) &&
14277       (FunctionContainingLocalClass =
14278            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14279     // C++11 [class.friend]p11:
14280     //   If a friend declaration appears in a local class and the name
14281     //   specified is an unqualified name, a prior declaration is
14282     //   looked up without considering scopes that are outside the
14283     //   innermost enclosing non-class scope. For a friend function
14284     //   declaration, if there is no prior declaration, the program is
14285     //   ill-formed.
14286 
14287     // Find the innermost enclosing non-class scope. This is the block
14288     // scope containing the local class definition (or for a nested class,
14289     // the outer local class).
14290     DCScope = S->getFnParent();
14291 
14292     // Look up the function name in the scope.
14293     Previous.clear(LookupLocalFriendName);
14294     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14295 
14296     if (!Previous.empty()) {
14297       // All possible previous declarations must have the same context:
14298       // either they were declared at block scope or they are members of
14299       // one of the enclosing local classes.
14300       DC = Previous.getRepresentativeDecl()->getDeclContext();
14301     } else {
14302       // This is ill-formed, but provide the context that we would have
14303       // declared the function in, if we were permitted to, for error recovery.
14304       DC = FunctionContainingLocalClass;
14305     }
14306     adjustContextForLocalExternDecl(DC);
14307 
14308     // C++ [class.friend]p6:
14309     //   A function can be defined in a friend declaration of a class if and
14310     //   only if the class is a non-local class (9.8), the function name is
14311     //   unqualified, and the function has namespace scope.
14312     if (D.isFunctionDefinition()) {
14313       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14314     }
14315 
14316   //   - There's no scope specifier, in which case we just go to the
14317   //     appropriate scope and look for a function or function template
14318   //     there as appropriate.
14319   } else if (SS.isInvalid() || !SS.isSet()) {
14320     // C++11 [namespace.memdef]p3:
14321     //   If the name in a friend declaration is neither qualified nor
14322     //   a template-id and the declaration is a function or an
14323     //   elaborated-type-specifier, the lookup to determine whether
14324     //   the entity has been previously declared shall not consider
14325     //   any scopes outside the innermost enclosing namespace.
14326     bool isTemplateId =
14327         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14328 
14329     // Find the appropriate context according to the above.
14330     DC = CurContext;
14331 
14332     // Skip class contexts.  If someone can cite chapter and verse
14333     // for this behavior, that would be nice --- it's what GCC and
14334     // EDG do, and it seems like a reasonable intent, but the spec
14335     // really only says that checks for unqualified existing
14336     // declarations should stop at the nearest enclosing namespace,
14337     // not that they should only consider the nearest enclosing
14338     // namespace.
14339     while (DC->isRecord())
14340       DC = DC->getParent();
14341 
14342     DeclContext *LookupDC = DC;
14343     while (LookupDC->isTransparentContext())
14344       LookupDC = LookupDC->getParent();
14345 
14346     while (true) {
14347       LookupQualifiedName(Previous, LookupDC);
14348 
14349       if (!Previous.empty()) {
14350         DC = LookupDC;
14351         break;
14352       }
14353 
14354       if (isTemplateId) {
14355         if (isa<TranslationUnitDecl>(LookupDC)) break;
14356       } else {
14357         if (LookupDC->isFileContext()) break;
14358       }
14359       LookupDC = LookupDC->getParent();
14360     }
14361 
14362     DCScope = getScopeForDeclContext(S, DC);
14363 
14364   //   - There's a non-dependent scope specifier, in which case we
14365   //     compute it and do a previous lookup there for a function
14366   //     or function template.
14367   } else if (!SS.getScopeRep()->isDependent()) {
14368     DC = computeDeclContext(SS);
14369     if (!DC) return nullptr;
14370 
14371     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14372 
14373     LookupQualifiedName(Previous, DC);
14374 
14375     // Ignore things found implicitly in the wrong scope.
14376     // TODO: better diagnostics for this case.  Suggesting the right
14377     // qualified scope would be nice...
14378     LookupResult::Filter F = Previous.makeFilter();
14379     while (F.hasNext()) {
14380       NamedDecl *D = F.next();
14381       if (!DC->InEnclosingNamespaceSetOf(
14382               D->getDeclContext()->getRedeclContext()))
14383         F.erase();
14384     }
14385     F.done();
14386 
14387     if (Previous.empty()) {
14388       D.setInvalidType();
14389       Diag(Loc, diag::err_qualified_friend_not_found)
14390           << Name << TInfo->getType();
14391       return nullptr;
14392     }
14393 
14394     // C++ [class.friend]p1: A friend of a class is a function or
14395     //   class that is not a member of the class . . .
14396     if (DC->Equals(CurContext))
14397       Diag(DS.getFriendSpecLoc(),
14398            getLangOpts().CPlusPlus11 ?
14399              diag::warn_cxx98_compat_friend_is_member :
14400              diag::err_friend_is_member);
14401 
14402     if (D.isFunctionDefinition()) {
14403       // C++ [class.friend]p6:
14404       //   A function can be defined in a friend declaration of a class if and
14405       //   only if the class is a non-local class (9.8), the function name is
14406       //   unqualified, and the function has namespace scope.
14407       SemaDiagnosticBuilder DB
14408         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14409 
14410       DB << SS.getScopeRep();
14411       if (DC->isFileContext())
14412         DB << FixItHint::CreateRemoval(SS.getRange());
14413       SS.clear();
14414     }
14415 
14416   //   - There's a scope specifier that does not match any template
14417   //     parameter lists, in which case we use some arbitrary context,
14418   //     create a method or method template, and wait for instantiation.
14419   //   - There's a scope specifier that does match some template
14420   //     parameter lists, which we don't handle right now.
14421   } else {
14422     if (D.isFunctionDefinition()) {
14423       // C++ [class.friend]p6:
14424       //   A function can be defined in a friend declaration of a class if and
14425       //   only if the class is a non-local class (9.8), the function name is
14426       //   unqualified, and the function has namespace scope.
14427       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14428         << SS.getScopeRep();
14429     }
14430 
14431     DC = CurContext;
14432     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14433   }
14434 
14435   if (!DC->isRecord()) {
14436     int DiagArg = -1;
14437     switch (D.getName().getKind()) {
14438     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14439     case UnqualifiedIdKind::IK_ConstructorName:
14440       DiagArg = 0;
14441       break;
14442     case UnqualifiedIdKind::IK_DestructorName:
14443       DiagArg = 1;
14444       break;
14445     case UnqualifiedIdKind::IK_ConversionFunctionId:
14446       DiagArg = 2;
14447       break;
14448     case UnqualifiedIdKind::IK_DeductionGuideName:
14449       DiagArg = 3;
14450       break;
14451     case UnqualifiedIdKind::IK_Identifier:
14452     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14453     case UnqualifiedIdKind::IK_LiteralOperatorId:
14454     case UnqualifiedIdKind::IK_OperatorFunctionId:
14455     case UnqualifiedIdKind::IK_TemplateId:
14456       break;
14457     }
14458     // This implies that it has to be an operator or function.
14459     if (DiagArg >= 0) {
14460       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14461       return nullptr;
14462     }
14463   }
14464 
14465   // FIXME: This is an egregious hack to cope with cases where the scope stack
14466   // does not contain the declaration context, i.e., in an out-of-line
14467   // definition of a class.
14468   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14469   if (!DCScope) {
14470     FakeDCScope.setEntity(DC);
14471     DCScope = &FakeDCScope;
14472   }
14473 
14474   bool AddToScope = true;
14475   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14476                                           TemplateParams, AddToScope);
14477   if (!ND) return nullptr;
14478 
14479   assert(ND->getLexicalDeclContext() == CurContext);
14480 
14481   // If we performed typo correction, we might have added a scope specifier
14482   // and changed the decl context.
14483   DC = ND->getDeclContext();
14484 
14485   // Add the function declaration to the appropriate lookup tables,
14486   // adjusting the redeclarations list as necessary.  We don't
14487   // want to do this yet if the friending class is dependent.
14488   //
14489   // Also update the scope-based lookup if the target context's
14490   // lookup context is in lexical scope.
14491   if (!CurContext->isDependentContext()) {
14492     DC = DC->getRedeclContext();
14493     DC->makeDeclVisibleInContext(ND);
14494     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14495       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14496   }
14497 
14498   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14499                                        D.getIdentifierLoc(), ND,
14500                                        DS.getFriendSpecLoc());
14501   FrD->setAccess(AS_public);
14502   CurContext->addDecl(FrD);
14503 
14504   if (ND->isInvalidDecl()) {
14505     FrD->setInvalidDecl();
14506   } else {
14507     if (DC->isRecord()) CheckFriendAccess(ND);
14508 
14509     FunctionDecl *FD;
14510     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14511       FD = FTD->getTemplatedDecl();
14512     else
14513       FD = cast<FunctionDecl>(ND);
14514 
14515     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14516     // default argument expression, that declaration shall be a definition
14517     // and shall be the only declaration of the function or function
14518     // template in the translation unit.
14519     if (functionDeclHasDefaultArgument(FD)) {
14520       // We can't look at FD->getPreviousDecl() because it may not have been set
14521       // if we're in a dependent context. If the function is known to be a
14522       // redeclaration, we will have narrowed Previous down to the right decl.
14523       if (D.isRedeclaration()) {
14524         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14525         Diag(Previous.getRepresentativeDecl()->getLocation(),
14526              diag::note_previous_declaration);
14527       } else if (!D.isFunctionDefinition())
14528         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14529     }
14530 
14531     // Mark templated-scope function declarations as unsupported.
14532     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14533       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14534         << SS.getScopeRep() << SS.getRange()
14535         << cast<CXXRecordDecl>(CurContext);
14536       FrD->setUnsupportedFriend(true);
14537     }
14538   }
14539 
14540   return ND;
14541 }
14542 
14543 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14544   AdjustDeclIfTemplate(Dcl);
14545 
14546   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14547   if (!Fn) {
14548     Diag(DelLoc, diag::err_deleted_non_function);
14549     return;
14550   }
14551 
14552   // Deleted function does not have a body.
14553   Fn->setWillHaveBody(false);
14554 
14555   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14556     // Don't consider the implicit declaration we generate for explicit
14557     // specializations. FIXME: Do not generate these implicit declarations.
14558     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14559          Prev->getPreviousDecl()) &&
14560         !Prev->isDefined()) {
14561       Diag(DelLoc, diag::err_deleted_decl_not_first);
14562       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14563            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14564                               : diag::note_previous_declaration);
14565     }
14566     // If the declaration wasn't the first, we delete the function anyway for
14567     // recovery.
14568     Fn = Fn->getCanonicalDecl();
14569   }
14570 
14571   // dllimport/dllexport cannot be deleted.
14572   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14573     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14574     Fn->setInvalidDecl();
14575   }
14576 
14577   if (Fn->isDeleted())
14578     return;
14579 
14580   // See if we're deleting a function which is already known to override a
14581   // non-deleted virtual function.
14582   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14583     bool IssuedDiagnostic = false;
14584     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14585       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14586         if (!IssuedDiagnostic) {
14587           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14588           IssuedDiagnostic = true;
14589         }
14590         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14591       }
14592     }
14593     // If this function was implicitly deleted because it was defaulted,
14594     // explain why it was deleted.
14595     if (IssuedDiagnostic && MD->isDefaulted())
14596       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14597                                 /*Diagnose*/true);
14598   }
14599 
14600   // C++11 [basic.start.main]p3:
14601   //   A program that defines main as deleted [...] is ill-formed.
14602   if (Fn->isMain())
14603     Diag(DelLoc, diag::err_deleted_main);
14604 
14605   // C++11 [dcl.fct.def.delete]p4:
14606   //  A deleted function is implicitly inline.
14607   Fn->setImplicitlyInline();
14608   Fn->setDeletedAsWritten();
14609 }
14610 
14611 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14612   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14613 
14614   if (MD) {
14615     if (MD->getParent()->isDependentType()) {
14616       MD->setDefaulted();
14617       MD->setExplicitlyDefaulted();
14618       return;
14619     }
14620 
14621     CXXSpecialMember Member = getSpecialMember(MD);
14622     if (Member == CXXInvalid) {
14623       if (!MD->isInvalidDecl())
14624         Diag(DefaultLoc, diag::err_default_special_members);
14625       return;
14626     }
14627 
14628     MD->setDefaulted();
14629     MD->setExplicitlyDefaulted();
14630 
14631     // Unset that we will have a body for this function. We might not,
14632     // if it turns out to be trivial, and we don't need this marking now
14633     // that we've marked it as defaulted.
14634     MD->setWillHaveBody(false);
14635 
14636     // If this definition appears within the record, do the checking when
14637     // the record is complete.
14638     const FunctionDecl *Primary = MD;
14639     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14640       // Ask the template instantiation pattern that actually had the
14641       // '= default' on it.
14642       Primary = Pattern;
14643 
14644     // If the method was defaulted on its first declaration, we will have
14645     // already performed the checking in CheckCompletedCXXClass. Such a
14646     // declaration doesn't trigger an implicit definition.
14647     if (Primary->getCanonicalDecl()->isDefaulted())
14648       return;
14649 
14650     CheckExplicitlyDefaultedSpecialMember(MD);
14651 
14652     if (!MD->isInvalidDecl())
14653       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14654   } else {
14655     Diag(DefaultLoc, diag::err_default_special_members);
14656   }
14657 }
14658 
14659 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14660   for (Stmt *SubStmt : S->children()) {
14661     if (!SubStmt)
14662       continue;
14663     if (isa<ReturnStmt>(SubStmt))
14664       Self.Diag(SubStmt->getBeginLoc(),
14665                 diag::err_return_in_constructor_handler);
14666     if (!isa<Expr>(SubStmt))
14667       SearchForReturnInStmt(Self, SubStmt);
14668   }
14669 }
14670 
14671 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14672   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14673     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14674     SearchForReturnInStmt(*this, Handler);
14675   }
14676 }
14677 
14678 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14679                                              const CXXMethodDecl *Old) {
14680   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14681   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14682 
14683   if (OldFT->hasExtParameterInfos()) {
14684     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14685       // A parameter of the overriding method should be annotated with noescape
14686       // if the corresponding parameter of the overridden method is annotated.
14687       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14688           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14689         Diag(New->getParamDecl(I)->getLocation(),
14690              diag::warn_overriding_method_missing_noescape);
14691         Diag(Old->getParamDecl(I)->getLocation(),
14692              diag::note_overridden_marked_noescape);
14693       }
14694   }
14695 
14696   // Virtual overrides must have the same code_seg.
14697   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14698   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14699   if ((NewCSA || OldCSA) &&
14700       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14701     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14702     Diag(Old->getLocation(), diag::note_previous_declaration);
14703     return true;
14704   }
14705 
14706   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14707 
14708   // If the calling conventions match, everything is fine
14709   if (NewCC == OldCC)
14710     return false;
14711 
14712   // If the calling conventions mismatch because the new function is static,
14713   // suppress the calling convention mismatch error; the error about static
14714   // function override (err_static_overrides_virtual from
14715   // Sema::CheckFunctionDeclaration) is more clear.
14716   if (New->getStorageClass() == SC_Static)
14717     return false;
14718 
14719   Diag(New->getLocation(),
14720        diag::err_conflicting_overriding_cc_attributes)
14721     << New->getDeclName() << New->getType() << Old->getType();
14722   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14723   return true;
14724 }
14725 
14726 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14727                                              const CXXMethodDecl *Old) {
14728   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14729   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14730 
14731   if (Context.hasSameType(NewTy, OldTy) ||
14732       NewTy->isDependentType() || OldTy->isDependentType())
14733     return false;
14734 
14735   // Check if the return types are covariant
14736   QualType NewClassTy, OldClassTy;
14737 
14738   /// Both types must be pointers or references to classes.
14739   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14740     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14741       NewClassTy = NewPT->getPointeeType();
14742       OldClassTy = OldPT->getPointeeType();
14743     }
14744   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14745     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14746       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14747         NewClassTy = NewRT->getPointeeType();
14748         OldClassTy = OldRT->getPointeeType();
14749       }
14750     }
14751   }
14752 
14753   // The return types aren't either both pointers or references to a class type.
14754   if (NewClassTy.isNull()) {
14755     Diag(New->getLocation(),
14756          diag::err_different_return_type_for_overriding_virtual_function)
14757         << New->getDeclName() << NewTy << OldTy
14758         << New->getReturnTypeSourceRange();
14759     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14760         << Old->getReturnTypeSourceRange();
14761 
14762     return true;
14763   }
14764 
14765   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14766     // C++14 [class.virtual]p8:
14767     //   If the class type in the covariant return type of D::f differs from
14768     //   that of B::f, the class type in the return type of D::f shall be
14769     //   complete at the point of declaration of D::f or shall be the class
14770     //   type D.
14771     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14772       if (!RT->isBeingDefined() &&
14773           RequireCompleteType(New->getLocation(), NewClassTy,
14774                               diag::err_covariant_return_incomplete,
14775                               New->getDeclName()))
14776         return true;
14777     }
14778 
14779     // Check if the new class derives from the old class.
14780     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14781       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14782           << New->getDeclName() << NewTy << OldTy
14783           << New->getReturnTypeSourceRange();
14784       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14785           << Old->getReturnTypeSourceRange();
14786       return true;
14787     }
14788 
14789     // Check if we the conversion from derived to base is valid.
14790     if (CheckDerivedToBaseConversion(
14791             NewClassTy, OldClassTy,
14792             diag::err_covariant_return_inaccessible_base,
14793             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14794             New->getLocation(), New->getReturnTypeSourceRange(),
14795             New->getDeclName(), nullptr)) {
14796       // FIXME: this note won't trigger for delayed access control
14797       // diagnostics, and it's impossible to get an undelayed error
14798       // here from access control during the original parse because
14799       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14800       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14801           << Old->getReturnTypeSourceRange();
14802       return true;
14803     }
14804   }
14805 
14806   // The qualifiers of the return types must be the same.
14807   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14808     Diag(New->getLocation(),
14809          diag::err_covariant_return_type_different_qualifications)
14810         << New->getDeclName() << NewTy << OldTy
14811         << New->getReturnTypeSourceRange();
14812     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14813         << Old->getReturnTypeSourceRange();
14814     return true;
14815   }
14816 
14817 
14818   // The new class type must have the same or less qualifiers as the old type.
14819   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14820     Diag(New->getLocation(),
14821          diag::err_covariant_return_type_class_type_more_qualified)
14822         << New->getDeclName() << NewTy << OldTy
14823         << New->getReturnTypeSourceRange();
14824     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14825         << Old->getReturnTypeSourceRange();
14826     return true;
14827   }
14828 
14829   return false;
14830 }
14831 
14832 /// Mark the given method pure.
14833 ///
14834 /// \param Method the method to be marked pure.
14835 ///
14836 /// \param InitRange the source range that covers the "0" initializer.
14837 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14838   SourceLocation EndLoc = InitRange.getEnd();
14839   if (EndLoc.isValid())
14840     Method->setRangeEnd(EndLoc);
14841 
14842   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14843     Method->setPure();
14844     return false;
14845   }
14846 
14847   if (!Method->isInvalidDecl())
14848     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14849       << Method->getDeclName() << InitRange;
14850   return true;
14851 }
14852 
14853 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14854   if (D->getFriendObjectKind())
14855     Diag(D->getLocation(), diag::err_pure_friend);
14856   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14857     CheckPureMethod(M, ZeroLoc);
14858   else
14859     Diag(D->getLocation(), diag::err_illegal_initializer);
14860 }
14861 
14862 /// Determine whether the given declaration is a global variable or
14863 /// static data member.
14864 static bool isNonlocalVariable(const Decl *D) {
14865   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14866     return Var->hasGlobalStorage();
14867 
14868   return false;
14869 }
14870 
14871 /// Invoked when we are about to parse an initializer for the declaration
14872 /// 'Dcl'.
14873 ///
14874 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14875 /// static data member of class X, names should be looked up in the scope of
14876 /// class X. If the declaration had a scope specifier, a scope will have
14877 /// been created and passed in for this purpose. Otherwise, S will be null.
14878 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14879   // If there is no declaration, there was an error parsing it.
14880   if (!D || D->isInvalidDecl())
14881     return;
14882 
14883   // We will always have a nested name specifier here, but this declaration
14884   // might not be out of line if the specifier names the current namespace:
14885   //   extern int n;
14886   //   int ::n = 0;
14887   if (S && D->isOutOfLine())
14888     EnterDeclaratorContext(S, D->getDeclContext());
14889 
14890   // If we are parsing the initializer for a static data member, push a
14891   // new expression evaluation context that is associated with this static
14892   // data member.
14893   if (isNonlocalVariable(D))
14894     PushExpressionEvaluationContext(
14895         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14896 }
14897 
14898 /// Invoked after we are finished parsing an initializer for the declaration D.
14899 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14900   // If there is no declaration, there was an error parsing it.
14901   if (!D || D->isInvalidDecl())
14902     return;
14903 
14904   if (isNonlocalVariable(D))
14905     PopExpressionEvaluationContext();
14906 
14907   if (S && D->isOutOfLine())
14908     ExitDeclaratorContext(S);
14909 }
14910 
14911 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14912 /// C++ if/switch/while/for statement.
14913 /// e.g: "if (int x = f()) {...}"
14914 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14915   // C++ 6.4p2:
14916   // The declarator shall not specify a function or an array.
14917   // The type-specifier-seq shall not contain typedef and shall not declare a
14918   // new class or enumeration.
14919   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14920          "Parser allowed 'typedef' as storage class of condition decl.");
14921 
14922   Decl *Dcl = ActOnDeclarator(S, D);
14923   if (!Dcl)
14924     return true;
14925 
14926   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14927     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14928       << D.getSourceRange();
14929     return true;
14930   }
14931 
14932   return Dcl;
14933 }
14934 
14935 void Sema::LoadExternalVTableUses() {
14936   if (!ExternalSource)
14937     return;
14938 
14939   SmallVector<ExternalVTableUse, 4> VTables;
14940   ExternalSource->ReadUsedVTables(VTables);
14941   SmallVector<VTableUse, 4> NewUses;
14942   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14943     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14944       = VTablesUsed.find(VTables[I].Record);
14945     // Even if a definition wasn't required before, it may be required now.
14946     if (Pos != VTablesUsed.end()) {
14947       if (!Pos->second && VTables[I].DefinitionRequired)
14948         Pos->second = true;
14949       continue;
14950     }
14951 
14952     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14953     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14954   }
14955 
14956   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14957 }
14958 
14959 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14960                           bool DefinitionRequired) {
14961   // Ignore any vtable uses in unevaluated operands or for classes that do
14962   // not have a vtable.
14963   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14964       CurContext->isDependentContext() || isUnevaluatedContext())
14965     return;
14966   // Do not mark as used if compiling for the device outside of the target
14967   // region.
14968   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
14969       !isInOpenMPDeclareTargetContext() &&
14970       !isInOpenMPTargetExecutionDirective())
14971     return;
14972 
14973   // Try to insert this class into the map.
14974   LoadExternalVTableUses();
14975   Class = Class->getCanonicalDecl();
14976   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14977     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14978   if (!Pos.second) {
14979     // If we already had an entry, check to see if we are promoting this vtable
14980     // to require a definition. If so, we need to reappend to the VTableUses
14981     // list, since we may have already processed the first entry.
14982     if (DefinitionRequired && !Pos.first->second) {
14983       Pos.first->second = true;
14984     } else {
14985       // Otherwise, we can early exit.
14986       return;
14987     }
14988   } else {
14989     // The Microsoft ABI requires that we perform the destructor body
14990     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14991     // the deleting destructor is emitted with the vtable, not with the
14992     // destructor definition as in the Itanium ABI.
14993     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14994       CXXDestructorDecl *DD = Class->getDestructor();
14995       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14996         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14997           // If this is an out-of-line declaration, marking it referenced will
14998           // not do anything. Manually call CheckDestructor to look up operator
14999           // delete().
15000           ContextRAII SavedContext(*this, DD);
15001           CheckDestructor(DD);
15002         } else {
15003           MarkFunctionReferenced(Loc, Class->getDestructor());
15004         }
15005       }
15006     }
15007   }
15008 
15009   // Local classes need to have their virtual members marked
15010   // immediately. For all other classes, we mark their virtual members
15011   // at the end of the translation unit.
15012   if (Class->isLocalClass())
15013     MarkVirtualMembersReferenced(Loc, Class);
15014   else
15015     VTableUses.push_back(std::make_pair(Class, Loc));
15016 }
15017 
15018 bool Sema::DefineUsedVTables() {
15019   LoadExternalVTableUses();
15020   if (VTableUses.empty())
15021     return false;
15022 
15023   // Note: The VTableUses vector could grow as a result of marking
15024   // the members of a class as "used", so we check the size each
15025   // time through the loop and prefer indices (which are stable) to
15026   // iterators (which are not).
15027   bool DefinedAnything = false;
15028   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15029     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15030     if (!Class)
15031       continue;
15032     TemplateSpecializationKind ClassTSK =
15033         Class->getTemplateSpecializationKind();
15034 
15035     SourceLocation Loc = VTableUses[I].second;
15036 
15037     bool DefineVTable = true;
15038 
15039     // If this class has a key function, but that key function is
15040     // defined in another translation unit, we don't need to emit the
15041     // vtable even though we're using it.
15042     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15043     if (KeyFunction && !KeyFunction->hasBody()) {
15044       // The key function is in another translation unit.
15045       DefineVTable = false;
15046       TemplateSpecializationKind TSK =
15047           KeyFunction->getTemplateSpecializationKind();
15048       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15049              TSK != TSK_ImplicitInstantiation &&
15050              "Instantiations don't have key functions");
15051       (void)TSK;
15052     } else if (!KeyFunction) {
15053       // If we have a class with no key function that is the subject
15054       // of an explicit instantiation declaration, suppress the
15055       // vtable; it will live with the explicit instantiation
15056       // definition.
15057       bool IsExplicitInstantiationDeclaration =
15058           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15059       for (auto R : Class->redecls()) {
15060         TemplateSpecializationKind TSK
15061           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15062         if (TSK == TSK_ExplicitInstantiationDeclaration)
15063           IsExplicitInstantiationDeclaration = true;
15064         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15065           IsExplicitInstantiationDeclaration = false;
15066           break;
15067         }
15068       }
15069 
15070       if (IsExplicitInstantiationDeclaration)
15071         DefineVTable = false;
15072     }
15073 
15074     // The exception specifications for all virtual members may be needed even
15075     // if we are not providing an authoritative form of the vtable in this TU.
15076     // We may choose to emit it available_externally anyway.
15077     if (!DefineVTable) {
15078       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15079       continue;
15080     }
15081 
15082     // Mark all of the virtual members of this class as referenced, so
15083     // that we can build a vtable. Then, tell the AST consumer that a
15084     // vtable for this class is required.
15085     DefinedAnything = true;
15086     MarkVirtualMembersReferenced(Loc, Class);
15087     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15088     if (VTablesUsed[Canonical])
15089       Consumer.HandleVTable(Class);
15090 
15091     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15092     // no key function or the key function is inlined. Don't warn in C++ ABIs
15093     // that lack key functions, since the user won't be able to make one.
15094     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15095         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15096       const FunctionDecl *KeyFunctionDef = nullptr;
15097       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15098                            KeyFunctionDef->isInlined())) {
15099         Diag(Class->getLocation(),
15100              ClassTSK == TSK_ExplicitInstantiationDefinition
15101                  ? diag::warn_weak_template_vtable
15102                  : diag::warn_weak_vtable)
15103             << Class;
15104       }
15105     }
15106   }
15107   VTableUses.clear();
15108 
15109   return DefinedAnything;
15110 }
15111 
15112 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15113                                                  const CXXRecordDecl *RD) {
15114   for (const auto *I : RD->methods())
15115     if (I->isVirtual() && !I->isPure())
15116       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15117 }
15118 
15119 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15120                                         const CXXRecordDecl *RD) {
15121   // Mark all functions which will appear in RD's vtable as used.
15122   CXXFinalOverriderMap FinalOverriders;
15123   RD->getFinalOverriders(FinalOverriders);
15124   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15125                                             E = FinalOverriders.end();
15126        I != E; ++I) {
15127     for (OverridingMethods::const_iterator OI = I->second.begin(),
15128                                            OE = I->second.end();
15129          OI != OE; ++OI) {
15130       assert(OI->second.size() > 0 && "no final overrider");
15131       CXXMethodDecl *Overrider = OI->second.front().Method;
15132 
15133       // C++ [basic.def.odr]p2:
15134       //   [...] A virtual member function is used if it is not pure. [...]
15135       if (!Overrider->isPure())
15136         MarkFunctionReferenced(Loc, Overrider);
15137     }
15138   }
15139 
15140   // Only classes that have virtual bases need a VTT.
15141   if (RD->getNumVBases() == 0)
15142     return;
15143 
15144   for (const auto &I : RD->bases()) {
15145     const CXXRecordDecl *Base =
15146         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15147     if (Base->getNumVBases() == 0)
15148       continue;
15149     MarkVirtualMembersReferenced(Loc, Base);
15150   }
15151 }
15152 
15153 /// SetIvarInitializers - This routine builds initialization ASTs for the
15154 /// Objective-C implementation whose ivars need be initialized.
15155 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15156   if (!getLangOpts().CPlusPlus)
15157     return;
15158   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15159     SmallVector<ObjCIvarDecl*, 8> ivars;
15160     CollectIvarsToConstructOrDestruct(OID, ivars);
15161     if (ivars.empty())
15162       return;
15163     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15164     for (unsigned i = 0; i < ivars.size(); i++) {
15165       FieldDecl *Field = ivars[i];
15166       if (Field->isInvalidDecl())
15167         continue;
15168 
15169       CXXCtorInitializer *Member;
15170       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15171       InitializationKind InitKind =
15172         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15173 
15174       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15175       ExprResult MemberInit =
15176         InitSeq.Perform(*this, InitEntity, InitKind, None);
15177       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15178       // Note, MemberInit could actually come back empty if no initialization
15179       // is required (e.g., because it would call a trivial default constructor)
15180       if (!MemberInit.get() || MemberInit.isInvalid())
15181         continue;
15182 
15183       Member =
15184         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15185                                          SourceLocation(),
15186                                          MemberInit.getAs<Expr>(),
15187                                          SourceLocation());
15188       AllToInit.push_back(Member);
15189 
15190       // Be sure that the destructor is accessible and is marked as referenced.
15191       if (const RecordType *RecordTy =
15192               Context.getBaseElementType(Field->getType())
15193                   ->getAs<RecordType>()) {
15194         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15195         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15196           MarkFunctionReferenced(Field->getLocation(), Destructor);
15197           CheckDestructorAccess(Field->getLocation(), Destructor,
15198                             PDiag(diag::err_access_dtor_ivar)
15199                               << Context.getBaseElementType(Field->getType()));
15200         }
15201       }
15202     }
15203     ObjCImplementation->setIvarInitializers(Context,
15204                                             AllToInit.data(), AllToInit.size());
15205   }
15206 }
15207 
15208 static
15209 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15210                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15211                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15212                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15213                            Sema &S) {
15214   if (Ctor->isInvalidDecl())
15215     return;
15216 
15217   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15218 
15219   // Target may not be determinable yet, for instance if this is a dependent
15220   // call in an uninstantiated template.
15221   if (Target) {
15222     const FunctionDecl *FNTarget = nullptr;
15223     (void)Target->hasBody(FNTarget);
15224     Target = const_cast<CXXConstructorDecl*>(
15225       cast_or_null<CXXConstructorDecl>(FNTarget));
15226   }
15227 
15228   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15229                      // Avoid dereferencing a null pointer here.
15230                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15231 
15232   if (!Current.insert(Canonical).second)
15233     return;
15234 
15235   // We know that beyond here, we aren't chaining into a cycle.
15236   if (!Target || !Target->isDelegatingConstructor() ||
15237       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15238     Valid.insert(Current.begin(), Current.end());
15239     Current.clear();
15240   // We've hit a cycle.
15241   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15242              Current.count(TCanonical)) {
15243     // If we haven't diagnosed this cycle yet, do so now.
15244     if (!Invalid.count(TCanonical)) {
15245       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15246              diag::warn_delegating_ctor_cycle)
15247         << Ctor;
15248 
15249       // Don't add a note for a function delegating directly to itself.
15250       if (TCanonical != Canonical)
15251         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15252 
15253       CXXConstructorDecl *C = Target;
15254       while (C->getCanonicalDecl() != Canonical) {
15255         const FunctionDecl *FNTarget = nullptr;
15256         (void)C->getTargetConstructor()->hasBody(FNTarget);
15257         assert(FNTarget && "Ctor cycle through bodiless function");
15258 
15259         C = const_cast<CXXConstructorDecl*>(
15260           cast<CXXConstructorDecl>(FNTarget));
15261         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15262       }
15263     }
15264 
15265     Invalid.insert(Current.begin(), Current.end());
15266     Current.clear();
15267   } else {
15268     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15269   }
15270 }
15271 
15272 
15273 void Sema::CheckDelegatingCtorCycles() {
15274   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15275 
15276   for (DelegatingCtorDeclsType::iterator
15277          I = DelegatingCtorDecls.begin(ExternalSource),
15278          E = DelegatingCtorDecls.end();
15279        I != E; ++I)
15280     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15281 
15282   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15283     (*CI)->setInvalidDecl();
15284 }
15285 
15286 namespace {
15287   /// AST visitor that finds references to the 'this' expression.
15288   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15289     Sema &S;
15290 
15291   public:
15292     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15293 
15294     bool VisitCXXThisExpr(CXXThisExpr *E) {
15295       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15296         << E->isImplicit();
15297       return false;
15298     }
15299   };
15300 }
15301 
15302 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15303   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15304   if (!TSInfo)
15305     return false;
15306 
15307   TypeLoc TL = TSInfo->getTypeLoc();
15308   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15309   if (!ProtoTL)
15310     return false;
15311 
15312   // C++11 [expr.prim.general]p3:
15313   //   [The expression this] shall not appear before the optional
15314   //   cv-qualifier-seq and it shall not appear within the declaration of a
15315   //   static member function (although its type and value category are defined
15316   //   within a static member function as they are within a non-static member
15317   //   function). [ Note: this is because declaration matching does not occur
15318   //  until the complete declarator is known. - end note ]
15319   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15320   FindCXXThisExpr Finder(*this);
15321 
15322   // If the return type came after the cv-qualifier-seq, check it now.
15323   if (Proto->hasTrailingReturn() &&
15324       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15325     return true;
15326 
15327   // Check the exception specification.
15328   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15329     return true;
15330 
15331   return checkThisInStaticMemberFunctionAttributes(Method);
15332 }
15333 
15334 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15335   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15336   if (!TSInfo)
15337     return false;
15338 
15339   TypeLoc TL = TSInfo->getTypeLoc();
15340   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15341   if (!ProtoTL)
15342     return false;
15343 
15344   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15345   FindCXXThisExpr Finder(*this);
15346 
15347   switch (Proto->getExceptionSpecType()) {
15348   case EST_Unparsed:
15349   case EST_Uninstantiated:
15350   case EST_Unevaluated:
15351   case EST_BasicNoexcept:
15352   case EST_DynamicNone:
15353   case EST_MSAny:
15354   case EST_None:
15355     break;
15356 
15357   case EST_DependentNoexcept:
15358   case EST_NoexceptFalse:
15359   case EST_NoexceptTrue:
15360     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15361       return true;
15362     LLVM_FALLTHROUGH;
15363 
15364   case EST_Dynamic:
15365     for (const auto &E : Proto->exceptions()) {
15366       if (!Finder.TraverseType(E))
15367         return true;
15368     }
15369     break;
15370   }
15371 
15372   return false;
15373 }
15374 
15375 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15376   FindCXXThisExpr Finder(*this);
15377 
15378   // Check attributes.
15379   for (const auto *A : Method->attrs()) {
15380     // FIXME: This should be emitted by tblgen.
15381     Expr *Arg = nullptr;
15382     ArrayRef<Expr *> Args;
15383     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15384       Arg = G->getArg();
15385     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15386       Arg = G->getArg();
15387     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15388       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15389     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15390       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15391     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15392       Arg = ETLF->getSuccessValue();
15393       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15394     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15395       Arg = STLF->getSuccessValue();
15396       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15397     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15398       Arg = LR->getArg();
15399     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15400       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15401     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15402       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15403     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15404       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15405     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15406       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15407     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15408       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15409 
15410     if (Arg && !Finder.TraverseStmt(Arg))
15411       return true;
15412 
15413     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15414       if (!Finder.TraverseStmt(Args[I]))
15415         return true;
15416     }
15417   }
15418 
15419   return false;
15420 }
15421 
15422 void Sema::checkExceptionSpecification(
15423     bool IsTopLevel, ExceptionSpecificationType EST,
15424     ArrayRef<ParsedType> DynamicExceptions,
15425     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15426     SmallVectorImpl<QualType> &Exceptions,
15427     FunctionProtoType::ExceptionSpecInfo &ESI) {
15428   Exceptions.clear();
15429   ESI.Type = EST;
15430   if (EST == EST_Dynamic) {
15431     Exceptions.reserve(DynamicExceptions.size());
15432     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15433       // FIXME: Preserve type source info.
15434       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15435 
15436       if (IsTopLevel) {
15437         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15438         collectUnexpandedParameterPacks(ET, Unexpanded);
15439         if (!Unexpanded.empty()) {
15440           DiagnoseUnexpandedParameterPacks(
15441               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15442               Unexpanded);
15443           continue;
15444         }
15445       }
15446 
15447       // Check that the type is valid for an exception spec, and
15448       // drop it if not.
15449       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15450         Exceptions.push_back(ET);
15451     }
15452     ESI.Exceptions = Exceptions;
15453     return;
15454   }
15455 
15456   if (isComputedNoexcept(EST)) {
15457     assert((NoexceptExpr->isTypeDependent() ||
15458             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15459             Context.BoolTy) &&
15460            "Parser should have made sure that the expression is boolean");
15461     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15462       ESI.Type = EST_BasicNoexcept;
15463       return;
15464     }
15465 
15466     ESI.NoexceptExpr = NoexceptExpr;
15467     return;
15468   }
15469 }
15470 
15471 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15472              ExceptionSpecificationType EST,
15473              SourceRange SpecificationRange,
15474              ArrayRef<ParsedType> DynamicExceptions,
15475              ArrayRef<SourceRange> DynamicExceptionRanges,
15476              Expr *NoexceptExpr) {
15477   if (!MethodD)
15478     return;
15479 
15480   // Dig out the method we're referring to.
15481   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15482     MethodD = FunTmpl->getTemplatedDecl();
15483 
15484   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15485   if (!Method)
15486     return;
15487 
15488   // Check the exception specification.
15489   llvm::SmallVector<QualType, 4> Exceptions;
15490   FunctionProtoType::ExceptionSpecInfo ESI;
15491   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15492                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15493                               ESI);
15494 
15495   // Update the exception specification on the function type.
15496   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15497 
15498   if (Method->isStatic())
15499     checkThisInStaticMemberFunctionExceptionSpec(Method);
15500 
15501   if (Method->isVirtual()) {
15502     // Check overrides, which we previously had to delay.
15503     for (const CXXMethodDecl *O : Method->overridden_methods())
15504       CheckOverridingFunctionExceptionSpec(Method, O);
15505   }
15506 }
15507 
15508 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15509 ///
15510 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15511                                        SourceLocation DeclStart, Declarator &D,
15512                                        Expr *BitWidth,
15513                                        InClassInitStyle InitStyle,
15514                                        AccessSpecifier AS,
15515                                        const ParsedAttr &MSPropertyAttr) {
15516   IdentifierInfo *II = D.getIdentifier();
15517   if (!II) {
15518     Diag(DeclStart, diag::err_anonymous_property);
15519     return nullptr;
15520   }
15521   SourceLocation Loc = D.getIdentifierLoc();
15522 
15523   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15524   QualType T = TInfo->getType();
15525   if (getLangOpts().CPlusPlus) {
15526     CheckExtraCXXDefaultArguments(D);
15527 
15528     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15529                                         UPPC_DataMemberType)) {
15530       D.setInvalidType();
15531       T = Context.IntTy;
15532       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15533     }
15534   }
15535 
15536   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15537 
15538   if (D.getDeclSpec().isInlineSpecified())
15539     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15540         << getLangOpts().CPlusPlus17;
15541   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15542     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15543          diag::err_invalid_thread)
15544       << DeclSpec::getSpecifierName(TSCS);
15545 
15546   // Check to see if this name was declared as a member previously
15547   NamedDecl *PrevDecl = nullptr;
15548   LookupResult Previous(*this, II, Loc, LookupMemberName,
15549                         ForVisibleRedeclaration);
15550   LookupName(Previous, S);
15551   switch (Previous.getResultKind()) {
15552   case LookupResult::Found:
15553   case LookupResult::FoundUnresolvedValue:
15554     PrevDecl = Previous.getAsSingle<NamedDecl>();
15555     break;
15556 
15557   case LookupResult::FoundOverloaded:
15558     PrevDecl = Previous.getRepresentativeDecl();
15559     break;
15560 
15561   case LookupResult::NotFound:
15562   case LookupResult::NotFoundInCurrentInstantiation:
15563   case LookupResult::Ambiguous:
15564     break;
15565   }
15566 
15567   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15568     // Maybe we will complain about the shadowed template parameter.
15569     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15570     // Just pretend that we didn't see the previous declaration.
15571     PrevDecl = nullptr;
15572   }
15573 
15574   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15575     PrevDecl = nullptr;
15576 
15577   SourceLocation TSSL = D.getBeginLoc();
15578   MSPropertyDecl *NewPD =
15579       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15580                              MSPropertyAttr.getPropertyDataGetter(),
15581                              MSPropertyAttr.getPropertyDataSetter());
15582   ProcessDeclAttributes(TUScope, NewPD, D);
15583   NewPD->setAccess(AS);
15584 
15585   if (NewPD->isInvalidDecl())
15586     Record->setInvalidDecl();
15587 
15588   if (D.getDeclSpec().isModulePrivateSpecified())
15589     NewPD->setModulePrivate();
15590 
15591   if (NewPD->isInvalidDecl() && PrevDecl) {
15592     // Don't introduce NewFD into scope; there's already something
15593     // with the same name in the same scope.
15594   } else if (II) {
15595     PushOnScopeChains(NewPD, S);
15596   } else
15597     Record->addDecl(NewPD);
15598 
15599   return NewPD;
15600 }
15601